Determinant of symmetric matrix is an irreducible polynomial

Question:
In short: why is the determinant of a symmetric matrix an irreducible polynomial in the upper-triangular elements as variables?

The determinant of a square matrix $(x_{ij}) \in \Bbb F^{n \times n}$ is of course a polynomial $p$ of degree $n$ in the $n^2 $ variables $x_{ij}$. This polynomial is irreducible, a fact which is proved nicely here.
When looking at symmetric polynomials, the determinant is a different polynomial $f$ in $\frac{n(n+1)}{2}$ variables, namely $(x_{ij})_{i\leq j}$. Note that $f$ is a quadratic polynomial in each variable, whereas $p$ is linear in each variable.
How do we know that $f$ is an irreducible polynomial too? This post gives a seemingly-simple proof that I don't get:
Suppose by contradiction that $f=gh$. Then we claim that $f=q^2$ for some polynomial $q$ in the variables $(x_{ij})_{i\leq j}$. To justify this, we look at the identity $\det (AA^T)=\det(A)^2$, so we know that $p(x_{ij})^2$ is always equal in value to $f(y_{ij})_{i\leq j}$, where $y_{ij}=\sum \limits_k x_{ik}x_{kj}$. Since the variables $y_{ij}, x_{ij}$ are not the same, I don't understand how we can claim from the identity $p(x_{ij})^2=f(y_{ij})$ that the required $q$ exists, and I also don't see where we use our assumption by way of contradiction that f is reducible.
I arrived at the question in the book by Shafarevich, where he sadly just comments that it is "easy to see":
Answer: This can also be done in a similar way as described in the post linked in the question for general square matrices. Letting $f\in\mathbb F[x_{ij}]_{1\le i\le j\le n}$ be the determinant, suppose that it decomposes as $f=gh$. We need to show that $g$ or $h$ is constant. This follows from the following properties of the determinant (when expressed as a linear combination of monomials in the $x_{ij}$),

For each $i=1,\ldots,n$, $f$ is first order in $x_{ii}$.
For each $1\le i < j\le n$, $f$ contains terms containing $x_{ij}$ but does not contain any terms containing $x_{ii}x_{ij}$ or $x_{jj}x_{ij}$.

I will make use of the following simple statements about factorisation in polynomial rings. (i) If a linear term in $k[x]$ factorizes into a product of two polynomials, then one is linear in $x$ and the other is independent of $x$. (ii) If $f=gh$ for $g\in k[x]\setminus k$ and $h\in k[y]\setminus k$ then $fg$ contains monomial terms containing $xy$.
Now, for the argument that if $f=gh$ then either $g$ or $h$ is constant. By property (1) above, for each $i$, either $g$ is first order in $x_{ii}$ and $h$ is independent of $x_{ii}$, or vice-versa.
Choose any $1\le i < j\le n$ such that $g$ is linear in $x_{ii}$. Then:

$h$ is independent of $x_{ii}$.
$h$ is also independent of $x_{ij}$ otherwise $gh$ will contain terms containing $x_{ii}x_{ij}$, contradicting (2).
$g$ depends on $x_{ij}$ otherwise $gh$ would be independent of $x_{ij}$, contradicting (2).
$g$ is linear in $x_{jj}$ otherwise $h$ would be linear in $x_{jj}$ and $gh$ would contain terms containing $x_{jj}x_{ij}$, contradicting (2).

Supposing that $g$ is linear in $x_{11}$ (wlog) the above argument can be applied to each $i < j$ to show that $h$ is independent of all the indeterminates $x_{ii},x_{jj},x_{ij}$ and, hence, is constant.
Answer: Denote by $\phi$ be the ring endomomorphism  ${\mathbb F}[x_{ij}]_{i\leq j} \to {\mathbb F}[x_{ij}]_{i\leq j}$ uniquely defined by $\phi(x_{ij})=y_{ij}$ for $i\leq j$. Then $\phi$ is $\mathbb F$-linear.
I claim that the kernel of $\phi$ is zero. To see why, let $h\in{\mathsf Ker}(\phi)$. We can view $h$ as a function on symmetric $n\times n$ matrices in the obvious way. Then the hypothesis says that $h$ is zero on all matrices of the form $AA^T$. Let $M=(m_{ij})$ be a symmetric, positive definite $(n-1)\times (n-1)$ matrix. Let $v\in{\mathbb R}^{n-1}$, $a\in{\mathbb R}$ and let $M'$ be the $n\times n$ symmetric matrix defined by
$$
M'=
\left(\begin{array}{cc}
M  & v \\
   &   \\
v^T& a \\
\end{array}\right)
$$
There is a threshold $\alpha(M,v)$ such that $M'$ is still positive definite whenever
$a>\alpha(M,v)$. For those values of $a$, $M'$ will have a unique positive definite square root, so $h(M')=0$. Since $h$ is a polynomial, we see that (for this value of $M$) $h$ does not depend on $v$ or $a$ and that $h(M,.)=0$. Iterating this argument in smaller dimensions, we eventually obtain $h=0$ as wished.
So the kernel of $\phi$ is zero and $\phi$ is therefore injective.
Write $f$ as a product of irreducibles, $f=f_1f_2\ldots f_r$ (where some of
the $f_i$ may be equal, but all the $f_i$ are nonconstant). We then have the identity $p^2=\phi(f_1)\phi(f_2)\ldots \phi(f_r)$. Since all the $\phi(f_i)$ are nonconstant, the only possiblity is $r=2$, $\phi(f_1)=\phi(f_2)=p$ (after rescaling constant factors).
Since $\phi$ is injective, we deduce $f_1=f_2$ and this is the $q$ you're looking for.
Answer: Clearly $\det$ on complex symmetric matrices has no square factors, since $\det$ restricted to diagonal matrices hasn't. Therefore, we have to show that the variety of complex symmetric complex matrices with determinant $0$ is irreducible. But it is the image of the map  ( reduction of complex quadratic form to diagonal form)
$$M_{n\times n-1}(\mathbb{C}) \to M_{n\times n}(\mathbb{C})\\
A \mapsto A\cdot A^t$$
so being an image of an irreducible variety it is also irreducible.
A similar approach works for the usual determinant. (However, it will not work for the determinant on skew-symmetric matrices)
Note $\det$ restricted to some classes of matrices ( circulant, or group determinants) is reducible. But it should be irreducible on Hankel, Toeplitz, and Hessenberg matrices.


Drupal views contextual filter: use last argument as filter value

Question: I would like a views contextual filter to only use the last argument in the url.    Given the following taxonomy structure, I would want /term-a to return Term A1 and Term A2 only (which works fine).  However, if the url is /term-a/term-a1 I would want only Term A1a to be returned, which isn't working, it's still returning Term A1 and Term A2
Within views, I don't see a way to use the last part of the path for the filter.  I tried to remove the argument from the path and then use the following as a default argument:
$path = arg();
return array_pop($path);

Here is the sample term hierarchy:
- Term A
  - Term A1
    - Term A1a
  - Term A2
- Term B
  - Term B1
  - Term B2

Just to reiterate what is returned:
The path /term-a returns:

Term A1
Term A2

The path term-a/term-a1 returns:

Term A1
Term A2

The path /term-a1 returns:

Term A1a
Answer: One solution would be hook_views_pre_view()
function MYMODULE_views_pre_view(&$view, &$display_id, &$args) {
    if ($view->name == 'view_machine_name' && $display_id == 'my_display_id') {
        $args = array(end($args));
    }
}

For a view with one contextual filter this would always set the argument to the last argument from the URL.
Comment: I believe your default value won't work because it's the default value for when it's NOT in the URL, but in your case the filter value is in the URL.
Comment: I thought about this solution, and it may be the way to go as I need to alter the view for other things. Any idea why the Default Value PHP code wouldn't work here?
Answer: Use one view with two page displays.
The first display will take one contextual filter of /term-a
The second display will take two contextual filters. The first filter will be global null (so you can throw it away), and the second will be term-a1
Comment: I see, thanks.  Is there a reason you would use this route instead of getting the last argument from the path? Or are they just two equally viable solutions?


Referencing numpy array locations within if statements

Question: I have the following section of Python:
for j in range(0,T):
    for x in xrange(len(index)):
        for y in xrange(x+1,len(index)):
            if index(y) == index(x):

            continue

For which I have been attempting to translate successfully from a MATLAB equivalent. In matlab, this operation is simple as follows:
    for iter = 1:T
    for i = 1:length(index)
    for j = i+1:length(index)
        if index(j) == index(i)
            continue;
        end

However, when I attempt to execute my code I receive a "numpy.ndarray object is not callable" error. Why does this arise, and how would I go about writing this in a proper python manner to successfully execute?
Comment: I'm guessing that means you want `index[y] == index[x]` (square brackets, not parenthesis)
Comment: Also I think python's `len` and matlab's `length` are different. In python, `len` of an array is `numpy.size(array, axis=0)` in matlab `length` is `MAX(SIZE(MATRIX))`.
Comment: @BiRico - You are correct.
Answer: Looks like index is an array of some sort, but when you do index(y) and index(x), Python thinks you're trying to call a function index() using x and y as parameters, respectively.
If you're trying to simply access the elements, use index[x] and index[y].


Regex to Identify an URL Parameter Not Knowing Which Parameter It Will Be

Question: So I've been working on building out an haproxy cluster (1.5.x) and hit a snag where for a particular webapp I'm wanting to pitch API GETs to a read-only app cluster and the PUTs into a much smaller write cluster.
I've tried using a path_reg, which doesn't seem to want to match anything beyond a filename. The urlp derivatives seem to be what I should be using, but their proper usage has eluded me. The one tricky nuance with the URL parameters I'm trying to capture and differentiate all begin with either a "get" or "set" something...but the parameters do not have values. From what I've understood or attempted to, the urlp derivatives generally expect there to be a value associated with a parameter, so it seems like I can't simply use something like:
acl api_gets urlp_reg(get) (get?){1}

from an URL with parameters like:
/api.foo?apikey=stuff&param1=foo&getsomething&param2=bar

Similarly, path_reg seems to not pick up anything beyond a filename, so rudimentary testing of trying to match the following as a proof of concept were also fruitless:
acl path_sanity_check path_reg ^\/api\.foo\?apikey.*

Whereas simply making the regex pattern ^/api.foo will pick up where the requests are being sent to.
Should I be using urlp_reg for this even if the parameter(s) don't have values? What alternatives are there if not using an urlp derivative?
Answer: Path fetches the path.  The query isn't part of the path.  capture.req.uri fetches the full URI.
Although sloppy, you could match that with something like this:
acl foo capture.req.uri -m reg [&\?]get

The character class escaping might require adjustment, but the idea is to find either ?get or &get in the request URI.
If you are building a new cluster, use HAProxy 1.6, which has a number of new, useful fetches and converters, plus optional Lua integration for more complicated logic.
urlp_reg is the wrong solution, because the regex match is for the value of the parameter, not its name... and you don't have values.
Comment: Ah, I see. I didn't stumble on the *capture.req.uri* before. I had a gut feeling trying the urlp derivatives that they were always going to fail because the particular parameters I wanted didn't have values as you indicate and confirm.

Your suggestion did just the trick - thanks a lot!


Domain blocked and no data scraped

