Upload files to create nodes

Question: I am trying to create an online catalog of products, that could be filtered, sorted, etc, and I followed these steps:

I have created a content type (product)
I have created a view where I can view and filter/sort these products

Now, the major problem is to manually enter hundreds of products!
I have product descriptions in Excel, and image files with links, but I don't know how to upload everything in bulk.
How could I do this?
Comment: if you have an excel sheet, then you can create its csv. Now create a php script that will iterate through every entries and create node programmatically
Comment: Welcome to DA! I've written down an answer that should be appropriate for both a "site builder" and a "developer" role. I'm not sure how well Feeds will handle images, but I wish you the best of luck and hope my answer is of use to you. :)
Answer: Maximum flexibility:
I would use the Migrate module. It has CSV support, and there's even direct spreadsheet support in the works. Migrate documentation.
It will require some coding, yes, and Migrate module is not the easiest module to get a grip on, so if you're new to coding, you may need some help with that, but I think it's by far the best solution.
Easier implementation:
The Feeds module claims that it can

Import or aggregate CSV files

I haven't used that particular piece of functionality myself, but from previous use of Feeds, I'm under the impression that this could be configured from the UI, and thus wouldn't require any code. Feeds documentation.
Comment: Thank you for welcoming me and of course for your help! I'll definitely check out Migrate module to import text fields. As for images - I will still be waiting suggestions from DA community. Thanks again
Comment: Your welcome. :) Migrate handles files (and thus images) just fine. Not sure about feeds though.
Comment: I used feeds combined with feeds tamper module to upload text and multi-value fields and it worked great! thanks again!

Upload files to create nodes


Will I be able to declare a constexpr lambda inside a template parameter?

Question: I know it's like opening the Pandora box but it doesn't stop bothering me. Consider a simple example:
#include <type_traits>

template <auto>
struct Foo: std::false_type { };

template <>
struct Foo<[](){return 1;}()>:std::true_type { };

int main() {
    static_assert(Foo<1>::value);
}

I know lambdas cannot be declared inside unevaluated context, but obviously this is not the case here. What is even more weird clang 5.0.0 (which, I guess, first partially supports constexpr lambda) does compile it.
Is it a compiler bug or will C++17 allow this?
Answer: No, that is a compiler bug. gcc 7.1 correctly rejects the code.
[expr.prim.lambda]/2:

A lambda-expression is a prvalue whose result object is called the closure object. A lambda-expression shall not appear in an unevaluated operand, in a template-argument, in an alias-declaration, in a typedef declaration, or in the declaration of a function or function template outside its function body and default arguments.

As you can see from the part that I marked as bold, a lambda expression cannot appear in a template argument list.
This is also made clear in a subsequent note:

[ Note: The intention is to prevent lambdas from appearing in a signature. — end note ]

If I were to guess, I would say that the bug comes about because starting with C++17, lambdas are implicitly constexpr, which makes them valid to be called in compile time expressions, like template arguments. But actually defining a lambda in a template argument is still illegal.

Note that this restriction has been lifted in C++20. :)
Comment: @DanielJour No, sorry. But that would make meta programming even *more* confusing :)
Comment: @W.F. Jup, the paragraph I'm quoting is gone :) http://eel.is/c++draft/expr.prim.lambda#2
Comment: Nice finding! Thanks for sharing! Lets hope coders will use it reasonably ;)
Comment: Wait! Now lambda can be declared in decltype? :o
Comment: yep I thought the standard committee intention was to present it, that's why I was surprised clang did compiler the code. I'll wait a bit and then accept your answer. Thanks!
Comment: Any idea as to *why* this has been made illegal? Seems pretty useful, making meta programming a lot easier...
Comment: Is it official?
Comment: @W.F. Yes, finally :)
Comment: Wow! Cool wind of changes!
Comment: @DanielJour It seems like the committee agreed and in C++20 it works now :)
Answer: In C++17 you can pass pointer to lambda function as template parameter with function pointer type:
# include <cassert>

template<int(*fn)()>
int get_twice()
{
    return fn() * 2;
}

int main()
{
    int result = get_twice <+[]() { return 42; }> ();
    assert(result == 84);
}


Finding Duplicate rows in datatable in VB.net

Question: I have a datatable in VB.net with few columns - Number, Name , Salary.
I want to get a list/table of "Number" that has the same ID and Salary Reapeted more than once.
for example:

Number: 1 , Name: Dan, Salary: 2000
Number: 2 , Name: Robert, Salary: 300
Number: 1 , Name: Shone, Salary: 2000
Number: 3 , Name: Kelvin, Salary: 2000
Number: 3 , Name: Arnon, Salary: 5000

For this table I will get back "1". because it has duplicate 1 with a salary of 2000.
Thanks for anyone help
Comment: GroupBy Number and Salary and see what Groups have more than one item -- Are both Number and Salary Integer Types? Or maybe Salary is Decimal? Other?
Comment: Both are int64. And I need the code to handle the datatable in VB.net
Comment: Well, we need to see what code you have that doesn't work as expected. If you don't have any, take the hint in my previous comment and post your own implementation. -- You need to reference both `System.Data` and `System.Data.DataSetExtensions`. -- Salary should be `Decimal`.
Comment: You should also specify if you want to do this with a query, in code or, possibly, both, depending on some *states* / use-cases.
Comment: This can certainly be done in VB on a `DataTable` but it will be a little laborious. It would be easier to do in SQL against the database. Is that an option? If not, are you required to use a loop, because it would be more concise to use LINQ. LINQ basically lets you hide a loop in a single query.
Answer: I created the DataTable, then used Linq to group it by Number and salary. The Where clause only chooses groups with count greater than 1. The Select collects the Number field.
<code>Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
    Dim dt As New DataTable
    dt.Columns.Add("Number", GetType(Long))
    dt.Columns.Add("Name", GetType(String))
    dt.Columns.Add("Salary", GetType(Long))
    dt.Rows.Add(1, "Dan", 2000)
    dt.Rows.Add(2, "Robert", 300)
    dt.Rows.Add(1, "Shone", 2000)
    dt.Rows.Add(3, "Kelvin", 2000)
    dt.Rows.Add(3, "Arnon", 5000)

    Dim result = From row In dt
                 Group row By NumberSalary = New With {
                     Key .Number = row.Field(Of Long)("Number"),
                     Key .Salary = row.Field(Of Long)("Salary")}
                     Into Group
                 Where Group.Count > 1
                 Select New With {
                     Key .Number = NumberSalary.Number}
    For Each r In result
        Debug.Print(r.ToString) 'Prints { Number = 1 } in the Immediate window
    Next
End Sub
</code>


jQuery multiple selectors with window or document

Question: I know how to use multiple CSS selectors with jQuery, but how can I bind an event listener to multiple selectors when one of them is an object, the document or the window object for instance.
The following doesn't work :
$('html, body', document).scroll(function () {
    if(Screen.detectScroll() === 'down') {
        self.hide();
    } else {
        self.show();
    }
});

Comment: `$('html, body').add(document)`
Comment: @cookiemonster Yep, I actually just found that. Answer my question if you wish.
Comment: I'll let someone else. Go ahead if you'd like.
Answer: You can use jQuery's Add() to add selectors.
$('html, body').add(document).scroll(function () {
    if(Screen.detectScroll() === 'down') {
        self.hide();
    } else {
        self.show();
    }
});


active record perform order on only last x records

