Trying to form array of callback results from multiple sources of $.getJSON()

Question: The code will process an array of calls from darkForecastAPIArray[] which go into the $.getJSON() but it will only return a single callback after processing the other calls indexed into the $.getJSON(). So after the code block is done I cannot get each instance of API requests into the array where it says APIResults.push(), it finishes the calls before it reaches the array and then it leaves only one callback on return. Any suggestions how to get all calls from the "result" into the following APIResults[] array? The whole script works somewhat like a form of indexing multiple JSON pages then placing them into an array to read each page of JSON. To simplify it appears to be finishing the $.getJSON method scope then do the callback once.
$.each(numDaysAPITimes, function(a, time) {
    darkForecastAPIArray.push(darkForecastAPI = /*"http://api.wunderground.com/api/" + currentAPIKey + "/history_" + time + "/q/" + state + "/" + city +".json?callback=?"; */
        "http://api.forecast.io/forecast/" + currentAPIKey + "/" + city + time + "?callback=?");
    console.log(darkForecastAPI);
});
//https://api.forecast.io/forecast/APIKEY/LATITUDE,LONGITUDE,TIME
//$.each(darkForecastAPIArray, function(b, APICallRequest) {
    var deferreds = $.map(darkForecastAPIArray, function(url, index) {
        return $.getJSON(url, {
            tags: "WxAPI[" + index + "]",
            tagmode: "any",
            format: "json"
        });
    });
    $.when.apply($, deferreds).then(function(results) {
        $.each(results, function(index, data) {
            // do something

    APIResults.push(data);
    console.log(index);
    console.log(data);

        for (c = 0; c <= data.daily.data.length - 1; c += 1) {
            if (data.daily.data[c].precipIntensity >= 0.0000 && data.daily.data[c].precipType === "rain") /*Number(result.history.dailysummary.precipm, result.history.dailysummary.rain*/ {
                eachPrecipSum = data.daily.data[c].precipIntensity;
                totalPrecipSinceDate = eachPrecipSum + totalPrecipSinceDate; ///Write mean precip
                alert(Math.round(eachPrecipSum * 10000) / 10000);
                $("body").append("p").text("There has been as least a total of " + Math.round(totalPrecipSinceDate * 10000) / 10000 + " inches per hour of rain at the location in the last " + userDataDatePick + " days");

            } else if (data.daily.data[c].precipIntensity >= 0.0000 && data.daily.data[c].precipType !== "rain") {
                alert("There is was no rain on ____" /*+ result.history.dailysummary.mon + "/" + result.history.dailysummary.mday + "/" + result.history.dailysummary.year*/ );
              }
        }
    });
         });

numDaysAPITimes = 0;
}