Question: I recently purchased the domain www.iacro.dk from UnoEuro and installed WordPress planning to integrate blogging with Facebook. However, I cannot even get to share a link to the domain.
When I try to share any link on my timeline, it gives the error "The content you're trying to share includes a link that's been blocked for being spammy or unsafe: iacro.dk". Searching, I came across Sucuri SiteCheck which showed that McAfee TrustedSource had marked the site as having malicious content. Strange considering that I just bought it, it contains nothing but WordPress and I can't find any previous history of ownership. But I got McAfee to reclassify it and it now shows up green at SiteCheck. However, now a few days later, Facebook still blocks it. Clicking the "let us know" link in the FB block dialog got me to a "Blocked from Adding Content" form that I submitted, but this just triggered a confirmation mail stating that individual issues are not processed.
I then noticed the same behavior as here and here: When I type in any iacro.dk link on my Timeline it generates a blank preview with "(No Title)". It doesn't matter if it's the front page, a htm document or even an image - nothing is returned. So I tried the debugger which returns the very generic "Error Parsing URL: Error parsing input URL, no data was scraped.". Searching on this site, a lot of people suggest that missing "og:" tags might cause no scraping. I installed a WP plugin for that and verified tag generation, but nothing changed. And since FB can't even scrape plain htm / jpg from the domain, I assume tags can be ruled out.
Here someone suggests 301 Redirects being a problem, but I haven't set up redirection - I don't even have a .htaccess file.
So, my questions are: Is this all because of the domain being marked as "spammy"? If so, how can I get the FB ban lifted? However, I have seen examples of other "spammy" sites where the preview is being generated just fine, e.g. http://dagbok.nu described in this question. So if the blacklist is not the only problem, what else is wrong?
This is driving me nuts so thanks a lot in advance!
Comment: Probably your best bet is to file a [bug report](https://developers.facebook.com/bugs) on this. The "create a bug" link appears when you start typing in the search box.
Comment: That's what I feared. I'll give it a shot, but all similar bugs have been closed with comments like "Closing as this is not a platform bug.". Makes it very difficult to do anything about it.
Answer: I don't know the details, but it is a problem that facebook has with web sites hosted on shared servers, i.e. the server hosting your web site also hosts a number of other web sites.

Domain blocked and no data scraped


Azure DNS not propagating

Question: I forwarded my domain to the Azure DNS nameservers:
<code>ns1-01.azure-dns.com.
ns2-01.azure-dns.net.
ns3-01.azure-dns.org.
ns4-01.azure-dns.info.
</code>
That's an NS record on the Azure side. The registrar is ...not entirely important, as far as I know, but it's Ionos.
I have two servers on different sides of the world. One is an Azure VM. The A records used to just point to that VM. I am now trying to redirect some of the records to my new server; e.g. @.mydomain.org, with CNAME www.mydomain.org.
This wasn't my problem. I don't have any inaccurate records. I do not know if it could be this because I'm not sure how to check the routers of the nameservers. The four nameservers above all return the address I want; 18.104.22.168 and 188.8.131.52 return the old IP. It's been 24 hours since I changed these records and the original TTL was 12 hours. I've since set that to ten minutes (600s).
I have never had this happen before with DNS so I don't have the foggiest idea of how to fix it. Any suggestions or advice would be appreciated. Happy to post more information if it is helpful.
Comment: What was the value of your zone TTL on the old server? Maybe the old info is still cached ...
Comment: The old value was 43200, which has expired (and then some).
Comment: Do you mind saying what is the domain?
Comment: machetessl.org is the base domain, which is pointing to 188.8.131.52, which is a test domain. There's a CNAME web.machetessl.org -> machetessl.org. The other domains I can't really go into.
Answer: You probably need to look at your registrar again. A quick whois shows they're still announcing ui-dns servers for the name servers. Changing the NS records is not the same as pointing your domain name to a different set of DNS servers. Most registrars will have an option to either host dns or use a different dns provider.
This guide might be helpful, assuming this wasn't what you followed before.
For reference this is what I see when I run a whois:
<code>$ whois machetessl.org | grep Name
Domain Name: MACHETESSL.ORG
Name Server: NS1068.UI-DNS.DE
Name Server: NS1068.UI-DNS.COM
Name Server: NS1068.UI-DNS.BIZ
Name Server: NS1068.UI-DNS.ORG
</code>
Because these aren't Azure, no matter what you do in Azure won't matter.
Comment: whois is not the tool to use to troubleshoot DNS problems in most cases. you should instead query the parent (registry) authoritative nameservers. Or use online troubleshooting tools (that use only DNS) like Zonemaster or DNSviz
Comment: "it does tell us who the authoritative name servers are for a domain" This information can be wrong, and is better retrieved from the registry authoritative nameservers themselves (the parent zone). While the whois outpout is also under the control of the registry, and comes from the same data, it has not coupled to DNS resolution, and whois output is not necessarily real-time, while DNS is. whois is useful to see the statuses of the domain, like if it has `clientHold` for example. but this is second step, first step is DNS.
Comment: Interesting! Yes I did look at their documentation but I will have a look at it again... I suppose on Monday when I can contact them. If it checks out I'll accept your answer! Thanks.
Comment: Agreed @PatrickMevzek. While whois is not the tool to use to troubleshoot all DNS issues, it does tell us who the authoritative name servers are for a domain. You can get this dig, nslookup, or the websites you mentioned as well. In this case, there are many ways to look into the issue. For the additional idea, I'm giving you a upvote on your comment.  Zonemaster does give details on delegation issues (ie the ui-dns.* servers say they are authoritative but the name servers in the record say different servers are).

Azure DNS not propagating


How are points in the ATP/WTA ranking computed in case tournament final is delayed (and finished during the following week)?

Question: It happens quite often that a tennis tournament is not finished on Sunday. Due to weather or other reason. A few examples (I wanted to include various leves - Grand Slam, ATP Tour, ATP Challenger Tour; I have no doubt that many other examples can be found):

In 2012 US Open the final match between Andy Murray and Novak Djokovic was played on Monday, September 10..
At 2012 Internazionali BNL d'Italia the men's final was played on Monday.
The final of 2013 Traralgon Challenger was suspended on Sunday and finished on Monday. See here or here.

Basically my question is:

How are the rankings calculated when some event has not been finished on Sunday? Will they be published as scheduled, or only after the event is finished? Are the rules different for events of different levels (Grand Slams, Masters, ATP Tour, Challengers)1?

The solutions which I could imagine could be:

Delaying publishing new rankings.
Not dropping the last year's points for the players still active in the tournament.
Dropping the last year's points for the players still active in the tournament, but counting the points which they already have from the current edition. (I.e., if the final is finished after publishing the new rankings, the finalist would both have points for the final, in the following edition the winner would get more points.)

1I am aware of the fact that this is a non-issue for futures, since the points for futures tournamets are counted with one week delay anyway. According to 2014 ATP Rulebook, Chapter IX. Emirates ATP Rankings:
The Emirates ATP Rankings or Emirates ATP Doubles Rankings period is the immediate past 52 weeks, except for: a) Barclays ATP World Tour Finals, singles and doubles, which is dropped on the Monday following the last ATP World Tour event of the following year. b) Futures Series tournaments that are only entered into the system on the second Monday following the tournament's week.
Answer: When the final match is delayed for some reason, or not played until the next day (Monday) - the new rankings will be delayed also and not published until the winners of the tournament final(s) are determined.
Since the Men's US Open final has been played on Monday the past 4 years now - let's use that tournament as an example. This year (2014), the tournament started on Monday Aug 25th and the Men's final was played on Monday, Sep 8th, with Marin Cilic winning the title - which comes along with 2,000 rankings points for being the champion.
If you look at Cilic's ranking and points going into the tournament (for the week starting Aug. 25th) - he's ranked #16 with 1,845 points.
Then, if you look at the rankings that were published "after" the US Open - for the week starting September 8th - his ranking there is #9 and he has 3,845 points - up 2,000 points for his US Open title.
So, even though the Men's US Open final was played on the day representing the rankings for that week, the results were still taken into consideration for that week.
Hope that helps - let me know if you have any other questions.
EDIT: Also, just to clarify something - rankings points earned from playing the tournament the previous year drop off of every players total before the tournament begins, so no players are still carrying around any points from the previous year once the tournament has started. I.E. points earned from a players 2014 US Open result will drop off before they begin playing in the 2015 US Open.
Comment: With your Cilic example it is perhaps worth mentioning that he [defended 0 points](http://en.wikipedia.org/wiki/2014_US_Open_(tennis)#Singles_seeds), since he did not play at [2013 US Open](https://en.wikipedia.org/wiki/2013_US_Open_(tennis)#Withdrawn_players) (because of a suspension).


Regular backup and archival options for a client device that runs MS SQL Express including restores

Question: In the current environment, a client application has been deployed on a single endpoint device e.g. laptop. The client application records & retrieves information that is needed for regulatory and compliance purposes and as it stands today, there is no backup of the data.
Since the data is deemed critical for regulatory and compliance reporting, backup and archival options are being explored.
What available options exist for backing up, archiving and restoring the client database?
Environment

Client device runs off Windows 7
MS SQL Express 2008

Requirements

RTO - 24 hours
RPO - 15 minutes
Answer: I'm going to assume your budget is limited (because it always is, isn't it?).
Head on over to Ola Hallengren's site and grab a copy of his maintenance solution. Run the script after you've configured the basics:
SET @BackupDirectory     = N'C:\Backup' -- Specify the backup root directory.
SET @CleanupTime         = NULL         -- Time in hours, after which backup files are deleted. If no time is specified, then no backup files are deleted.

Since you are using Express edition, you won't have the SQL Agent that allows you to schedule tasks, so use the windows task scheduler to set up your backups. Because your RPO is 15 minutes, I would recommend 1 daily full (at midnight for example) and a log backup every 5 minutes. Make sure your databases are in FULL.
A typical job would look like this:
sqlcmd -E -S MYSERVER\MYINSTANCE -d master -Q "EXECUTE dbo.DatabaseBackup @Databases = 'ALL_DATABASES', @Directory = N'F:\SQLBackup', @BackupType = 'FULL'" -b

(schedule this every day)
sqlcmd -E -S MYSERVER\MYINSTANCE -d master -Q "EXECUTE dbo.DatabaseBackup @Databases = 'ALL_DATABASES', @Directory = N'F:\SQLBackup', @BackupType = 'LOG'" -b

(schedule this every 5 min)
While you are using this solution, look into the other possibilities for updating statistics and index maintenance, ...
When restoring, restore the FULL and all following LOG-backups in order. Be sure to restore with NORECOVERY until you have applied the last logfile. Because there might be a lot of files, you might want to look into scripting this. Look here for more info on that.
Now comes the hard part. If the machine dies, you still won't get your RPO, so you need to get the backups off the machine (and maybe even to a place that is geographically far away). There are a ton of options here.
What I usually do is just back it up to a different data center/machine with the backup tool that is used in the environment for flat file backups. If there is none, you might want to look into getting maybe an Amazon Web Services account and move it to S3. If you are worried about security, you can encrypt your backups with applications like Arq.
So, final: RTO.
This can be tricky, depending on how you look at it. Do you have a team that can deploy a new SQL Server if needed and restore the backups (from AWS)? Is there an on call rotation system? are you going to pick up the phone 24/7?
If you want to automate this, things get a lot more complicated and you will need additional servers for sure. Since you are on 2008, you could
set up log shipping. This is a feature in SQL Server that you can use for free with every possible version. It makes a copy of the log files and restores them to your secondary sql server. I can elaborate if you want.
Please, make sure to test your solution and monitor if backups are running good! Nothing sucks more than having to do a restore and noticing at that time the backup hasn't run in 5 days. If it needs to be cheap, mailing the results works, but that gets old really fast. Maybe look into a monitoring system like Icinga if money is an issue.
PSA: I'm not affiliated with any of the solutions I propose here, it's just what I do usually when I come across this issue.
Answer: I think you're conflating high availability with back ups. They're two different things. Always On Availability groups aren't related to backing up the SQL database. You also don't need to backup the database to a SQL farm (whatever it is that you think a SQL farm is). You can simply script a database backup at intervals that meet your RPO on the client machine where SQL Server Express is installed.
Comment: Thanks. I did conflate the terms. My apologies. I updated the post. Frankly, the term `farm` gets banded around a fair bit by the DBAs without context. How do applications such SQL Backup Master compare to scripts i.e. which is more effective?
Answer: MSSQL Express version lacks of SQL Server Agent. You can use a combination of OSQL Utility (command line utility) and Windows Scheduler to execute t-sql BACKUP DATABASE statement. You can backup to external location (if mssql process account allows for it). You may use FULL restore mode and combination of BACKUP DATABASE / BACKUP LOG to have kind of continuous backup (ie. log backup every 15 minutes). Do not forget about system databases (master, model, msdb).
You may use Dropbox (or similar) as an external location also. In fact dropbox folder is local one, so you won't have problems with accessing network folders (mssql windows account can limit it). MSSQL 2008 R2 may compress data on backup (not sure if express version can).