Question: I have this active record collection and am using it in a sortable table within the view. I want the table to display the last 50 videos and I want to perform the ordering (of created_at, response_count, watched_count) on only these last 50 videos, but when I pass in the parameter to order them, it reselects from the entire collection of videos and then takes the last 50 after ordering.
Basically I'm wondering - how can I first take the 50 most recent videos and THEN order them by these attributes instead of doing the ordering first and then taking 50.
Even when I take the .order clause out and do that seperately, active record still treats @videos as a big sql query and combines everything together.
@videos = Video.select("videos.*,
                            COALESCE(SUM(video_activities.video_watched_count),0) AS watched_count,
                            COALESCE(SUM(video_activities.response_count),0) AS response_count,
                            COALESCE(SUM(video_activities.email_opened_count),0) AS email_opened_count,
                            MAX(video_activities.updated_at) AS last_activity")
                    .joins("INNER JOIN customers ON videos.customer_id = customers.id AND customers.id = #{current_customer.id}
                            LEFT JOIN video_activities ON videos.id = video_activities.video_id
                            LEFT JOIN people on videos.person_id = people.id")
                    .where.not(videos: {template: true})
                    .order("#{sort} #{params[:direction]}  NULLS LAST")
                    .group("#{group_by}")
                    .limit(50)

Answer: What I will suggest is, fetch 50 most recent videos from the database using the query. Than order them by these attributes in memory. Don't do both the things in the same SQL query.
To do this, either covert @videoes to an array by using to_a, or directly use sort on it, as order will add another order by in the query and mess up your results.
Comment: I try, I move the .order out of the query and always do that separately but the entire thing still gets converted into 1 query.

@videos.order!("#{sort} #{params[:direction]}  NULLS LAST")
Comment: For that, instead of using ActiveRecord's method `order!` use ruby's `sort` function.
Comment: yeah I was thinking of converting it to an array then using sort but was having trouble with the correct parameters for the sort function
Comment: Yes, that is what you have to do, as `order` is an Active record function and it will append order by in the query, messing up your results.


Number of ways to write set $S$ as union of $l$ unique $k$-subsets

Question: The $k$-subsets can, of course, overlap. The answer should be in terms of $k,l$ and $|S|=n$. I have a very complicated solution involving inclusion-exclusion in mind, so I thought I'd post here first to see if anyone can think of a simpler answer.
Comment: Is a "$k$-subset" a subset of size $k$?
Comment: Additionally, is it a collection of $l$ subsets, or an ordered list of $l$ subsets? Finally, do the $l$ subsets have to be distinct?
Comment: @6005 Yes, collection, yes. You can just divide/multiply by $l!$ anyway for the collection issue
Answer: Using the  Polya Enumeration  Theorem and  the unlabeled  set operator
$\def\textsc#1{\dosc#1\csod}
\def\dosc#1#2\csod{{\rm #1{\small #2}}}\textsc{SET}$
we obtain the generating function
$$Z(P_l)([z^k] \prod_{q=1}^n (1+z A_q)).$$
The cycle index here is evaluated with the rule
$$a_d = [z^k] \prod_{q=1}^n (1+z A_q^d).$$
Now we  need to remove those  terms from the generating  function that
are missing  some of the  $n$ elements  represented by the  $A_q,$ and
this  is  done  by  inclusion-exclusion. We  will  subtract  from  the
generating  function  those  terms  that have  one  or  more  elements
missing, then  add those with  two or more  and so on.   The remaining
terms in  the generating  function are  set to  one. For  $p$ elements
missing  we   set  the  corresponding   variables  to  zero   and  the
substitution becomes
$$a_d = [z^k] (1+z)^{n-p} = {n-p\choose k}.$$
Given that
$$Z(P_l) = [w^l]
\exp\left(\sum_{d\ge 1} (-1)^{d+1} a_d \frac{w^d}{d}\right)$$
the substituted cycle index becomes
$$[w^l] \exp\left({n-p\choose k}
\sum_{d\ge 1} (-1)^{d+1} \frac{w^d}{d}\right)
\\ = [w^l] \exp\left({n-p\choose k} \log(1+w)\right)
= [w^l] (1+w)^{n-p\choose k}
\\ = \frac{1}{l!} {n-p\choose k}^{\underline{l}}.$$
Here we have chosen to expand  the second binomial coefficient to make
the formula  easier to read.   Inclusion-exclusion now yields  for the
answer
$$\bbox[5px,border:2px solid #00A000]{
\frac{1}{l!} \sum_{p=0}^n {n\choose p} (-1)^p
{n-p\choose k}^{\underline{l}}.}$$
In terms of operators we have treated the combinatorial class
$$\textsc{SET}_{=l}(\textsc{SET}_{=k}(
\mathcal{A}_1+\mathcal{A}_2+\cdots+\mathcal{A}_n)).$$
Here  is  the  Maple code  to  compute  these  values  as a  means  of
clarifying the interpretation  of the problem that  was used. (Warning
-- total  enumeration only  practicable for small  configurations. The
latter  routine was  deliberately  left unoptimized  to represent  the
problem statement before processing.)

pet_cycleind_set :=
proc(n)
option remember;

    if n=0 then return 1; fi;

    expand(1/n*add((-1)^(l-1)*a[l]*
                   pet_cycleind_set(n-l), l=1..n));
end;

pet_varinto_cind :=
proc(poly, ind)
local subs1, subs2, polyvars, indvars, v, pot, res;

    res := ind;

    polyvars := indets(poly);
    indvars := indets(ind);

    for v in indvars do
        pot := op(1, v);

        subs1 :=
        [seq(polyvars[k]=polyvars[k]^pot,
             k=1..nops(polyvars))];

        subs2 := [v=subs(subs1, poly)];

        res := subs(subs2, res);
    od;

    res;
end;

X_CIND :=
proc(n, k, l)
    option remember;
    local gf, gfA, src, idx, term, res;

    src := add(A[q], q=1..n);

    idx := pet_cycleind_set(k);
    gf := expand(pet_varinto_cind(src, idx));

    idx := pet_cycleind_set(l);
    gfA := expand(pet_varinto_cind(gf, idx));

    res := 0;

    for term in gfA do
        if nops(indets(term)) = n then
            res := res + term;
        fi;
    od;

    subs([seq(A[q]=1, q=1..n)], res);
end;

X :=
(n, k, l) ->
add(binomial(n,p)*(-1)^p*binomial(binomial(n-p,k), l),
    p=0..n);

X2 :=
(n, k, l) ->
add(binomial(n,p)*(-1)^p*mul(binomial(n-p,k)-q, q=0..l-1),
    p=0..n)/l!;

Sanity  check I  Dec 3  2016. When  $l=1$ we  should get  just one
possibility when  $k=n$ and  zero otherwise. To  verify this  we start
from
$$\sum_{p=0}^n {n\choose p} (-1)^p {n-p\choose k}$$
and observe that
$${n\choose p} {n-p\choose k}
= \frac{n!}{p! k! (n-p-k)!}
= {n\choose k} {n-k\choose p}$$
which yields for the sum
$${n\choose k} \sum_{p=0}^n  {n-k\choose p} (-1)^p.$$
We may certainly lower the upper  limit to $n-k$ as the inner binomial
coefficient is zero when $n-k\lt p \le n$ and get
$${n\choose k} \sum_{p=0}^{n-k}  {n-k\choose p} (-1)^p.$$
When $k=n$ this evaluates to
$${n\choose n} [z^0] (1+z)^0 = 1$$
as claimed. Furthermore when $k\lt n$ we get
$${n\choose k} (-1+1)^{n-k} = 0$$
which confirms  the sanity check.  We could  also treat this  with the
Egorychev method, introducing
$${n-p\choose k} =
\frac{1}{2\pi i}
\int_{|z|=\epsilon}
\frac{1}{z^{k+1}} (1+z)^{n-p}
\; dz$$
to get for the sum
$$\frac{1}{2\pi i}
\int_{|z|=\epsilon}
\frac{1}{z^{k+1}} (1+z)^{n}
\sum_{p=0}^n {n\choose p} (-1)^p \frac{1}{(1+z)^p}
\; dz
\\ = \frac{1}{2\pi i}
\int_{|z|=\epsilon}
\frac{1}{z^{k+1}} (1+z)^{n}
\left(1-\frac{1}{1+z}\right)^n
\; dz
\\ = \frac{1}{2\pi i}
\int_{|z|=\epsilon}
\frac{1}{z^{k+1}} z^n
\; dz.$$
This is $[z^k] z^n$ which is one when $k=n$ and zero otherwise.
Observe furthermore that for $k=1$ the formula produces
$$\sum_{p=0}^n {n\choose p} (-1)^p {n-p\choose l}$$
and we once more get one for $l=n$ and zero otherwise. This is because
we cannot  cover $n$  with singletons  if there are  less than  $n$ of
them.  There is  one possibility  when $l=n$  (one singleton  for each
element of $[n]$).  There are no admissible  configurations when $l\gt
n$  because the  subsets have  to  be unique  and there  are only  $n$
different ones available.
Sanity check II Dec  3 2016. We can treat the  case $l=2$ where we
obtain
$$\frac{1}{2}\sum_{p=0}^n {n\choose p} (-1)^p {n-p\choose k}
\left({n-p\choose k} - 1\right)
\\ = -\frac{1}{2} [[n=k]]
+ \frac{1}{2}\sum_{p=0}^n {n\choose p} (-1)^p {n-p\choose k}^2
\\ = -\frac{1}{2} [[n=k]]
+ \frac{1}{2} {n\choose k}
\sum_{p=0}^n {n-k\choose p} (-1)^p {n-p\choose k}.$$
Lowering the upper limit to $n-k$ and using the earlier integral (both
as before) we get for the sum
$$\frac{1}{2\pi i}
\int_{|z|=\epsilon}
\frac{1}{z^{k+1}} (1+z)^{n}
\sum_{p=0}^{n-k} {n-k\choose p} (-1)^p \frac{1}{(1+z)^p}
\; dz
\\ = \frac{1}{2\pi i}
\int_{|z|=\epsilon}
\frac{1}{z^{k+1}} (1+z)^{n}
\left(1-\frac{1}{1+z}\right)^{n-k}
\; dz
\\ = \frac{1}{2\pi i}
\int_{|z|=\epsilon}
\frac{1}{z^{2k-n+1}} (1+z)^{k}
\; dz.$$
Therefore we have the closed form
$$-\frac{1}{2} [[n=k]]
+ \frac{1}{2} {n\choose k}
{k\choose 2k-n}.$$
Counting these from combinatorial  principles suppose $q$ elements are
common to both sets where $0\le  q\le k$, this means that $q+2(k-q)=n$
or $q=2k-n$ for a contribution of
$$\frac{1}{2} {n\choose q} {n-q\choose k-q}
= \frac{1}{2} {n\choose 2k-n} {2n-2k\choose n-k}.$$
Note  however  that  this  produces $\frac{1}{2}  {n\choose  n}  [z^0]
(1+z)^0 = \frac{1}{2}$ when $n=k$ while the correct result is zero (no
possibility for two  unique sets of $n$ elements as  there is only one
available or alternatively we must have  $q\lt n$ because the two sets
are unique) so we finally get
$$-\frac{1}{2} [[n=k]]
+ \frac{1}{2} {n\choose 2k-n} {2n-2k\choose n-k}.$$
To verify that this matches the result from the integral we write
$${n\choose 2k-n} {2n-2k\choose n-k}
= \frac{n!}{(2k-n)!(n-k)!(n-k)!}
= {n\choose k} {k\choose 2k-n}.$$
Comment: DAMMMMM this is the kind of stuff I need to learn how to do. Is there any way to get that sum into a closed form, though?
Comment: Again, this answer is just absolutely brilliant.
Comment: Also: I'm really interested in getting a lower bound on the sum. Is it possible to substitute the factorials with Stirling's approximation and then integrate? How would one ensure the integrals are a lower bound on the sum? Or would it even be possible to sum directly?
Answer: I don't think an Inclusion-Exclusion solution is so complicated. In fact, it is pretty straightforward.
For each element $x\in S$, define property $P_x$ to be "$x$ does not belong to any subset in a given $l$-collection of $k$-subsets". We want to find the enumerate the number $e_0$ of $l$-collections of $l$ $k$-subsets that satisfy exactly $0$ properties in $\Omega=\{P_x\mid x\in S\}$.
Given an arbitrary subset $T$ of $\Omega$, let $N(\supseteq T)$ be the number of $l$-collections of $k$-subsets that satisfy at least all the properties in $T$. Let $S_T=\{x\mid P_x\notin T\}$, then all $k$-subsets that satisfy at least all properties in $T$ are subsets of $S_T$. The number of $k$-subsets of $S_T$ is
$$
\binom{|S_T|}{k}=\binom{n-|T|}{k},
$$
so the number of $l$-collections of such subsets is
$$
\binom{\binom{n-|T|}{k}}{l}.
$$
Let
$$
N_j=\sum_{\substack{T\subseteq\Omega\\|T|=j}} N(\supseteq T).
$$
There are $\binom{n}{j}$ subsets $T\in\Omega$ of cardinality $j$, so
$$
N_j=\binom{n}{j}\binom{\binom{n-j}{k}}{l}.
$$
But then the formula (4.2.6) on page 112 of generatingfunctionology says that the number we want is
$$
e_0=\sum_{j\ge 0}(-1)^j N_j = \sum_{j\ge 0}(-1)^j \binom{n}{j}\binom{\binom{n-j}{k}}{l}
=\sum_{j=0}^{n}(-1)^j \binom{n}{j}\binom{\binom{n-j}{k}}{l}.
$$


I know the limit of a subsequence exists, but how do I find it?

Question: I know intuitively that for:
$(a_n) = (1,1,2,1,2,3,1,2,3,4, ...)$
for any $m$ in the positive natural number there is a subsequence (m,m,m,..) that tends to m as n tends to infinity. I believe I must find a function from n to a function of n, which takes every element equal to m from $(a_n)$.
How would such a function be defined?
Comment: It seems fairly pointless to me to find an explicit formula. But here goes. The $k$-th "cycle" ends at the $k(k+1)/2$-th term.   We want the indices at which $m$ occurs. These are the indices $k(k+1)/2+m$, where $k$ is large enough, that is, $\ge m-1$.
Answer: The first occurence of $m$ occurs at the $\frac{m(m+1)}{2}$th position. The $i$th subsequent instance occurs after $m + (m+1) + \dots + (m+i-1) = i\cdot m + \frac{(i-1)i}{2}$th positions. So, in general, the $n$th occurence of $m$ will be at
$$
\frac{m(m+1)}{2} + (n-1)m + \frac{(n-2)(n-1)}{2}
$$
Answer: $m$ appears first after $m-1$ pattern cycles, at the index
$$
m+\sum_{i=1}^{m-1} i = \frac {m \left ( m+1 \right )}{2}
$$
after that we just have increments of $m+1, m+2,...$ i.e.
$$
a_n=m \iff n=m+ \frac {i \left ( i+1 \right )}{2} \ , \ i>m-2
$$


Calling WS with SSL in java

Question: I connect to a web service with this client that work fine:
WSCSI WSCS = new WSCSI("http://localhost:8080/ServiceV2/services/WSCSISoap?wsdl","WSCSI","WSCSISoap");
IScoring instance = new ScoringCFA(WSCS);

assertEquals(true, instance.statusService());

I need to use SSL, So i change the url to:
https://localhost:8181/ServiceV2/services/WSCSISoap?wsdl
And add this in the VM Options:
-Djavax.net.ssl.trustStore="C:\cacerts.jks"

('Keytool -list -keystore "C:\cacerts.jks', when i run this command i see that the certificate that i need is there)
When i run the client get this error:
java.security.cert.CertificateException: No name matching localhost found.)

Answer: That's probably because the cert you're using is issued against a specific hostname (www.myhost.com).  Try the solution in this article.
But be warned, the code sample is only intended for localhost testing, remove it once you move onto the integration/assembly testing on a proper server.
Comment: Thank you very much!
Now, when I have to deploy the proyect in production,

I would need that the cert have the name of the domain that I'm trying to connect?
(Thats a cert problem outside the code...?)

And
If I deploy the client with this "FIX", the problem is that maybe I connect to a unknow host?
Comment: JMira - this 'fix' is not a fix, but a 'hack' only intended for localhost testing, you should remove that code before you go to production. Yes, the risk is you could be calling an improperly identified host (although the 'hack' will only work with 'localhost' as a host name).  In production, the URL you're trying to invoke has to match the hostname that the server is identifying with, so yes, the name in the cert needs to match the domain you're connecting to.  Hope this provides further clarity.
Answer: Sounds to me that disabling SSL hostname verification might work for you. Another example here.

Calling WS with SSL in java


Similarities and dissimilarities in classical multidimensional scaling

Question: I am having trouble reconciling between several terms in MDS.
According to [1], Section 14.8, Classical MDS takes similarities as inputs.
In [2], also cited in Wikipedia, Classical MDS takes dissimilarities as inputs.
What is the agreed upon terminology?
[1] Hastie, T, R Tibshirani, and JH Friedman. The Elements of Statistical Learning. Springer, 2003.
[2] Borg, I., and P. J. F. Groenen. Modern Multidimensional Scaling: Theory and Applications. 2nd edition. New York: Springer, 2005.
Comment: I suppose you may be mistaken. Term "Classic MDS" or "simplest MDS" is usually understood as unweighted euclidean MDS, that is, not INDSCAL model. Classic MDS works with one matrix. It can be similarities or dissimilarities. Usually a program first converts the first into the second and proceeds. Because the algorithm itself is typically written for dissimilarities.
Comment: Plugging similarities or dissimilarities in the squared stress function leads to different solutions (see discussion in [1] between Eq(14.100) and Eq.(14.101)). It is thus of importance to define which goes into the stress function.
Answer: These two books are in full agreement.
Classical multidimensional scaling (where by "classical MDS" I understand Torgerson's MDS, following both Hastie et al. and Borg & Groenen) finds points $z_i$ such that their scalar products $\langle z_i, z_j \rangle$ approximate a given similarity matrix as well as possible. However, any dissimilarity matrix can be converted into a similarity matrix: dissimilarities are assumed to be Euclidean distances, from which centered scalar products can be computed and taken as similarities.
So the algorithm of classical/Torgerson MDS is as follows: $$\text{Euclidean distances}\to\text{Centered scalar products}\to\text{Optimal mapping},$$ i.e. $$\text{Dissimilarities}\to\text{Similarities}\to\text{Optimal mapping}.$$ What you consider an "input" here, does not really matter.
This is exactly what is written in Hastie et al.:

In classical scaling, we instead [as opposed to metric scaling in general] start with similarities [...]. This is attractive because there is an explicit
  solution in terms of eigenvectors [...]. If we have distances
  rather than inner-products, we can convert them to centered inner-products
  if the distances are Euclidean [...]. If the similarities are in fact centered inner-products, classical scaling is exactly equivalent to principal components [...]. Classical scaling is not equivalent to least squares scaling [that minimizes reconstruction of dissimilarities].

See my answer in What's the difference between principal components analysis and multidimensional scaling? for mathematical details.
Comment: Thank you.
 What you are saying is that Borg & Groenen definition is wrong: the stress is not a function of dissimilarities, but rather of similarities. Put differently, Borg & Groenen "classical MDS" is Hastie's Least Squares Scaling.
Would you agree?
Comment: No, definitely not. Borg & Groenen seem to be in full agreement with Hastie et al., and use the term "classical scaling" (Chapter 12) to refer to Torgerson scaling, which is what Hastie et al. also do.
Comment: @amoeba, I've just surfed over some texts on MDS and I found a confusion with the definition of term "Classical MDS". Some sources define it as you did, as =Torgerson's MDS aka PCoA. But more sources define it as "single matrix Euclidean model MDS" (I myself thought this way and continue to agree with that custom). If to admit to it then Classical MDS (aka Identity MDS) _is_ what is not Replicated MDS or Weighted/Generalized MDS (INDSCAL's versions).
Comment: (cont.)  It - classical MDS - can be metric or nonmetric, be based on different stress measures, be algorithmically based on eigen or ALSCAL or PREFSCAL etc. Torgerson's PCoa is just one (and simplest) kind of it. Note that [in my answer](http://stats.stackexchange.com/a/14017/3277) I implied that definition of classical mds.
Comment: See also http://stats.stackexchange.com/a/31291/3277 where I also implied that definition of classical mds.
Comment: @ttnphns, Thanks, it is good to know that there is this terminological ambiguity. I was not aware of that. However, just to be clear: both books that OP is citing use the term "classical MDS" in the sense "Torgerson's MDS". I will explicitly mention this in my answer now, to remove potential confusion.
Comment: Ah, ambiguities are everywhere... It might be nice to quit the term "classical mds" altogether. Identity (= single matrix unweighted) MDS. Torgerson's PCoA. Two nice terms.
Comment: @ttnphns: Agree. But I don't like the term "PCoA" and would rather avoid it; I am happy to use the term "Torgerson['s] MDS" though.
Comment: I don't like the acronym much either, because it is, mathematically, just _double centering_ then PCA. But the term is relatively well established.
Comment: @John, perhaps you could point me to a specific bit in Borg & Groenen that you think is in disagreement with Hastie et al.? Then I could try to clarify it further. At the moment I am not sure where the confusion is.
Comment: Eq.(12.4) in Borg & Groenen does indeed agree with Eq.(14.100) in Hastie.
I guess my problem is just with the [Wikipedia](http://en.wikipedia.org/wiki/Multidimensional_scaling) statement: "... takes an input matrix giving dissimilarities between pairs of items and outputs a coordinate matrix whose configuration minimizes a loss function called strain" which implies that the loss if defined w.r.t dissimilarities, while it is actually not.
Comment: @JohnRos, But you can easily define the loss function ("strain") via dissimilarities! The scalar products must approximate the similarity matrix, yes, but the similarity matrix is given by a transformation of the dissimiliarity matrix (see my linked answer or either of these textbooks). So you can plug this transformation into the loss function and obtain a loss function explicitly defined via dissimilarity matrix!


Keep Summary field deployed

Question: I'm using the node's Summary field for article teasers. Although not mandatory, this field is being constatly populated by content editors for article content types. I'm trying to make it visible instead of Drupal's default collapsed state, but I've hit a wall on identifying the related JS function and how to modify it without hacking core files.
Any idea on achieving the desired UI modification?
EDIT: OK, seems like the /modules/text/text.js is the file in charge of adding the link that shows/hides the Summary field.
Since I don't want to simply comment out or edit core files, I think I'll have to make a custom module to unset this js file and not allow it to be loaded. I'm no JS expert but by looking into the code it seems to me that this file impacts only the text summary. Hence my updated question would be:  are there any side effects to unset this file?
Answer: For the default value for the field (under Field Settings), in the "Summary" field, you can put a blank " ". This will force the summary field to show up. If you want to do it the correct way, then you will have to check the Javascript that shows/hides the field.
Comment: Thanks Abhijit. I'll keep this solution under my sleeve in case I fail to produce a proper custom module.
Comment: And for the JS, I think you can use hook_js_alter to do it. You can copy the JS file and rename it and comment out the lines. Unset the core JS and add your copy.
Comment: After talking this through, with an content editor, the solution you provided in #1 will suffice.
I'm setting that as the accepted answer :)
Answer: You can also do this through template.php.
Functionality: Strip out any js that you specify in an array in your .info file:
function mytheme_js_alter(&$javascript) {
  $excludes = _mytheme_alter(mytheme_theme_get_info('exclude'), 'js');
  $javascript = array_diff_key($javascript, $excludes);
}

function _mytheme_alter($files, $type) {
  $output = array();

  foreach($files as $key => $value) {
    if(isset($files[$key][$type])) {
      foreach($files[$key][$type] as $file => $name) {
        $output[$name] = FALSE;
      }
    }
  }
  return $output;
}

Then in your .info file:
exclude[js][] = 'modules/field/modules/text/text.js'

All that text.js contains is the summary show/hide javascript. Without it, summaries always show.
You can alter these functions for css excludes as well (mytheme_css_alter), which is handy to clear out Drupal core crud :)

Keep Summary field deployed


Question about eigenvalue problem range space

Question: A theorem from Axler's Linear Algebra Done Right says that if  is a linear operator on a complex finite dimensional vector space , then there exists a basis  for  such that the matrix of  with respect to the basis  is upper triangular.
In the proof, he defines U=range(T-I) (as we have proved atleast one eigenvalue must exist)and says that this is invariant under T.
First I want understand what the range space is here. Suppose we are in 2D and I choose some basis consisting on an eigenvector($e_v$) and another free vector(v): ( $e_v$, v) Now this v can be anything not necessarily an eigenvector. So there are many possibilities. Are all contained in U? U can have dimension 1 but all these possibilities are not linearly independent so what exactly is U? Is it a set of all vectors not in the span of $e_v$? Does this not conflict with U having dimension 1?
He then proves this by saying if u belongs to U then Tu=(T-I)u + Tu and both (T-I)u and Tu belong to U. But if I had chosen a non-eigenvalue for my basis, then Tu does not scale it so it is mapped to some other span. Therefore I'm guessing U is a set.
Any other comments about (T-I)v would be appreciated. How to think of it in the context of our original T? (I know the null space is the eigenvector)
Answer: $T-\lambda I$ is a linear map as it is the sum of two linear map(if you think of $\lambda I$ as the linear map that sends a vector $v$ to $\lambda v$). The image of a linear map is always a subspace. And hence $U:=range(T-\lambda I)$ is indeed a subspace of $V$.
The proof says $U$ is invariant under $T$. He did not consider eigenvector basis at all, He says pick $u\in U$, then $T(u)=T(u)-\lambda u+\lambda u=(T-\lambda I)(u)+\lambda u$. And from there, he deduced $T(u)$ is in $U$ as both $(t-\lambda I)(u)$ and $\lambda u$ is in $U$.
Now,since $T-\lambda I$ is not surjective, $dim(U)<dim(V)$.So we can apply induction on $U$ to get a basis $B_U$ for $U$ in which $T$ restricted to $U$ is upper triangular(Here we used the fact that $U$ is invariant under $T$ as otherwise we wouldn't be able to apply the induction hypothesis). Then when we complete $B_U$ to a basis $B$ for $V$, we have that $T$ with respect to the basis $B$ is upper triangular where he proved that result using the conditions for a linear map to be upper triangular.
So I'm not sure what is $img(T-\lambda I)$.
Comment: You didnt answer my question. If a space has dim 2, then :=(−) for a  must have dim 1 as the null space is the eigenvector space. However U may contain more than one linearly independant vectors, as if the eigenvector was (1,1) then vectors (1,2) and (1,3) must be in U and they are independant, so doesent the dim of U now equal 2 ?
Comment: Ah, so if I understand correctly, let's say $V$ has dimension $2$ and we could have $U$ have dimension $2$ as well? Is that was the question, then notice that $U$ could not have dimension 2 as $T-\lambda I$ is not surjective.The null space of $T-\lambda I$ is not $U$, $U$ is the image of $T-\lambda I$ i.e the column space.
Comment: Yes, thats what I said in 2D space ':=(−) for a  must have dim 1 as the null space is the eigenvector space'. In the comment above I am saying suppose the eigenvector related to this  is span(1,1). So everything except span(1,1) must be in U. Therefore span(1,2) and span(1,3) must be in U. But notice that span(1,2) and span(1,3)  are linearly independant. This contradicts the statement that U is dim 1 as we have show two linearly independant vectors. Please let me know if any step is unclear.
Comment: good point, I don't understand either, Hopefully, someone will answer:) But by your argument, since there are infinitely many lines through the origin, and each of them is the span of some unit vector, each of those vectors are pairwise linearly independent, so then $R$ would be infinite dimensional. So the argument is wrong. The problem is that the image of $T-\lambda I$ is not whatever that is not in null of $T-\lambda I$.
Comment: Example, T(x,y)=(x,0) has null space the y-axis but image is the x-axis and not whatever that is not in the null space. And I'm charging $5 for my answer as pure mathematician usually can't find jobs except teaching at college :).
Comment: Your username is LOL. Are you Indian? That's Marathi right or a coincidence?


Obter valores do 4º nó do Firebase em Android

Question: Preciso buscar os valores grifados em vermelho na imagem, mas eu apenas conheço o item grifado em azul.

Tentei dessa maneira:
firebase = ConfiguracaoFirebase.getFirebase().child("tb_contato").child(identificador);
                valueEventListener = new ValueEventListener() {
                    @Override
                    public void onDataChange(DataSnapshot dataSnapshot) {
                        for (DataSnapshot filho: dataSnapshot.getChildren())
                        {
                            Contato contato = filho.getValue(Contato.class);
                            Log.i("Teste","Teste");
                        }
                    }

                    @Override
                    public void onCancelled(DatabaseError databaseError) {

                    }
                };
                firebase.addListenerForSingleValueEvent(valueEventListener);

Onde o "identificador" é o valor grifado em azul da imagem.
Mas ao tentar compilar, ele me retorna assim:
Comment: Pelo que colocou na pergunta, seu banco parece estar mal estruturado, é melhor evitar ao máximo o aninhamento de dados. A única forma que vejo é fazer um loop nas chaves, guardar em um array e usar para acessar os dados filhos
Answer: Resolvi dessa maneira, não sei se é o mais adequado, mas funcionou.
firebase = ConfiguracaoFirebase.getFirebase().child("tb_contato").child(identificador);
                valueEventListener = new ValueEventListener() {
                    @Override
                    public void onDataChange(DataSnapshot dataSnapshot) {
                        if (dataSnapshot.exists()) {
                            for (DataSnapshot filho: dataSnapshot.getChildren())
                            {
                                chaveServico = filho.getKey();
                                firebaseContato = ConfiguracaoFirebase.getFirebase().child("tb_contato").child(identificador).child(chaveServico);
                                valueEventListenerContato = new ValueEventListener() {
                                    @Override
                                    public void onDataChange(DataSnapshot dataSnapshot) {
                                        for (DataSnapshot filho: dataSnapshot.getChildren())
                                        {
                                            //===== Altera o nome do usuário no contato =======
                                            String chaveUsuario = filho.getKey();
                                            firebaseUsuario = ConfiguracaoFirebase.getFirebase();
                                            DatabaseReference hopperRef2 = firebaseUsuario.child("tb_contato").child(identificador).child(chaveServico).child(chaveUsuario);
                                            Map<String, Object> hopperUpdates2 = new HashMap<>();
                                            hopperUpdates2.put("cttUsrIDNomeSolicitante", txtNome.getText().toString());
                                            hopperRef2.updateChildren(hopperUpdates2);

                                            firebaseUsuario = ConfiguracaoFirebase.getFirebase();
                                            DatabaseReference hopperRef3 = firebaseUsuario.child("tb_contato").child(chaveUsuario).child(chaveServico).child(identificador);
                                            Map<String, Object> hopperUpdates3 = new HashMap<>();
                                            hopperUpdates3.put("cttUsrNomePrestador", txtNome.getText().toString());
                                            hopperRef3.updateChildren(hopperUpdates3);
                                            //=================================================
                                        }
                                    }

                                    @Override
                                    public void onCancelled(DatabaseError databaseError) {

                                    }
                                };
                                firebaseContato.addListenerForSingleValueEvent(valueEventListenerContato);
                            }
                        }
                    }

                    @Override
                    public void onCancelled(DatabaseError databaseError) {

                    }
                };
                firebase.addListenerForSingleValueEvent(valueEventListener);


Combinations - Course choosing

Question: Someone asked me this question:

Suppose there are $n$ students. Each student must choose 4 courses, and
  every two students can only have a maximum of one common course. How
  many courses are needed to satisfy this condition?

I tried to convert this into a graph theory problem but failed to figure it out.
Comment: 2n${}{}{}{}{}{{}}$
Comment: @Awesome if $n=2$, you need $7$ courses...
Comment: @Foga I always make silly mistakes...
Comment: I get a bizarre pattern, which I am not 1-- percent sure is correct. Starting with $n=1$, my pattern is $4,7,8,10,10,11,12$
Comment: @mathguy I get something different, I get $4,7,9,10,10,11,12$. I don't see how to do it with $8$ in the third step.
Comment: @G.Bach I meant to say 9. Sorry about that. Thanks!
Comment: $x_1=4, x_{n+1} = x_n + n\mod 4$?
Comment: @baudolino That fails at $n+1=2$ whether we read it as $(x_n+n)\mod 4$ or as $x_n+(n\mod4)$.
Answer: I presume that what is wanted is the minimum number of courses needed.
For $n=1\;thru\; 4,$ the pattern is $4,7,9,10$. The pattern for $n=5$ is shown below:
$\boxed{1,2}\;\boxed{1,3}\;\boxed{1,4}\;\boxed{1,5}\;\boxed{2,3}\;\boxed{2,4}\;\boxed{2,5}\;\boxed{3,4}\;\boxed{3,5}\;\boxed{4,5}\;$ and it repeats in cycles of $5$
Let number of courses needed for $(n\;mod\; 5)\;be\; k_i,\; i = 1\; thru\; 4$
Then minimum number of courses needed for $n$ students = $10\times \left[int\left(\dfrac{n}{5}\right)\right] + k_i$

Combinations - Course choosing


Simple bounds of the Wasserstein distance

Question: I have some "proofs" of simple assertions regarding the Wasserstein distance (=the earth mover's distance), but I'm having trouble in making them precise. Can I know if the following assertions are true, and whether my "proofs" are sound?

Denote by $W_p$ the $p$-Wasserstein distance.
Proposition 1. Let $M$ be a Polish metric space. Suppose $A, B \subseteq M$ are Borel measurable, and that there is a continuous bijection $f : A \rightarrow B$ which is bounded in the sense that $C := \sup_{x \in A} d_M(x, f(x)) < \infty$. Let $\mu$ be a Borel probability measure on $M$ with its support contained in $A$, and let $f_* \mu$ be the pushforward of $\mu$ along $f$. Then for any $p \ge 1$,
$$W_p(\mu, f_* \mu) \le C$$
"Proof". There is at least one transportation plan from $A$ to $B$, given by mapping each $x \in A$ to $f(x) \in B$ [what exactly, rigorously?]. The transportation cost $d_M(x, f(x))$ is bounded by the supremum of all such transportations, and thus we get the assertion.
Proposition 2. Let $M$ be a Polish metric space with a finite diameter $D := \sup_{x,y \in M} d_M(x,y)$. Fix a Borel probability measure $\mu$ on $M$. Let $f$ be a Lipschitz continuous function on $M$ with the Lipschitz constant $\alpha$, such that $\int_M f(x) \text{d} \mu(x) = 1$. Let $\mu_f$ be the Borel probability measure on $M$ given by taking $f$ as the probability density function. Then for any $p \ge 1$,
$$W_p(\mu_f, \mu) \le \alpha D^2 $$
"Proof". Note that $\mu$ is the 'uniform measure' with respect to itself, in that $\mu(A) = \int_A 1 \cdot \text{d}\mu(x)$. Also observe that by the Lipschitz property we have that $\sup_{x \in X} f(x) - \inf_{x \in X} f(x) \le \alpha D$. Thus the task is essentially about flattening a 'pile of earth' with bounded height fluctuations. The total amount of mass that must be transported is at most $\alpha D$, and the cost of transportation per unit mass is at most $D$ [but how do we realize an explicit transportation plan?]. Multiplying, we get the bound $\alpha D \cdot D = \alpha D^2$.

In my context, it's fine to prove the assertion for simpler cases such as when $M= \mathbb R^n$ for some $n> 0$. Correspondingly, the measure $\mu$ in the Proposition 2 may be taken to be the Lebesgue measure.
Answer: The joint probability distribution needed for the proof of Prop. 1 is the pushforward of $\mu$ under the map $x \mapsto (x,f(x))$ from $M$ to $M \times M$.
The heuristic argument given for proposition 2 only applies to $p=1$; for larger $p$ the bound is a bit different.
Since $\int f \, d\mu =1$, we have
$$(*) \quad \forall x \in M \quad  |f(x)-1| \le \alpha D \,.$$
The joint probability distribution needed for the proof of Prop. 2
is $\gamma$ defined as follows. Let $g(x)=f(x) \wedge 1$ and
$ \, c=1- \int g(x) \, d\mu(x)$, so by $(*)$,
$$(**) \quad 0  \le c \le \alpha D \,.$$ If $c=0$ then $\mu=\mu_f$, so we may assume that $c>0$. Then define $\gamma$ via integration against  bounded continuous functions $h \in C(M \times M)$ by
$$\int h(x,y) \, d\gamma(x,y):=   \int h(x,x) g(x) \, d\mu(x) \\
+ c^{-1}\int \int h(x,y) (1 -g(x)) (f(y)-g(y)) \,d\mu(x) \, d\mu(y) \,.
$$
It is easy to verify that $\gamma$ is a coupling of $\mu$ and $\mu_f$.
Moreover,
$$\int d(x,y)^p \, d\gamma(x,y) \\ \le c^{-1}\int \int D^p (1 -g(x)) (f(y)-g(y)) \,d\mu(x) \, d\mu(y) =c D^p \le \alpha D^{p+1} \,,
$$
by $(**)$. Thus
$$W_p(\mu,\mu_f) \le (\alpha D^{p+1})^{1/p} \,.$$
Comment: Now Prop 1 makes sense and the proof is fine.
Comment: Great, I think that resolves it. Here, $g = 1 \wedge f$ means $g = \min(1,f)$ right?
Comment: Yes $\wedge$ means min
Comment: Thanks for the answer. I meant to have $\mu_B$ be induced by $\mu_A$, and I forgot to include that in the original question. Please see if the updated assertion is correct.
Comment: Thank you. May I know how a joint probability distribution to realize such a transportation plan would be defined?
Comment: See the revised answer.


Firebase Database Rules - Get displayName

Question: I added Firebase to my website and created a signup form.
When the user clicks the "signup" button it creates a user using "Firebase Authentication", then it updates the user's displayName, and finally adds some data about the user to the database:
firebase.auth().createUserWithEmailAndPassword(email, password).then(function () {

    profile = firebase.auth().currentUser;

    profile.updateProfile({
       displayName: "name-value"
    }).then(function() {

        // Update successful.

        firebase.database().ref("/users/" + profile.uid).set({
            data:{
                country: "country-value",
                city: "city-value"
            }
        });
    });
}).catch(function(error) {
    // Handle Errors here.
});

Everything worked fine until I changed the database rules from:
{
    "rules": {
        ".read": true,
        ".write": true
        }
    }
}

To:
{
    "rules": {
        "users": {
            ".read": true,
            "$user": {
                ".write": "auth.token.name !== null"
            }
        }
    }
}

I used auth.token.name as it is written in the guide to check whether or not the user's displayName exists (I planned to make it check some more things about it later).
Somehow "firebase rules" 'thinks' that auth.token.name equals null, even though I set the displayName before. Why is it happening and what can I do to make it work?
Thanks in advance :)
Comment: Are you trying using the same user previously created with a name or are you trying to signup a new user?
Comment: The purpose of the page that I've created is signing up a new user, changing the displayName, and finally uploading some data about him to the database.
Comment: @OmerShahar so, sir, did you ever find a fix for this? I have similar rule in my db which is $displayName == auth.token.name but this is never true and i cannot test what auth,.token.name actually have as value because i am sure that user has updated displayName!
Comment: @lowzyyy I tried to check and see what was my solution back then. It looks like I gave up on `displayName` and instead just saved it in the DB. I found it more reliable, and you can still use values from the DB in your security rules. However, I wrote that code more than four years ago, so things might have changed since then.
Comment: @OmerShahar i gave up too. tried solution with uid and it works ($uid==auth.uid as rule). Google firebase software is full of bugs. It's not the first time that something does not work
Answer: First, Firestore has replaced Realtime Database and should be used for all projects going forward - more features.
Re Realtime DB rules, it's is best practice to check uid variable vs display name. See Variables:
{
  "rules": {
    ".read": true,
    "$comment": {
      ".write": "!data.exists() && newData.child('user_id').val() == auth.uid"
    }
  }
}

Finally, IIF you implement database security rules using Firebase Authentication, you MUST use .onAuthStateChanged to drive your application as your auth() variables WILL BE null for a second on initial page/app load as this is an asynchronous method. So, don't try and write or read anything on DOM ready. You must trigger db conversations within .onAuthStateChanged like below:
firebase.auth().onAuthStateChanged(function(user) {
    if (user) {
        //USER SIGNED IN. WE ARE READY
    }
    else {
        //USER IS NOT SIGNED IN
    }
});

Comment: "Firestore has replaced Realtime Database and should be used for all projects going forward - more features." While Firestore is definitely the newest database product from Firebase, this blanket statement is simply not true. See https://firebase.google.com/docs/firestore/rtdb-vs-firestore for a good comparison.
Comment: Just taking a single quote from that page doesn't do it justice, there's too much information in there to simply copy/paste here (which is why I didn't). And even then, the page is incomplete missing a significant section on presence (see: https://firebase.google.com/docs/firestore/solutions/presence). Everyone making the choice should read the page in its entirety and then make their own choice.
Comment: I'll simply have to defer to Lord Puf , I will no longer say Firestore is preferred going forward. Pardon the overreach :-)
Comment: Thank you for your detailed answer, but even after I moved the parts of code (where I updated the displayName and added data to the databse) into .onAuthStateChanged, it still didn't work. Then I tried the same thing with Firestore, as you suggested (allow write: if request.auth.name != null;), but it also didn't work... It still says that the displayName equals to null...
Comment: @FrankvanPuffelen What would be a use case for Realtime DB over Firestore besides sharding? The link you shared says _Cloud Firestore is Firebase's new flagship database for mobile app development. It ...  features richer, faster queries and scales better than the Realtime Database._
Comment: It all depends on your project. If you don't need presence, can do with the slower realtime, want web offline, then I definitely go with Firestore. It's just not a blanket call. I usually say something like "if you're just getting started on this, I'd definitely consider using Firestore".
Comment: @RonRoyston So, as I commented a few days ago, I tried to use `.onAuthStateChanged` (with both Realtime and Firestore) but the rules still 'thought' that `request.auth.name` is null. Do you have another solution that might work? Thanks in advance :-)
Comment: @Programmer use `auth.uid` not `request.auth.name`
Answer: I had the same problem and figured out a better solution. Firebase has a feature called custom claims that is meant for the use case we have. You want to set some id on a Firebase Anonymous Auth User that is accessible from database security rules.
The high-level of the solution is to make a Cloud Function that uses the admin api to set a custom claim. You can't set custom claims from the client side.
Next, call the cloud function to update the custom claim then use Auth.auth().currentUser?.getIDTokenResult(forcingRefresh: true,... in order to retrieve the updated token which includes the custom claim. This step is critical because you need your custom claim to be sent as part of every request moving forward.
If anyone actually reads this I can type up a more detailed implementation example.


Method of Characteristic and IVP

Question: Using the method of characteristic determine $u(x,t)$ when
$u_t + 2xu_x = x$ , $u(x,0)=cos (x)$.
I let $v(t) = u((x(t), t)$. I determined $v(t)$ using integration by parts. My answer for $u(x,t)$ came out to be $cos(xe^{-2t}) + \frac{x(2t-1)}{4}$. However, based on the initial condition $u(x,0)=cos (x)$, I do not think I am correct.
Can anyone help me? Thanks in advance!
Answer: It is close.  Just writing $\dot{x}=2x$, $\dot{t}=1$, $\dot{z}=x$  with $x(0)=x_0$, $t(0)=0$ and $z(0)=\cos(x_0)$, gives $u(x,t)=z(x_0,t)=\cos(xe^{-2t})+\frac{x}{2}(1-e^{-2t})$.
Comment: can you explain how you got the $\frac{x}{2}(1-e^{-2t})$ term?
Comment: Let $s$ parametrize the characteristic, then $t=s,$ $x=x_0 e^{2s}$ and $z=\frac{x_0}{2}e^{2s}+C$. For the integration constant $C$ we get the Cauchy data $C=\cos(x_0)-\frac{x_0}{2}$, therefore $u(x,t)=z(s) = \frac{x_0}{2}(e^{2t}-1)+\cos(x_0)$. It remains to find the value $x_0$ so that $(x,t)$ is on the characteristic starting at $(x_0,0)$; in our case we can use the solution $x=x_0 e^{2t}$ to find $x_0=e^{-2t}x$.

Method of Characteristic and IVP


Como faço para que o Jquery Mask não aceite números?

Question: Estou recebendo um dado que seria os três primeiros dígitos carácteres alfabéticos e os outros 4 numéricos (Uma placa de veículo).
Vi em um site que para recebermos apenas letras no Jquey Mask, basta utilizar o "A"
Exemplo:
$('.placa').mask('AAA-0000');

Mas utilizando este exemplo, o usuário pode inserir números antes do hífen sem problemas algum...
Alguém sabe como posso resolver isto?
Answer: Vou tentar deixar essa resposta bem completa já que essa pergunta é bem interessante e eu mesmo a tempos atrás estava a procura disso e creio que outras pessoas também irão procurar sobre isso.
Neste exemplo foi utilizado apenas

HTML
jQuery

Bem simples usando o plugin jQuery Masked Input, no exemplo há 3 campos, um apenas texto, outro texto e número e por fim apenas número.

$(function() {
  $('#apenasnumero').mask('(99) 9999-9999');

  $('#apenasletra').mask('aaaaaaaa');

  $('#letrasnumeros').mask('********');
});

Apenas Letras:
<input type="text" id="apenasletra" />

Letras e Números
<input type="text" id="letrasnumeros" />

Apenas Número:
<input type="text" id="apenasnumero" />

Se tiver alguma dúvida, é só comentar.


touchesBegan with physhicsBody

Question: I am creating a 2x2 matrix, and putting nodes into it. When I select a node inside a position of the matrix, he changes his color to red using the colorize action.
The problem is that if the node image is too big he'll recognize the touch even if i touch in another square of the matrix.
For example :
[0-0][0-1]
[1-0][y]

My node is in the Y square (position : 1-1). If the image is bigger than the size of the square he will get the touch even if I click on the 1-0 square.
I can't get the touch using the matrix position of the node because the image overlaps it so it never touches the matrix square.
Is there anyway I could get the touch using the PhyshicsBody of the node instead of the
let location = touch.locationInNode(self)
let node = nodeAtPoint(location)

Answer: If I understand your issue.
I understand you need paint element conform touch position.
What I do, in this example I am using Scene for reference, but you can do with others Sprite, well, I slice my screen in 4 pieces, and I got the touch point and verify position in Scene.
class test:SKScene{
    override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {
        if let touch = touches.first as? UITouch{
            let touchLocation = touch.locationInNode(self)

            if touchLocation.x < self.size.width/2 && touchLocation.y < self.size.height/2 {
                //paint red [1,0]
            }else if touchLocation.x < self.size.width/2 && touchLocation.y > self.size.height/2 {
                //paint red [0,0]
            }else if touchLocation.x > self.size.width/2 && touchLocation.y > self.size.height/2 {
                //paint red [0,1]
            }else if touchLocation.x > self.size.width/2 && touchLocation.y < self.size.height/2 {
                //paint red [1,1]
            }
        }
    }
}

Hope helped you..
Comment: Ok, I understand, but you can do other way, you can create 2 nodes, a node to add image, and a node to verify touch. or you can do some function to get id in Array of Elements like it API `func getTouchId(ids:[Int], sizeOfScene:CGRect, touchPosition:CGPoint)->Int` .. I think helped you
Comment: This helps in a way, but im actually doing a 5x9 matrix. So it will be a major work to do 45 else ifs. I dont get why the nodeAtLocation gets my Sprite over my PhyshicsBody. There isnt any way to change this behavior?
Comment: Thanks! I think that should help. But before i'll try a different aproach

touchesBegan with physhicsBody


Preprocessor macro with dot?

Question: Is it possible to define a macro that would accept expression like: object.method()? I would like to make a macro that changes that expression into... nothing (kind of deletes it). With just function() I would do: #define function (without any value) but is it possible to create a macro with dot in it?
Edit: Regarding MooingDuck's comment:
object.Method("text", "other");

Definition:
void Class::Method(std::string arg1, std::string arg2)
{
#if 0
    if (condition)
    {
        Method2(arg1, arg2);
    }
#endif
}

Disassembly:
    object.Method("text", "other");
00394396  mov         edi,5
0039439B  mov         eax,offset string "other" (396348h)
003943A0  lea         esi,[ebp-4Ch]
003943A3  mov         dword ptr [ebp-38h],0Fh
003943AA  mov         dword ptr [ebp-3Ch],ebx
003943AD  mov         byte ptr [ebp-4Ch],bl
003943B0  call        std::basic_string<char,std::char_traits<char>,std::allocator<char> >::assign (393360h)
003943B5  mov         dword ptr [ebp-4],1
003943BC  mov         edi,4
003943C1  mov         eax,offset string "text" (396350h)
003943C6  lea         esi,[ebp-30h]
003943C9  mov         dword ptr [ebp-1Ch],0Fh
003943D0  mov         dword ptr [ebp-20h],ebx
003943D3  mov         byte ptr [ebp-30h],bl
003943D6  call        std::basic_string<char,std::char_traits<char>,std::allocator<char> >::assign (393360h)
003943DB  mov         esi,10h
003943E0  mov         dword ptr [ebp-4],0FFFFFFFFh
003943E7  cmp         dword ptr [ebp-1Ch],esi
003943EA  jb          main+0B9h (3943F9h)
003943EC  mov         eax,dword ptr [ebp-30h]
003943EF  push        eax
003943F0  call        dword ptr [__imp_operator delete (3960ECh)]
003943F6  add         esp,4
003943F9  mov         edi,0Fh
003943FE  mov         dword ptr [ebp-1Ch],edi
00394401  mov         dword ptr [ebp-20h],ebx
00394404  mov         byte ptr [ebp-30h],bl
00394407  cmp         dword ptr [ebp-38h],esi
0039440A  jb          main+0D9h (394419h)
0039440C  mov         ecx,dword ptr [ebp-4Ch]
0039440F  push        ecx
00394410  call        dword ptr [__imp_operator delete (3960ECh)]
00394416  add         esp,4

Comment: This sounds like an [XY Problem](http://meta.stackexchange.com/questions/66377).  If you *did* have this macro, how/when would you be using it?
Comment: A macro name must be an identifier; it cannot include a `.` character.
Comment: @NPS: Just conditionally compile the code within said method. If the method is empty, it will be inlined away to nothing.
Comment: @NPS: Did you check in Release mode?  In debug mode, inlining is disabled.
Comment: For something like this you would use the `#ifdef`/`#endif` constructs. Using macros for this is almost certainly a bad idea (if it's even possible). What problem are you trying to solve, exactly?
Comment: For *any* named method?  Or for a specific set of named methods?
Comment: @Insilico How exactly would I use `#ifdef`/`#endif`? @DrewDormann For one specified method.
Comment: I assume In silico means you put #ifdef around the definition / implementation of the "offending" method.  I would agree with his original question... why do you want to do this?
Comment: @NPS: Take a look here for an example: http://msdn.microsoft.com/en-us/library/ew2hz0yd.aspx (scroll down a bit). Basically, it allows you to "turn off" code fragments based on the presence of a `#define`.
Comment: @Insilico I want to turn some class's methods off in Release mode but keep them on in Debug. Kind of like `assert()` but with class's methods.
Comment: @K-ballo I thought so too but checked the dissasembly and it wasn't (it still created/copied parameters and did other stuff). VS2010.
Comment: @MooingDuck Yes, I checked in Release mode.
Comment: @K-ballo: That doesn't sound right at all.  In release mode, empty functions shouldn't have that.  Are you certain that the code in the function was entirely conditionally compiled away?  Is the function virtual?  Does copying the parameters have side effects?
Comment: @MooingDuck: I believe you meant that for _NPS_, not me
Comment: @MooingDuck See the edit to my question for code samples and disassembly.
Comment: @NPS: Why does your function make copies of the strings?  I'm not good with assembly, but that looks like it's constructing the two string parameters and then destroying them both. The function has indeed been entirely compiled away.  Use `const std::string&` instead of just `std::string`, and see if that fixes the issue.
Comment: @MooingDuck Corrected it and the disassembly changed a little but the problem remains the same - the method body is gone but it does some work with the parameters. :P
Comment: Oh wait, you're right, because it's converting the string literals to `std::string` still.
Answer: Your code is:
void Class::Method(const std::string& arg1, const std::string& arg2)
{
#if 0
    if (condition)
    {
        Method2(arg1, arg2);
    }
#endif
}

But the problem is that when you call this with string literals, it's still constructing the std::string objects because the process of constructing them might have side effects.
I think I would try this, which won't do conversions until inside of the function, and thus the compiler can elide the std::string constructions as well.
template<class arg1_t, class arg2_t>
void Class::Method(const arg1_t& arg1, const arg2_t& arg2)
{
#if 0
    if (condition)
    {
        Method2(arg1, arg2);
    }
#endif
}

Comment: That works, thanks. I had different solution but this one's better as it allows only my class's methods to be ignored. But it still relies on the compiler's ability to optimize (get rid of) the methods. But that's something I won't avoid. Or will I?
Comment: There's always `#define Method(X, Y) Method`, but I REALLY don't recommend that.
Comment: @NPS http://www.parashift.com/c++-faq/inline-vs-macros.html and http://stackoverflow.com/questions/14041453/why-preprocessor-macros-are-evil-and-what-is-the-real-alternative-c11
Comment: Except for global scope of names, I don't really see why you wouldn't recommend that.
Comment: Actually your solution doesn't work for this method call: `object.Method("text", std::string("other"));` I wanted compiler to get rid of the call completely and here it wastes time on creating `std::string`. Just noticed. :P
Comment: The macro in my comment should work for that situation though
Answer: The name of the macro is an identifier. There is no way around.
Different compilers may allow different characters into identifier (like $), but none of them allow .. At the end of the day C-preprocessor was designed to be a "light preprocessor", not intended for fancy conversions like other, much more powerful preprocessors, that were existing in mid 80's.
Although you can do something like this (not really recommended):
struct DoNothing
{
    void method() { }
};

DoNothing g_inst;

#define object g_inst

Almost certainly the macro generated code will be completely removed by the optimizer. This approach is sensitive to all used names. Everything should be explicitly mentioned.

Preprocessor macro with dot?


Sending a post request with swift 3 (self-signed certificate issues)

Question: I am trying to send some data that the user will select to a mysql database on a LAMP server that is on a different network. Recently I downloaded a server on my own machine and everything was fine.  The action in the app sent to the php file which was in the server and then of course the php handled sending this to the mysql database.  Recently I was given access to a server which we will need to use.  Now when I try to do the same thing I get an error saying the certificate for this server is invalid.  I know that previously I was dealing with http and now it will need to be https, but I am not clear on how I should change this to make it work properly. I see a lot of different responses here on how to do this, but they are often countered with comments such as "This is a workaround" or "the app could be rejected" and so forth.
Here is my current function:
func sendToServer(firstEntry: String, secondEntry: String, serverAddr: String){

let uid = firstEntry
let gender = secondEntry
let request = NSMutableURLRequest(url: NSURL(string: serverAddr)! as URL)
request.httpMethod = "POST"
let postString = "UID=\(uid)&Gender=\(gender)"
request.httpBody = postString.data(using: String.Encoding.utf8)

let task = URLSession.shared.dataTask(with: request as URLRequest) {
    data, response, error in

    if error != nil {
        print("error=\(error)")
        return
    }

    print("response = \(response)")

    let responseString = NSString(data: data!, encoding: String.Encoding.utf8.rawValue)
    print("responseString = \(responseString)")
}
task.resume()

}
I read things such as not using shared here to get it to work, but I am still not quite clear on this.  All I want to do is send this data to a php located on the server.  The data itself is not sensitive, it is just simply gender and yes or no answers that get sent to a database.  However, I would need this to be secure enough where there are no attacks that effect the user experience and where it won't be rejected for this reason.  Any help here would be much appreciated.  Thanks
Answer: You need to do two things:

Add the domain exception to your plist file, I will refer you to this stackoverflow post How do I load an HTTP URL with App Transport Security enabled in iOS 9?
You need to implement your URLSessionDelegate. This one method is the bare minimum for your https request. You will find an almost exact method on URLSessionTaskDelegate, that method is for task specific authentication, this one is for session wide authentication. As you can see from the code, the crucial part is URLCredential(trust: challenge.protectionSpace.serverTrust!) where you specify that you trust that server.

    class RequestDelegate: NSObject, URLSessionDelegate {

        public func urlSession(_ session: URLSession, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Swift.Void) {
            completionHandler(URLSession.AuthChallengeDisposition.useCredential, URLCredential(trust: challenge.protectionSpace.serverTrust!))
        }
    }

Then you just make the URLSession(configuration: URLSessionConfiguration.default, delegate: RequestDelegate(), delegateQueue: nil) with your delegate as an argument
Tested and working on IOS 10.
Hope this helps, this is actually my first post on stackoverflow, so Hello World.
Comment: is it possible to elaborate a bit more please.
Comment: @nyxee where did you get stuck?
Answer: I have all this (called SSL Pinning)...
// MARK: URL session delegate
func urlSession(_ session: URLSession, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
    //Implementation 1: VERY WEAK METHOD
    /*if challenge.previousFailureCount > 0{
     completionHandler(URLSession.AuthChallengeDisposition.cancelAuthenticationChallenge, nil)
     }else{
     completionHandler(URLSession.AuthChallengeDisposition.useCredential, URLCredential(trust:challenge.protectionSpace.serverTrust!))
     }*/

    //Implementation 2:
    var disposition: URLSession.AuthChallengeDisposition = URLSession.AuthChallengeDisposition.performDefaultHandling
    var credential:URLCredential?

    if challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust {
        //certificate-based server credentials are used when verifying the server's identity
        credential = URLCredential(trust: challenge.protectionSpace.serverTrust!)

        if (credential != nil) {
            disposition = URLSession.AuthChallengeDisposition.useCredential
        }
        else{
            disposition = URLSession.AuthChallengeDisposition.performDefaultHandling
        }
    }
    else{
        disposition = URLSession.AuthChallengeDisposition.cancelAuthenticationChallenge
    }
    print("==============",#file.getClass()," ", #function,"  disposition: ", disposition)
    print("==============",#file.getClass()," ", #function,"  disposition: ", credential!)

    //completionHandler(disposition, credential);

    //Implementation 3:
    let serverTrust = challenge.protectionSpace.serverTrust
    let certificate = SecTrustGetCertificateAtIndex(serverTrust!, 0)

    // Set SSL policies for domain name check
    let policies = NSMutableArray();
    policies.add(SecPolicyCreateSSL(true, (challenge.protectionSpace.host as CFString)))
    SecTrustSetPolicies(serverTrust!, policies);

    // Evaluate server certificate
    var result = SecTrustResultType(rawValue: 0)!
    SecTrustEvaluate(serverTrust!, &result)

    let isServerTrusted:Bool = (result == SecTrustResultType.unspecified || result == SecTrustResultType.unspecified || result == SecTrustResultType.proceed)
    print("==============",#file.getClass()," ", #function,"  isServerTrusted: ", isServerTrusted)
    print("==============",#file.getClass()," ", #function,"  result: ", result.hashValue,"  SecTrustResultType.unspecified: ", SecTrustResultType.unspecified.hashValue,"  SecTrustResultType.proceed: ", SecTrustResultType.proceed.hashValue)
    var certName = ""
    if self.isSimulatingCertificateCorruption {
        certName = corruptedCert
    } else {
        certName = cert
    }

    // Get local and remote cert data
    let remoteCertificateData = SecCertificateCopyData(certificate!) as Data
    let pathToCert            = Bundle.main.path(forResource: certName, ofType: "der")
    let localCertificate      = try! Data(contentsOf: URL(fileURLWithPath: pathToCert!))
    print(" remoteCertificateData: ", remoteCertificateData,"       localCertificate: ", localCertificate, "       serverTrust: ", serverTrust.debugDescription  )

    if ( remoteCertificateData == localCertificate) { //TODO:- this is strictly for tesing puposes, to allow untrusted severs. REMOVE IN PRODUCTION.
        let credential:URLCredential = URLCredential(trust: serverTrust!)
        completionHandler(.useCredential, credential)
    }else if (isServerTrusted && (remoteCertificateData == localCertificate)) {
        let credential:URLCredential = URLCredential(trust: serverTrust!)
        completionHandler(.useCredential, credential)
    } else {
        completionHandler(.cancelAuthenticationChallenge, nil)
    }
}

will explain more if necessary.
The function is supposed to be in the Class with the URLSession. The class should extend URLSessionDelegate.
Answer: self.isSimulatingCertificateCorruption implementaion is missing.


Transforming Equations: Unable to change the equation from one form to other

Question: There is this one differentiation problem in my textbook. I solved it by using Quotient rule and the author solved it by rationalising the denominator first. Now, I have two equations (I plotted them on a graphing calculator and both have the same graph so they are essentially the same thing written in different forms). For other questions, I am able to manipulate one equation and change it to another form; however, I am unable to do this here. Could someone help?
$$\dfrac14\left(\dfrac{1}{\sqrt{x+1}}+\dfrac{1}{\sqrt{x-1}}\right)=\dfrac14\left(\dfrac{\sqrt{x+1}-\sqrt{x-1}}{-x^2+1+x\sqrt{x^2-1}}\right)$$
Comment: Please enter using MathJax. I do not see any attachment.
Comment: Sorry. Image added.
Comment: Instead of pasting an image, please take the time to enter those expressions as text using MathJax. Your question should be comprehensible with images disabled. Moreover, images are neither searchable nor accessible to screen readers. You can find a quick reference for MathJax [here](https://math.meta.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference),
Comment: @amd will surely do it next time onwards.
Comment: I have written the expressions under text form.
Answer: After some easily understood transformations, we have to prove that :
$$\dfrac{\sqrt{x+1}+\sqrt{x-1}}{\sqrt{(x-1)(x+1)}}=\dfrac{\sqrt{x+1}-\sqrt{x-1}}{-(\sqrt{(x-1)(x+1)})^2+x\sqrt{(x-1)(x+1)}},$$
Simplifying the denominators by the common factor $\sqrt{(x-1)(x+1)}$, we are reduced to prove that :
$$\sqrt{x+1}+\sqrt{x-1}=\dfrac{\sqrt{x+1}-\sqrt{x-1}}{-\sqrt{(x-1)(x+1)}+x},\tag{1}$$
which is a relationship of the form $A=\frac{B}{C}$.
Let us prove that $AC=B$ :
$$(\sqrt{x+1}+\sqrt{x-1})(-\sqrt{(x-1)(x+1)}+x)=\sqrt{x+1}-\sqrt{x-1}$$
Expanding the LHS, we get :
$$-(x+1)\sqrt{x-1}+x\sqrt{x+1}-(x-1)\sqrt{x+1}+x\sqrt{x-1}=\sqrt{x+1}-\sqrt{x-1}$$
a relationship which becomes evident by grouping terms containing $\sqrt{x+1}$ and $\sqrt{x-1}$ resp. in the LHS.
Remark : (1) could have been proved as well by using relationship :
$$x-\sqrt{x^2-1}=\left(\sqrt{\frac{x-1}{2}}-\sqrt{\frac{x+1}{2}}\right)^2$$
Comment: Thanks a lot!!! I didn't think of that denominator common factor thing.


Information geometry tutorial

Question: I would like to know more about the topic of information geometry, but i don't want to delve deeply into it. The resources i found was either too complicated or just very messy presentations like this one:
http://www.riken.jp/lab-www/theory/colloquium/amari.pdf
can someone give me some useful links for motivation and use?
Comment: Google for the following "machine learning and information geometry" (without the quotes). Seems to give some interesting hits. If those are not suitable, explain why.
Comment: My background is in machine learning, i was just curious about information geometry and how it relates to likelihood function.
Comment: What is your background? Why do you want to learn information geometry?
Answer: You can give a try to:

Information Geometry and Its Applications: An Overview
Pattern learning and recognition on statistical manifolds: An information-geometric review

Information geometry tutorial


read jSON response

Question: I am trying to read a json response from my python based backend. I am using this code for accessing the information.
URL for first call
public static final String JSON_RESPONSE_STRING="http://192.168.2.5:8000/mobile/";

URL forsecond call
public static final String PICKUP_DETAILS="http://192.168.2.5:8000/mobile/shippments/";

common method using
public static String GetJSONResponse(String stringUrl) throws IOException
    {
        StringBuilder response  = new StringBuilder();

        URL url = new URL(stringUrl);
        HttpURLConnection httpconn = (HttpURLConnection)url.openConnection();
        if (httpconn.getResponseCode() == HttpURLConnection.HTTP_OK)
        {
            BufferedReader input = new BufferedReader(new InputStreamReader(httpconn.getInputStream()),8192);
            String strLine = null;
            while ((strLine = input.readLine()) != null)
            {
                response.append(strLine);
            }
            input.close();
        }

        return response.toString();
    }

django url patterns
urlpatterns = patterns('mobile_api.views',
                       url(r'^$','login_authenticate'),
                       url(r'^shippments/(?P<id>\w+)','pickup_details'),
                       url(r'^report/post/','pickup_report')
                       )

I am using this method twice in my code. For the first time this code is working absolutely fine and parsing the json response .
When I am using this method at other place I am call it
pick_up_id=getIntent().getStringExtra("pickup_id");
        String stringUrl=Constants.PICKUP_DETAILS+"555";
        String response = null;
        try {
            response = PickupList.GetJSONResponse(stringUrl);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        //String response=GetPickUpDetails(pick_up_id);
        System.out.println("second call response"+response);

and getting this response
03-22 12:19:37.979: I/System.out(20703): second call response<!doctype html>              <meta charset="utf-8">    <title>ECOM</title>            <meta http-equiv="X-UA-Compatible" content="IE=Edge;chrome=1" >    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0">            <meta name="description" content="">    <meta name="author" content="">        <meta name="apple-mobile-web-app-capable" content="yes" />        <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent" />            <meta property="og:image" content="http://www.domain.com/images/logo.png"/>    <meta property="og:title" content="-- description here --"/>    <meta property="og:url" content="http://www.domain.com"/>            <link rel="shortcut icon" href="/static/assets/img/favicon.ico" />    <link rel="apple-touch-icon" href="/static/assets/img/apple-touch-icon.png">    <link rel="apple-touch-icon" sizes="72x72" href="/static/assets/img/apple-touch-icon-72x72.png">    <link rel="apple-touch-icon" sizes="114x114" href="/static/assets/img/apple-touch-icon-114x114.png">             <link rel="stylesheet" href="/static/assets/css/styles.css" />                              <link rel="stylesheet" href="/static/assets/css/popup.css" />

Track Shipment

          Login

          <form action="." method="POST">
<input type='hidden' name='csrfmiddlewaretoken' value='p0SPV6QzpX2nP2p588V5lDU9s9LLWZDO' />
              <input type= "text" name ="username" placeholder="Username" class="user-name"/>            <input type= "Password" name="password" placeholder="Password"/>            <input type="submit" class="button-login"/>            Forgot Your Password?          </form>

          Ecom Express News

      ×
Record

             x

P.S Also, if there is any problem with the code then why is it working for first call.
NOTE 1 Both the response are json objects I have verified several times.my backend is dJango. On hitting the url on browser I am getting the correct response in .json format
Comment: plz share Constants.PICKUP_DETAILS value
Comment: as in output currently server returning full html of Login Page. just make sure u are using right url for getting json
Comment: What url are you passing in the first time? As @ρяσѕρєяK points out, you could be using a wrong url.
Comment: You seem to be appending `555` to your url. Is that intended? Is that the same thing you do for the first call too?
Comment: @all question has been modified
Comment: have you disabled django's csrf check for your url?
Comment: @KorniltsevAnatoly u mean `@csrf_exempt` ? I am using this in views.py
Answer: check for csrf_exempt or proper permission for access to the url from app

read jSON response


Conside the topology $A = \{0\} \cup (1,2)$, then $\{0\}$ is closed or open?

Question: In Are Singleton sets in $\mathbb{R}$ both closed and open?, the best answer says that

The notion of "open" and "closed" depends on a topology you are considering.

Therefore, for example:

In $\mathbb{R}$, the singleton $\{0\}$ is closed.

Now consider the new topological space $A = \{0\} \cup [1,2]$. As in the first paragraph of wiki, the singleton {0} is an open set in the topological space $A$.
Why?  I try to answer this in two ways:

$\exists \ \ r$ such that the circle $B_r(0) \in \{0\}$, since we consider only $A$ now.
Since the complement of the open set is closed, $\{0\} = A-[1,2] = [1,2]^c$ is open.

By 1., or 2. we prove that $\{0\}$ is open in the topological space $A$.

My problem is:
If  $A = \{0\} \cup (1,2)$, then $\{0\}$ is open or closed?
From 1., it seems open; however, from 2., it seems closed. (Or the reasoning is not correct? )
Answer: I assume you mean that your set $A = \{ 0 \} \cup (1,2)$ has the subspace topology of $\mathbb R$. In which case the open sets of $A$ are the intersection of open sets in $\mathbb R$ with $A$.
More precisely, if $\tau$ is the collection of open sets of $\mathbb R$, that is the topology of $\mathbb R$, then a topology of $A$ is given by
$$\tau_A = \{ A \cap U \ : \ U \in \tau \}$$
The pairing $(A, \tau_A)$ is the set together with the topology of the set and formally comprise a topological space.
That being the case, $\{ 0 \}$ is an open set in $(A, \tau_A)$ because $\{ 0 \} \in \tau_A$. For example,
$$A \cap \left(-\frac 12, \frac 12\right) = \{ 0 \}$$
The set $(1,2)$ is another open set, as $(1,2) = A \cap (1,2) \in \tau_A$.
Last we see that since $\{ 0 \}$ is the complement in $A$ of the open set $(1,2)$, the set $\{ 0 \}$ is closed.
Comment: My question is $(1,2)$ instead of $[1,2]$, which is the case in wiki.
Comment: Corrected. None of the conclusions or logic changed.
Comment: So the conclusion is that $\{0\}$ is clopen?
Comment: Yes. $\{ 0 \}$ is closed and open in $(A, \tau_A)$.


preg_replace_callback store match in global array and replace

Question: I'm trying to compress an HTML code, but keep the style, script, pre and conditional IE untouched.
My problem is that I can't store the matches of function inside an array. I can succesfully replace the regex results, but the resulting array is empty $idarray:
function html_compress($string){

    //Substitute style, script and pre tag with unique id

    $idarray=array();

    $search=array('@))*<!\[endif\]-->@','@@','@@','@
]*>(?:[^<]+|)
@','@//<!\[CDATA\[(?:[^<]+|)//]]>@');
    $string=preg_replace_callback($search,
                                  function($m){
                                      $id=uniqid();
                                      global $idarray;
                                      $idarray[]=array($id,$m);
                                      return '<!['.$id.']!>';
                                  },
                                  $string
    );

    $search = array('/\>[^\S ]+/s','/[^\S ]+\</s','/(\s)+/s');
    $replace = array('>','<','\\1');
    $string = preg_replace($search, $replace, $string);

    //Remove blank lines
    $string=preg_replace("/(^[\r\n]*|[\r\n]+)[\s\t]*[\r\n]+/", "\n", $string);

    //Replace unique id with script, style, pre original tag
    $c=count($idarray);
    for($i=0;$i<$c;$i++){
        $string = str_replace($idarray[$i][0], $idarray[$i][1], $string);
    }

    Mage::log(print_r($idarray, true), null, 'idarray.log');

    return $string;
}

Answer: Ok, at the beginning:
global $idarray;
$idarray=array();


How to add a slideshow inside a node with Slick?

Question: I created a Content Type with an Image Field that could take multiples images.
I would like to display a slideshow of these images.
So for each node of this Content Type, I would have a different slideshow, directly inside the node.
On Drupal 7, there is the Field Slideshow module that seems to do that, but I'm on Drupal 8.
So I installed Slick Carousel and Slick Extras so I can use the formatter called Slick Image for my multiple images field.
But there are many options and I can't find the correct ones to have the slideshow working.
Here are the options :

Can anyone give me the right options ?
Answer: The problem comes from an incompatibility from the theme I use, Zircon, with Slick carousel.
The full explanation and the solution can be found here : https://www.drupal.org/node/2875173#comment-12075392
In brief, the solution is to comment the following lines in zircon.libraries.yml with the <code>#</code> sign :
<code># assets/includes/slick/slick/slick.js: {}
assets/includes/bootstrap/js/bootstrap.js: {}
assets/includes/flexslider/jquery.flexslider.js: {}
assets/includes/flexslider/jquery.flexslider-min.js: {}
assets/js/slideshow.js: {}
# assets/js/carousel.js: {}
</code>
This file is in /themes/zircon/ folder


TextBox em datagrid WPF

Question: Boa tarde, como adiciono um TextBox conforme a imagem abaixo.

Já vi alguns softwares em C#/WPF com DataGrid e filtrando desta maneira.
Answer: Existem várias soluções para o seu problema, mas na minha opinião, as melhores soluções são aquelas que usam apenas estilos com o DataGrid e controle padrão do WPF.
Algumas soluções que podem te atender:
Opção 1: Filtragem automática de DataGrid do Toolkit de WPF
Opção 2: Filtro automático para o DataGrid do Microsoft WPF
Opção 3: Filtrando o DataGrid do WPF automaticamente por meio do cabeçalho
Comment: Obrigado.
A primeira opção resolveu meu problema !
Comment: Favor ler [Queremos respostas que contenham somente links?](https://pt.meta.stackoverflow.com/q/42/75104)

TextBox em datagrid WPF


The solution of the equation $a + b \cdot k \equiv 0 \pmod{n}$ for given values $a$, $b$ and $n$ (we are looking for value $k$)

Question: I have a problem.
I looking solution of the equation $a + b \cdot k \equiv 0 \pmod{n}$ for given values $a$, $b$ and $n$ (we are looking for value $k$). $k$ is positive integer.
How can we calculate it quickly?

For example:
$a = 10554$, $b = 6370$ and $n = 16383$
Solutions:

$10554 + 6370 \cdot 2025 \equiv 0 \pmod{16383}$
$10554 + 6370 \cdot 18408 \equiv 0 \pmod{16383}$
$10554 + 6370 \cdot 34791 \equiv 0 \pmod{16383}$
$10554 + 6370 \cdot 51174 \equiv 0 \pmod{16383}$

...
General: $k = 2025 + 16383 \cdot k_2$
When solutions do not exist?
Answer: If $\gcd(b,n) = 1$, then we are guaranteed a solution, as the inverse of $b$ modulo $n$ exists. In general if $\gcd(b,n) \mid a$ then we are guaranteed a solution too, as we can get rid of the $\gcd(b,n)$ factor. Indeed the later condition is necessary too, as then $nm - bk=a$ and so $\gcd(b,n) \mid a$.
To find solutions you might use the Extended Euclidean Algorithm. It's pretty easy application and just some basica algebra.
Answer: Hint:
Consider the possible cases:

$a\equiv 0\mod \gcd(b,n)$,
$a\not\equiv 0\mod \gcd(b,n)$.

Let $d=\gcd(n,b)$. So we can write $b=dba'$, $n=dn'$,where $\gcd(b',n')=1$, and the congruence becomes
$$a+d(b'k)\equiv 0\pmod{dn'},\enspace\text{which implies  }\;a\equiv 0\mod d.$$
Thus, if $a=da'$ we can simplify the congruence to
$$a'+kb'\equiv 0\pmod{n'}.$$
Can you proceed?
Answer: As you already state, x≡2015 (mod 16383) is a solution to 6370x≡-10554 (mod 16383).
The method I used to solve the example problem may be used to solve any problem of the form a+bx≡0 (mod n). The method has two phases: the constraint generation phase and the basis conversion phase. The constraint generation phase tells us if a solution exists, no solution exists or the greatest common factor. It is possible to solve the problem via symbolic manipulation. However it may be better to solve a problem by hand using an augmente matrix representation. Furthermore, the augmented matrix representation may be used as a basis for further improving the method by using a more compact representation (such as a sparse, augmented matrix).
For more information, you can follow this think to a PDF version of this reply: https://www.academia.edu/36814068/How_I_Solved_10554_6370x_0_mod_16383_A_Reply_to_a_Question_at_Mathematics_Stack_Exchange
.
I am also including images of the pages here:


How to evaluate/calculate sums?

Question: If you have this expression,
$$x + x/2 + x/4 + x/8 + \ldots $$, it equates to roughly $2x$, why is this?
Which area of maths is this? To deal with these kind of sums, and getting a result. I am studying Computer science and we get these sequences a lot, but I struggle to evaluate them and make them equal to a smaller version. How can I get better at this?
Thanks in advance.
Comment: If you can get your hands on it, read "Concrete mathematics" by Donald Knuth and co-authors.
Comment: Perfect. This is exactly what I was looking for, what sub-topic of Maths it is so I can read on it.
Comment: You can see for yourself, surprisingly the electronic text is found in Google as a first result: https://www.google.ru/url?sa=t&source=web&rct=j&url=https://www.csie.ntu.edu.tw/~r97002/temp/Concrete%2520Mathematics%25202e.pdf&ved=2ahUKEwjB0-bnrbPeAhUB2CwKHW-AB-oQFjANegQIAhAB&usg=AOvVaw1_O9t-0tYozPRwDGqjtDWj
Comment: My day just got a lot better (and my life)! Thanks!
Answer: Rewrite the sum as$$x+\frac 12x+\frac 14x+\frac 18x+\ldots=x\sum\limits_{k\geq0}\left(\frac 12\right)^k$$The inner sum has a closed form. The proof is simple. If we let $S$ denote the result, then$$S=\sum\limits_{k\geq0}r^k=1+r+r^2+\ldots$$$$Sr=\sum\limits_{k\geq0}r^{k+1}=r+r^2+r^3+\ldots$$Subtracting the first equation from the latter gives$$S(1-r)=1\qquad\implies\qquad S=\frac 1{1-r}$$where $|r|<1$ for the series to converge. Therefore$$\begin{align*}x+\frac 12x+\frac 14x+\frac 18x+\ldots=\frac x{1-\frac 12}=2x\end{align*}$$
Comment: This is great, makes a lot of sense now. Thanks!
Answer: HINT
We have that
$$x + x/2 + x/4 + x/8 +\ldots+ x/2^n = x(1+1/2+1/4+\ldots+1/2^n)=x\sum_{k=0}^n\left(\frac12\right)^k$$
which is a geometric series.
Comment: Ok, putting it like this makes a lot of sense to me now. Factoring the x, and now you can see if you add those factors together to infinity you will get that 1, making x + 1 + 1
Comment: @AderL Indeed often write sum in compact form may help to see it better.
Comment: But I don't understand how you got to 1/2^n, do you just see that or is there a way to get it?
Comment: @AderL It can be easily shown that $1+1/2+1/4+1/8+...$ converges to $2$, take  a look to the given hint or take a look in some book about geometric series.
Comment: I can see how that converges to 2, but I don't quite how you evaluated to ... + (1 / 2) ^ n
Comment: We have $(1/2)^0=1$, $(1/2)^1=1/2$, $(1/2)^2=1/4$,...,$(1/2)^n=1/2^n$.
Answer: Notice that the sequence is in Geometric Progression where the number of terms are infinite. I hope you know the formula for finding the sum of series of an infinite GP which is $\frac a {(1-r)}$ where $a$ is the first term and $r$ is the common ratio.
Comment: @Ader you can use the above formula to see how the series converges to 2.

How to evaluate/calculate sums?


Access to the url of a node from another one

Question: I'm a bit stuck there ! here what i do :
I have two content types : Ad Lock, Ad complete.
When a user create a node Ad Lock, i use rules to clone it and then convert the original in Ad complete.
So now i have two nodes in two different content types.
Now i need to copy the url of Ad complete to fill a field in Ad Lock. Is this possible ?
Thanks in advance guys !
Answer: Ok so my mistake was : that i used a module called "url field" and it was not recognise by rule. With a normal text field i can copy the link i want


If $A$ is a bounded operator on a Banach space $X$, is there a topological decomposition $X=\mathcal N(A)\oplus_1X_2$?

Question: Let $X,Y$ be Banach spaces and $A\in\mathfrak L(X,Y)$.

Under which conditions can we show that

$X=\underbrace{\mathcal N(A)}_{=:\:X_1}\oplus_1\underbrace{(1-\pi)X}_{=:\:X_2}$ (topological direct sum) for some projection $\pi\in\mathfrak L(X)$;
$X_2$ is complete;
$\left.A\right|_{X_2}$ is bijective?

Note that if $X$ is a Hilbert space, all claims are easily established, since we can take $\pi$ as the orthogonal projection of $X$ onto $X_1$. In that case, $X_2=X_1^\perp$.
The problem with the Banach space case is that the annihilator $X_1^\perp$ is a space of functionals (which can be identified with vectors of $X$ by Riesz' representation theorem in the Hilbert space case).
Answer: Any closed subspace $X_1$ of $X$ is the null space for some bounded  linear map, e.g. the quotient map $$X\to X/X_1.$$
So the question is really whether or not every closed subspace is complemented.
A famous Theorem by Lindenstrauss and Tzafriri [1] asserts that every Banach space which is not isomorphic to a Hilbert space has a non complemented closed subspace.
On the other hand, should there be a closed subspace $X_2$ such that $X$ is the algebraic direct sum of $N(A)$ and $X_2$, then the projections onto both $N(A)$ and $X_2$ are bounded, thanks to the closed graph Theorem, and the restriction of $A$ to $X_2$ is injective.
Finally, if $A$ is surjective, then $A|_{X_2}$ is bijective, hence also an isomorphism, by the open mapping Theorem.
[1] Lindenstrauss, J., Tzafriri, L. On the complemented subspaces problem. Israel J. Math. 9, 263–269 (1971).


Does changing acoustic guitar strings require a re-setup?

Question: I'm currently using D'Addario EZ920 (0.12-0.54) and I'm planning to change to D'Addario EJ16 (0.12-0.53) which is slightly lighter. I'm wondering if this will affect the intonation and needs readjustment.
They are almost the same but in terms of diameter the EJ16 is slightly lighter.
EZ920: .012, .016, .025, .034, .044, .054
EJ16:  .012, .016, .024, .032, .042, .053
Comment: Some would say you should re-setup your instrument after 6 months, even with the same strings.  Anyway, tweaking the action, intonation (on some models), and relief does not take long, so why not?
Answer: Even though the gauges are close they are not identical. There also will likely be variances in string tension between two sets that are the same brand but different types because of materials, type of core, etc. For that reason it's a good idea to at least check the neck relief and adjust the truss rod if necessary for optimal feel.
Most acoustic guitars have fixed bridges so intonation adjustment is not an option but if it is then that should be at least checked with a tuner and adjusted as well.
Answer: I doubt whether even the most discerning player will notice the difference in feel between the two sets. The sound may be very, very slightly different, but that will mainly be due to new strings always being brighter, anyway, than the old ones just taken off.
Tension-wise, there's really no need to adjust anything, the truss rod will happily cope, and the intonation will be quite adequate. Get changing!


about $C([0,1])$ with sup metric

Question: Define the space $C([0,1])$ as the space of continuous functions $f : [0,1] \mapsto \Bbb R$ with   $C([0,1])$ $$ d(f,g) = \sup _{x \in [0,1]}{|f(x)-g(x)|} ,  $$
so  let $$A= \left\{f \in C([0,1])\ \middle| \ 0 <\int_0^1 f(x)  \ \mathrm{d}x  < 1\right\}$$  now is $A$ open , close , bounded , connect or compact ?
I think $A$ is open because for every $f \in A $ we have $B_t (f) \subseteq A $ such that $t:= 1- \int_0^1 f(x)  \ \mathrm{d}x $.(note that $B_t (f) $ is open ball with center $f$ and radios $t)$. $A$ is not close because if we let $f_n (x)= \frac{1}{n}$ then $ 0< \int_0^1 f_n(x)  \ \mathrm{d}x=\frac{1}{n} <1 $ and for every $1< n \in \mathbb{N}$ ,$  f_n(x) \in A$ and $lim_{n \to \infty} f_n(x)=0$  then $  \int_0^1 lim_{n \to \infty} f_n(x)  \ \mathrm{d}x=0  $ then
 $ lim_{n \to \infty} f_n(x) \notin A$ hence $A$ is not close and yet $A$ is not compact .
Answer: The integral function is a linear application and a member of the dual of the space $C([0,1])$ so you have that
$A=(\int_0^1dx)^{-1}((0,1))$
that it is open because it is the inverse image of an open set with respect to a continuos function.
So $A$ it is not closed because $A\neq C([0,1])$, $A\neq \emptyset$ and  $C([0,1])$ is a topological vector space and so it is connected.
$A$ it is not compact because it is not closed in $C([0,1])$
It is connected because it is a convex subset.
It is not bounded because you can choose for every $\epsilon>0$ a continuos function $f_\epsilon$ such that there exists $x\in [0,1]$ for which $f_\epsilon(x)>\epsilon$ but $0<\int_0^1f_\epsilon(x)dx<1$
Comment: We can also say that $A$ is not compact because it is unbounded. Also that if $f_n(x)=1/n$ for all $x\in [0,1]$ then the set $B=\{f_n:n\in \Bbb N \} \subset A,$ and the constant function $0$ is in $\overline B$ so $A$ is not closed...........+1
Answer: $A$ is not bounded
The piecewise linear map defined by $f_n(0)=f_n(1/n)=f_n(1)=0$ and $f_n(1/(2n))=n$ is such that $\int_0^1 f_n = 1/2$ but $d(f_n,0) = n$ is unbounded.
$A$ is connected
$A$ is connected because it is convex.
Answer: The map$$\begin{array}{rccc}I\colon&C\bigl([0,1]\bigr)&\longrightarrow&\mathbb{R}\\&f&\mapsto&\displaystyle\int_0^1f(x)\,\mathrm dx\end{array}$$is continuous. Since $A=I^{-1}\bigl((0,1)\bigr)$, $A$ is open. But $A$ is not closed, by the argument that you used. SInce it is not closed, it is not compact. But it is connected: if $f,g\in A$, just consider$$\begin{array}{rccc}\gamma\colon&[0,1]&\longrightarrow&A\\&t&\mapsto&tg+(1-t)f.\end{array}$$Then $\gamma$ is continuous, $\gamma(0)=f$, and $\gamma(1)=g$. Therefore $A$ is path-connected.
Comment: @JoséCarlosSantos José, $A$ is not bounded. See my answer.
Comment: Is $A$ bounded ?
Comment: Yes, since $A\subset D_1(0)$.
Comment: Why $A \subset D_1(0) $ ?
Comment: @mathcounterexamples.net You're right. My mistake.

about $C([0,1])$ with sup metric