Comment: I would recommend looking in to jQuery deferreds and [$.when](https://api.jquery.com/jquery.when/) - or, what you could do is keep a count of json loaded/failed and when it reaches the length of your url array then call a method to go over each API Result, instead of on each callback since you are appending results each time.
Comment: http://stackoverflow.com/questions/6538470/jquery-deferred-waiting-for-multiple-ajax-requests-to-finish
Comment: I have looked into $.When some and deferreds. I am not experienced much with either, When I did `$.when.apply($, [APIcollection]).then(function(results))` it would still yield one correct array then make three others after putting them in a `collection.push($.getJSON())`. The deferreds are a little complicated. I am not sure how those work and have not found a decent example to explain it yet.
Comment: I did this before: ` JSONAPIS.push($.getJSON(darkForecastAPI, {
            tags: "WxAPI[" + i + "]",
            tagmode: "any",
            format: "json",

          }));
    });
    $.when(JSONAPIS).done(function(result) {`
Comment: when you do it that way you need to do a couple things. First, try `$.when.apply($, JSONAPIS) //...` and then expect that your `arguments` list passed to the done function will have one entry for each ajax item you loaded. This can be seen in the examples on https://api.jquery.com/jquery.when/
Comment: I edited my code sample. It currently gets only one correct array object as before. It seems to finish the scope where it says $.getJSON() first then add the callback/when function with one.... still thinking.
Answer: You are on the right track in your comment about using this recipe. Something like this should work:
var deferreds = $.map(urlArray, function(url, index) {
    return $.getJSON(url, {
        tags: "WxAPI[" + index + "]",
        tagmode: "any",
        format: "json"
    });
});
$.when.apply($, deferreds).then(function(results) {
    $.each(results, function(index, data) {
         // do something
    });
 });

Comment: The data parameter in this $.each callback is your callResult above, so I don't think you need your "$.each(APIResults...)" call.
Comment: Do you think I could bypass the $.getJSON statement entirely and use a when with the API_URLs then return the JSON? There is no other way to format JSON to a variable context?
Comment: I tried what you said. I will edit my post again. The result was one correct dataset then a "success" object followed by an array object full of references to the obejct but not the API call data.
Comment: By API call data, do you mean the list of urls? You want to match those to the results? You could "zip(darkForecastAPIArray, results)" where zip is something like this: https://stackoverflow.com/questions/4856717/javascript-equivalent-of-pythons-zip-function
Comment: Or just to darkForecastAPIArray[index] in this case.
Comment: I meant the JSON that returns from the $.getJSON(//with API url) result. IS zip a custom function then? Would this be a callback?.... I am sorry I need to turn in for the night and will continue tomorrow.
Comment: results should be an array of the json returned by each $.getJSON call.
Comment: Yes. But I get the $.getJSON() success object and another one I don't know what with the results array which is meant for the JSON. I will have to think about the zip() method tomorrow.
Comment: This is an idea: `var deferreds = $.map(darkForecastAPIArray, function(url, index) {
        return $.getJSON(url, {
            tags: "WxAPI[" + index + "]",
            tagmode: "any",
            format: "json"
        });
    });
    for(f = 0; f <= deferreds.length - 1; f += 1)
     {
        $.when.apply(deferreds[f]).then(function(result)
            {
               console.log(result);
                $.each(results, function(index, data) {
                    // do something`
Comment: Added a `for()` loop to try to get each deferred to process in the `$.when.apply().done()` but it gives me some issues like "undefined". Do you think this could be made to work?
Answer: SOLUTION:
Instead of using the loops that come with basic computer snippets I made a function level for() loop to solve the problem and broke the sections of code down into several functions. The functional level for() loop increments as each API call was made until it meets the number of elements. The function I simply named function done() {} The typical for() loop will terminate at its given scope so this one is unique and integrates the multiple callbacks which otherwise could not be used by using an array or deferred since deferreds or $.when() does not return multiple form arrays properly but with extraneous information that is hard to parse out.
Here is the code:
function searchRainPrecip() {

            //.......more code........//

    $.each(numDaysAPITimes, function(a, time) {
        darkForecastAPIArray.push(darkForecastAPI = /*"http://api.wunderground.com/api/" + currentAPIKey + "/history_" + time + "/q/" + state + "/" + city +".json?callback=?"; */
            "http://api.forecast.io/forecast/" + currentAPIKey + "/" + city + time + "?callback=?");
     //   console.log(darkForecastAPI);
    });
    //https://api.forecast.io/forecast/APIKEY/LATITUDE,LONGITUDE,TIME
          getDataCallbackResults();
    }

function getDataCallbackResults() { //call this function in loop for each call
    console.log(darkForecastAPIArray[z]);
    console.log(z);
    APIinstance = darkForecastAPIArray[z];
    $.getJSON(APIinstance, {
            tags: "WxAPI[" + f + "]", //Is this tag the name of each JSON page? I tried to index it incase this is how to refer to the JSON formatted code from the APIs.
            tagmode: "any",
            format: "json"
        },
        function(results) {
        APIResults.push(results);
        console.log(results.daily.data.length);
          processAPIPage(results);

        });
}

function processAPIPage(results) {
            for (c = 0; c <= results.daily.data.length - 1; c += 1) {
                if (results.daily.data[c].precipIntensity >= 0.0000 && results.daily.data[c].precipType === "rain" && results.daily.data[c].time <= unixEpoch) /*Number(result.history.dailysummary.precipm, result.history.dailysummary.rain*/ {
                    eachPrecipSum = results.daily.data[c].precipIntensity;
                    console.log(eachPrecipSum);
                    totalPrecipSinceDate = eachPrecipSum + totalPrecipSinceDate; ///Write mean precip
                    alert(Math.round(eachPrecipSum * 10000) / 10000);
                    d = new Date(results.daily.data[c].time * 1000); //Convert to UTC  ~ SAVE FOR OTHER API SERVICES THAT USE UTC ~
                    curr_date = ("0" + d.getDate()).slice(-2);
                    curr_month = ("0" + (d.getMonth() + 1)).slice(-2); //Months are zero based
                    curr_year = d.getFullYear();
                    console.log(d.getMonth());

                    $("body").append("p").text("There has been as least a total of " + Math.round(totalPrecipSinceDate * 10000) / 10000 + " inches per hour of rain at the location in the since " + curr_month.toString() + "/" + curr_date.toString() + "/" + curr_year.toString());

                } else if (results.daily.data[c].time > unixEpoch) {
                    console.log(results.daily.data[c].time + " > " + unixEpoch);
                } else if (results.daily.data[c].precipIntensity >= 0.0000 && results.daily.data[c].precipType !== "rain" && results.daily.data[c].time <= unixEpoch) {
                    //Also can be named backDateEpochTime to convert next line; Get each day (UNIX seconds)
                    d = new Date(results.daily.data[c].time * 1000); //Convert to UTC  ~ SAVE FOR OTHER API SERVICES THAT USE UTC ~
                    curr_date = ("0" + d.getDate()).slice(-2);
                    curr_month = ("0" + (d.getMonth() + 1)).slice(-2); //Months are zero based
                    curr_year = d.getFullYear();
                    console.log(d.getMonth());

                    alert("There is was no rain on " + curr_month.toString() + "/" + curr_date.toString() + "/" + curr_year.toString());
                }
            }

    numDaysAPITimes = 0;
    result = null;
    done();
}

function done(){
//Global Function level for() loop or get point loops
    z += 1;
    if (z <= darkForecastAPIArray.length-1)
    {
    getDataCallbackResults()
    }
    else
    {
    console.log("All calculations complete.");
    }
}


Distribution of difference between two normal distributions

Question: I have two probability density functions of normal distributions:
$$f_1(x_1 \; | \; \mu_1, \sigma_1) = \frac{1}{\sigma_1\sqrt{2\pi} } \; e^{ -\frac{(x-\mu_1)^2}{2\sigma_1^2} }$$
and
$$f_2(x_2 \; | \; \mu_2, \sigma_2) = \frac{1}{\sigma_2\sqrt{2\pi} } \; e^{ -\frac{(x-\mu_2)^2}{2\sigma_2^2} }$$
I'm looking for the probability density function of the separation between $x_1$ and $x_2$. I think that means I'm looking for the probability density function of $|x_1 - x_2|$. Is that correct? How do I find that?
Comment: Also, I don't wanna be "that guy" but did you try Google? "Difference between normal distributions" found me an answer pretty much right away.
Comment: If this is homework please use the `self-study` tag. We accept homework questions, but we handle them a little differently here.
Comment: @ssdecontrol no, not homework, but it is for a hobby project, so I don't mind having to find out some stuff myself if I'm put on the right track. I did try google, but my grasp on the matter is so limited that I probably wouldn't recognize it if it was right in front of me. with quotes I found lots of stuff similar to "what's the difference between a normal distribution and x" for some x.
Answer: This question can be answered as stated only by assuming the two random variables $X_1$ and $X_2$ governed by these distributions are independent.  This makes their difference $X = X_2-X_1$ Normal with mean $\mu = \mu_2-\mu_1$ and variance $\sigma^2=\sigma_1^2 + \sigma_2^2$.  (The following solution can easily be generalized to any bivariate Normal distribution of $(X_1, X_2)$.) Thus the variable
$$Z = \frac{X-\mu}{\sigma} = \frac{X_2 - X_1 - (\mu_2 - \mu_1)}{\sqrt{\sigma_1^2 + \sigma_2^2}}$$
has a standard Normal distribution (that is, with zero mean and unit variance) and
$$X = \sigma \left(Z + \frac{\mu}{\sigma}\right).$$
The expression
$$|X_2 - X_1| = |X| = \sqrt{X^2} = \sigma\sqrt{\left(Z + \frac{\mu}{\sigma}\right)^2}$$
exhibits the absolute difference as a scaled version of the square root of a Non-central chi-squared distribution with one degree of freedom and noncentrality parameter $\lambda=(\mu/\sigma)^2$.  A Non-central chi-squared distribution with these parameters has probability element
$$f(y)dy = \frac{\sqrt{y}}{\sqrt{2 \pi } } e^{\frac{1}{2} (-\lambda -y)} \cosh \left(\sqrt{\lambda y} \right) \frac{dy}{y},\ y \gt 0.$$
Writing $y=x^2$ for $x \gt 0$ establishes a one-to-one correspondence between $y$ and its square root, resulting in
$$f(y)dy = f(x^2) d(x^2) = \frac{\sqrt{x^2}}{\sqrt{2 \pi } } e^{\frac{1}{2} (-\lambda -x^2)} \cosh \left(\sqrt{\lambda x^2} \right) \frac{dx^2}{x^2}.$$
Simplifying this and then rescaling by $\sigma$ gives the desired density,
$$f_{|X|}(x) = \frac{1}{\sigma}\sqrt{\frac{2}{\pi}} \cosh\left(\frac{x\mu}{\sigma^2}\right) \exp\left(-\frac{x^2 + \mu^2}{2 \sigma^2}\right).$$

This result is supported by simulations, such as this histogram of 100,000 independent draws of $|X|=|X_2-X_1|$ (called "x" in the code) with parameters $\mu_1=-1, \mu_2=5, \sigma_1=4, \sigma_2=1$.  On it is plotted the graph of $f_{|X|}$, which neatly coincides with the histogram values.

The R code for this simulation follows.
#
# Specify parameters
#
mu <- c(-1, 5)
sigma <- c(4, 1)
#
# Simulate data
#
n.sim <- 1e5
set.seed(17)
x.sim <- matrix(rnorm(n.sim*2, mu, sigma), nrow=2)
x <- abs(x.sim[2, ] - x.sim[1, ])
#
# Display the results
#
hist(x, freq=FALSE)
f <- function(x, mu, sigma) {
 sqrt(2 / pi) / sigma * cosh(x * mu / sigma^2) * exp(-(x^2 + mu^2)/(2*sigma^2))
}
curve(f(x, abs(diff(mu)), sqrt(sum(sigma^2))), lwd=2, col="Red", add=TRUE)

Comment: @user77005 The answer to that is in my post: it's a non-central chi-squared distribution.  Follow the link for details.
Comment: How would this be different if I want to get the squared difference? For example if I want $(f_1(.) -f_2(.))^2$?
Answer: I am providing an answer that is complementary to the one by @whuber in the sense of being what a non-statistician (i.e. someone who does not know much about non-central chi-square distributions with
one degree of freedom etc) might write, and that a neophyte could
follow relatively easily.
Borrowing the assumption of independence as well as the notation from  whuber's answer, $Z = X_1-X_2 \sim N(\mu, \sigma^2)$ where $\mu = \mu_1-\mu_2$
and $\sigma^2 = \sigma_1^2+\sigma_2^2$. Thus, for $x \geq 0$,
\begin{align}
F_{|Z|}(x) &\triangleq P\{|Z| \leq x\}\\
&= P\{-x \leq Z \leq x\}\\
&= P\{-x < Z \leq x\} &\scriptstyle{\text{since}~Z~\text{is a continuous random variable}}\\
&= F_Z(x) - F_Z(-x),
\end{align}
and of course, $F_{|Z|}(x) = 0$ for $x < 0$.
It follows upon differentiating with respect to $x$ that
\begin{align}f_{|Z|}(x) &\triangleq \frac{\partial}{\partial x}
F_{|Z|}(x)\\
&= [f_Z(x) + f_Z(-x)]\mathbf 1_{(0,\infty)}(x)\\
&= \left[ \frac{\exp\left(-\frac{(x-\mu)^2}{2\sigma^2}\right)}{\sigma\sqrt{2\pi}}
+ \frac{\exp\left(-\frac{(x+\mu)^2}{2\sigma^2}\right)}{\sigma\sqrt{2\pi}}\right]\mathbf 1_{(0,\infty)}(x)\\
&=  \frac{\displaystyle\exp\left(-\frac{x^2+\mu^2}{2\sigma^2}\right)}{\sigma\sqrt{2\pi}}\left(\exp\left(\frac{x\mu}{\sigma^2}\right)
+ \exp\left(\frac{-x\mu}{\sigma^2}\right)\right)\mathbf 1_{(0,\infty)}(x)\\
& = \frac{1}{\sigma}\sqrt{\frac{2}{\pi}} \cosh\left(\frac{x\mu}{\sigma^2}\right) \exp\left(-\frac{x^2 + \mu^2}{2 \sigma^2}\right)\mathbf 1_{(0,\infty)}(x)
\end{align}
which is the exact same result as in whuber's answer, but arrived at
more transparently.
NOTE: Missing Neg Sign added to 2nd to Last Line - 2021/04/23
Comment: +1 I always like to see solutions that work from the most basic possible principles and assumptions.
Answer: The distribution of a difference of two normally distributed variates X and Y is also a normal distribution, assuming X and Y are independent (thanks Mark for the comment). Here is a derivation:
http://mathworld.wolfram.com/NormalDifferenceDistribution.html
Here you are asking the absolute difference, based on whuber's answer and if we assume the difference in mean of X and Y is zero, it's just a half normal distribution with two times the variance (thanks Dilip for the comment).
Comment: In addition to the assumption pointed out by Mark, you are also ignoring the fact that the means are different. The half normal case works only when $\mu_1 = \mu_2$ so that the difference has mean $0$.
Comment: You and Wolfram Mathworld are implicitly assuming that the 2 normal distributions (random variables) are independent. The difference is not even necessarily normally distributed if the 2 normal random variables are not bivariate normal, which can happen if they are not independent..
Comment: Thank you for your comments. Now I revised my answer based on your comments and whuber's answer.


Normal and central subgroups of finite $p$-groups

Question: Suppose $G$ is a group where $|G| = p^k$ where $p$ is a prime and $k\gt 0$.  Prove that

$|Z(G)| \gt 1$; and
If $N$ is a normal subgroup of $G$ of order $p$, then $N$ is contained in $Z(G)$.
Comment: Welcome to MathSE. I see that this is your first question. So I wanted to let you know a few things about MathSE. We like to know the sources of questions. We also like to know what you've tried on a problem or what your thoughts are, so that the answer does not re-invent the wheel. Also, many users find questions posted in the imperative ("Show that", "Prove", "Do") unpleasant and somewhat rude. These sort of pleasantries usually result in more and better answers. Thank you!
Comment: Dear Connie, could you please read [this](http://meta.math.stackexchange.com/questions/1803/how-to-ask-a-homework-question)? Thanks,
Answer: For 1, use the Class Equation.
For 2, use the Class Equation (if $N$ is normal, then it must be a union of conjugacy classes; conjugacy classes have either order $1$, or order a power of $p$; but $N$ contains at least one conjugacy class of order $1$, hence...)
Answer: Here's the way I'd like to think about it, but it could be just a rewording of what has already been said. Using the orbit stabilizer theorem one can prove that if $G$ is a finite $p$-group acting on a finite set $X$ then $\#(X^G)\equiv \#(X)\text{ mod }p$ where $X^G$ denotes the set $\{x\in X:gx=x\text{ for all }g\in G\}$ of fix points.
So, let $G$ be a finite $p$-group and $N\unlhd G$ be nontrivial. Let $G$ act on $N$ on by conjugation. By the above we see that $\#(N^G)\equiv |N|\text{ mod }p$. But, since $p\mid |N|$ (since it's a nontrivial subgroup of a finite $p$-group) this implies that $p\mid \#(N^G)$. But, write it out and see that $N^G=N\cap Z(G)$ and so this prove that $p\mid |N\cap Z(G)|$ for any nontrivial normal subgroup $N$ of $G$, and so in particular, $N\cap Z(G)$ is nontrivial. Taking $N=Z(G)$ gives 1. immediately. It also gives 2. with a little thought, since we know that $p\mid |N\cap Z(G)|$ and $|N\cap Z(G)|\leqslant p$ we must have that $|N\cap Z(G)|=p$ and so clearly $N\cap Z(G)=N$ and so $N\subseteq Z(G)$.
Answer: This follows directly from the class equation. Since the order of $G$ is a prime power, all of its conjugacy classes are of prime power order. Remember that the center of the group consists entirely of the singleton conjugacy classes (the classes of size $1$). If the center was trivial, the class equation would be $1$ plus positive prime powers. So we would have $1+p(\mathrm{something})=p^k$. This implies that $1=0$ mod $p$ (contradiction). Therefore, the center must contain more than one element.
By a similar line of reasoning, a normal subgroup consists of entire conjugacy classes unioned together (since $N$ is closed under conjugation, if part of a conjugacy class is in $N$, then the whole class must be in $N$). Since conjugacy classes have prime power cardnalities, the identity is in $N$ (whose class has size 1), and $|N|=p$, we have that all of the remaining classes are prime powers smaller than $p$. Thus $N$ is the union of classes of size 1. These are precisely elements of the center.
Answer: Do you know the class equation? Define an action of the group on itself by conjugation:
$$G\times G\to G\,\,,\,\,g\cdot x:=x^g:=g^{-1}xg$$
Now, under this action, we get
$$\forall\,\,x\in G\,\,,\,\mathcal O(x):=\{x^g\;:\;g\in G\}\,\,,\,Stab(x):=\{g\in G\;:\;x^g=x\}=C_G(x)$$
Well, now just use the basic lemma $\,|\mathcal O(x)|=[G:Stab(x)]\,$ and , of course, the fact that $\,G\,$ is a $\,p-\,$group...


How do I debug an IIS problem where the requests queued suddenly ramps up and the server can't respond?

Question: I have an IIS 6 server serving an application using a mix of classic ASP and ASP.NET.
I'm increasingly getting problems where the number of requests in the ASP.NET requests queue (observed using the ASP.NET\Requests Queued counter) starts to increase to a point where the server can no longer service the requests. That happens a three or four minutes  from the point where queued requests starts increasing. Recycling the application pool restores service.
Normally, requests queued is zero and occasionally there'll be small spikes but it seems that once or twice a day, a number of requests are blocking the queue and queued requests starts to increase.
I suspect there are network problems causing clients to lose their connection (and re-submit their request) and the requests in the queue continue despite losing their client.
How can I diagnose the problem? Can I look at the status of requests in the queue? Do I need the MS Debug Diagnostic Tool or one of these tools?
Comment: Do you know how many requests/sec you're servicing before this starts happening?
Comment: A maximum of 6 requests/sec, averaging around 1 request/sec (from the ASP.NET Applications(__Total__)\Requests/Sec counter)
Answer: I've discovered that the MS Trace Diagnostics tool (IISReqMon) from this list of "Useful tools and add-ons for IIS troubleshooting and IIS7" will give me information about the current worker processes and their requests in an application pool.
Answer: Not much help in debugging, but I would suspect a deadlock in code rather than network as IIS is pretty well debugged as far as connectivity. I would not expect it to fail like that.
I'm guessing your site has got busier of late, hence the deadlock issues.


Twiml Connect method issue

Question: So i'm trying to make it so an outbound call gets redirected to my Autopilot system, but my Twiml does seem to recognize the connect function built into the voice response method
I've tried to have the account sid be provided, call, and even load the link in a browser, it just gives the same error
Heres the code im using
exports.handler = function(context, event, callback) {
    let res = new Twilio.twiml.VoiceResponse();
    console.log(res.toString());
    res.connect().autopilot(context.AI_SID);
    console.log(res.toString());
    callback(null, res);
};

It should return the code below, but seems like this doc is not accurate: https://www.twilio.com/docs/voice/twiml/connect
<Response>
  <Connect>
    <Autopilot>#####</Autopilot>
  </Connect>
</Response>

Answer: Update the Twilio helper libraries under your Twilio Functions, Configure, to use a release that added this verb.
https://github.com/twilio/twilio-node/blob/master/CHANGES.md
Comment: Oh, perfect, thank you! I was using verion 3.6.3, the default version when u open an account, i've been way out of date. Thank you very much :)

Twiml Connect method issue


ORM for SQLite in iOS

Question: I am trying to convert a C# application we had developed to an iPad application. As we developed the app with Entity framework, I am looking for a counterpart for iOS.
According to this answer, there are several ORM libraries for SQLite in iOS:

FMDB
chibi-ORM
sqlitepersistentobjects

But after reading each of the web sites, I still can't decide which package to use. Can anybody who has experience with one of them tell me advantages/disadvantages of the packages?
Comment: Did you look into Core Data? http://developer.apple.com/library/ios/#documentation/DataManagement/Conceptual/iPhoneCoreData01/Introduction/Introduction.html
Comment: if you are going to redesign the database I agree with @SB., you should try Core Data, but if you plan to use the same database (or database structure) from the libraries that you mention I have worked with fmdb with pretty good results, it is fast and easy to use (I haven't tested the other ones)
Comment: I would NOT recommend CoreData, it's painful to discover you cannot make complex queries with it. We have lost several days of work after achieving this.
Comment: @tkanzakic Thanks for your great tip. Redesigning database is the last thing we want to do as we already have existing database from current C# application.
Comment: @SB I looked into it but many people say that it is not ORM so I kind of stayed away from it so far.
Comment: @Tae-SungShin try this https://github.com/LakithaRav/OLCOrm
Answer: UPDATE: DBAccess has now been replaced by the open source ORM Shark.
We have recently released a free to distribute and use ORM for Objective-c / iOS called DBAccess, which can be downloaded from http://db-access.org/, it has taken several years to develop and has now been deployed within many applications.
It may not be for everyone, but I hope our effort will help some in the community.
NOTE, I have been alerted to the fact that it is bad form to promote your own products in a forum such as this, but I just wanted to add that I am only posting this in answer to the OP because I feel it does bring something useful to the table and I sincerely hope it will prove helpful to some people, even if it's not for everyone.
UPDATE: DBAccess has now been replaced by the open source ORM Shark.  It is API compatible, and is available on github.  http://sharkorm.com and https://github.com/sharksync/sharkorm
Thanks Adrian_H
Comment: What's the license for your project? I'm a bit leery to try it without knowing what I'm getting myself into :).
Comment: Hi Max, we are going for the MIT license. It seemed the easiest and most applicable for our wishes.
Comment: Hi Adrian, is there any guide for upgrading table? Like adding, renaming, removing field from table?
Comment: Hi Tek, the database is modelled from the classes, so if you add a new property to a class it automatically gets added to the table, and the same with removing a property.  Renames will create a new column and remove the old one.  If you send me your email address I can email you a category that exposes the upgrade mechanism which is not yet finished, which will enable you to migrate data from deleted columns.
Comment: @Adrian_H I know this thread is a bit old but I'm wondering if this can be used for FTS (Full Text Searching).... If yes, how can I get a guide?
Comment: @ragingprodigy, there is no support for SQLite's implementation of FTS in DBAccess atm, although it sounds like a good idea and if you email us we will keep you posted on progress.  In theory it should be something nice and quick to implement.  We would like to discuss how we would go about implementation with people to make sure we understand the requirements.  It would be a nice, differentiating, feature.
Answer: I've dealt with the limited number of ORMs for quite some time, and I finally did something to improve the limited options available. I've written an ORM and released it under a BSD license for everyone to use. It's posted on GitHub.
Answer: The best way to convert an c# app to iOS is Xamarin i think, there is a library sqlite-net , works good.

ORM for SQLite in iOS


If $p\equiv 1\pmod{8}$, then $-1$ is fourth power?

Question: I know that $-1$ is a square modulo $p$ iff $p\equiv 1\pmod{4}$. Curious about this, I'm trying to show that $-1$ is a fourth power if and only if $p\equiv 1\pmod{8}$, for $p$ odd.
I know that if $a^4\equiv -1\pmod{p}$ for some $a$, then
$$
(-1)^{(p-1)/4}\equiv (a^4)^{(p-1)/4}\equiv a^{p-1}\equiv 1\pmod{p}.
$$
So since $p$ is odd, $(-1)^{(p-1)/4}=1$, so $(p-1)/4$ is even, and thus $p\equiv 1\pmod{8}$.
How can the converse be shown? I was trying to break $(p-1)!$ into a power of $4$, by grouping the factors together without success. Thanks.
Answer: This is a direct consequence of the following more general result.
Theorem: Let $m$ be a positive integer that has a primitive root, and suppose that $\gcd(a,m)=1$. Then the congruence $x^k\equiv a\pmod{m}$ has a solution if and only if
$$a^{\varphi(m)/\gcd(\varphi(m),k)}\equiv 1\pmod {m}.\tag{$1$}$$
To prove the result, let $g$ be a primitive root of $m$, and let $d=\gcd(\varphi(m),k)$. Taking indices with respect to $g$, we see that the congruence $x^k\equiv a\pmod{p}$ holds iff
$$k\,\text{ind}\, x\equiv \text{ind}\,a \pmod{\varphi(m)}.\tag{$2$}$$
The linear congruence $(2)$ has a solution for $\text{ind}\,x$ iff $d$ divides $\text{ind}\, a$.
To complete the proof, we show that $(1)$ holds iff $d$ divides $\text{ind}\,a$.
By taking indices, we can see that $(1)$ is equivalent to $\frac{\varphi(m)}{d}\text{ind}\, a\equiv 0\pmod {\varphi(m)}$. This holds iff $d$ divides $\text{ind}\,a$.
Comment: Thanks André, what does it mean to "take indices?"
Comment: Let's take your case, $m=p$. Let $g$ be a primitive root of $p$. Let $b$ be relatively prime to $p$. Then since $g$ is a generator, there is a unique $k\lt p-1$ such that $b\equiv g^k \pmod{p}$. This $k$ is called the index of $b$. It behaves like the logarithm. "Take indices" means take the discrete logarithm of both sides.
Comment: I understand now. Thanks again!
Answer: You can also use the fact that the multiplicative group of a finite field is cyclic (not difficult to prove directly, but proofs can be found in many textbooks, for example "Topics in Algebra" by Herstein). Let $a$ be an element of (multiplicative) order $p-1$ in the field $\mathbb{Z}/p\mathbb{Z}$. Then if $p \equiv 1 $ (mod 8), we see that $b = a^{\frac{p-1}{8}}$ is an element of (multiplicative) order $8$ in $\mathbb{Z}/p\mathbb{Z}$. Then $c = b^{4}$ satisfies $c^{2} = 1 \neq c,$ and so $c = -1,$ which has also been expressed as the fourth power of $b.$
Comment: I'm aware of that result, but hadn't thought to use it like this. Very nice, thanks.


Power analysis without a prior and for observational data

Question: I am trying to develop the design for an observational study, but I am struggling with the number of observations that would allow us to estimate our model and generalize its results. As a dependent variable, we have a score of a psychological structure (varies between 1-100), and we have two families of predictors:

Measurements of other psychological factors.
Socio-economic controls.

We will probably be going to explore different specifications for the dependent variable (enter it as it is, enter it as a dummy variable for whether a person is placed among the highest 25 percentile of the distribution, etc.).
A popular thumb rule for deciding the required number of observations is the one-in-ten rule (or one of its variations), but it seems to better fit a classification problem, and even worse, oversimplistic. I came across this article, that presents a more scientific method, but it refers mainly to linear models with priors for the sizes of the expected coefficients.
Our main goal in this part of our research is to find which variables have the strongest predictive powers for $y$. We will have about ~50 predictors, and for most of them, we don't have any prior (there is no other article that correlated these measurements).
Is there any method to simulate the number of required observations under observational study, that does not require priors on the coefficients?
Thanks!
Answer: See these two articles (choose which one depending on the nature of your outcome variable) https://onlinelibrary.wiley.com/doi/abs/10.1002/sim.7993 and https://onlinelibrary.wiley.com/doi/10.1002/sim.7992
Note that power is almost irrelevant in this context.
Comment: Hi, thanks for your answer. I am pretty new to power analysis and did not learn it in a class. Why isn't power relevant in this context? We want to make sure we would be able to consistently measure the parameters in the model.
Thanks again!
Comment: It does depend on the ultimate goal.  If you are interested in the adjusted effect of a single special variable then power can be relevant, although IMHO precision is a better basis for sample size assessment (i.e., margin of error; width of key confidence interval).   If you are interested in developing a prediction model or are interested in many variables at once then the two references I provided are more relevant.
Comment: Thank you very
 much, sir.
Comment: On this site thanks is not expressed in a comment but rather by upvoting.


Include files used by multiple modules

Question: I have some include files (.inc) that have classes in them that are used by multiple modules. Where should these be stored so that they are accessible to files[] in a modules .info file? Preferably without having to store copies of the files in each modules directory.
Answer: Probably the sanest way to do this would be to create a new module which has little to no functionality, but includes the .inc files; then make your other modules dependent on that module. As you develop the other modules and find other functionality you want to share between them, just implement it in the "parent" module, and away you go.
If adding another module is objectionable for some reason, you could implement it as a "library" and use the Libraries API module - but that's intended for Drupal-external third-party PHP libraries like TinyMCE, not things you've built yourself.
Comment: This is fine, I can see how that would work, but it seems silly to have to create a module that's only purpose is to serve as a wrapper for my classes. Can a modules .info files[] option only look inside that modules directory for files? Or can it look elsewhere?
Comment: It will only find include files within the module directory itself (even if that's not technically true, that is the convention). And at any rate, this sort of thing is not unprecedented; for example, the Token module doesn't really do anything by itself, but provides functionality for other modules that depends on it.
Comment: If adding a new module is something you really want to avoid, you could also implement it as a library; I added another paragraph to my answer about that. I think the module approach makes more sense for your own code, though.
Comment: Libraries API is intended for _any_ 3rd party library. Who's to say I didn't write TinyMCE myself, for example? ;)
Comment: Hehehe, I definitely did not write TinyMCE. But as an addition to this line of thinking. If I do go the way you are suggesting, creating a module for this purpose. Do I even need to write a .module file for it? If the entire purpose is just to provide a link to the .inc files using the .info files[] declaration? And if so, what exactly needs to be in it then?
Comment: Drupal will not recognize a module directory without a .module file as a valid module; it won't show up on the module listing page and you won't be able to enable it. The .module file can be entirely empty; it just has to exist. That being said, as I said above, as you go along with your development and find that you want to implement a function for common use among the submodules, now you have an easy place to put it. :)
Comment: @ArakTai'Roth Me neither! For good or for bad, the only way to extend any core functionality (including which files/classes are available and autoloaded), is to create a module. It might seem like an unnecessary extra step, but without changing core files (or, even worse, adding your own logic to a conveniently placed contrib module) that's the only way to get the job done. As Garrett says it does then give you a catch-all place for random functionality on that project too, should you need it

Include files used by multiple modules


UIScrollView in UITableCellView, cell doesn't update

Question: I have a custom UITableViewCell with a UIScrollView in it that is wired to the cell controller.  When I assign text to the scrollview, some cells get the correct text, some are blank, some redisplay old text and others have the scrollview clipped around the 2nd or 3rd line of text.  It seems random on what will happen.  I followed the suggestion here of using a timer to fix blank cells, http://www.bdunagan.com/2008/12/08/uitextview-in-a-uitableview-on-the-iphone/, but that didn't help.  I placed the timer code in the cellForRowAtIndexPath method.
I've also tried calling
<code>[cell.textview setNeedsDisplay];
</code>
after text is assigned to the textview but it doesn't have any affect.
When I use a textfield or label, everything looks fine.  However, I need something that can scroll text.  Any suggestions on a fix or better way?
Answer: Update: Found this on the dev forums (specifically mentions your problem):
https://devforums.apple.com/message/38944#38944
I would follow the link it has some more detailed info.
<code> // view controller

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
     NSArray*     visibleCells = [self.tableView visibleCells];

     for (UITableViewCell* cell in visibleCells)
     {
          if ([cell.reuseIdentifier isEqualToString:kTextViewCellID])
          {
               [(MTextViewCell*)cell refresh];
          }
     }
}

// MTextViewCell

- (void)refresh
{
     // mucking with the contentOffset causes the textView to redraw itself
     CGPoint     contentOffset = mTextView.contentOffset;
     CGPoint     contentOffset1 = { contentOffset.x, contentOffset.y + 1.0f };

     mTextView.contentOffset = contentOffset1;
     mTextView.contentOffset = contentOffset;
}
</code>

Try calling:
<code>[tableView reloadData];
</code>
After you update all the textViews.
Comment: textViews are updated in cellForRowAtIndexPath.  I tried calling [tableView reloadData]; there but it had no affect.
Comment: Right before return cell; I do NSLog(@"\nrow=%d textview.text: %@",row, cell.textview.text); and it always has the correct value.  But hardly ever displays it.  Usually the cells are blank.
Comment: if you scroll the table, do the values get updated as you scroll?
Comment: No.  It is random.  Most are blank, some are repeats, some appear to be correct (by order).  This is very similar to the problem I'm experiencing: http://discussions.apple.com/thread.jspa?messageID=8203919.
Comment: Excellent! That works.  From the forum post, seems as though 3.0 has a fix for this.


/root/.ssh/config: line 2: Bad configuration option: sapiauthentication

Question: My virtual environment/system:
# uname -a
Linux X 4.9.0-18-amd64 #1 SMP Debian 4.9.303-1 (2022-03-07) x86_64 GNU/Linux
# cat /etc/debian_version
9.13
# ssh -V
OpenSSH_7.4p1 Debian-10+deb9u7, OpenSSL 1.0.2u  20 Dec 2019
#

I unable to figure out how to I disable SAPIAuthentication
# /usr/bin/sftp -i /root/.ssh/id_rsa -b /root/test firstname.lastname@example.com -v
/root/.ssh/config: line 2: Bad configuration option: sapiauthentication
/root/.ssh/config: terminating, 1 bad configuration options
Couldn't read packet: Connection reset by peer
# cat ~/.ssh/config
Host X.Y.Z
  SAPIAuthentication no
#

Please advise)
Thank you in advance!
Comment: Where this "SAPIAuthentication" came from? OpenSSH never knew anything about such thing — exactly what it is telling you, a "bad configuration option:. I think this is just the syntax error, probably it was meant to be "GSSAPIAuthentication" (which *is* a valid OpenSSL configuration parameter). So just remove this.
Comment: I'm not really sure why any of downvotes... I meant to replicate `-o GSSAPIAuthentication=No` and somehow during copy and paste, I manage to introduce a typo, which I didn't realized until now.
Answer: You can't disable SAPIAuthentication but you could disable GSSAPIAuthentication.


How do I configure SSL/TLS to connect to a Cloud SQL instance?

Question: As far as I can see connection over SSL/TLS is always available with Cloud SQL. If I enforce it, it becomes required. But the maximum level of protection I was able reach is verify-ca from the perspective of both the client and the server. That is:

the server won't make sure (auth-options) the common name in the client certificate matches the user I'm trying to connect as (any common name can be used)
the client won't make sure the common name in the server certificate matches the hostname I'm connecting to (any hostname can be used)

According to the docs I can connect with sslmode=verify-full but either I don't know what instance name they mean, or the information in the docs is out of date. (1) How do I connect with verify-full?
The docs also says:

An SSL mode of verify-full is not required; verify-ca is enough because the CA is instance-specific.

In the pg docs I can see:

The difference between verify-ca and verify-full depends on the policy of the root CA. If a public CA is used, verify-ca allows connections to a server that somebody else may have registered with the CA. In this case, verify-full should always be used. If a local CA is used, or even a self-signed certificate, using verify-ca often provides enough protection.

(2) What does this mean? If the CA is local, only authorized people can create a certificate and a private key, and sign the certificate with the CA's root certificate? And although one can probably get the server's certificate (if the server is public), but one can't get the private key? As such, no unauthorized person can have a valid certificate? As such, if a certificate is valid, it was created by an authorized person, and it doesn't matter what the CN is? Why? It seems like I'm close, but there's still something I'm missing.
(3) If the CA is local, verify-ca == verify-full (no eavesdropping, no MITM)?
More details on what exactly I did can be found here.
Comment: Since Google Cloud SQL is a fully managed RDBMS service, some of the native functions may differ or may not work as intended. There are certain functions like [configuring SSL/TLS certificates](https://cloud.google.com/sql/docs/postgres/configure-ssl-instance) which is configured differently with native PostgreSQL. You may still use `verify-full` by following this [documentation](https://cloud.google.com/sql/docs/postgres/connect-admin-ip#connect-ssl:~:text=to%20use%20the-,verify%2Dfull,-mode%20of%20PostgreSQL) for your setup.
Comment: @RobertG It occurred to me that I indeed can use `verify-full` but then I need to use this long domain (e.g. `xx-xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx.europe-central2.sql.goog`) as a host. Which might occasionally change (who knows?). And I see no other way to figure it out other than by trying to connect with an incorrect value. Actually it says "and 1 other name" but this one I don't know how to elicit. All this leads me to believe that `verify-full` better be avoided (not to be used).
Answer:
How do I connect with verify-full?

You first need to figure out the server certificate's CN:
$ psql -h xx.yyy.xx.yyy -U postgres sslmode=verify-full
psql: error: connection to server at "xx.yyy.xx.yyy", port 5432 failed: server certificate for "31-0628fb91-0e3b-4c89-adca-ad557023a699.europe-central2.sql.goog" (and 1 other name) does not match host name "xx.yyy.xx.yyy"

Then you can connect:
$ psql -U postgres 'sslmode=verify-full hostaddr=xx.yyy.xx.yyy host=xx-xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx.europe-central2.sql.goog'
Password for user postgres:
psql (15.4, server 11.19)
SSL connection (protocol: TLSv1.3, cipher: TLS_AES_256_GCM_SHA384, compression: off)
Type "help" for help.

postgres=>

I don't know other ways to figure it out (the CN) other than by using this trick. As such, it doesn't seem like you're supposed to use verify-full or that it makes any sense. The documentation suggests that verify-full at least not significantly better than verify-ca.

What does this mean?

With a local CA only authorized people can obtain a certificate, as such no unauthorized person can fake the target server.

If the CA is local, verify-ca == verify-full (no eavesdropping, no MITM)?

verify-ca != verify-full, but supposedly there's not much difference in terms of security. Particularly no MITMs should be possible.
Example of configuring SSL/TLS can be found here.


The projective space of all lines through the origin

Question: I have a question to the following example:
Assume that $\mathbb{A}_2$ is an affine plane over a field $\mathbb{K}$, and we have fixed affine coordinates $x, y$ on $\mathbb{A}_2$. Let $\mathbb{P}$ be the set of all lines through the origin of $\mathbb{A}_2$. Take $\mathbb{K}^2$ as vector space and $\pi$ to map the couple $(a,b)$ to the line with equation
$ax+by=0$. Then $(\mathbb{P},\mathbb{K}^2,\pi)$ is a one-dimensional projective space over $\mathbb{K}$.
In this one-dimensional projective space $(\mathbb{P},\mathbb{K}^2,\pi)$, take as reference the lines $x=0$, $y=0$ and the line $x-y=0$ as unit point . Then the line $ax+by=0$ has projective coordinates $(a,-b)$.
Now my question is: Why is the coordinate vector $(a,-b)$? I thought it would be $(a,b)$.
Answer: Because you take $x-y=0$ as the unit point $(1,1)$, you have to reverse signs. If you were to take $x+y=0$ as the unit, then $(a,b)$ would be the coordinates of $ax+by=0$.


How to change input option text with jQuery?

Question: I want to target this input and change it dynamically with jQuery:
<select id="sub_cat" style="" name="sub_cat">
<option selected="selected" value="-10">All</option>

I want to be able to change 'All' with an if statement based on different variables. Is this possible with jQuery? And how? Any help is appreciated. Thanks
Comment: `$('#option_id').text('target text');` would change the option text to whatever you want, the if statements shouldn't be too hard to do
Comment: @NicolasBrown I'm too lazy :D
Comment: @Izzey got it, why didnt u just post it as an answer?
Answer: jsFiddle Example
var option = $('#sub_cat').find('option:contains("All")');
option.text('New Text');

Answer: This will change the value of the selected option depending on the value of a lang variable.
$("#sub_cat option").each(function() {
  var option = $(this);
  var val = option.val();
  if(val === "All") option.val("Hepsi");
});


Multiple DNS with multiple WAN

Question: I'm having a Linux gateway with two WANs each one is connected to different provider, each provider has his own DNS server, And local users are connected to the internet via this server [it's also serves as proxy server].
The Question is that  is it possible to specify which DNS the server[Or the Proxy server i'm using Squid] will use based on the source ip of the local user ?
Comment: It can help to show any research you've already done.
Comment: All the results that i get is, adding a second name server in the resolve.conf, and i know this is not what needed in this case cause this works in round robin fashion, i have not been luck till now.
Comment: Why do you want to do this?? Is the Server acting as a DNS server as well?
Comment: @ChrisS No the server does not act as a DNS, but since it is proxy server , the proxy server uses the DNS to resolve URLs, i'm using Squid proxy server and i have configured it to support dual WANS.
Answer: You can have them all use the same fake IP for DNS server, and route to the right DNS according to the selected WAN.
Unsure how you determine how is the traffic going to get out (which one of your two ISPs...), but I would assume that you have two WAN NICs, let's call them eth0 and eth1.
Let's assume your fake DNS IP is 22.214.171.124 and that the "right" DNS for eth0 is 22.214.171.124 and the "right" DNS for eth1 is 188.8.131.52.
I believe this would do the trick:
<code>iptables -t nat -I POSTROUTING -o eth0 -d 18.104.22.168 -j DNAT --to-destination 220.127.116.11
iptables -t nat -I POSTROUTING -o eth1 -d 220.127.116.11 -j DNAT --to-destination 18.104.22.168
</code>
Comment: Sounds that this would do the trick, but in addition we need to specify the source IP [-s 192.168.20.0/24], i will test this and keep you updated with the results, i have to check one more thing, the source ip of the DNS query, if the source ip of the DNS is ip of proxy server this will fail. hope it's not!
Comment: Why would you need to specify the source IP? What determines (per your explanation, the way I understand it) the rule by which the DNS is selected, is per the WAN connection selected for the outgoing packets. The origin of those packets thus should not matter (IMHO) - you care about the target.

Granted, you may be looking for ways to select which source goes to which WAN (that's what I was referring to when I said "Unsure how you determine how is the traffic going to get out") - but that's a routing decision, and the DNS needs to be the right one, no matter what...
Comment: Will, i guess you are right, and it seems to me that it's going to work, it's just a matter of time to test it, cause this is a production server, Thanks Again.
Answer: One way would be to use DHCP.  DHCP manages the configuration of a client's network, and can include the configuration of the DNS resolver.  With DHCP you can specify that a certain network, or certain range, or certain hosts will be given a particular network configuration, which can also include which DNS servers they will use.
In this case, hosts in network A could be configured in the DHCP scope to use DNS server B, and then hosts in network Y could be configured in the DHCP scope to use DNS server Z.
Comment: -1 Sorry! Great throught, but completely wrong. It's not the clients that are doing the DNS resolution, it's a proxy server. He wants it to use different DNS servers depending on the client's IP.
Comment: @ChrisS yes the proxy is resolving.
Answer: Yes, You can do this using views and forwarding in bind, these two questions have the answer (or something close to it):

BIND9 Forwarding by view
How do I make my internal dns forward requests to a given server

I'm not sure how this will work in practice tho, NAT half your clients to one provider and half to the other?
Comment: -1 Sorry, but also completely wrong. He's asking how to make a Proxy server use different DNS servers based on the client's IP.

Multiple DNS with multiple WAN


PHP file does not receive data from AJAX post

Question: jQuery code:
$(document).ready(function(){
    $('.tablePend tbody').on('click','.btn',function(){
        // var id=$('#test-pend').val();
        var currow=$(this).closest("tr");
        var colId = currow.find('td:eq(3)').text();
        var id = colId;
        alert(id);
        $.post("../admin/detail.php", {
            pid:id
        });
    });
});

So the code above works perfectly, the alert shows the result that I want
<?php
include('dbh.inc.php');
include_once('header.php');

if(isset($_POST['pid'])) {
    $id = mysqli_real_escape_string($conn, $_POST['pid']);
    $sql= "SELECT event_name, event_desc, event_date, event_id FROM events WHERE event_id='$id'";
    $result= mysqli_query($conn, $sql);
    echo $id;
} else {
    echo 'nothing';
}

include_once 'footer.php';
?>

So right here, the PHP automatically goes to the else statement which shows nothing, I don't know what went wrong, I've tried all possible ways, for days, this is really making me frustrated, and I also believe that I made a simple mistake but I can't find it.
Comment: Your `if` test should be `if(isset($_POST['pid'])) {`, not `if(!isset($_POST['pid'])) {`
Comment: ouhhh sorry ,i forgot to change that, i've already tried before this that what you suggest, and it still does not work
Comment: what does "still does not work" mean?
Comment: if(isset($_POST['pid'])) {, not if(!isset($_POST['pid'], i,ve tried doing what you asked, and the same error still occurs
Comment: It's not possible to get the same output if you change the `if` condition. Either you will get the word `nothing` or you will get the value of `$id`.
Comment: so what do i need to change in the code for me to get the $id, because right now it only shows nothing
Comment: is the filename of your `php` is `detail.php` and in correct directory?
Comment: yes the filename is detail.php and it is in the correct directory
Comment: What do you get if you `print_r($_POST);`?
Comment: do i need to put print_r($_POST);  outside the if else statement? edit: i've put print_r($_POST); out the if else statement and it shows this Array ( ) nothing
Comment: If `print_r($_POST);` gives you `Array ()` then there are no values in the `$_POST` array, which means that your ajax query is not working properly. You should add `.done` and `.fail` callbacks to your `$.post` to see if you are getting an error from that
Comment: how do I use **.done** and **.fail**  inside my js file, never use those, sorry
Comment: @MuhdIqbal Did my answer help, or did I misunderstand how you are seeing `nothing`?
Comment: `Don't Panic`, the actual reason why I use jqury in the first place is that, I needed to access a value in a table tag, so after accessing it, I want to send it to a php file and make data display on that php file based on the data I access, but from the reasearch that I made, it is said that I needed to use js to access the data in html table, and in order to send it to another php file, i need to do it through ajax, so I've done that, and the result is like the question I stated here
Comment: After that, Khang Than mentions that the data I want it to be display based on the data I received will be display on the page same with the html table, so that's why I get the output nothing, right now, what I want is just to send the value I access to another php file and display it huhuhuhu
Comment: @MuhdIqbal Your code is correct for getting data from the table and sending it via AJAX to PHP, without leaving the page with the table.  You can get a response from that PHP file, and for eg "live update" the page you are on, without refreshing or reloading.  Is that what you are trying to do?
Answer: I had to do some sleuthing to come up with this answer.
Your $.post() jQuery code does not include a success (or error) handler.  That means no matter what happens, you won't see the results of what your PHP file says.  But in your question, you say you can see nothing.  So, this makes me suspect that you are not actually submitting via AJAX at all.
You have shown us jQuery code where you have an event handler attached to your button.  My guess is your button is inside a a <form>.  When you click a button in a form, it will submit it.  If you want your jQuery to handle it instead, you have to explicitly specify that the normal form submission should not happen.  And your your jQuery code does not do that.
So what all this means is that when you click the button, the form is submitted normally.  Your event handler maybe fires, and that code starts, but meanwhile the browser has moved on to your <form> target, and the jQuery never gets far.  Your <form> does not actually include an id, you set that dynamically with jQuery.  So you wind up on the <form> target, with no id POSTed, and you see nothing on the page.
The fix is to stop the normal form submission:
$(document).ready(function(){
    $('.tablePend tbody').on('click','.btn',function(event){
        event.preventDefault();
        // rest of your code

Note I have added event as a parameter passed to the event handler, and then used its preventDefault() method.  There is an example of this shown in the .post() documentation.


Use a search bar (exposed filter) to search for different node fields

Question: I am trying to make an advanced search with exposed filters and views in drupal.
I am trying to achieve the following:

On the left textfield, the user would input whatever he wants to search, and the views will only search by the field selected in the list at the right (field_A in the picture example). (In short, the column by which to search would be the one selected in field to the right)
NOTE: field_A, field_B, etc, would be all from the SAME node type.
I can make it work easily if I only have 1 field to search by (this field is set by interface when you configure the autocomplete functionality in drupal).
What I want is to be able to dynamically supply the field to search by, because said field will depend on what the user chooses from the combo box at the right (as explained in the note, this combo box will have different choiches field_A, field_B, field_C....etc).
Would it be better to create a custom module instead of using Views with exposed filters?
Thanks.
Answer: Views with exposed filters, and then a bit of custom js should do the job fine.
Basically loop over the fields that are there and use them to build a select so users can choose which field to search. The existing fields names relate to the query string key that we need to use.
Something like this should suffice:
(function($) {
  Drupal.behaviors.viewsSearchBar = {
    attach: function(context, settings) {

      // Build the HTML for the new field we are adding.
      var newField = '
';
      newField += '<input type="text" class="form-text" maxlength="128" size="30" value="" name="combined-search-text" id="combined-search-text">';
      newField += '<select id="combined-search-field">';

      // Loop over the existing widgets to add options to our new select.
      $('.views-exposed-widgets .views-exposed-widget').each(function(){

        var title = $(this).find('label').text().trim();
        var value = $(this).find('input').attr('name');

        if(title && value) {
          newField += '<option value="'+value+'">'+title+'</option>';
          // This this widget
          $(this).hide();
        }

      });

      newField += '</select>
';

      // Add our new field.
      $('.views-exposed-widgets').prepend(newField);

      // Create a submit function for the views search form.
      $('.view-filters form').submit(function(e){

        // Stop the form doing it's default action.
        e.preventDefault();

        // Build the new URL.
        var baseURL = window.location.protocol + '//' + window.location.host + window.location.pathname;
        var field = $('#combined-search-field').val();
        var text = $('#combined-search-text').val();

        // Off we go...
        window.location = baseURL + '?' + field + '=' + text;

      });

    }
  };

})(jQuery);

Further work that needs to be done:

Check if there is already a search argument in the query string and set the default value of the custom search field and select.


Trouble understanding what a natural transformation is

Question: I understand that an arrow is between two objects, a functor is between two categories. And then a natural transformation is, according to Goldblatt's Topoi, a comparison of two functors.
Here is Goldblatt's definition:

A natural transformation from functor $F: \mathscr C \to \mathscr D$ to functor $G: \mathscr C \to \mathscr D$ is an assignment $\tau$ that provides, for each $\mathscr C$-object $a$, a $\mathscr D$-arrow $\tau_a :F(a) \to G(a)$, such that for any $\mathscr C$-arrow $f:a\to b$, the diagram commutes in $\mathscr D$, ie. $\tau_b \circ F(f)=G(f)\circ \tau_a$. We use the symbolism $\tau: F \xrightarrow{\tau} G$ to denote that $\tau$ is a natural transformation from $F$ to $G$.

I have absolutely no idea what's going on. I tried to understand the diagram, but I can't even understand where the $F(a)/F(b)$ and $F(f)$ are coming from. (Is this similar to how structures are preserved under homomorphism? Because the way the composition is formulated looks a bit similar)
I think I am lacking an intuitive understanding of what it means to compare two functors.
Could anyone help please?

It's been pointed out that another question has already covered what I am asking (What intuitive notion is formalized by "natural transformation" in category theory?); the question does also ask for an intuitive perspective on natural transformation.
However it's framed around topology and other mathematical structures, but I really would like to avoid those because coming from a non-mathematical background, framing it around those does not really help (I have no idea what those structures are). If possible, I would like to keep any other structure away from the explanation.
Comment: But $F$ is defined also on arrows; thus $a,b$ and $f$ are in $\mathscr C$ while $F(a),F(b)$ and $F(f)$ are in $\mathscr D$. The same for $G$.
Comment: Now consider $\mathscr D$ : we have objects $F(a)$ and $G(a)$ and thus the "natural transf" $\tau_a$ is an arrow in $\mathscr D$ that maps $F(a)$ to $G(a)$.
Comment: $F$ is one of the two functors - the other is $G$. Remember that functors act on both objects and arrows. "$F(a)$" and "$F(b)$" are the objects in $\mathcal{D}$ which $F$ sends $a$ and $b$ to, respectively, and "$F(f)$" is the arrow in $\mathcal{D}$ that $F$ sends $f$ to. So our initial idea is that, in order to compare $F$ and $G$, we should begin by trying to relate (via the $\tau$s) what they do to a single arrow $f$ (and when we're looking at an arrow $f$ we should also pay attention to its source $a$ and target $b$).
Comment: $F: \mathscr C \to \mathscr D$ is a functor from *categories*, where a category is "made of" *objects* and *arrows*. $a$ is a $\mathscr C$-object and $f$ a $\mathscr C$-arrow. Thus, also $b$ is $\mathscr C$-object.
Comment: $F(a)$ is the "image" of $a$ with the *functor* $F$, and thus is an object of $\mathscr D$, because $F$ maps $\mathscr C$  in $\mathscr D$. The same for $F(b)$.
Comment: @DanielMak "I really would like to avoid those because coming from a non-mathematical background, framing it around those does not really help. If possible, I would like to keep any other structure away from the explanation." I don't think that category theory by and large is accessible without some significant background in other mathematical topics - specifically, at least some algebra and/or topology. So I'm not sure that's a realistic goal.
Comment: @ArnaudD. The question does also ask for an intuitive perspective on natural transformation. However it's framed around topology and other mathematical structures, but I really would like to avoid those because coming from a non-mathematical background, framing it around those does not really help. If possible, I would like to keep any other structure away from the explanation.
Answer: A natural transformation is between two functors, just as a functor is between two categories, i.e. they are simply arrows in a suitable category. The word 'comparison' has no special meaning here.
Note that in Goldblatt's definition, $F$ and $G$ are given functors, both $\mathscr C\to\mathscr D$, so that they already assign the object $F(a)$ [resp. $G(a)$] of $\mathscr D$ to any object $a$ of $\mathscr C$.
Also, they assign arrows $\underset{a\to b}f\ \mapsto \underset{F(a)\to F(b)}{F(f)}$ [resp. $\underset{G(a)\to G(b)}{G(f)}$].
We can also view natural transformations simply as functors $\mathscr C\to(\mathscr D^\to)$ where $\mathscr D^\to$ is the arrow category of $\mathscr D$, whose objects are the arrows of $\mathscr D$, and a morphism $\underset{a\to b}f\ \to \ \underset{a'\to b'}g$ is defined to be a commutative square
$$\matrix{a&\overset f\to & b\\ \downarrow & & \downarrow \\ a' & \underset g\to & b'}$$
In that setup, i.e. if a functor $\varphi:\mathscr C\to (\mathscr D^\to)$ is given, we can recover $F$ and $G$ by composing $\varphi$ with the domain [resp. the codomain] functor $(\mathscr D^\to) \to\mathscr D$, which assigns its arrow on the left [resp. right]  to a commutative square.


In a DevExtreme (grouped) dxList can I change the "items" to "elements" of the input array?

Question: I have a grouped DevExtreme dxList.
My input data array coming from the server looks like this:
inputArray = [{
            label: "group1",
            elements: [{ text: "a" }, { text: "b" }]
        },
        {
            label: "group2",
            elements: [{ text: "a" }, { text: "b" }]
        }];

So I have "elements" instead of "items" and this won't work:

Is there a configuration way to tell the dxList to use "elements" instead of "items"?
Answer: Use DataSource map function.
http://js.devexpress.com/Documentation/ApiReference/Data_Library/DataSource/Configuration/?version=14_2#map
dataSource = new DevExpress.data.DataSource({
        store: inputArray,
        map: function (item) {
            return {
                key: item.label,
                items: item.elements
            };
        }
    });

See following fiddle http://jsfiddle.net/tabalinas/bjqmbume/


Can a vector field pass through an area and have zero flux?

Question: Consider $x^3$ for example, at $x=0$ , the tangent line is also intersects the function. The tangent line passes through to the other side at the same point it is tangent to the function.
It got me wondering, why can't a vector field enter a closed surface (creating a negative flux) and get out tangent to the surface, with zero flux, leaving total of negative flux in contradiction to gauss's law.
Comment: Anyone knows what tags can I add?
Comment: Can you sketch the vector field you have in mind?
Comment: Which "Gauss's Law" did you have in mind? There's one related to electromagnetism. If you omit all physical requirements, and also all kinds of discontinuities and/or singularities inside the closed surface, you can do a lot of things to your vector field.
Comment: @user7530 Added. Tried to draw all the lines tangent to the surface at the exit points, same as $x^3$
Comment: @DavidK All I know is that the flux through a closed surface should be zero, when there are no sources inside the surface, zero divergence.
Comment: The divergence theorem applies to a complete vector field, not just a few streamlines. If you do manage to draw a complete field that appears to have non-zero net flux, look for where you have non-zero divergence.
Answer: The total flux is only zero when the vector field is divergence-free.
If your example vector field (a) is divergence-free and (b) can be extended to complete the diagram without introducing a region of positive flux, then indeed you would have a counter-example to Stokes's theorem. But you can prove that constructing such an example is impossible.
If your vector field (call it $v$) is divergence-free, then its 90-degree-counterclockwise rotation $v^{\perp}$ is curl-free, and so is the gradient of some function,
$$v^{\perp} = \nabla f.$$
Let's think about what $f$ must look like to match your picture. We can set $f$, WLOG, to equal zero at the middle-left point on the boundary (where your first streamline enters the region). Let's imagine what happens to $f$ as we move clockwise around the boundary.
In the top-left part of your diagram, $f$ increases. This is because $v^{\perp} = \nabla f$ points to the upper-right, and is aligned with the direction of travel.
In the region where $v$ leaves the region parallel to the boundary, $v^{\perp}$ leaves perpendicular to the boundary. Therefore $\nabla f$ is perpendicular to the boundary and $f$ is constant along that part of the boundary.
So we have that $f$ started at $0$ in the middle-left, increased to some positive value as we moved towards the top of the region, and then didn't change as we moved along the right part of the boundary. Now by the time we finish winding around the boundary, and return to our starting point, $f$ must decrease back to zero. This means that $\nabla f$ must point to the right along the bottom portion of the boundary, and so $v$ must point down. In other words, any divergence-free completion of your vector field must have streamlines that exit through the bottom of the boundary, providing the positive flux required by Stokes's theorem.
Comment: Do we have to complete the vector field? If I only have a thin stream of water, does it's flux through a closed surface can be non zero?
Comment: @EB97 You need a sufficiently-smooth divergence-free field for Stokes's theorem to imply that the flux is zero.

If you model a stream of water as a velocity field supported within a thin volumetric tube, that is divergence-free and vanishes as you approach the boundary (no-slip conditions), then yes, the flux is zero.
Comment: In any case, I did not assume anywhere above that $v$ doesn't vanish in some places. It can vanish, but as I argued above, if it's divergence-free, there must be a region along the bottom boundary where $v$ passes downwards over the boundary and has positive flux.
Comment: The divergence-free condition is very important and may be stronger than you intuitively think. If you draw some arbitrary streamlines, they will *not* in general correspond to a divergence-free vector field. And of course, arbitrary vector fields that are not divergence-free can have arbitrary net flux.


Multiple Regression: Only interpret unstandardized coefficients when all variables have the same scale (0-10)?

Question: I am developing a multiple regression model using three predictor and one outcome variable.
All variables use the same scale (0-10).
Therefore it should suffice to look at the unstandardized coeffients for interpretation, shouldn't it? Are the coeffecients comparable as to "size" of their effect?
Kind regards
Answer: It's always fine to look at unstandardized coefficients.  I don't typically use standardized coefficients for much.  Comparing the values of different coefficients to each other and interpreting that as a measure of 'importance' (which is what I think you're getting at) is a dicey affair.  To do so, you need to assume that the units of the different variables are commensurate (if X1 is meters and X2 is seconds, how many meters equals 1 second?), which is usually not reasonable.  The fact that your variables are all scaled 0-10 makes this look less suspicious, but doesn't necessarily make it better in actuality.
A different issue is whether your outcome variable is also 0-10.  It sounds like it is.  If so, standard (i.e., OLS) multiple regression may not be valid.  If the Y data don't approach the bounds and the residuals look normal enough, you should be fine, but otherwise you may want to do ordinal logistic regression.


Can we somehow create Server Side Filters using Python?

Question: I get around 100k mails everyday and client side filters are not working due to crash of Outlook and Thunderbird. I wrote following code in Python to delete all messages:
<code>import imaplib
box = imaplib.IMAP4_SSL('imap.mail.microsoftonline.com', 993)
box.login("firstname.lastname@example.com","password")
box.select('Inbox')
typ, data = box.search(None, 'ALL')
for num in data[0].split():
 box.store(num, '+FLAGS', '\\Deleted')
box.expunge()
box.close()
box.logout()
</code>
But then I am getting socket error. If somehow I can create filters on Server Side using python, then it would be really easy for me to handle these emails.
Please help!!
Answer: It might have something to do with you closing the connection before logging out.
Comment: Actually, its happening because of too much load .. . Anyways, the main mission is not deleting all messages I have but rather manage them somehow.. . So anyidea how I can create server side filters?


Cartesian Product and Relations

Question: If a relation is defined between the first coordinate and the second coordinate of an ordered pair(aRb), then how come R = {(1,2),(5,6)} is a relation ? How can there be more than 1 ordered pair in a relation ?
Comment: Not very clear... $R = \{ (a, b) \mid a \in A \text { and } b \in B \} \subseteq A \times B$ is a relation. $R$ is a *set* of pairs.
Comment: You need a better understanding of what a relation is.  You use relations in your everyday life... you just might not know it by those words.  Consider for example the words "*hello world*" and the relation between each of these words and a letter in those words.  $\{(hello, h),(hello, e),(hello, l),(hello,o),(world,w),(world,o),(world,r),(world,l),(world,d)\}$ would be the representation of this relation.  "*How can there be more than 1 ordered pair in a relation?*" because there are many words and because there are many letters per word...  *Of course* there are multiple pairs.
Comment: Do not confuse and conflate *an element of the relation* with *the relation itself*.
Comment: Relations in everyday life: "*Who lives near me?*"  "*Who is related to who?*"  "*Who is taller than who?*"  "*What company owns what product?*"  "*What is the meaning of words?*"...  In math we try to generalize and formalize such concepts.
Answer: A relation on $A$ is defined as any subset of $A\times A$. As such, $\{(1,2), (5,6)\}$ is a relation on $\mathbb R$ (and on $\mathbb Q$, and $\mathbb N$, for that matter). In other words, a relation is a set of pairs, not just a single pair.
In your particular relation, you have $1R2$ and you have $5R6$, because writing $aRb$ is just shorthand for saying $(a,b)\in R$.

Cartesian Product and Relations


Is it possible in JS to get an object , assign value to property send it to another function in one line?

Question: here is piece of JS code:
function getObj(){
    return {p1: "None"};
}

function printObj(obj){
    console.log(obj.p1);
}
//Create an object
let o = getObj();

// Assign val
o.p1 = "Val2";

//send to Print
printObj(o);

Is it possible to do the same in one short line  - something like the following ?
printObj(getObj().p1 = "Val1");

Edit
In this post  wrote short code to compare the different approaches.
Comment: @PeterSeliger I wrote some short code to speed wise compare, the different ways. Posted [here](https://stackoverflow.com/questions/65789589/js-performance-compare-simple-task-4-different-ways-surprising-results). Looks like `{ p1: 'Val1' }` also creates an object as has been properly mentioned there
Comment: `printObj(Object.assign(getObj(), { p1: 'Val1' }));` ... this approach directly changes the return value of `getObj()`; thus skipping the creation of yet another object like one does with e.g. `{ ...getObj(), p1: "Val1" }` with the latter being similar to `Object.assign({}, getObj(), { p1: 'Val1' })`.
Answer: you can use spread operator, which will get an object from your function and generate a new object with all of your object fields.
Than all that's left is to override the prop
printObj({...getObj(), p1: "Val1"});

function getObj(){
    return {p1: "None"};
}

function printObj(obj){
    console.log(obj.p1);
}
//Create an object
let o = getObj();

// Assign val
o.p1 = "Val2";

//send to Print
printObj(o);

//all in one line
printObj({...getObj, p1: "Val2"});
Comment: `p1: "Val1"`, `=` isn't valid there.
Comment: @OrYaacov Is it better though in terms of efficiency and speed? what's the better way - this solution or the simple 3 lines of code approach?


Difficulty to configure Activiti into a Springboot application api

Question: First of all is it a viable thing to embed Activiti into an API type application for use within that application or should Activiti be run standalone?
The error below is due to bean definition but I'm not sure where the beans should be defined and how - if thats correct approach for version 6. Our standards with Springhboot 2 is to annotate beans in java rather than xml context
Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2019-04-10 21:17:43.924 ERROR 19516 --- [  restartedMain] o.s.b.d.LoggingFailureAnalysisReporter   :

***************************
APPLICATION FAILED TO START
***************************

Description:

Field runtimeService in ma.cvmeeting.workflow.WorkflowApplication$MyrestController required a bean of type 'org.activiti.engine.RuntimeService' that could not be found.

The injection point has the following annotations:
    - @org.springframework.beans.factory.annotation.Autowired(required=true)

Action:

Consider defining a bean of type 'org.activiti.engine.RuntimeService' in your configuration.

Process finished with exit code 0

code:
import org.activiti.engine.RuntimeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@SpringBootApplication
public class WorkflowApplication {

public static void main(String[] args) {
    SpringApplication.run(WorkflowApplication.class, args);
}

@RestController
public static class MyrestController{

    @Autowired
    private RuntimeService runtimeService;

    @GetMapping("/start-process")
    public String startProcess() {

        runtimeService.startProcessInstanceByKey("Potulerauneoffre");
        return "Process started. Number of currently running"
                + "process instances = "
                + runtimeService.createProcessInstanceQuery().count();
    }
}

pom.xml:
<project>

    <groupId>ma.cvmeeting</groupId>
    <artifactId>workflow</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>workflow</name>
    <description>Demo project for Spring Boot</description>

   <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.4.RELEASE</version>
        <relativePath/>
    </parent>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.activiti</groupId>
            <artifactId>activiti-engine</artifactId>
            <version>7-201802-EA</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
        </dependency>

        <dependency>
            <groupId>org.thymeleaf</groupId>
            <artifactId>thymeleaf</artifactId>
            <version>3.0.11.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>org.h2database</groupId>
            <artifactId>h2database</artifactId>
            <version>1.0.20061217</version>
        </dependency>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

Answer: There are two ways to initialize the engine when you embed it in your spring based application:
1.) let spring initialize it for you so you can use all the engine services right away without need of any configuration. this requires activiti-spring-boot-starter as dependency.
2.) You initialize engine by your self and provide the services beans from @Configuration class. for this you will require only activiti-engine core as dependency
The reason your application cannot find the RuntimeService because you are trying the second approach add the below dependency in your pom.xml and remove the engine one
<dependency>
    <groupId>org.activiti</groupId>
    <artifactId>activiti-spring-boot-starter</artifactId>
</dependency>

you should follow documentation for more help.
Answer: We recommend activiti 7 core if you are planning to use spring boot 2.x and the use of the new APIs. This is great time if you want to get involved with the new APIs and project initiatives
Answer: You could write a @Configuration class and define Activiti services, like this :
@Configuration
public class ActivityConfig {

    @Autowired
    DataSource dataSource;

    @Bean
    public DataSourceTransactionManager getTransactionManager() {
        return new DataSourceTransactionManager(dataSource);
    }

    @Bean
    public ProcessEngineConfigurationImpl getProcessEngineConfiguration() {
        SpringProcessEngineConfiguration res = new SpringProcessEngineConfiguration();
        res.setDataSource(dataSource);
        res.setTransactionManager(getTransactionManager());
        return res;
    }

    @Bean
    public ProcessEngineFactoryBean getProcessEngine() {
        ProcessEngineFactoryBean res = new ProcessEngineFactoryBean();
        res.setProcessEngineConfiguration(getProcessEngineConfiguration());
        return res;
    }

    @Bean
    public RepositoryService getRepositoryService() throws Exception {
        return getProcessEngine().getObject().getRepositoryService();
    }

    @Bean
    public FormService getFormService() throws Exception {
        return getProcessEngine().getObject().getFormService();
    }

    @Bean
    public TaskService getTaskService() throws Exception {
        return getProcessEngine().getObject().getTaskService();
    }

    @Bean
    public RuntimeService getRuntimeService() throws Exception {
        return getProcessEngine().getObject().getRuntimeService();
    }

    @Bean
    public HistoryService getHistoryService() throws Exception {
        return getProcessEngine().getObject().getHistoryService();
    }

    @Bean
    public IdentityService getIdentityService() throws Exception {
        return getProcessEngine().getObject().getIdentityService();
    }
}


Homeomorphism between convex set and a sphere

Question: For $C$ a compact convex set of $\mathbb{R}^n$ $(n\geq 1)$ whose interior is nonempty and whose boundary $\partial C$ is a smooth manifold, is $\partial C$ homeomorphic to the sphere $\mathbb{S}^{n-1}$?
Answer: Yes. You can suppose that $B_1(0)\subset C$. Then in the halfline of positive scalar multiples of every unit vector $v$ there is only one point of $\partial C$, because if $\lambda>\mu>0$, $\mu v$ is in the convex envelope of $B_1(0)$ and $\lambda v$, which is open, and so it can't belong to $\partial C$.
So the continuous function $\rho:{\mathbf R}^n\setminus 0 \to {\mathbf S}^{n-1}$ restricts to a bijective continuous function $\partial C\to {\mathbf S}^{n-1}$. Since $\partial C$ is compact and ${\mathbf S}^{n-1}$ is Hausdorff's, by a famous lemma of topology it is a homeomorphism.
By extending it linearly on every ray, it can even been proved that $C$ is homeomorphic to $\overline{B_1}(0)$.
Comment: Thank you, is it possible to prove that $\partial C$ diffeomorphic to the sphere $\mathbb{S}^{n-1}$?
Comment: It depends on the regularity. If $\partial C$ is a $C^k$ hypersurface, it is $C^k$-diffeomorphic to $S^{n-1}$. It is because we already know a homeomorphism, which is the restriction of a $C^k$ function. To prove that the inverse is $C^k$, by the inverse function theorem, you only need to prove that the differential of $\rho:\partial C\to S^{n-1}$ is invertible everywhere. It is the restriction of the differential of $\rho:\mathbf{R}^n\setminus\{0\}\to S^{n-1}$, which kernel at every point is spanned by the radial vector. (continue)
Comment: So to prove the invertibility one has to prove that the tangent space of $\partial C$ at $p$ doesn't contain that vector. This can be proved observing that $C$ contains a cone with vertex $p$ (the one that joines $p$ with the points of $B_1(0))$.


"Filtrar" registros iguais em uma lista somando seus quantitativos

Question: namespace ConsoleApplication10
{
    class Program
    {
        static void Main(string[] args)
        {
            List<Teste> lstTeste = new List<Teste>
            {
                new Teste {Codigo = 1, Quantidade = 10},
                new Teste {Codigo = 2, Quantidade = 10},
                new Teste {Codigo = 1, Quantidade = 10},
                new Teste {Codigo = 3, Quantidade = 10},
                new Teste {Codigo = 2, Quantidade = 10}
            };
        }
    }

    public class Teste
    {
        public int Codigo { get; set; }
        public int Quantidade { get; set; }
    }

Eu quero criar uma nova lista, ou remover os itens repetidos da lista original, porém quero somar os quantitativos.
A "nova" lista ficaria:
Codigo = 1, Quantitativo = 20
Codigo = 2, Quantitativo = 20
Codigo = 3, Quantitativo = 10

Answer: Utilizando LINQ você pode agrupar os itens por código e somar a quantidade em cada grupo. Entretanto, o LINQ só está disponível a partir da versão 3.5 e em alguns casos precisamos trabalhar com versões anteriores, então fiz também uma solução agrupando e somando utilizando um Dictionary como estrutura chave/valor para agrupar os itens por código e somar as quantidades diretamente no valor do item no dicionário.
Com LINQ
namespace ConsoleApplication10
{
    class Program
    {
        static void Main(string[] args)
        {
            List<Teste> lstTeste = new List<Teste>
            {
                new Teste {Codigo = 1, Quantidade = 10},
                new Teste {Codigo = 2, Quantidade = 10},
                new Teste {Codigo = 1, Quantidade = 10},
                new Teste {Codigo = 3, Quantidade = 10},
                new Teste {Codigo = 2, Quantidade = 10}
            };

            List<Teste> lstAgrupado = lstTeste
                .GroupBy(i => i.Codigo)
                .Select(j => new Teste()
                {
                    Codigo = j.First().Codigo,
                    Quantidade = j.Sum(ij => ij.Quantidade)
                })
                .ToList();
        }
    }

    public class Teste
    {
        public int Codigo { get; set; }
        public int Quantidade { get; set; }
    }
}

Sem LINQ
namespace ConsoleApplication10
{
    class Program
    {
        static void Main(string[] args)
        {
            List<Teste> lstTeste = new List<Teste>
            {
                new Teste {Codigo = 1, Quantidade = 10},
                new Teste {Codigo = 2, Quantidade = 10},
                new Teste {Codigo = 1, Quantidade = 10},
                new Teste {Codigo = 3, Quantidade = 10},
                new Teste {Codigo = 2, Quantidade = 10}
            };

            Dictionary<int, Teste> agrupamentoSomado = new Dictionary<int, Teste>();

            foreach (Teste item in lstTeste)
            {
                if (agrupamentoSomado.ContainsKey(item.Codigo))
                {
                    agrupamentoSomado[item.Codigo].Quantidade += item.Quantidade;
                }
                else
                {
                    agrupamentoSomado.Add(item.Codigo, item);
                }
            }

            List<Teste> lstAgrupado = new List<Teste>(agrupamentoSomado.Values);
        }
    }

    public class Teste
    {
        public int Codigo { get; set; }
        public int Quantidade { get; set; }
    }
}

Answer: Eu fiz em três formas diferentes para escolher o que melhor te atende:
using System.Collections.Generic;
using System.Linq;
using static System.Console;

namespace ConsoleApplication10 {
    public class Program {
        public static void Main(string[] args) {
            List<Teste> lstTeste = new List<Teste> {
                new Teste {Codigo = 1, Quantidade = 10},
                new Teste {Codigo = 2, Quantidade = 10},
                new Teste {Codigo = 1, Quantidade = 10},
                new Teste {Codigo = 3, Quantidade = 10},
                new Teste {Codigo = 2, Quantidade = 10}
            };

            //Forma declarativa
            WriteLine("Forma declarativa");
            var items = from item in lstTeste
                group item by item.Codigo
                into g
                select new{Codigo = g.Key, Quantidade = g.Sum(item => item.Quantidade)};
            items.ToList().ForEach(item => { WriteLine(
                $"Item: {item.Codigo} Quantidade: {item.Quantidade}"); });

            //forma imperativa
            WriteLine("Forma imperativa");
            var lista = lstTeste.GroupBy(g => g.Codigo).Select(g => new {
                Codigo = g.First().Codigo, Quantidade = g.Sum(g => g.Quantidade) });
            lista.ToList().ForEach(item => { WriteLine(
                $"Item: {item.Codigo} Quantidade: {item.Quantidade}"); });

            //forma com dicionário - Sem LINQ
            WriteLine("Forma com dicionário");
            var dicionario = new Dictionary<int, Teste>();
            foreach (var item in lstTeste) {
                if (dicionario.ContainsKey(item.Codigo)) {
                    dicionario[item.Codigo].Quantidade += item.Quantidade;
                } else {
                    dicionario[item.Codigo] = item;
                }
            }
            foreach (var item in dicionario.Values) {
                WriteLine($"Item: {item.Codigo} Quantidade: {item.Quantidade}");
            }
       }
    }

    public class Teste {
        public int Codigo { get; set; }
        public int Quantidade { get; set; }
    }
}

Veja funcionando no ideone. E no .NET Fiddle. Também coloquei no GitHub para referência futura.
Answer: Uma resposta usando os métodos de extensão do System.Linq e retorno com objetos anônimos:
var resultado = lstTeste
      .GroupBy(x => x.Codigo)
      .Select(x => new {
          Quantitativo = x.Sum(y => y.Quantidade),
          Codigo = x.First().Codigo
      });

Veja funcionando aqui: https://dotnetfiddle.net/S1FKzY
Answer: public static List<Teste> SomarIguais(List<Teste> list)
{
    if(list == null) return null;
    List<Teste> resultado = new List<Teste>();
    foreach(Teste t in list)
    {
        bool nenhum = true;
        foreach(Teste t1 in resultado)
        {
            if(t1.Codigo == t.Codigo)
            {
                nenhum = false;
                t1.Quantidade += t.Quantidade;
            }
        }
        if(nenhum) resultado.Add(t);
    }
    return resultado;
}

Comment: É uma questão de boa prática, Christian. O que pode ser trivial pra você pode não ser pra outras pessoas. Pra quem fez a pergunta, por exemplo, claramente não é uma questão tão boba.
Comment: Christian, procure explicar um pouco da lógica que você adotou quando postar uma resposta. E se não tiver o LINQ disponível sugiro a utilização de `Dictionary` ;)
Comment: Eu sinceramente nunca tinha usado o Linq. Quanto a lógica pareceu tão "boba" que nem achei necessário


lots of errors in dns log

Question: I've got lots of errors in my DNS log:
<code>Mar 18 17:26:38 server named[3240]: validating @0x2aacec5b18e0: com NS: got insecure response; parent indicates it should be secure
Mar 18 17:26:38 server named[3240]: error (insecurity proof failed) resolving 'com/NS/IN': 2001:470:20::2#53
Mar 18 17:26:38 server named[3240]: validating @0x2aace80c3cc0: com NS: got insecure response; parent indicates it should be secure
Mar 18 17:26:38 server named[3240]: error (insecurity proof failed) resolving 'com/NS/IN': 184.108.40.206#53
Mar 18 17:26:38 server named[3240]: error (chase DS servers) resolving 'addthisedge.com/DS/IN': 188.8.131.52#53
Mar 18 17:26:38 server named[3240]: validating @0x2aacec5cba60: com NS: got insecure response; parent indicates it should be secure
Mar 18 17:26:38 server named[3240]: error (insecurity proof failed) resolving 'com/NS/IN': 2001:470:20::2#53
Mar 18 17:26:38 server named[3240]: validating @0x2aace80c3cc0: com NS: got insecure response; parent indicates it should be secure
Mar 18 17:26:38 server named[3240]: error (insecurity proof failed) resolving 'com/NS/IN': 22.214.171.124#53
</code>
They do not affect my DNS operation, what does them mean? I've set up 2 forwarders, do they matter?
Answer: They're messages relating to DNSSEC, and the fact that your resolver is trying to work with it but being stymied.  Read the manual for your version of BIND to find out more, and for information on how to configure it correctly (or disable it, if necessary).
Comment: I've disabled auto validation and the errors now disappeared

lots of errors in dns log


Asymptotically confidence interval of level $1-2\alpha$

Question: For fixed $k$, the variables $(2k+1)\hat{f}_k(\lambda)$ are asymptotically distributed according the Gamma distribution with shape parameter $2k+1$ and mean $(2k+1)f_X(\lambda)$. It turns out that this suggests a confidence interval of the form
\begin{align}
\bigg(\frac{(4k+2)\hat{f}_k(\lambda)}{\chi^2_{4k+2,1-\alpha}}, \frac{(4k+2)\hat{f}_k(\lambda)}{\chi^2_{4k+2,\alpha}} \bigg), \qquad (*)
\end{align}
where $\chi^2_{k,\alpha}$ the $\alpha$-quantile of the chi-square distribution with $k$ degrees of freedom.
I want to show that this interval is asymptotically of level $1-2\alpha$.
I know that a $\Gamma(m/2,1/2)$-distribution is identical to a $\chi^2_m$-dsitribution. So in $(*)$ we have a fraction of two object which are Gamma-distributed. However, I do not see how to make ends meet? Any help is appreciated!
Answer:
For fixed $k$, the variables $(2k+1)\hat{f}_k(\lambda)$ are asymptotically distributed according the Gamma distribution with shape parameter $2k+1$ and mean $(2k+1)f_X(\lambda)$.

The mean of $\Gamma(\alpha,\beta)$ equals to
$$\frac{\alpha}{\beta}=\frac{2k+1}{\beta}=(2k+1)f_X(\lambda) \quad\Rightarrow\quad\beta=\frac{1}{f_X(\lambda)}.
$$
Rewrite your statement as
$$
(2k+1)\,\hat{f}_k(\lambda) \xrightarrow{d} \Gamma\left(2k+1,\frac{1}{f_X(\lambda)}\right).
$$
Use the PDF of $\Gamma(\alpha,\beta)$:
$$
f_Y(x)=\dfrac{\beta^{\alpha}}{\Gamma(\alpha)}x^{\alpha-1}e^{-\beta x},\,x>0
$$
and check that the multiplying $Y\sim\Gamma(\alpha,\beta)$ by $c>0$ results in changing $\beta$ to $\beta/c$ only: $cY\sim \Gamma(\alpha, \frac{\beta}{c})$.
So, in order to get asymptotically chi-squared distribution $\chi^2_{4k+2}=\Gamma(2k+1,\frac12)$, divide original estimator $(2k+1)\hat{f}_k(\lambda)$ by $f_X(\lambda)$ and multiply by $2$:
$$
\frac{2(2k+1)\,\hat{f}_k(\lambda)}{f_X(\lambda)} \xrightarrow{d} \Gamma\left(2k+1,\frac{1}{2}\right)=\chi^2_{4k+2}.
$$
$$\begin{multline}
\mathbb P\bigg(\frac{(4k+2)\hat{f}_k(\lambda)}{\chi^2_{4k+2,1-\alpha}}\leq f_X(\lambda) \leq \frac{(4k+2)\hat{f}_k(\lambda)}{\chi^2_{4k+2,\alpha}} \bigg)=\cr =\mathbb P\bigg(\chi^2_{4k+2,\alpha}\leq\underbrace{\frac{(4k+2)\hat{f}_k(\lambda)}{f_X(\lambda)}}_{\begin{array}{c}\displaystyle\downarrow{\tiny{d}}\cr\displaystyle\chi^2_{4k+2} \end{array}} \leq \chi^2_{4k+2,1-\alpha} \bigg)\to 1-2\alpha.
\end{multline}
$$


Phonegap/Cordova WebSql transaction not firing

Question: I'm using cordova's latest version (3.5) and I want to save some data using WebSQL but when I call database.transaction(query,success,error) it does nothing. Both my sucess method and error method have alert() to notify error or success but none of them fire.
Here's my code:
    function onDeviceReady(){
        var db = window.openDatabase("Database", 1, "PhoneGap Demo");
        db.transaction(populateDB, errorCB, successCB);
    }

    function populateDB(tx) {
        tx.executeSql('DROP TABLE IF EXISTS DEMO');
        tx.executeSql('CREATE TABLE IF NOT EXISTS DEMO (id unique, data)');
        tx.executeSql('INSERT INTO DEMO (id, data) VALUES (1, "First row")');
        tx.executeSql('INSERT INTO DEMO (id, data) VALUES (2, "Second row")');
    }

    function errorCB(err) {
        alert("Error processing SQL: "+err.code);
    }

    function successCB() {
        alert("success!");
    }

As I said the alert boxes are not being displayed. What could be the problem?
For more
information: I'm using Cordova 3.5 and being tested on an iPhone simulator.
I executed the code on chrome with my laptop and seems to work.
Comment: You need to add callbacks as parameters in .executeSql, i.e. tx.executeSql(sql, values, successCB, errorCB);
Comment: I've added the callbacks but still not working. It's so strange! Why in my laptop's browser is working? @zvona
Comment: @MarcOrtiz first and foremost check whether `onDeviceReady()` is getting fired by putting an `alert()` call inside. If `alert()` does not fire that means the phonegap app is not configured properly. Check If you have included `cordova.js` in the index.html file. Hope you have added `document.addEventListener('deviceready', onDeviceReady,false);` in you index.html file.
Comment: @frank Yes I've already checked the onDeviceReady function gets called and works. I've also added alerts() after the code: db.transaction(populateDB, errorCB, successCB); and before
Answer: Environment : cordova 3.4
device : Emulator ( Nexus 7)
OS : Android KitKat 4.4
I just checked your code and got the error "Insufficient Number of arguments" on line
var db = window.openDatabase("Database", 1, "PhoneGap Demo");

As per the API doc there should be four arguments, I changed the code to
var db = window.openDatabase("Database", "1.0", "PhoneGap Demo", 1000);

and it worked. The last argument is the initial size of the database in bytes.
Hope the above solution works for iPhone as well.
I used console.log() call as well as alert() for debugging.