Is it possible to to have more than 2 groups for biased coin randomization? If no, is there any modifications supporting multiple groups?

Question:
Is it possible to have more than 2 groups for biased coin randomization?

If no, is there any modifications of biased coin randomization supporting multiple groups?

This is my R code for generating randomization sequence for 2 groups (this code works fine.):
library(randomizeR)

N <- 100
p <- 0.5
groups <- LETTERS[1:2]

main_path="c:/del/4/"

obj_my_par<-ebcPar(N, p, groups)

(ebc_seq<-genSeq(obj_my_par, r=1))

(mylist<-getRandList(ebc_seq))
table(mylist)

But if I change LETTERS[1:2] to LETTERS[1:4] (increase number of groups) I am getting error:
Error in validObject(.Object) :
  invalid class "ebcPar" object: Length of groups is 4. Should have length 2.

Comment: Please explain what you mean by "biased coin randomization."
Comment: @whuber I mean Efrons version of it and other versions derived/based from/on it: https://projecteuclid.org/download/pdf_1/euclid.lnms/1215451477
Answer: Efron's biased coin design is predicated on two groups. From the error message you're getting, it seems like the R function you're using has not been extended to more than 2 groups. Proposing an extension would be pretty straightforward, although establishing its mathematical properties would probably be non-trivial, given the amount of maths in Efron's paper with just two groups.
Suppose there are $J$ possible treatment assignments and an available sample size of $N$. Let $T_i\in\{1,\ldots,J\}$ be the $i$th treatment assignment, $i=1,\ldots, N$. Let $n_{ij}=\sum_{i'=0}^{i-1} 1[T_{i'} = j]$ denote the number of assignments to arm $j$ just prior to assignment $i$. Under simple randomization, we would use $\Pr(T_i = j)\propto 1$. Under a biased randomization analogous to Efron's proposal, given some weight $\theta > 1$, you could consider
\begin{align}
\Pr(T_i=j)\propto
\begin{cases}
1, & n_{ij} = \max_{j'} n_{ij'}\\
\theta, & n_{ij} < \max_{j'} n_{ij'}
\end{cases}
\end{align}
When $J=2$, then setting $\theta = p/(1-p)$, where $p$ is as defined at the top of page 405 of Efron's paper, reduces to his original design.


How do I solve inequalities with Sympy?

Question: Objective: I want to implement a Fourier-Motzkin Elimination using Sympy. The first step for this would be to solve a number of inequalities.
Problem: The tools for solving inequalities with Sympy like solveset, solve_poly_inequality or reduce_inequalities do no seem to work.
Data:
from sympy import *
u1, u2, x1, x2 = symbols('u1 u2 x1 x2')
y1, y2, y3, y4, y5 = symbols('y1 y2 y3 y4 y5')

list_of_inequalities = [50*u2 - y5, -x2 + y5, 0, -u2 + 1, -35*u2 + y4 + y5, 35*u2 + x1 + x2 - y4 - y5 - 35, 35*u2 - y4 - y5, -35*u2 - x1 - x2 + y4 + y5 + 35, 50*y1 - y4, 50*u1 - x1 - 50*y1 + y4, -50*y1 + y4, -50*u1 + x1 + 50*y1 - y4, u2 - y1, -u1 - u2 + y1 + 1, 50*u2 - y5, -50*u2 - x2 + y5 + 50, 65*y1, 65*u1 - 65*y1, 35*u2 + 65*y1 - y4 - y5]

These are all expressions that are >=0.
I want to get rid of all the y-variables with Fourier-Motzkin Elimination. So, in a first step I would like to start with y1.
Desired Solution:
For example for list_of_inequalites[8] which is 50*y1 - y4 I should get y1>=y4/50 or similar.
In the end I want to have two lists. One with expressions that are smaller than y1 which would contain y4/50 and one with expressions larger than y1.
I will need these lists for the next step in the Fourier-Motzkin Elimination.
My Try:
y_1=[]
for eq in list_of_equations:
    expr= eq>=0
    if y1 in eq.free_symbols:
        y_1.append(solveset(expr.lhs>=0,y1,domain=S.Reals))

This way I get a list like this:
[ConditionSet(y1, 50*y1 - y4 >= 0, Reals), ConditionSet(y1, 50*u1 - x1 - 50*y1 + y4 >= 0, Reals), ConditionSet(y1, -50*y1 + y4 >= 0, Reals), ConditionSet(y1, -50*u1 + x1 + 50*y1 - y4 >= 0, Reals), ConditionSet(y1, u2 - y1 >= 0, Reals), ConditionSet(y1, -u1 - u2 + y1 + 1 >= 0, Reals), Interval(0, oo), ConditionSet(y1, 65*u1 - 65*y1 >= 0, Reals), ConditionSet(y1, 35*u2 + 65*y1 - y4 - y5 >= 0, Reals)]

I do not understand how to deal with these ConditionSets. They are certainly not the solution of my problem.
Another way would be to work with solve_poly_inequality:
for eq in list_of_equations:
    expr= eq>=0
    if y1 in eq.free_symbols:
        y_1.append(solve_poly_inequality(Poly(expr.lhs,y1),'>='))

This way I get a
NotImplementedError                       Traceback (most recent call last)
<ipython-input-269-686426e9455b> in <module>
      9     expr= eq>=0
     10     if y1 in eq.free_symbols:
---> 11         y_1.append(solve_poly_inequality(Poly(expr.lhs,y1),'>='))

~\Anaconda3\lib\site-packages\sympy\solvers\inequalities.py in solve_poly_inequality(poly, rel)
     56                 "could not determine truth value of %s" % t)
     57
---> 58     reals, intervals = poly.real_roots(multiple=False), []
     59
     60     if rel == '==':

~\Anaconda3\lib\site-packages\sympy\polys\polytools.py in real_roots(f, multiple, radicals)
   3498
   3499         """
-> 3500         reals = sympy.polys.rootoftools.CRootOf.real_roots(f, radicals=radicals)
   3501
   3502         if multiple:

~\Anaconda3\lib\site-packages\sympy\polys\rootoftools.py in real_roots(cls, poly, radicals)
    385     def real_roots(cls, poly, radicals=True):
    386         """Get real roots of a polynomial. """
--> 387         return cls._get_roots("_real_roots", poly, radicals)
    388
    389     @classmethod

~\Anaconda3\lib\site-packages\sympy\polys\rootoftools.py in _get_roots(cls, method, poly, radicals)
    717             raise PolynomialError("only univariate polynomials are allowed")
    718
--> 719         coeff, poly = cls._preprocess_roots(poly)
    720         roots = []
    721

~\Anaconda3\lib\site-packages\sympy\polys\rootoftools.py in _preprocess_roots(cls, poly)
    696         if not dom.is_ZZ:
    697             raise NotImplementedError(
--> 698                 "sorted roots not supported over %s" % dom)
    699
    700         return coeff, poly

NotImplementedError: sorted roots not supported over ZZ[x1,y4,u1]

The inequality that causes this error is 50*u1 - x1 - 50*y1 + y4 >= 0.
The last way I found for solving inequalities is reduce_inequalities:
for eq in list_of_equations:
    expr= eq>=0
    if y1 in eq.free_symbols:
        y_1.append(reduce_inequalities(expr>=0,[y1]))

But, this time I get the following error:
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-266-50cdf532f9fa> in <module>
     22     expr= eq>=0
     23     if y1 in eq.free_symbols:
---> 24         y_1.append(reduce_inequalities(expr>=0,[y1]))
     25 #     print(y_1[-1])
     26

~\Anaconda3\lib\site-packages\sympy\solvers\inequalities.py in reduce_inequalities(inequalities, symbols)
    985
    986     # solve system
--> 987     rv = _reduce_inequalities(inequalities, symbols)
    988
    989     # restore original symbols and return

~\Anaconda3\lib\site-packages\sympy\solvers\inequalities.py in _reduce_inequalities(inequalities, symbols)
    900             if len(common) == 1:
    901                 gen = common.pop()
--> 902                 other.append(_solve_inequality(Relational(expr, 0, rel), gen))
    903                 continue
    904             else:

~\Anaconda3\lib\site-packages\sympy\core\relational.py in __new__(cls, lhs, rhs, rop, **assumptions)
     87                             Eq and Ne; all other relationals expect
     88                             real expressions.
---> 89                         '''))
     90             # \\\
     91             return rv
TypeError:
A Boolean argument can only be used in Eq and Ne; all other
relationals expect real expressions.

Do you have any ideas how I can solve this problem?
Comment: When you ask about an error, show the **whole thing**!  For example what actually produces the `truth value` error?  `if y>0: print('yes')` produces that error, since `y>0` is a symbolic relation, which can't be used in a context like `if` with expects a simple True/False.
Comment: There is some work [here](https://github.com/sympy/sympy/pull/22389) with a reference to another approach there, too.
Comment: Beyond some basics it is hard to generalize `sympy` solutions.  You have to study the docs.  I haven't done much with inequalities, or what I think is being called `relationals`.  And if your `solve_set` produces `ConditionSets`, then you need to study that part of the documentation.  Also the coverage of subpackages varies widely; this is a open source project, not something that was developed and maintained by a company with paid staff.
Comment: Hmm, actually I couldn't reproduce the ````truth value```` error, but got ````NotImplementedError: sorted roots not supported over ZZ[x1,y4,u1]````.
Otherwise, I now included the whole error.
Comment: `u1, u2, x1, x2 = smp.symbols('u1 u2 x1 x2')`

gives

`NameError: name 'smp' is not defined`
Comment: This looks like it's using iPython and Anaconda - infrequently restarting the kernel and re-running all the cells or copying the relevant parts to a simple script may help a great amount with debugging (for example as @Nasser shows, there's probably at least a line with `import sympy as smp` not shown amongst any amount of others..)
Comment: I restarted the kernel and re-ran all the cells in a simple script. But, the errors are exactly the same. I also got rid of the 'smp'.
Comment: Is there any other way to solve linear inequalities with Python? I actually solved the example problem by hand. So I could also start to work with string manipulations to solve it. I just thought Sympy should have a way to solve this easily.
Answer: I don't know exactly the nature of your particular problem. But maybe we can work around it.
First solution
solve is also capable of solving inequalities, though it might not be easy to extract the proper solution:
sols = [solve(t >= 0, y1) for t in list_of_inequalities if y1 in S(t).free_symbols]
sols

# [(y1 < oo) & (y1 >= y4/50),
#  (-oo < y1) & (y1 <= u1 - x1/50 + y4/50),
#  (-oo < y1) & (y1 <= y4/50),
#  (y1 < oo) & (y1 >= u1 - x1/50 + y4/50),
#  (y1 <= u2) & (-oo < y1),
#  (y1 < oo) & (y1 >= u1 + u2 - 1),
#  (0 <= y1) & (y1 < oo),
#  (y1 <= u1) & (-oo < y1),
#  (y1 < oo) & (y1 >= -7*u2/13 + y4/65 + y5/65)]

# now a bit of post-processing:
from sympy.core.numbers import Infinity, NegativeInfinity
test_inf = lambda x: x.has(Infinity) or x.has(NegativeInfinity)
correct_arg = lambda x, y: x.args[0] if not x.args[0].has(y) else x.args[1]
final = [
    correct_arg(u, y1) for u in # extract the arguments from Relational that doesn't contain y1
    [t[0] if not test_inf(t[0]) else t[1] for t in # exclude arguments containing infinity
    [s.args[:2] for s in sols]] # extract args from Boolean And
]
final

# [y4/50,
#  u1 - x1/50 + y4/50,
#  y4/50,
#  u1 - x1/50 + y4/50,
#  u2,
#  u1 + u2 - 1,
#  0,
#  u1,
#  -7*u2/13 + y4/65 + y5/65]

Second solution
Since your inequalities appear to be linear, maybe we can solve them as equations, thus sparing us some post-processing. For example:
sols = [solve(t, y1)[0] for t in list_of_inequalities if y1 in S(t).free_symbols]
sols

# [y4/50,
#  u1 - x1/50 + y4/50,
#  y4/50,
#  u1 - x1/50 + y4/50,
#  u2,
#  u1 + u2 - 1,
#  0,
#  u1,
#  -7*u2/13 + y4/65 + y5/65]

Third solution
I believe that solveset returned ConditionSet because it doesn't know the nature of your symbols. If your symbols represent real variables, you can set assumptions on them:
u1, u2, x1, x2 = symbols('u1 u2 x1 x2', real=True)
y1, y2, y3, y4, y5 = symbols('y1 y2 y3 y4 y5', real=True)

list_of_inequalities = [50*u2 - y5, -x2 + y5, 0, -u2 + 1, -35*u2 + y4 + y5, 35*u2 + x1 + x2 - y4 - y5 - 35, 35*u2 - y4 - y5, -35*u2 - x1 - x2 + y4 + y5 + 35, 50*y1 - y4, 50*u1 - x1 - 50*y1 + y4, -50*y1 + y4, -50*u1 + x1 + 50*y1 - y4, u2 - y1, -u1 - u2 + y1 + 1, 50*u2 - y5, -50*u2 - x2 + y5 + 50, 65*y1, 65*u1 - 65*y1, 35*u2 + 65*y1 - y4 - y5]

sols = [solveset(t >= 0, y1, S.Reals) for t in list_of_inequalities if y1 in S(t).free_symbols]
sols

# [Interval(y4/50, oo),
#  Interval(-oo, u1 - x1/50 + y4/50),
#  Interval(-oo, y4/50),
#  Interval(u1 - x1/50 + y4/50, oo),
#  Interval(-oo, u2),
#  Interval(u1 + u2 - 1, oo),
#  Interval(0, oo),
#  Interval(-oo, u1),
#  Interval(-7*u2/13 + y4/65 + y5/65, oo)]

# extract the expressions, disregarding the infinity symbols
from sympy.core.numbers import Infinity, NegativeInfinity
test_inf = lambda x: x.has(Infinity) or x.has(NegativeInfinity)
[t[0] if not test_inf(t[0]) else t[1] for t in [s.args[:2] for s in sols]]
# [y4/50,
#  u1 - x1/50 + y4/50,
#  y4/50,
#  u1 - x1/50 + y4/50,
#  u2,
#  u1 + u2 - 1,
#  0,
#  u1,
#  -7*u2/13 + y4/65 + y5/65]

Comment: I have solved it differently, but your answer is much more flexible. Thanks!

How do I solve inequalities with Sympy?


what is the best approach for factor analysis when the data has more attributes than inputs?

Question: i think i should ask the question like this:
i am having a data set of 20 participants with 89 attributes , almost all of the attributes have values between 5 to 0 and there exist more than 20 attributes that they are only (0 or 1 ).
i want to perform a factor analysis on this data and calculate the weights for prediction job.
i am having two big problem here:
first most of the functions that i am using will give me errors while performing ( ex : matrix is not positive definite; something has done , or ex 2: the objective function is not defined ,....). but they still give me the results, but i am not sure if i can trust these results or not ?
second problem is in finding the number of factors:
i am trying some visual methods and some analytical methods to extract the number of necessary factors. For example when i use fa.parallel it first gives me the error that matrix is not positive definite, something has done. then suggest me to use 4 factors or 4 components.  but the problem is that when i use only 4 factors it covers only up to 41 % of the total variance.
when i use prcomp() function to see how much load is on the components i can see 19 components are covering the whole variance.
and when i use some visual methods i can see they are suggesting me between 5 to 18( base on eigen values greater than the mean) or base on parallel analysis.
that is why i am not sure that what should i do for choosing the factors or which method i can use that wont give me error while performing.
i hope some one can help me or advise me with this issue
Comment: Your question contains several separate questions: 1) FA and sample size, 2) FA and data type; 3) FA and number of factors. Each of these were asked and answered not once on this site. Please make a search. If you then still have what to ask - please do it, but be maximally specific.
Comment: For 0,1 columns, you could try multiple correspondence analysis: http://factominer.free.fr/classical-methods/multiple-correspondence-analysis.html
Answer: FA or PCA is commonly done on the variable-by-variable ($p \times p$) covariance $\mathbf{C}$ or correlation matrix $\mathbf{R}$.  In your case, since the $p$ variables exceeds the $n$ records ($p>>n$), then by definition, there will be $p-n$ zero eigenvalues of $\mathbf{R}$.   In this case, the use of singular value decomposition (SVD) of your $\mathbf{R}$ will overcome your problems.  As a totally relevant aside, a problem with FA is that there is an infinite number of solutions, whereas for PCA there is not.


Ruby on Rails Routing

Question: Estou tendo problemas para setar a pagina home como root na minha aplicação.
no arquivo config/routes.rb já fiz vários tentativas como:
root :to => 'static_pages#home'

e
root   'static_pages#home'

Mas nenhuma funciona, estou trabalhando com ela dessa forma:
get 'home' => 'static_pages#home'

Qual sintaxe é a correta para por como root?
Comment: Você conseguiu solucionar o problema?
Answer:
Conforme a documentação Ruby on Rails para criar uma rota para o root basta fazer igual ao seu segundo exemplo.
Pode ser root to: 'static_pages#home' ou root 'static_pages#home'.
Lembrando que neste exemplo static_pages seria seu controller e home sua action.
Obs: Para versões antigas do Ruby on Rails é recomendado apagar o seu arquivo "/public/index.html".

Ruby on Rails Routing


IOS Push notification for messaging app

Question: I am working with a messaging app and the app needs to receive the notification from the server (chat message). I am facing the problem when receiving the silent notification, most of the notification can't received by the device, the scenario as below:

iOS 10 – Bring the app into background and push the silent notification, all notification can receive by the device.
iOS 11 – Bring the app into background and push the silent notification, device only can receive first 10 notifications and the rest of the notification disappear, I try to reboot the device and put the app into the background, able to receive another few notification and after that all not receive again.
Both iOS 10 and 11 – Kill the app and push the silent notification, all the notifications not receive.
<code>func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
    logging(cls: self, mod: "APP", msg: "Did receive remote notification")
}
</code>

I try the Whatsapp push notification, even I kill the app and turn off the background app refresh in setting, all the notification still come in, I'm curious how Whatsapp handle the push notification?
How do I solve this notification issue?
Comment: Hey did you able to solve this? Any heads-up?
Answer: Ideally you should use XMPP server base for live chat.
XMPP server has RTC ( Real time communication ) protocol, where 2 or more parties can connect, exchange document, live chat, video call, audio call etc.
You can also integrate websocket, for knowing user is online / office and other activities.
Integrating apple push, is not a 100% solution for live chat app like whatsapp, facebook messager, skype etc.
Get more information about Pushkit
Answer: From iOS 8, Apple introduced a new kind of push notification service called VoIP push. VoIP push is provided by the Apple's PushKit framework.
Normal push notification service has the following drawbacks,

Delivery: Apple doesn't promise a delivery time or priority.
Need permission to send push: Not all users understand that they need to allow it to receive calls.
The app doesn't know about a push until the user decides to act on the push.
Apple might throttle your push messages if you send too many.

Now coming to PushKit framework,
The benefits of PushKit framework are,

You don't need to allow push; it works without the user knowing about it.
Apple promises to deliver these push notifications high priority.
Your push notifications won't get lost.
You have total control over push notifications.

So, for messaging apps like yours, the usage of PushKit framework is recommended. Here is a tutorial on Github which explains how to implement PushKit in your apps.
Comment: Can we use the voip pushkit without voice support in the app?
Comment: Many apps are using VoIP push without VoIP calling. So give it a try :)
Comment: Update- Looks like Apple is not approving apps with PushKit support without VoIP calls.

IOS Push notification for messaging app


Time limit exceeded in bubble sort

Question: Problem-To sort array in ascending order
Algorithm used-Bubble sort
Error-Time limit exceeded
Compiler-ideone online editor /Codeblocks
What could be the possible alternative for this?
int a[5];
int i,t,j;
for(i=0;i<=4;i++)  //for initialising the elements
 {
 printf("Enter 5 numbers");
 scanf("%d",&a[i]);
 }

for(j=0;j<5;i++)  //for sorting
{

  for(i=0;i<5;i++)
  {
  if(a[i]>a[i+1])
    {
  t=a[i+1];
  a[i+1]=a[i];
  a[i]=t;
    }
  }
 }
for(i=0;i<=4;i++)  //for printing the sorted array
{

   printf("%d\n",a[i]);
}

Answer:
Your loop:
for(j=0;j<5;i++)  //for sorting

should say j++, so it should be
    for(j=0;j<5;j++)

Your second loop:
for(i=0;i<5;i++)

should be
    for(i=0;i<4;i++)

Time limit exceeded in bubble sort


HIPAA compliance in Microsoft computer vision?

Question: is computer vision already HIPAA compliant? Or, if it is not, will it be coming soon?
Edit: to further clarify: Microsoft categorizes its cloud services into categories. See here more information: https://www.microsoft.com/en-us/TrustCenter/Compliance/HIPAA
I am asking if Computer Vision/Cognitive Services will be added into the in scope list.
Thanks!
Comment: @RobertColumbia, That is correct. After talking with Microsoft Support, I was told that the engineers monitor this tag, and will answer my question over here.
Comment: @RobertColumbia, I have clarified my question. It is aimed at the MS engineers, I was directed by support over here. Thanks.
Comment: unfortunately, we are not Microsoft support. Your question would be better asked to Microsoft or to a support site for Microsoft products.
Answer: Microsoft Cognitive service Vision APIs are not currently HIPAA compliant. You can stay up to date with updates and announcements via Cognitive Services Blog


How to add class member to vector and use it correctly?

Question: Suppose I have this class
class Employee {
string name;
vector<Employee> subEmployee;

Employee(string name, vector<Employee> subEmployee) {
    this -> name = name;
    this -> subEmployee = subEmployee;
}
vector<Employee> getSubEmployee() {
    return this -> subEmployee;
}};

and I create several objects and connect them,
Employee yunfei("yunfei",{});
Employee yuqi("yuqi",{});
Employee yuwei("yuwei",{});
Employee aona("aona",{});
Employee shang("shang",{});
yuqi.addNewEmployee(yuwei);
yuqi.addNewEmployee(aona);
yunfei.addSubEmployee(yuqi);

Then I want to check how many subemployee yunfei has, so I use:
yunfei.getSubEmployee();

The result shows vector contains yuqi,
however, when I try to use:
yunfei.getSubEmployee()[0].getSubEmployee();

I just get an empty list, but when I use:
yuqi.getSubEmployee();

I get the correct answer, so I want to know why that happened.
Comment: `std::vector::push_back` (which I'm assuming `addNewEmployee` uses internally) creates a copy of the object in the vector. You want the vector to store pointers to the actual employees instead.
Comment: You're passing and returning everything by value, so when you add elements to `yuqi` it has no effect on the vector inside `yunfei`.
Comment: You're calling functions that do not exist, mate.
Comment: Also I notice you're passing/returning everything by value. In addition to performance issues this will probably lead to problems down the road. Do some research on passing/returning objects by reference and const reference.
Comment: `vector` is not permitted by Standard C++ there. Even if your compiler appears to support it, it might have odd behaviour.  The template type for `vector` must be complete. A class cannot contain a vector of itself.
Answer: Like most people have mentioned, you want to make use of references to ensure you are always referencing the same employee.
class Employee
{
    using EmployeeList = std::vector<std::shared_ptr<Employee>>;
    std::string mName;
    EmployeeList mSubEmployees;

public:
    Employee(const std::string& name, const EmployeeList& subEmployees = {})
        : mName(name), mSubEmployees(subEmployees)
    {}

    const EmployeeList& GetSubEmployees() const { return mSubEmployees; }
    const std::string& GetName() const { return mName; }
    void AddSubEmployee(const std::shared_ptr<Employee>& employee) { mSubEmployees.push_back(employee); }
}

// I can make these employees first.
auto yuwei = std::make_shared<Employee>("yuwei");
auto aona = std::make_shared<Employee>("aona");
auto shang = std::make_shared<Employee>("shang");

// I can construct these employees using existing employees
auto yuqi = std::make_shared<Employee>("yuqi", { yuwei, aona });
auto yunfei = std::make_shared<Employee>("yunfei",{ yuqi });

// I can add new subs now
yunfei.addSubEmployee(shang);

// Even brand new employees
yunfei.addSubEmployee(new Employee("Aesthete");

These employees only exist int the context where you declared them. All other employees now only hold reference to the others. You could now iterate the employee tree using recursion.
void PrintEmployeeTree(const Employee& e, int level = 1)
{
    for (const auto& employee : e->getSubEmployees)
    {
        std::cout << std::string(level, '-') << employee->GetName() << std::endl;
        PrintEmployeeTree(employee, level+1);
    }
}

PrintEmployeeTree(yunfei);

Should give you something like this:
-yunfei
--yuwei
---yuki
---aona
--shang
--Aesthete

Try to use references wherever makes sense. Same goes for const. Notice how even the employee name is return by reference. Look at where all the references I have made are, and how many copies they have avoided. This will ensure you're always working with the same set of data.
Comment: This isn't a very good design; for example if someone writes `{ Employee e("e",{});  list.AddSubEmployee(e); }`, or `list.AddSubEmployee(Employee("e",{}));` then the list will contain a dangling reference.   It'd be better to use shared_ptr here.
Comment: Not sure what you mean about "match your example" as the original example did not have the possibility of dangling references
Comment: The example was intended to show the use of references primarily, but sure, I've changed it to use ptrs.


Given a compact set, how to find a relative compact and connected neighborhood.

Question: Let $X$ be a non-compact connected manifold and $K\subset X$ be a compact set.
Question: How do I find a connected open set $U\subset X$ such that
$$K\subset U\subset\overline{U}\subset X$$ and $\overline{U}$ is compact?
It is trivial if the connectedness for $U$ is removed. So, is there a way to modify the usual argument to put the connectedness on $U$?
Answer: First suppose that $K$ is path-connected. Since $X$ is locally compact and locally path-connected, we can choose, for each $x\in K$, a path-connected neighbourhood $U_x$ of $x$ with $\overline{U_x}$ compact. Since $K$ is compact, we can go to a subcover $U_1,\ldots,U_n$. It is straightforward to show that $\bigcup_{i=1}^n U_n$ is a (path-)connected neighbourhood of $K$ with compact closure.
Now assume $K$ arbitrary. Since $X$ is connected and locally path-connected, it is (globally) path-connected.
Fix a point $k\in K$. For each $x\in K$, choose a path $P_x$ from $x$ to $k$. Apply the previous case to each $P_x$, i.e., find (path-)connected neighbourhoods $U_x$ of $P_x$ with compact closure and pass to a subcover $U_1,\ldots,U_n$.
Then $U=\bigcup_{i=1}^n U_i$ is a neighbourhood of $x$ with compact closure. Moreover, $\bigcap_{i=1}^n U_i$ is nonempty (it contains $k$), so $U$ is also (path-)connected.
Comment: This is too complicated, just use open ball neighborhoods of points in K.
Comment: @studiosus Yeah, I know it also works like that, but in this case (at least in the way I am thinking) we need a more general form of the statement in the fourth paragraph, for which I couldn't easily find a reference, and there are a few arguments by contradiction which are avoided in this solution.


How to iterate through array and pass each element as parameter to a constructor in php

Question: I want to loop through an array and get each element to pass as parameters to a constructor.
here is my example
[user_by_province] => Array
    (
        [label] => Array
            (
                [0] => a
                [1] => b
                [2] => c
                [3] => d
                [4] => e
                [5] => f
            )

        [count] => Array
            (
                [0] => 2
                [1] => 1
                [2] => 1
                [3] => 1
                [4] => 7
                [5] => 1
            )

    )

Here is the constructor:
$pc = new C_PhpChartX(array(array('a','2'),
                            array('b','1'),
                            array('c','1'),
                            array('d','1'),
                            array('e','7'),
                            array('f','1')));

so how can i do that with php thanks for any help, may we can do that with array_map or no? thanks for any help
Answer: As you suggested array_map with multiple arguments could be a good solution.
<?php

$userByProvince = array(
    'label' => array('a', 'b', 'c', 'd', 'e', 'f'),
    'count' => array('1', '2', '3', '4', '5', '6'),
);

function combine($arg1, $arg2)
{
    return array($arg1, $arg2);
}

$arguments = array_map('combine', $userByProvince['label'], $userByProvince['count']);

$pc = new C_PhpChartX($arguments);

If you are using PHP 5.3 you can even substitute the function with a lambda expression to make the code more compact (see docs).
Answer: It's easier to use array_combine.
Answer: you can do something like this:
$my_array=array("user_by_province"=>array("label"=>array('a','b','c','d','e','f'),"count"=>array(2,1,1,1,7,1)));
   $new_array=array();
   for($i=0;$i< count($my_array['user_by_province']['label']);$i++){
       $new_values=array();
       array_push($new_values,$my_array['user_by_province']['label'][$i],$my_array['user_by_province']['count'][$i]);
       array_push($new_array,$new_values);
   }

Answer: supposed your given array is ordered and has the same amount of data, i.e. pairs:
loop over your data:
$input = array("user_by_province"
         => array("label" => array('a', 'b', 'c'),
                  "count" => array(1, 2, 3)));

$combined = array();

for($i = 0; $i < count($input['user_by_province']['label'] && $i < count($input['user_by_province']['count']; $i++)
{
    $combined[] = array($input['user_by_province']['label'][$i], $input['user_by_province']['count'][$i]);
}

$pc = new C_PhpChartX($combined);


Convergence of a bounded continuous function whose derivative vanishes at infinity

Question: Let $x(t):[0,\infty) \to \mathbb{R}$ be a differentiable function.
Suppose $|x'(t)| \le Ce^{-t}$ (which implies that $\sup_t |x(t)| < \infty$).

Can we claim that $\lim_{t\to \infty} x(t) = x^*$ for some $x^*$?

I think this is true, however, I cannot rigorously prove or disprove it.
Any answers/comments/suggestions will be very appreciated.
Answer: Hint: Using Mean Value Theorem,  show $x(n)$ is a Cauchy sequence...
Comment: Further hint: $|x(n+1) - x(n)| \le C e^{-n}$.
Comment: But if $|x(n+1) - x(n)| \le C e^{-n}$, $|x(m) - x(n)| \le C (e^{-n} + e^{-n-1} + \ldots)$.
Comment: Thank you for the hint! Actually, I was able to show that (from the uniform boundedness) there exists a sequence that converges to some point $x^*$, i.e., $\lim_{k \to \infty} x(t_k) = x^*$. But this only shows one discrete path and wasn't clear to see how to proceed next.
Comment: It seems that for large $t$ since the derivative is very small so that $x(t)$ cannot change too much. Thus, I think I can use this fact to show a contradiction assuming $\lim_{t\to \infty} x(t) \ne x^*$. Am I on the right track?
Comment: I thought I got it, but it seems it isn't. I tried to show the sequence $\{x(n)\}$ is Cauchy using your hint. But, it seems that for $m > n$, we have $|x(m) - x(n)| \le C|m-n|e^{-n}$. Thus, it is unclear to see whether this sequence is Cauchy. Since $m$ could grow fast enough so that the RHS may not be small...
Comment: Now I got it. Thank you so so much for your help. I really appreciate it!
Answer: I'm going to use Cantor's Intersection Theorem:

Suppose $(A_n)_{n \in \Bbb{N}}$ is a sequence of closed subsets of $\Bbb{R}$ (or indeed, any complete metric space) such that $A_{n+1} \subseteq A_n$, and
  $$\operatorname{diam} A_n := \sup_{x, y \in A_n} |x - y| \to 0$$
  as $n \to \infty$. Then,
  $$\left|\bigcap_{n \in \Bbb{N}} A_n\right| = 1.$$

Let $A_n = \overline{x[n, \infty)}$. Then clearly $A_n$ is closed, and $A_{n+1} \subseteq A_n$ (this is true for any real function). We can use the bound on the derivative to show that $\operatorname{diam} A_n \to 0$.
Suppose $t \in (n, \infty)$. Then,
\begin{align*}
x(t) - x(n) &= \int_n^t x'(s) \, \mathrm{d}s \\
&\le \int_n^t |x'(s)| \, \mathrm{d}s \\
&\le \int_n^t Ce^{-s} \, \mathrm{d}s \\
&= C(e^{-n} - e^{-t}) \\
&\le Ce^{-n} \to 0.
\end{align*}
This shows us that elements of $x[n, \infty)$ can be no more than $Ce^{-n}$ apart, which is also true of the closure $A_n$. Hence, by the Cantor Intersection Theorem, there exists a unique $x^* \in \Bbb{R}$ such that
$$x^* \in \bigcap_{n \in \Bbb{N}} A_n.$$
I claim that this is the limit we need. For all $\varepsilon > 0$, there exists some $N \in \Bbb{N}$ such that $n \ge N \implies |Ce^{-n}| < \varepsilon$, hence
$$t \ge N \implies x(t), x^* \in A_N \implies |x(t) - x^*| \le |Ce^{-N}| < \varepsilon.$$
Comment: You need more than just differentiability to say $x(t) - x(n) = \int_n^t x'(s)\; ds$.


leaflet CSS import issue using VueJs2 and webpack

Question: I'm trying to make a single file component using vuejs2 to display a Leaflet map.
Although my map component is mounted correctly I'm struggling with leaflet css import. The tiles of the map appear all messy and I'm guessing that no style is applied on map block:Unordered tiles. Neither webpack nor the browser console are displaying error.
Any clue to load style sheets the proper way?
sources are available at github repo
Answer: There are at least two issues:

In webpack.config.js, you have options: {modules: true} enabled for CSS files. This causes webpack to pre-process your leaflet.css file and mangle all selector names. Change modules option to false
Your map container needs to have an explicit size. For instance in the


Awaiting Task Completion in SwiftUI View

Question: I am working with a view that displays a list of locations. When a user taps on a location, a didSet block containing a Task is triggered in a separate class wrapped with the @ObservedObject property:
struct LocationSearch: View {
    @StateObject var locationService = LocationService()
    @ObservedObject var networking: Networking
    var savedLocations = SavedLocations()

    var body: some View {
        ForEach(locationService.searchResults, id: \.self) { location in
            Button(location.title) {
                getCoordinate(addressString: location.title) { coordinates, error in
                    if error == nil {
                        networking.lastLocation = CLLocation(latitude: coordinates.latitude, longitude: coordinates.longitude)
                        // wait for networking.locationString to update
                        // this smells wrong
                        // how to better await Task completion in didSet?
                        DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
                            savedLocations.all.append(networking.locationString!.locality!)
                            UserDefaults.standard.set(savedLocations.all, forKey: "savedLocations")
                            dismiss()
                        }
                    }
                }
            }
        }
    }
}

The Task that gets triggered after networking.lastLocation is set is as follows:
class Networking: NSObject, ObservableObject, CLLocationManagerDelegate {
    @Published public var lastLocation: CLLocation? {
        didSet {
            Task {
                getLocationString() { placemark in
                    self.locationString = placemark
                }
                getMainWeather(self.lastLocation?.coordinate.latitude ?? 0, self.lastLocation?.coordinate.longitude ?? 0)
                getAQI(self.lastLocation?.coordinate.latitude ?? 0, self.lastLocation?.coordinate.longitude ?? 0)
                locationManager.stopUpdatingLocation()
            }
        }
    }

What is a better way to ensure that the task has had time to complete and that the new string will be saved to UserDefaults versus freezing my application's UI for one second?
In case it isn't clear, if I don't wait for one second, instead of the new value of locationString being saved to UserDefaults, the former value is saved instead because the logic in the didSet block hasn't had time to complete.
Comment: You're right that it smells wrong.  Rather than relying on a `didSet` you should explicitly invoke a function to perform the operation. In that function you can use `await` or a completion handler to save the data once the network operations are complete.  User Defaults probably isn't the right way to store your data. With concurrent operations you are almost certainly going to end up with data loss.  Use something like Core Data
Comment: Convert everything to async await, right now to you have a crazy mixture of closures,  delegates, DispatchQueue and async await.
Answer: The first thing I think is odd about your code is that you have a class called "Networking" which is storing a location.  It seems that you are conflating storing location information with making network requests which is strange to me.
That aside, the way you synchronize work using Async/Await is by using a single task that can put the work in order.
I think you want to coordinate getting some information from the network and then storing that information in user defaults.  In general the task structure you are looking for is something like:
Task {
    let netData = await makeNetworkRequest(/* parameters /*)
    saveNetworkDataInUserDefaults()
}

So instead of waiting for a second, or something like that, you create a task that waits just long enough to get info back from the network then stores the data away.
To do that, you're going to need an asynchronous context in which to coordinate that work, and you don't have one in didSet.  You'll likely want to pull that functionality out into a function that can be made async.  Without a lot more detail about what your code means, however, it's difficult to give more specific advice.


Laço repetição jquery

Question: Caros, estou com um problemas e ainda não consegui encontrar uma solução, ainda sou novo em jquery, gostaria de uma pequena ajuda, por favor.
No codigo abaixo eu tenho um procedimento para chamar um dialog, o qual será carregado com uma tabela preenchida com o php. Essa tabela possui um campo input text para pesquisa e todas as linhas possuem um checkbox, para quando selecionado e o botão pressionado, o nome seja enviado para a pagina anterior. Tudo está funcionando perfeitamente, porém tenho q repetir o codigo 3 vezes, caso queira usar em 3 campos diferentes. Gostaria de saber como posso passar o id do botao clicado e a partir dele fazer um if e executar o procedimento. Deve ser algo simples, mas não consegui ainda. Obrigado

Answer: Por acaso você já chegou a testar o seletor jQuery por classe? Você pode definir nomes específicos das classes que deseja que tenha as funções atreladas e utilizá-las como seletor, veja:

Talvez esta não seja a solução, mas pode te encaminhar para ela.
Comment: Obrigado pela resposta, está funcionando corretamente agora.
Answer:
Gostaria de saber como posso passar o id do botao clicado e a partir
  dele fazer um if e executar o procedimento.

Utilize uma classe nos seus botões. Exemplo: classe 'botoes'. Você só vai precisar chamá-lo uma vez e vai passar o id dele para a função (uma função apenas).

Comment: A questão do if eu não entendi muito bem. Pode tentar ser mais claro pra eu implementar a resposta?
Comment: Obrigado pela resposta,esta funcionando corretamente.
Comment: Só mais uma duvida, eu consigo fazer isso para os dialogs também?
Comment: Opa, ja consegui, obrigado

Laço repetição jquery


Non- simplicity of $\text{Bir}(\mathbb{P}_\mathbb{R}^2)$.

Question: It was proven by Serge Cantat and Stéphane Lamy that the Cremona group $\text{Bir}(\mathbb{P}_\mathbb{C}^2)$ is not simple. It is later proven separately that the real Cremona group $\text{Bir}(\mathbb{P}_\mathbb{R}^2)$ is also not simple, albeit using slightly different techniques. However in their paper: https://perso.univ-rennes1.fr/serge.cantat/Articles/nsgc-acta-c.pdf the authors said that their result 'directly implied' that  $\text{Bir}(\mathbb{P}_\mathbb{R}^2)$ is not simple as well. How can we infer the non-simplicity of  $\text{Bir}(\mathbb{P}_\mathbb{R}^2)$ just from the fact that  $\text{Bir}(\mathbb{P}_\mathbb{C}^2)$ is not simple?
I am thinking of choosing a proper normal subgroup, say $N$, of $\text{Bir}(\mathbb{P}_\mathbb{C}^2)$ and intersecting it with $\text{Bir}(\mathbb{P}_\mathbb{R}^2)$. But there is no guarantee that $\text{Bir}(\mathbb{P}_\mathbb{N}^2)\cap N$ is non-trivial. How do I justify that $\text{Bir}(\mathbb{P}_\mathbb{N}^2)\cap N$ is nontrivial?
Comment: You cannot see this directly; instead, you have to read their proof to conclude that their normal subgroup can be chosen to have proper intersection with the real Cremona group.
Comment: Do you know how to choose such a normal subgroup? This is because the normal subgroup they choose is on  some surface $X$ birational to the projective plane, not directly on the projective plane itself.
Answer: This is to convert my comment into a proper answer.
In the main result of the linked paper, Theorem A, they prove that there exists an integer $k$ such that if $g\in G=Bir({\mathbb C}P^2)$ is a "general element" of degree $d\ge 2$ then for any $n\ge k$, the normal closure in $G$ of the cyclic subgroup $\langle g^n\rangle$ is a proper subgroup of $G$. Moreover, this subgroup does not contain any element $f\in G-\{1\}$ whose degree is $<nd$.
Here an element of an (irreducible) algebraic variety $V$ (in this case, the variety is $V_d$ consisting of degree $d$ rational maps of ${\mathbb C}P^2$ ) is general if it belongs to the complement of a countable union of proper Zariski closed subsets of $V$. Hence, a more careful statement of their Theorem A is that for each $d\ge 2$ there exists a countable union $Z$ of (Zariski) closed proper subsets $Z_i\subset V_d$  such that for every element $g\in G- Z$ the normal closure of  $\langle g^n\rangle$ does not contain any  $f\in G-\{1\}$ whose degree is $<nd$.
Now, since the set $V_d({\mathbb R})$ of real points of $V_d$  is Zariski dense in $V_d$, it follows that every intersection $Z_i\cap V_d({\mathbb R})$ has empty interior, hence, $Z\cap  V_d({\mathbb R})$  is meagre (in the classical topology!), hence, by Baire theorem, its complement in $V_d({\mathbb R})$ is nonempty. Now, take any $g$ in this complement. Since the normal closure of $\langle g^n\rangle$ in $G$ does not contain any real birational transformation $f\ne 1$ whose degree is $<nd$, it follows that the normal closure of $\langle g^n\rangle$ in the real Cremona group $Bir({\mathbb R}P^2)$ is a proper normal subgroup. Hence, $Bir({\mathbb R}P^2)$ is not simple.
Comment: @thedilated: I just noticed that you asked the same question at MO: You should not do this. The standard protocol is to ask at one site, wait a bit (say, a week) and if you do not get a satisfactory answer, then ask at the other. This avoids duplication of efforts.
Comment: Thank you very much for the answer. Just to clarify something: we have that $Z_i\cap V_d$ has empty interior w.r.t. the Zariski topology. How can we conclude that $Z\cap V_d$ is meagre in the classical topology?
Comment: @thedilated: I am using the classical topology for this part of the argument: The intersection $Z_i\cap V_d({\mathbb R})$ has empty classical interior (if not, then the intersection would be Zariski dense over ${\mathbb R}$ and, hence, $Z_i$ would be Zariski dense over ${\mathbb C}$).
Comment: Sorry for that. Noted. Just to clarify one more thing. How is Baire's category used here? To use it we require that $V_d(\mathbb{R})$ is closed in the classical topology. How does one justify this?
Comment: @thedilated All you need to know is that this space is completely metrizable which holds since it is an open subset of a Euclidean space.


Zero-inflated model predicting only a small range of values. I need help

Question: I built a ZI model and it is producing predicted values that are from a very small range when compared to the observed values. Plus it does not produce any zeros. See the fitted vs. observed graph below.

My model structure is given below. My response is a count variable and the predictor is continuous water level measurements (scaled).
m.u.meanwl.gu <- zeroinfl(GU ~ MeanWLScaled | MeanWLScaled, data = uluabat_wl_fg, dist = "negbin", link = "logit")

I need help to figure out what's wrong and fix it. Thanks in advance.
Comment: What are your input variables?  It looks like the non-zero part of the fit doesn't "have much to go on".  What makes you think that zero-inflated captures the behavior of your system well?
Answer: If you call predict.zeroinfl() without any parameters, it uses the default setting for the type parameter, which is type="response". You will then get a prediction for the mean, or the expected response. This expectation will typically vary much less than your actual observations, will not be integer, and will be larger than zero.
To obtain a probabilistic prediction of the probabilities to observe specific actual count observations, use type="prob". An example:
> library(pscl)
> fm_zip <- zeroinfl(art ~ ., data = bioChemists)
> head(predict(fm_zip))
       1        2        3        4        5        6
2.037956 1.323124 1.308704 1.439982 2.363233 0.854771
> head(predict(fm_zip,type="prob"))
          0         1         2          3          4           5           6
1 0.2162690 0.1937560 0.2279639 0.17880748 0.10518810 0.049503684 0.019414543
2 0.3626973 0.2429423 0.2058847 0.11631983 0.04928840 0.016708046 0.004719819
3 0.3655549 0.2445794 0.2051107 0.11467420 0.04808441 0.016129943 0.004508999
4 0.3582308 0.2127514 0.2034182 0.12966290 0.06198734 0.023707199 0.007555727
5 0.1071273 0.2125181 0.2559524 0.20550920 0.12375553 0.059619449 0.023934814
6 0.5218005 0.2328010 0.1513963 0.06563783 0.02134296 0.005551943 0.001203522
            7            8            9           10           11           12
1 0.006526345 0.0019196452 5.019025e-04 1.181028e-04 2.526437e-05 4.954139e-06
2 0.001142821 0.0002421248 4.559820e-05 7.728561e-06 1.190849e-06 1.682002e-07
3 0.001080390 0.0002265110 4.221291e-05 7.080172e-06 1.079567e-06 1.508923e-07
4 0.002064075 0.0004933813 1.048304e-04 2.004632e-05 3.484891e-06 5.553353e-07
5 0.008236171 0.0024798688 6.637118e-04 1.598722e-04 3.500850e-05 7.027254e-06
6 0.000223623 0.0000363569 5.254177e-06 6.833844e-07 8.080398e-08 8.758139e-09
            13           14           15           16           17           18
1 8.967384e-07 1.507227e-07 2.364440e-08 3.477356e-09 4.813281e-10 6.292303e-11
2 2.192977e-08 2.654955e-09 2.999969e-10 3.177955e-11 3.168471e-12 2.983515e-13
3 1.946804e-08 2.332345e-09 2.607955e-10 2.733875e-11 2.697294e-12 2.513358e-13
4 8.168817e-08 1.115779e-08 1.422441e-09 1.700050e-10 1.912317e-11 2.031584e-12
5 1.302074e-06 2.240273e-07 3.597518e-08 5.415971e-09 7.673982e-10 1.026932e-10
6 8.762517e-10 8.140690e-11 7.058791e-12 5.738134e-13 4.390178e-14 3.172269e-15
            19
1 7.792861e-12
2 2.661494e-14
3 2.218703e-14
4 2.044694e-13
5 1.301911e-11
6 2.171585e-16
>

Look at ?predict.zeroinfl for more information.
Comment: Thank you for your reply, Sir. I understood what you said. However, this function is no longer available in the most recent form of `"pscl"`package. So I simply used the generic `predict()` function with `type ="prob"` command. It gave me a huge object with tons of numbers in it. It basically has probabilities for each possible value I guess. All I want to do is to use a basic predicted vs observed graph to see how well my model is performing and I still can't do it. Is there a way to get this plot by the method you said for either `zeroinfl` or `glmmTMB` objects.
Comment: `predict.zeroinfl()` is available in [`pscl` 1.5.2](https://cran.r-project.org/web/packages/pscl/index.html), see p. 60 in [the reference manual](https://cran.r-project.org/web/packages/pscl/pscl.pdf). ...
Comment: ... About getting a predicted vs. observed graph: there are different ways of predicting. What you had originally was a plot of predicted expectations. Which does not give an indication of variability. You could extract predicted probabilities, then calculate lower and upper quantiles and plot those. Then you could check whether, e.g., 80% of observations are between the 10% and the 90% quantile prediction.


$2$-variable integer program with equality constraint

Question: I have an integer program with variables $x, y \in \{0,1,\dots,m\}$. Somehow, I can prove that

the cost function will strictly decrease with both $x$ and $y$.
an optimal solution should satisfy $x+y=k$.

Do I still need to do linear search over $x \in \{0,1,\dots,k\}$? Or are there other simpler solutions?
ADD: I am wondering if I can substitute $y$ with $k-x$ so that the original problem is reduced to integer programming with just one variable $x$. Let's say the cost function becomes $f(x)$. And by computation, $f(x)$ will be minimized at $x^*$. Can I just search around $x^*$ and get the optimal solution?
Comment: How can you search "around $x^*$" when $x^*$ is unknown and is the solution ?
Comment: I am thinking the cost function is reduced to a one-dimensional function $f(x)$. So I can minimize $f(x)$ first to get $x^*$ (and $k-x^*$). Then I ASSUME that the optimal solution is around $(x^*,k-x^*)$. So I can just search around $(x^*,k-x^*)$. But I am not sure if the assumption is right or not.
Comment: Don't you realize that the optimal solution *is* $(x^*,k-x^*)$ ? So your proposal amounts to: 1) find the optimal solution, then 2) search in the vicinity of the optimal solution.
Comment: That's exactly my question. Can we guarantee that the optimal integer solution is in the vicinity of $(x^*,k-x^*)$?
Comment: In the end I understood what you mean. In your mind, $x^*$ is not integer and you find it with an "ordinary" solver (assuming that by some magic you can solve for the continuous case). Then this is a bad idea because the integer solution may very well be far from the continuous solution.
Comment: Thanks for your illustration. I understand that point. But I am still considering a special case. That is, we can prove that, in the continuous case, $f(x)$ will strictly decrease as $x$ increases.  We can then get the continuous optimal result $(x^*, k-x^*)$. Then can we say that the optimal integer solution is in the vicinity of $(x^*, k-x^*)$? The plot in your illustration does not apply to this special case.
Comment: You never said that $f(x)$ is decreasing (or you wrongly think that $f(x)$ is decreasing). And if it is, the optimal integer solution is perforce the last value. Stop the nonsense.
Answer: It is of course better to eliminate one of the unknowns to get a one-dimensional problem.
Anyway, when doing so, $c(x, k-x)$ loses the montonicity property and it is not even sure that it is unimodal. So exhaustive search is safer.

Update:
The integer minimum might not coincide with the continuous minimum. For the sake of illustration:
Comment: so, as described in the problem, the optimal solution is not guaranteed to be near $(x^*,k-x^*)$?
Answer: Unless you have more information about the cost function such as a discrete differential equation there is no simpler way.
I am assuming $m\geq k$ and that you are looking for the optimal solution and not a pseudo-optimal solution.
Comment: The first order discrete differential equation (regarding both $x$ and $y$) is strictly less than 0. So I am claiming that the cost function will decrease with both $x$ and $y$.
Comment: Yes, but it seems that you have no been given any information on the relation between the discrete partial derivatives of x and y. So without that I don't see any other option.
Comment: Response to the edit in your question: To find $x^*$ you would have to be given $f(x)$ or  $\frac{df(x)}{dx}$, making the solution trivial so I'm assuming you were not given these.


Handle multiple accounts and users in one CakePHP app with URL domain.com/account/controller/action

Question: What I need to accomplish is a single Application with a single database but multiple accounts (companies), each with multiple users.
The URL convention must be as follows: domain.com/account/controller/action
So ALL controllers are prefixed by the company/account name.
All accounts would share the single database, but each one would need to be able to restrict access to their data.
The question is, how do I implement this? I've thought about implementing some sort of htaccess rewrite where I strip out the first URL parameter (account) and pass as a query string parameter, which would be internally parsed by the app_controller. The challenge, however, is maintaining integrity with all of the links throughout the app. I.e. the cake routing would somehow need to be aware of the account parameter and pass it to all outputted links.
Has anyone accomplished something similar to this before?
Answer: It's perfectly possible to do this (but I've never done it).
I assume you use the standard CakePHP authentication scheme. If so, information about the currently logged in user can be found in the Auth->User array.
Cake expects you to have a users table in your database. You should alter your models to have a belongsTo relationship with the user table (i.e. all tables have a user_id field).
In your models you could probably utilize the afterFind() hook to check that the user_id field  matches the currently logged in user and return false if thats not the case. In your controller you should then check all model operations for falseness.
The .htaccess idea is probably not very good. You should put the authorization as close as possible to the data source, in cake that would be in your model (you could put the afterFind callback in the AppModel class).
Extending your example:
User requests /someController/someAction.
someAction:

if($this->someModel->someOperation(someArgument)) {

   //OK, show view

} else {

   // Something went wrong
   // Your afterFind method provides a clue via the model->failure attribute

   $this->flash($this->someModel->failure);

}

Answer: You can do two things, both with Routes.
First, setting a variable in the routes:
Router::connect('/:user/blog/*', array('controller' => 'blogs', 'action' => 'index'));

And now you can access the user variable with $this->params['user']. The thing with this is that you will have to manually set each controller and action you want to manage. I think it's no big deal, since most of the times it is better to rewrite the default routes architecture for CakePHP.
Second, you can tell you are waiting for a variable and will be accessible as a parameter in your function.
Router::connect('/(.*)/*', array('controller' => 'blogs', 'action' => 'index'));

In your controller:
function index($a, $b){
    pr($a);
    pr($b);
}

And now you will be getting both vars.
I don't know if it can be made automatically, perhaps rewriting the htaccess could be a good idea.
Hope it helped.


elementary embeddings $j$ in set theory with $V$ and $M$

Question: I'm confused by a variety of elementary non-trivial elementary embedings $j$ we might have.
There are 9 "syntactical" possiblities;Here $M$ is a transitive model. I'll name them with a wish that someone would tell me which are impossible, which are not useful and which are strong cardinals-like: $$j_1:L\to L,$$
$$j_2:L\to M,$$ $$j_3:L\to V,$$ $$j_4:M\to L,$$ $$j_5:M\to M,$$ $$j_6:M\to V,$$ $$j_7:V\to L,$$ $$j_8:V\to M,$$ $$j_9:V\to V.$$  What I know: $j_9$ is impossible by Kunen's barrier.$j_1$ implies $M\neq L$,$j_5$ implies $M\neq V$. $j_6$ and $j_8$ are a puzzle for me.
Answer: For simplicity I work throughout in an appropriate class theory, say $\mathsf{NBG}$ or $\mathsf{MK}$. Also, I'll blackbox the fact that "There is a nonprincipal countably closed ultrafilter on some uncountable cardinal" is equivalent to "There is a measurable cardinal." This is a good exercise if you haven't seen it before! Also, Hamkins/Kirmayer/Perlmutter's Generalizations of the Kunen inconsistency is a good general source on this topic.

First, note that since $\mathsf{V=L}$ is a first-order sentence, if either $A$ or $B$ is $L$ and $A$ is elementarily embeddable into $B$ then $A=B=L$. So $(1)$, $(2)$, and $(4)$ are equivalent to each other while $(3)$ and $(7)$ are outright inconsistent. Also, $(1)$ is equivalent to $(5)$ since if $j:M\rightarrow M$ is nontrivial elementary then so is $\hat{j}: L^M=L\rightarrow L^M=L$.
Next up we have $(6)$. When I originally wrote this answer I didn't know anything about this possibility, but today I ran into a very valuable source (see below). As earlier, an embedding $M\rightarrow V$ restricts to an embedding $L\rightarrow L$, so $(6)$ is at least as strong as $0^\sharp$. The obvious question (especially in light of the next section of this answer!) is the relationship between $(6)$ and a measurable cardinal. As it turns out, $(6)$ is rather weak, at least in consistency strength, unless one adds additional demands on the embedding or the source model $M$. See the beginning of Section $2$ of Vickers/Welch, On elementary embeddings from an inner model to the universe (or the rest of the paper more generally).

Now we get to the fun stuff. The existence of an embedding of type $j_8$ is exactly equivalent to a measurable cardinal - and this is indeed the motivating observation which begins the whole study of elementary embeddings of inner models, so it is worth understanding well! Here's a sketch of the argument (due to Scott):

One direction is easy: if $\mathcal{U}$ is a countably closed nonprincipal ultrafilter on an uncountable cardinal $\kappa$, then (utilizing Scott's trick to keep everything well-defined) we get an elementary embedding $\mathfrak{j}_\mathcal{U}$ from $V$ to the ultrapower $\prod V/\mathcal{U}$; by countable closure the latter is well-founded (and is easily seen to be set-like), and so it is definably-in-$V$ isomorphic to a unique inner model $M$. We usually conflate $\mathfrak{j}_\mathcal{U}$ with the induced elementary embedding of $V$ into this $M$.

The other direction is a bit trickier: an arbitrary nontrivial elementary $j:V\rightarrow M$ might not "come from" an ultrafilter! However, it still implies the existence of an ultrafilter of the above type. Specifically, let $\kappa=crit(j)$ and consider $$\mathcal{U}_j:=\{A\subseteq\kappa: \kappa\in j(A)\}.$$ Then $\mathcal{U}_j$ is nonprincipal and countably closed.

One consequence of the above argument is that the a-priori-class-referring principle "There is a nontrivial elementary embedding of $V$ into some inner model $M$" is actually expressible in set theory alone. At the same time, it's important to note that we generally lose information in the $j\mapsto\mathcal{U}_j$ construction, in the sense that $\mathfrak{j}_{\mathcal{U}_j}\not=j$ in general. Figuring out how to "approximate" elementary embeddings by set-sized blobs of data is a general theme in inner model theory; for example, look at the notion of an extender, which is a generalization of an ultrafilter which lets us faithfully capture more embeddings.
Comment: @user122424 That can't happen: remember that a nontrivial elementary embedding moves an ordinal, and ordinals are all in $L$.
Comment: Dear Noah, please how do you know this j hat is also non-trivial: $\hat{j}: L^M=L\rightarrow L^M=L$ ? What if restriction to $L^M$ gives identity ?
Comment: @user122424 I located the answer to (6), finally!


PHP's cURL suddenly failing to get an IP address, is file_get_contents a good replacement?

Question: We have a page on our site that uses cURL to get XML data from a remote domain. A few days ago it randomly started failing (perhaps 1/3 of requests fail). After debugging with our host and with the remote site's operators, we found that the curl error is 'name lookup timed out', indicating a DNS problem. Our CURLOPT_CONNECTTIMEOUT was set to 5. When I changed that to 30, it worked every time.
But this is a live page, I can't have visitors hanging for 30 seconds while waiting for a response. Plus, the increased timeout doesn't answer the question of why this started failing in the first place. The system had been in place for years prior and the 5 second timeout was always fine.
Furthermore I found that if I do a dns_get_record(), it works every time and I quickly get a valid IP address. So I modified the script to first do a dns_get_record(), then I cURL to the IP it returns, which gets around the name lookup on cURL's end. It works fine but it's silly.
So first question, does anyone have any suggestions as to how or why the cURL may be failing. Our host and the remote site's host both agree that it's a DNS server somewhere, but neither agrees on who's DNS server is responsible, because both say that their own servers are good, and our host says they can ping the remote domain without a problem.
Second question, is file_get_contents() a sufficient replacement for dns_get_record() + cURL? Or should I stick with dns_get_record() + cURL instead?
Comment: If it is deliberately set the remote server then you have no control over the failing even if you switch it to file_get_contents. Are you calling the remote server much faster than how you should be calling it normally?
Comment: @mauris No, it's just one request each time this page is hit. It's a popular page so it may be visited frequently, but each of those visits would be separate. Also note that dns_get_record() always succeeds, so maybe it works differently than cURL to get the IP address? And if so, maybe file_get_contents() works similarly?
Comment: if the server needs more time, either upgrade the remote server to make it faster, or use AJAX
Comment: @mauris yes but I think there's more to this than just the DNS server needing more time. The fails started happening suddenly, it's not like it was a gradual build implying a build in traffic that over time overloaded the server. Maybe something bad happened on the DNS server, but the question still remains - which server, and what happened to it? The other odd thing is that dns_get_record() has no problem with timing out, it returns an IP address almost instantly. It's only cURL that now needs extra time.
Comment: Maybe an easy and quick fix could be to write the dns settings of the remote domain in the hosts file of the server, this would work only if you're sure that the ip address of the remote domain will not change.
Comment: @Phenix Thanks, actually easier than that would be to just cURL to the IP address instead of the domain name. As you said that relies on the IP remaining the same, which is why we're doing the dns_get_record() first, grabbing a valid IP, and cURL to that IP instead.
Answer: Under the hood, both curl_exec and file_get_contents perform nearly identical operations; they both use libresolv to:

connect to a name server
issue a dns request
process the dns response

To further debug this, you can use curl_getinfo() to get detailed statistics about your requests; you can use this to get an idea of how long each part took using:

CURLINFO_NAMELOOKUP_TIME
CURLINFO_CONNECT_TIME
CURLINFO_PRETRANSFER_TIME
...


Solve the following diophantic equations

Question: I can't seem to find the solution to two problems in my textbook.
They ask us to solve the diophantic equations: 1)

$xy²-2y²-x-6=0$
$4x²-4xy+y²-9=0$

I tried several things but these two just don't work out in my head.
Even a step in the right direction would help.
Comment: For the second you can note that it is $(2x-y)^2 = 9$.
Comment: For the first one $y^2=\frac{x+6}{x-2}$, which means $x-2$ is a divisor of $x+6$.
Comment: 1. When does $(x-2)$ divide $(x+6)$? 2. 9 is a square.
Comment: i don't see how you have a form of ax²+bx+c=0 sure the -6 is c but but the other terms
Answer: Rewrite the first as: $x=\frac{2y^2+6}{y^2-1}=\frac{2(y^2-1)+8}{y^2-1}=2+\frac{8}{y^2-1}$.
Hence $y^2-1$ must equal $\pm1$, $\pm2$, $\pm4$ or $\pm8$. The only integer solution to this is $y^2-1=-1$ or $y^2-1=8$ giving $y=0,\pm3$ and hence $(x,y)=(-6,0),(3,-3),(3,3)$.
For the second one you can factorize it as: $(2x-y)^2=9$ and hence $2x-y=\pm3$ and hence $(x,y)=(t,\pm3+2t),\ t\in\mathbb{Z}$.
Comment: Rearrange it to $y=\pm3+2x$ then parameterize it by letting $x=t$.
Comment: I don't quite get how  you go from $2x-y = +- 3$ To the last part immediately


A list of all algebras?

Question: Reading @Qiaochu Yuan's blog the other day, I came across a new term: Poisson algebra. I had never heard of it before and wondered what other algebras are out there that I'm not aware of. Neither Wikipedia nor Google are of much help in this regard, since one can't regex google and Wikipedia has a rather paltry list of algebras.
Here are some algebras I'm familiar with:

Boolean algebra
Algebra of sets
various group algebras
Heyting algebra
Flag algebra
$\sigma$-algebras (OK, not really the same use of the word)
Exterior algebra

What are some more algebras that I'm missing out on?
Comment: What is the purpose of constructing this list?
Comment: (I mean: I can probably name 50 «algebras»... What good would it be for the OP or anyone else?)
Comment: [Term algebras](http://en.wikipedia.org/wiki/Term_algebra) in mathematical logic. Lots of special cases of associative algebras: offhand I can recall seeing Banach, Clifford, Hopf, incidence, and Lie algebras.
Comment: http://en.wikipedia.org/w/index.php?title=Special:Search&redirs=1&search=Algebra&limit=500&offset=0
Comment: Here's a [WP list of algebras](http://en.wikipedia.org/wiki/List_of_algebraic_structures).
Comment: Such a list will never be complete - *Algebra* is a highly common word and I would guess there are new constructions each year that are named "Algebras".
Comment: It is higlhly context-dependent, ancient word, it can mean anything, from subject kids learning in school to special types of set with special operations and properties. So the list is useless.
Answer: You forgot the von Neumann algebras and $C^*$-algebras, which are very important in non-commutative geometry, among other things. The basic idea is that you can understand certain topological spaces $T$ by looking at their (commutative) $C^*$-algebra $C^0(T,\mathbb{C})$. Non commutative geometry is a generalization of sorts of this correspondence to non-commutative algebras.
The classification of von Neumann algebras is a difficult and recent topic (see Connes, "Noncommutative Geometry"), and it is of course completely hopeless to classify all algebras...
Comment: «see Connes, "Non commutative geometry"» is funny in the same way as «it's en Euler's œuvre somewhere».
Comment: I agree with the last one. I can invent a new algebra right now, it forms a group with the elements S, T, E, V and E, and the addition operation is binary and takes any two and gives you some other one (defined by a table), and I'll call it Steve algebra.
Comment: @MarianoSuárez-Alvarez have you seen that video of J.P. Serre, "how to write bad mathematics" ? =)
Answer: A very important class of algebras: Lie algebras. An easy example is that of $\mathbb{R}^3$ paired with the cross product. Or take any associative algebra $\mathcal{A}$ and replace the multiplication operator with the commutator: $[a,b]=ab-ba$. In some sense all Lie algebra arise in this way (see: Universal Enveloping Algebra).
Not totally unrelated are Jordan algebras. To get examples take an associative algebra and replace the multiplication operator with $1/2$ the anti-commutator: $a \circ b = \frac{1}{2}(ab+ba)$.
A non-classical collection of algebras which in some sense unifies associative commutative algebras, Lie algebra, and Jordan algebras is Vertex Algebras.
Answer: Relational Algebra and Process Algebra. Although they're both narrow in problem scope, they're pretty important for Data Management and Simulation "Management" (translating model to actual simulation).

A list of all algebras?


Cropping PhantomJS screen capture sized to content

Question: PhantomJS is doing a great job of capturing web pages into image files for me. I am using a script based on rasterize.js.
However, for certain web elements of a fixed size, I need the resulting image to match the size of the web element.
e.g. I have a page like this:

       Content goes here...

In this example, I need it to produce an image sized at 600x400.  Is thre a way to get the viewport size dynamically based on a web element in the page I am rasterizing.
I know this one is not a easy one... Ideas?
Thanks
Answer: Wow. Not that hard after all. Just set the viewport really big and use the cropRect function. What a great tool!
Mods to rasterize.js:
page.open(address, function (status) {
    if (status !== 'success') {
        console.log('Unable to load the address!');
    } else {
        var height = page.evaluate(function(){
            return document.getElementById('wrapper').offsetHeight;
        });
        var width = page.evaluate(function(){
            return document.getElementById('wrapper').offsetWidth;
        });
        console.log('Crop to: '+width+"x"+height);

        page.clipRect = { top: 0, left: 0, width: width, height: height };
        window.setTimeout(function () {
            page.render(output);
            phantom.exit();
        }, 200);
    }
});

Comment: why are you using window.settimeout to render ?
Comment: To anyone that finds their way here on a quest for the perfect PDF - clipRect is for images only right now (even though it doesn't explicitly say that in the documentation). There's a bug filed.
Comment: If the page shows content with animations etc the timeout is needed to ensure all elements are visible.


How can I prove stochastic dominance if I don't know the CDF?

Question: Is there a smart way to show that one variable stochastically dominates the other without knowledge of the CDF? Thanks so much!
Comment: What do you *do* know about these variables?
Comment: Hey @user603 yes, I can. In fact the only reason why I don't know the CDF is because the integral is really hard, i.e. it's /int etr(matrix+Id)det(matrix+Id)0F1(scalar,matrix+Id) which messes up the conventional integrals worked out in Muirhead (1982). The entire problem is otherwise well-behaved, continuous, differentiable etc. all the good stuff just the integral of the density is not tractable but I have the CF so I am trying to get around the integral.
Comment: I have the CF of the intractable part already. The other is just chi-squared against which I want to compare this. Thanks @user603
Comment: Hey @user603 For one of them I know everything like density cdf and characteristic function for the other only characteristic function and maybe density.
Comment: Can you assume finite first moment for both?
Answer: Let $X$ and $Y$ be two real random variables with distributions $F$ and $G$ respectively
Lemma 1 in [0] establishes that if $E(X)$ and $E(Y)$ both exist, then:
$$X \underset{s}{>} Y\implies E(X)\geq E(Y)$$
Furthermore, suppose that $X$ and $Y$ are non negative random variables with $F(0)=G(0)$ and that they have densities $f$ and $g$ on $(0,\infty)$ with $F(0)=G(0)$. Then, in their lemma 2, the authors show that either one of the following two conditions implies $F \underset{s}{>} G$:

The densities $g$ crosses $f$ only once and from above,
$f[F^{-1}(t)]\leq g[G^{-1}(t)],\;\forall t\in (F(0),1)$.

[0] S. W. Dharmadhikari and K. Joag-dev (1983). Mean, Median, Mode III. Statistica Neerlandica, Volume 37, Issue 4, pages 165–168.
Comment: Ah thanks so much! So I can use the densities indeed. That is neat. I was also wondering if you can also use the characteristic functions of sorts? There is a related question of mine here http://stats.stackexchange.com/questions/136683/characteristic-functions-can-establish-stochastic-dominance?rq=1 @user603 Again, thank you so much!
Comment: But 2 requires one to compute the inverse of the cumulative distributions and also the two conditions are sufficient but not equivalent, is that correct?