Add bootstrap.inc to file to programatically save nodes

Question: In Drupal 6 I would add these two lines to my code so that I could programatically import fields without having to create a module for it
require_once './includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);

However, trying to do this in D7, I am getting all types of errors from defined constants not being defined.  What is the proper way to do this in d7?
I have my script ready, and I do not want to spend another several hours writing code just so this can fit nicely into drupal as a module.  Thoughts? thanks!
Answer: Drupal 7 uses the DRUPAL_ROOT constant that is set to the Drupal root directory path. If you look at the code of the index.php file, you will notice the following code.
/**
 * Root directory of Drupal installation.
 */
define('DRUPAL_ROOT', getcwd());

require_once DRUPAL_ROOT . '/includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);
menu_execute_active_handler();

The constant is also used from Drupal functions, such as module_load_include().
  if (function_exists('drupal_get_path')) {
    $file = DRUPAL_ROOT . '/' . drupal_get_path('module', $module) . "/$name.$type";
    if (is_file($file)) {
      require_once $file;
      return $file;
    }
  }

If you have to write, for any reason, a function similar to module_load_include() you should use DRUPAL_ROOT to get the Drupal root directory.
Supposing that in your case Drupal is not in the current directory, you can use the following code.
define('DRUPAL_ROOT', 'the directory containing Drupal');

require_once DRUPAL_ROOT . '/includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);

Answer: I am working on a MAC, and apparently there is an issue with how mysql sockets are handled.
If you are on a Mac and having issues with PDO exceptions as well as REMOTE_ADDR not found, do this:

Execute the following commands:

    sudo mkdir /var/mysql
    sudo ln -s /Applications/MAMP/tmp/mysql/mysql.sock /var/mysql/mysql.sock

Put this at the top of your PHP script:
$_SERVER['HTTP_HOST'] = 'example.org';
$_SERVER['REMOTE_ADDR'] = '127.0.0.1';

chdir('/root/drupal/folder/'); // Change this to your root Drupal address for local.
define('DRUPAL_ROOT', getcwd());
require_once DRUPAL_ROOT . '/includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);


ImportError: bad magic number in 'time': b'\x03\xf3\r\n' in Django

Question: I got this error while running the Django app file that I had downloaded from GitHub. How can I solve this problem?
Comment: Delete all `.pyc` files you downloaded with it.
Answer: Please go to your home directory.  And then:
 sudo find . -name "*.pyc" -exec rm -f {} \;

Comment: `find . -type f -name "*.pyc" -delete`, why `sudo`?
Comment: sudo "in your home directory" is not necessary
Answer: Finally, I found the answer, The project has .pyc files, which holds the previous version information and time date, so this error. After deleting those files I got the output.
Answer: You can delete all the .pyc files in your folder to resolve it.
find . -name \*.pyc -delete

Comment: @Hans You are both needlessly adding sudo to a command and also failing to properly quote an argument that might end up expanding. The original command is fine.
Comment: sudo find . -name \*.pyc -delete
Answer: Included in your checkout are .pyc files. These are byte cache files, storing cached bytecode so Python can avoid having to parse and compile the source files. Unless you plan to distribute a project without source files, these should not be included.
Just delete all .pyc files located in the same directory as .py files.
The "magic number" in the error message is a version number for the bytecode stored, and specific Python versions only work with specific bytecode magic numbers; the number in your error is equal to 62211 in decimal (when interpreted as a little-endian number), which shows the .pyc files were created with a Python 2.7 interpreter.
Python 3.2 switched to storing .pyc files in separate __pycache__ directories and including the Python version in the filename. However, any .pyc files still located next to the .py files are supported still to allow for bytecode-only releases. It's safe to delete such files because if you were to use a Python 2.7 interpreter in future, then the files will be re-created.
Answer: Delete the .pyc files created in your directory .'
ex : i have gitlab.py and gitlab.pyc
later i renamed it into gitlab-api.py
But while running python file , it is using gitlab.pyc so

Traceback (most recent call last):
File "gitlab-api.py", line 1, in
import gitlab
ImportError: bad magic number in 'gitlab': b'\x03\xf3\r\n'

it worked correctly when i deleted the gitlab.pyc
Answer: you will need to delete any pyc. pyc is the cache of your app. delete all files that end with .pyc and rerun your app.
Answer: If your OS is Windows you have to delete Python's older versions, then you are ready to use pip again. This is the best method, without errors.
Comment: You can also use [scoop](https://scoop.sh/) or [NuGet](https://www.nuget.org/downloads) to better manage your installed software on windows, and then the process of installing or uninstalling python will be significantly better.
Answer: Rename the class name or file name that you are importing, this fixed my issue.


Two sample t-test for data (maybe time series) with autocorrelation?

Question: I am new to statistics, so pardon any mistakes in my question.
I have two time series $X_i$ and $Y_i$. Assuming that they're stationary AR(1) processes with possibly different means, how do I test for difference of means?
I found this link (but tests only one sample) which discusses using gls: https://stat.ethz.ch/pipermail/r-help/2006-May/105495.html
So I am wondering how to extend this to multiple samples (use a dummy variable?) or if there are any other methods (preferably in R).
Answer: Since $X_i$ and $Y_i$ are AR(1) processes, we can treat $(X_i,Y_i)$ as a VAR(1) process. Then testing the difference of means means testing the restrictions on VAR coefficients. For this simple case there is a formula derived in Hamilton's book "Time series analysis". The formula in the link is the one before the start of new section. Unfortunately it is not implemented in R, as far as I know. I checked only vars package, but I can say with some confidence that if it is not implemented there, it is not implemented in other packages.
Here is some code I've cobbled to calculate this statistic for simulated AR(1) processes:
n <- 1000

e1 <- rnorm(n,2,sd=1)
e2 <- rnorm(n,2.5,sd=1)

xm <- arima.sim(n,model=list(ar=0.5),innov=e1)
ym <- arima.sim(n,model=list(ar=0.6),innov=e2)

eq1<-dynlm(xm~L(xm)+L(ym))
eq2<-dynlm(ym~L(xm)+L(ym))

res<-rbind(residuals(eq1),residuals(eq2))

omega <- 1/n*tcrossprod(res,res)

xx <- rbind(1,xm[-1000],ym[-1000])

xxinv <- solve(tcrossprod(xx,xx))

c1 <- coef(eq1)[1]
c2 <- coef(eq2)[1]

chi <- (c1-c2)^2/(xxinv[1,1]*(omega[1,1]-2*omega[1,2]+omega[2,2]))

1-pchisq(chi,1)

After playing with different values of means, it seems that statistic is working more or less. Of course the results should be tested for different values of variance of errors and different AR specifications and different sample sizes. On the other hand from theoretical point of view statistic is quite nice, since it allows unequal variances.
Update Out of curiosity I did some MC simulations. For this I wrote a bit more efficient version of test:
ham.test.lm2 <- function(xm,ym) {
    n <- length(xm)

    df <- cbind(x=xm[-1],y=ym[-1],lx=xm[-n],ly=ym[-n])
    eq1<-lsfit(df[,3:4],df[,1])
    eq2<-lsfit(df[,3:4],df[,2])

    res<-rbind(residuals(eq1),residuals(eq2))

    omega <- 1/n*tcrossprod(res,res)

    xx <- rbind(1,xm[-n],ym[-n])

    ch <- chol(tcrossprod(xx,xx))
    xxinv <- chol2inv(ch)

    c1 <- coef(eq1)[1]
    c2 <- coef(eq2)[1]

    chi <- (c1-c2)^2/(xxinv[1,1]*(omega[1,1]-2*omega[1,2]+omega[2,2]))

    res<-1-pchisq(chi,1)
    names(res) <-NULL
    res
}

This runs about 60 times faster than the original. Then I wrote special function for generating two AR(1) processes given their parameters.
gen.arima <-function(n,N,mn1,mn2,rho1,rho2,sd1=1,sd2=2,burn.in=50){
    foreach(i=1:N,.combine=c) %dopar% {
        e1 <- rnorm(n+burn.in,mn1,sd=sd1)
        e2 <- rnorm(n+burn.in,mn2,sd=sd2)

        xm <- arima.sim(n+burn.in,model=list(ar=rho1),innov=e1)
        ym <- arima.sim(n+burn.in,model=list(ar=rho2),innov=e2)

        list(window(cbind(xm,ym),start=burn.in+1))
    }
}

This function generates N pairs of n sized sample of two AR(1) processes.
Then I ran the following simulation.
library("iterators")
library("foreach")
library("multicore")
library("doMC")
registerDoMC(16) ##the simulations ran on server with 2 quad-core Xeon processors with HT

rho <- seq(0.1,0.9,by=0.1)
nr <- length(rho)

rr <- numeric()
for(i in 1:nr) {
    for(j in (i):nr)
      rr <- rbind(rr,cbind(rho[i],rho[j]))
}

mu <- seq(0,2,by=0.1)

rrm <- foreach(m=mu,.combine=rbind) %do% {
   cbind(rr,m)
}

nn <- c(10,30,100,500,1000)

rrmn <- foreach(n=nn,.combine=rbind) %do% {
   cbind(rrm,n)
}

rrmns <- foreach(s=c(0.1,0.5,1),.combine=rbind) %do% {
   cbind(rrmn,s)
}

colnames(rrmns) <- c("rho1","rho2","mudiff","slen","sigma")

cc <- system.time(res <- foreach(i=1:nrow(rrmns),.combine=rbind) %dopar% {
    a <- rrmns[i,]
    aa <- gen.arima(a[4],500,2,2+a[3],a[1],a[2],a[5],a[5])
    hm<-sapply(aa,function(x)ham.test.lm2(x[,1],x[,2]))
    tt<-sapply(aa,function(x)t.test(x[,1],x[,2])$p.value)
    h1<-sum(hm<0.05)/length(hm)
    t1<-sum(tt<0.05)/length(tt)
    c(a,h1,t1)
})

write.csv(file="hammc.csv",res)

This simulation calculates the number of times the statistic rejects the null hypothesis that the means are zero for various sample sizes and various combinations of parameters of AR(1) processes. I used the maximum burn in for $\rho=0.9$ when generating AR(1) processes. I also compare the performance of the statistic to simple t-test. The resulting data.frame can be downloaded here.
Here is a few graphs illustrating the perfomance.

This is for AR(1) processes with $\rho=0.1$, 0.1 and 1 indicate the variance of the errors. mudiff is the true difference of the means.
Here is the similar graph for $\rho=0.9$:

Now the same graphs for t.test ($\rho=0.1$):

And $\rho=0.9$:

Here is the code which produced the graphs:
mc <- read.csv("hammc.csv")
colnames(mc)[7] <- "Hamilton"
colnames(mc)[8] <- "t.test"
colnames(mc)[5] <- "sample.size"
qplot(x=sample.size,y=Hamilton,data=mc[mc$sigma!=0.5 & mc$rho1==0.1 & mc$rho2==0.1,],group=mudiff,geom="line",color=mudiff)+facet_wrap(~sigma)
qplot(x=sample.size,y=Hamilton,data=mc[mc$sigma!=0.5 & mc$rho1==0.9 & mc$rho2==0.9,],group=mudiff,geom="line",color=mudiff)+facet_wrap(~sigma)
qplot(x=sample.size,y=t.test,data=mc[mc$sigma!=0.5 & mc$rho1==0.1 & mc$rho2==0.1,],group=mudiff,geom="line",color=mudiff)+facet_wrap(~sigma)
qplot(x=sample.size,y=t.test,data=mc[mc$sigma!=0.5 & mc$rho1==0.9 & mc$rho2==0.9,],group=mudiff,geom="line",color=mudiff)+facet_wrap(~sigma)

Conclusions Note that the graphs measure the power of the statistic for mudiff greater than zero and size of the test for zero mudiff, so ideally the the blue line for mudiff=0 should be straight line at 0.05, and all the other lines should be straight lines at 0.95. Since the statistic is assymptotic this does not happen. What it is clear that t.test is not suitable for higher values of $\rho$, it performs quite nice for $\rho=0.1$, but very bad for $\rho=0.9$. Hamilton's test on the other hand has low power even for larger sample sizes when the true difference in means is not very large. Also the results are the same for error variance 0.1 and 1, so I do not rule out the error in my code.
Comment: What would your approach be when $X_i$ and $Y_i$ are sampled at different times?


How to measure similarity/agreement between two temperature time series?

Question: I am developing an application to compare temperatures from two locations, in the same span of time.
For example, temperature is measured every hour for three months straight in two different cities.
What would be a good way to compare these two data sets, and to come up with a agreement measure? What I am asking for is some measure of how identical or different the temperatures are. For example, if at 11 o'clock in a certain day in Oslo it is 3 degrees and in Athens it's 26 degrees, they would be markedly different, while if the temperatures were 23 and 21 degrees, respectively, we would consider them to be closer to the same measurement for these two cities. What I desire is to compare the lists of temperatures to make a combined report of how these temperatures agree/disagree overall.
Comment: As you're aware, similarity or more precisely dissimilarity between temperatures is measured as a difference. (That may seem obvious, but there are many variables where it's arguable that a ratio or something else is a better scale for comparison.) So far so good, but what else are you asking? The more places differ in location, the more cycles of daily and seasonal variation will differ, all the way down to phase differences as well as amplitude differences. More  positively, additive shift is often a very good first approximation for nearby places.
Comment: "What would be a good way"...clearly there are multiple ways emerging, so can you specify what your definition of "good" is?  Otherwise I'm afraid the thread is going to be closed as too open-ended.  Though maybe it seems people are spending more time evaluating your question than answering it :-(
Comment: Please explain what it means for two temperatures to be "similar," if it is anything other than *equal*.
Comment: All outside temperatures going to have daily cyclicality, and will look similar in that regard
Comment: @whuber Thanks for pointing that out. I edited the question.
Comment: did you try root mean squared difference between temperatures at the same time of the day?
Comment: I want to add to earlier comments and existing suggestions by suggesting that quoting mean temperatures and the difference between them is the most direct way of quantifying (dis)similarity, especially for non-technical audiences.
Comment: I am not trying to find fault (least of all with @Carl who is only trying to help) but I didn't vote to reopen. I am now focusing on how this may or may not be useful to future readers. I won't argue backwards from there being an accepted answer to the question being clear. The question has to stand on its own two feet and seem clear. Future readers wanting to know how to measure similarity would also be asking a vague general question if they asked the same question: it needs to be made precise. I work with environmental data and have even published a little on comparing temperatures!
Comment: (ctd) None of that stops the thread being indirectly helpful -- but is the question clear? Sorry, still no.
Comment: @Carl. No, no, no, as far as I am concerned. First, whether other questions have been handled badly is immaterial to this one being handled well. Second, it's not any member's job to decide what a question should have or might have been. Being a moderator or even having a moderate reputation doesn't change that. At most, the OP proposes, the community may dispose, but the community doesn't change the question. At most, one can make edits to trivia and trivia are what don't discernibly change the question.
Comment: https://stats.meta.stackexchange.com/questions/2810/editing-questions-dos-and-donts skates around this, but I think it is clear even if tacit: no member but the OP has privileged insight into what an OP's question really is, even if it turns out that they understand it well. That doesn't rule out suggesting a better or different question.
Comment: We're stuck here and it's far from ideal, but only the OP's rewording to make the question match the answer can salvage that, and I've got to say that sounds like an unfair and contrived request. I've answered threads here with "use concordance correlation" as the focus of an  answer, so I don't see need to do that again myself.
Comment: @Carl I am just one of several people who have commented and/or voted one way or the other. I am unhappy as you are unhappy (although not as much) about the status of the thread, but pretending to change my mind to make you happier is (I trust) not what you want me to do.  Further, I am queasy about discussing how much an OP knows as any kind of basis for what we do with a question. This is all Meta stuff again....
Comment: @Aksakal  Point taken. I added an edit to the question.
Comment: Weather is naturally more than a matter of temperature. It's not clear what that is crucial to your project.
Comment: Similarity would usually be measured by agreement, and, that would not be the best choice here. Better would be ARIMA or other regression. Better yet would be to have multiple years of data to make a lookup table of temperature conversion.
Comment: You can view the edits by left clicking on the red text "edited...ago" above my logo. If you don't like the edit, and wish to keep the prior version, look at the second (vertical) gray bar for the "rollback" button.
Comment: @NickCox I do not see what is currently wrong with this question, do you?
Comment: @NickCox I cannot imagine how to pose the question so that it is more clear. Let us invert this and ask you how to pose a question whose answer is Lin's concordance correlation coefficient. For my own sake the question seems natural and realistic. Consider the truly stupid question, e.g., https://stats.stackexchange.com/q/4768/99274. We suspend [disbelief](https://stats.stackexchange.com/a/339941/99274) to answer those, even though such questions are worthless. Can you edit this question to clarify it?
Comment: @NickCox This question was closed, then reopened then closed and is 2/5 reopened. OK, so there are two point of view here. I see "In what ways can we compare the temperature time series in two different geographic locations?" Sure the OP had an inclination toward a measure of agreement, but I do not see that as central to the question because the OP lacks experience and implied discarding that preference if needed. What is unclear for you in this question? This goes beyond curiosity for me; I just don't get it.
Comment: Let us [continue this discussion in chat](https://chat.stackexchange.com/rooms/75856/discussion-between-carl-and-nick-cox).
Comment: Sorry, no: I really have nothing else to add.
Answer: <code>Edit after OP edit and user comments, downvoters should reconsider their opinions, please. This is currently an accepted answer, one user has removed his downvote. Downvoting without leaving a comment is not constructive at this point.
</code>
I did not at first see the OP edit while I was answering. There are no really good answers to the question. What there is is a simplest answer to the question; to look up or calculate directly the mean temperatures in both locations, and then subtract them to find an expected difference in temperature at any particular time on any particular day. Mean temperatures require approximately 10 years of data to establish that mean, and or a time series like ARIMA. Three months of data from a single year would not be as useful. Next most useful would be regression, next most useful would be correlation. Agreement would not be a very useful measure because it is not information rich enough to explain how the temperatures covary. Details follow.
A squared correlation coefficient is called the coefficient of determination. The coefficient of determination, symbolically $r^2$, would give the fraction of variance  between temperatures that is mutually explained, and occurs at the same time.
I found daily average temperatures compiled during 2010 for Augusta, Maine and Miami, Florida. Here is a chart:

The correlation is $r=0.990128135$ and the coefficient of determination is   $r^2=0.980353723$. The 2261 km distance between those cities is similar to the 2607 km Athens to Oslo distance. Like Athens and Oslo, Miami and Augusta are in the same time zones, meaning that the daily temperature highs and lows will be correlated positively so that if hourly data were readily available, that would correlate. Now if unique measurements rather than averages were included, that may lower the coefficient of determination, nonetheless the correlations are higher than even I suspected. Note on the chart that there is a doubled hysteresis loop presumably largely due to the difference in timing of temperature modification by the proximity of the Labrador current in Maine, and the Gulf stream current for Miami.
One can convert between Miami and Augusta temperatures using bivariate regression, i.e., using Passing-Bablok invertible (unlike OLS) regression $F(Miami)= 0.3203 F(Augusta) + 62.38$. Moreover, the chart shows a quite smooth progression of temperatures along a curvilinear closed path in a one year loop. Now on any particular day of the year, or any particular time of day, there is a difference in temperature between the two sites that is on average fairly stable. If you want to know what it is, calculate or look up that difference. For example, for @gung, here are those average annual temperature differences between the two sites in degrees F compiled on days 0-365 of 2010.

If you want to measure agreement then Lin's concordance correlation coefficient would be one alternative, but not a very useful one (see below). This is similar to an intraclass correlation and measures how distant an agreement is from the identity line $y=x$. Agreement is not the right question to ask of a time series model, like an
<code> ARIMAProcess[1.8589*10^-17, {0.05033}, 2, {-1.58602, 0.747954}, 0.00377009].
</code>
See ARIMAProcess.
Here are average monthly temperatures from Oslo, Sweden and Melbourne, Australia in degrees centigrade with correlation and coefficient of determination. For the OP, coefficient of determination in Excel is =correl(cell:cell,cell:cell)^2.
<code>     Melbourne  Oslo
Jan      21      -3
Feb      21      -3
Mar      19       2
Apr      17       5
May      14      12
Jun      11      16
Jul      10      18
Aug      11      16
Sep      13      12
Oct      15       7
Nov      17       2
Dec      19      -3
</code>
$r=-0.981726823$ and $r^2=0.963787555$. Note how high the negative correlation is between two points on Earth that could not be further apart.
OLS regression shows this
<code> Term       |Coefficient |95% CI            |SE     |t statistic |DF |p
 Intercept  |37.77       |33.42 to 42.13    |1.955  | 19.32      |10 |<0.0001
 Slope      |-1.98       |-2.25 to -1.71    |0.121  |-16.31      |10 |<0.0001

 Oslo = 37.77 - 1.98 Melbourne
</code>
Let us compare those results with Lin's concordance:
$$r_c=\frac{2 \rho  \sigma _x \sigma _y}{\sigma _x^2+\left(\mu _x-\mu _y\right){}^2+\sigma _y^2}\,,$$
which is $r_c=0.148498 $ for the Augusta to Miami value, and $r_c=-0.38624$ for the Oslo to Melbourne concordance. So in the first case, the concordance is weak, and in the second case there is a slightly stronger disagreement. This doesn't go very far in explaining the differences in temperature.
Comment: (-1) Surely however closely correlated the hourly temperatures may be in Athens & Oslo, they're not *similar*.
Comment: I didn't downvote but sorry, I won't upvote this either. I am still unclear what the OP wants and won't answer an unclear question. . Trying to guess what the question is and then answering it is fine, but does not justify remarks like "peanut gallery" or "vindictive" directed at people who take a different view. Downvoting answers you think is wrong is allowed. If I was obliged to guess what the OP wants, I think it's not much more than a mean or median difference in temperature. I don't think $R^2$ or correlation or concordance correlation is likely to help at all, but that is just a guess.
Comment: Much better now IMO. Lin's concordance is perhaps the type of similarity index the OP's looking for, but I think you show how the reduction of two data series to a single number isn't very informative about the nature of the differences between them.
Comment: I don't think this merits 3 downvotes, although I don't think it's right, either. It is a valiant effort. Carl, you suggest $r^2$; the OP thought about the difference b/t temps. Consider the example you illustrate: $r^2=.98$, which sounds pretty similar, but consider that when A=19, M=68, a 49 degree difference, & when A=71, M=84, a 13 degree difference. Given the OP seems to want temps to have a small constant difference, do those seem as similar as $r=.98$ intuitively implies? They wouldn't to me.
Comment: For a fuller understanding of my concern about this, it may help to read my answer here: [Does Spearman's $r=0.38$ indicate agreement?](https://stats.stackexchange.com/a/199714/7290)
Comment: @Carl sometimes I think I need a degree in Law to post a question in this site. Thank you, your answer answered my question, although many people found it unclear.
Comment: @Scortchi Extensive edits performed, downvotes remain, please reconsider your downvote. I am frankly appalled and am reconsidering my participation on this site, too negative for my tastes.
Comment: @gung Thanks, I know, but agreement would be not very useful either as the differences are predictable, but a time series, not a constant.
Comment: @hms Your question was both clear and unpretentious. If you want, I can attempt a bit of a rewrite to try to get it off of a hold, but with no guarantees. Some of them, however, do have hearts of gold, speaking of which, thanks for the question, it took work to think it through and although the work is is own reward, it's nice to have it appreciated, at least occasionally, rather than just reacted to reflexly.
Comment: @NickCox Thanks, the OP just wanted something to quantify  concordance or intraclass correlation, but apparently lacked the vocabulary to express that request in standard form. Understanding that required thought, and multiple attempts on my part. Whilst I was doing that the negativity to both the question and its answer was off putting, insulting really to both the OP and your's truly. People can take any view they want on this site, and trust me, it is too often ill-considered. However, there are people who help as well, and I work for them.
Comment: @Scortchi Thanks, you had constructive criticism, and that helped. The downvotes didn't and having the question, which after due consideration is clear to me, on hold, I do not think meritorious.
Comment: @NickCox The "peanut gallery" comment is removed. Downvoting is not as useful to a democracy as either qualified expert opinion or upvoting, read  [this](https://stats.meta.stackexchange.com/a/4462/99274) please.
Comment: @gung Thanks. Your opinion helped me to appreciate that a measure quantifying agreement was central to the OP question, which allowed me to extensively rewrite my answer.


Intel quad port gigabit PCI-e card on Poweredge 410

Question: I installed the card and booted the server. It showed the embeded two ports as eth0 and eth1. From the PCI-e card it showed just 2 ports, one eth2, and another one as eth0-renamed.
I connected a cable to all the PCI-e card ethernet slots, only on two slots the backlit lights up, and on the other two it doesn't.
I booted into the BIOS and there also only two ports from the PCI-e card are shown.
So my question is: does ubuntu server kernel have divers for Intel quad port ethernet card? Or is it the card is a faulty one? And why are all 4 ports were not shown in the BIOS?
Comment: this is a server queston and I do not think it will do well on askubuntu personally.
Answer: If the bios itself cannot see all the ports, the card may be incompatible with the motherboard or the card may be defective.
Comment: Sounds correct. If two ports don't even get link-level lights then it's a faulty card.


Thought for Magento 1 ongoing support

Question: Magento team decided that they will postpone the support for Magento 1 (source) , Is there any specific reason behind this ? Because previously they Informed that they will end support for Magento 1 at 17 November 2018(@benmarks at at #mm17cz) .
Still Magento team not sure about Magento 2 ?  And for new projects should we continue with Magento 2 or Magento 1 ? Any thoughts for this ?
Thanks,
Answer: Now I always prefer M2 over M1 for new projects.
Because we all know in near future Magento will stop its support for M1, right now its just postponed. So may be in 2019 or after that, they might stop their support for Magento 1.
So for my point of view M2 is future.
Comment: Thanks for the answer @Murtuza, I do agree with you. But after this decision from Magento I am scratching my head :)

Thought for Magento 1 ongoing support


Several 3-way ANOVA vs one 4-way ANOVA

Question: I have experiment leading to 4-way ANOVA:

3 experimental groups.
participants in each group responded to 70 trials.
Reaction time as DV.
trials were divided into separate groups by full factorial design by three variables A,B and C.

I'm not sure what is the best way to analyze the data. I can run one 4-way ANOVA with (RT ~ group*A*B*C) or run three 3-way ANOVAs for each group separately (RT ~ A*B*C).
What is the best practice? Run one 4-way ANOVA, but harder to interpret, or run three 3-way ANOVAs and correct for multiple testing?
Comment: Please consider:  if each variable, A, B, and C, had just 2 levels, then there would be 2x2x2=8 groups.  Does this design really have only 3?  And if so, what splits the participants into these 3?  I suspect that where you speak of "variables" you actually have 3 levels of a single variable.
Comment: Sorry for the confusion. Group is also a variable (with 3 levels), variables A,B and C have 2,2 and 3 levels respectively.
Answer: If you are not really interested in the comparison between groups go for the 3-way definitely. The 4-way case will end up with A LOT of interactions for you to study. This is very complex and tiring...
Comment: Thank you, unfornutaly, I'm interested in comparison between groups. Can I run three 3-way anovas and correct for type I error? I'm not sure, how to interpret significant coeficients for higher level interactions.
Comment: So one analysis for each group is not an option. You could remove one of the factors or run the analysis with all 4 of them, selecting what interactions and main effects you think are important to be interpreted.

Several 3-way ANOVA vs one 4-way ANOVA


Using Google Chart's timeofday data type is drawing the hour data incorrectly. All hours are displayed 5 hours behind

Question: I am trying to draw a simple bar chart using the Google Charts API but I am very confused as to what I'm doing wrong with the 'timeofday' column data type. The Google Charts documentation says that timeofday should be an array of 3 or 4 numbers and they site this as an example
"For example, the time 8:30am would be: [8, 30, 0, 0], with the 4th value being optional ([8, 30, 0] would output the same timeofday value)."
When I open their example in a JSFiddle, the time you see above in my quoted example gets displayed in the bar chart as "3:30:45" This is very perplexing. All of the data I enter for time is displayed as 5 hours behind the hour value I enter. The hour value in the example above is 8, but when drawn becomes a 3.
Here is function where the data is entered
function drawChart() {

      var data = new google.visualization.DataTable();
      data.addColumn('timeofday', 'Time of Day');
      data.addColumn('number', 'Emails Received');

      data.addRows([
        [[7, 30, 0], 5],
         [[9, 30, 0], 12],
          [[20, 30, 0], 3],
           [[22, 30, 0], 22]
      ]);

      var options = google.charts.Bar.convertOptions({
        title: 'Total Emails Received Throughout the Day',
        height: 450
      });

      var chart = new google.charts.Bar(document.getElementById('chart_div'));

      chart.draw(data, options);
    }

Answer: it must be a bug with Material charts
if you console.log the formatted values prior to drawing
-- or --
draw a corechart in addition
this causes the values in the tooltip to show correctly on the Material chart
but nothing seems to resolve the axis values
tried adding hAxis.format and hAxis.ticks -- neither worked
the CoreChart seems to work fine
you could use theme: 'material' to get it close to the look of a Material chart
see following example...

google.charts.load('current', {
  callback: function () {
    var data = new google.visualization.DataTable();
    data.addColumn('timeofday', 'Time of Day');
    data.addColumn('number', 'Emails Received');

    data.addRows([
      [[7, 30, 0], 5],
      [[9, 30, 0], 12],
      [[20, 30, 0], 3],
      [[22, 30, 0], 22]
    ]);

    console.log(data.getFormattedValue(0, 0), (new Date()).getTimezoneOffset());
    console.log(data.getFormattedValue(1, 0), (new Date()).getTimezoneOffset());
    console.log(data.getFormattedValue(2, 0), (new Date()).getTimezoneOffset());
    console.log(data.getFormattedValue(3, 0), (new Date()).getTimezoneOffset());

    var options = {
      title: 'Total Emails Received Throughout the Day',
      height: 450,
      hAxis: {
        format: 'H:mm',
        ticks: [data.getValue(0, 0), data.getValue(1, 0), data.getValue(2, 0), data.getValue(3, 0)]
      },
      theme: 'material'
    };

    var chart = new google.charts.Bar(document.getElementById('chart_div'));
    chart.draw(data, google.charts.Bar.convertOptions(options));

    var chart2 = new google.visualization.ColumnChart(document.getElementById('chart_div2'));
    chart2.draw(data, options);
  },
  packages:['bar', 'corechart']
});

Answer: There is nothing wrong with your addRows call. The horizontal axis doesn't align no matter the dataset.  However, you can update your var options to resolve this. Below example formats the hAxis from 8a.m. to 2p.m skipping every other hour. The key is to tick on timeofday data.  For more information refer to Google doc:  https://developers.google.com/chart/interactive/docs/gallery/barchart and scroll to down to the hAxis.ticks section.
hAxis: {
  title: 'Time of day',
      ticks: [[8,0,0],[10,0,0],[12,0,0],[14,0,0]]
}


How to read Whatsapp email file in R?

Question: Whatsapp has an option to email the group conversation to yourself. I did that and now want to explore it in R. The problem is that it seems to have multiple separators which I don't know how to handle in R.
Here is what I tried:
library(readr)
library(dplyr)
> gf <- read_delim('df.txt', col_names = F, skip = 2, delim='\t')
Warning message:
15 problems parsing 'df.txt'. See problems(...) for more details.
> head(gf)
Source: local data frame [6 x 12]

       X1       X2                           X3 X4 X5 X6 X7 X8 X9 X10 X11 X12
1  9:14pm  Mar 31                  umair: Great       NA NA NA NA  NA  NA  NA
2  9:14pm  Mar 31              umair: I am back       NA NA NA NA  NA  NA  NA
3  9:15pm  Mar 31                     umair: ??       NA NA NA NA  NA  NA  NA
4 10:27pm  Mar 31      umair: Kon kon zinda hay       NA NA NA NA  NA  NA  NA
5 10:49pm  Mar 31   Kazim: Sab zinda hain .....       NA NA NA NA  NA  NA  NA
6 10:50pm  Mar 31              umair: Very good       NA NA NA NA  NA  NA  NA

Can you help me read this file so that the "sender:message" is separated into 2 columns? And the first 2 columns are read as separate columns as shown. Obviously I don't want columns X4 to X12.
Edit:
Here are the first few lines of the raw file:
9:14pm, Mar 31 - umair: Great
9:14pm, Mar 31 - umair: I am back
9:15pm, Mar 31 - umair:
10:27pm, Mar 31 - umair: Kon kon zinda hay
10:49pm, Mar 31 - Kazim: Sab zinda hain .....
10:50pm, Mar 31 - umair: Very good
10:52pm, Mar 31 - umair: Abid agaya dobara?
10:54pm, Mar 31 - Kazim: Nai wo nai aya
10:54pm, Mar 31 - umair: Hmmmmmmmmm

Comment: You could use `separate()` from the `tidyr` package or `cSplit()` from the `splitstackshape` package to separate sender and message. If you want to combine X1 and X2, you could use `unite()`. If you do not want to have X4-X12, you could simply drop the columns.
Comment: Add sample file. May be first few lines of `df.txt`
Comment: Great. I think you have something like this. I leave the following as a reference. `separate(gf, X3, c("sender", "message"), sep = ": ") %>% unite(date, X1, X2, sep = " ") %>% select(1:3)`
Answer: This question is old, yet when I wanted to do the same thing, my google search lead me here. I figured it out and put it into an R package. Install and read in the data:
devtools::install_github("JBGruber/rwhatsapp")
library(rwhatsapp)
gf <- rwa_read("df.txt")

Or you can directly paste in the lines
> lines <- c(
  "9:14pm, Mar 31 - umair: Great",
  "9:14pm, Mar 31 - umair: I am back",
  "9:15pm, Mar 31 - umair:  ",
  "10:27pm, Mar 31 - umair: Kon kon zinda hay",
  "10:49pm, Mar 31 - Kazim: Sab zinda hain .....",
  "10:50pm, Mar 31 - umair: Very good",
  "10:52pm, Mar 31 - umair: Abid agaya dobara?",
  "10:54pm, Mar 31 - Kazim: Nai wo nai aya",
  "10:54pm, Mar 31 - umair: Hmmmmmmmmm"
)
> rwa_read(lines)
# A tibble: 9 x 3
  time                author text
  <dttm>              <fct>  <chr>
1 2018-03-31 21:14:13 umair  Great
2 2018-03-31 21:14:13 umair  I am back
3 2018-03-31 21:15:13 umair  " "
4 2018-03-31 22:27:13 umair  Kon kon zinda hay
5 2018-03-31 22:49:13 Kazim  Sab zinda hain .....
6 2018-03-31 22:50:13 umair  Very good
7 2018-03-31 22:52:13 umair  Abid agaya dobara?
8 2018-03-31 22:54:13 Kazim  Nai wo nai aya
9 2018-03-31 22:54:13 umair  Hmmmmmmmmm

How to read Whatsapp email file in R?


investing in three stocks with minimum investment

Question: An investor wishes to invest up to ¤12K in three different stocks. Each investment
must be made in units of ¤1K. How many different possible investment strategies
does he have?
Comment: So, you are asking how many ways the sum of three nonnegative integers, $x+y+z \le 12$?  What have you tried?
Answer: Write them out.
0 0 12
0 1 11
0 2 10
0 3 9
0 4 8
0 5 7
0 6 6
1 1 10
1 2 9
1 3 8
1 4 7
1 5 6
2 2 8
2 3 7
2 4 6
2 5 5
3 3 6
3 4 5
4 4 4
Now for each combination take the # of permutations and then add all those numbers up.
For example, for 0 0 12, we have $\frac{3!}{2!}$, 3! because there are 3 elements and 2! because there are 2 elements that are the same.
Same for 1 1 10: $\frac{3!}{2!}$
What about 1 2 9?
What about 4 4 4?
Comment: Welcome to Math.SE!  This will get to the answer, but can you think of an approach that doesn't require a "write them out" step?
Comment: @hardmath Dynamic programming?
Comment: Since the OP wants only a count ("how many different..."), I was thinking about the usual stars-and-bars treatment, discussed in many previous Questions.


How to call function in a veiw in codeigniter?

Question:

this is my view file of index but iframe is not working properly please tell me , which source can i give?
<?php
class Home extends CI_Controller {

    function index()
    {       $this->load->helper('url');
            $this->load->view('index');
    }

    function slider()
    {
            $this->load->view('slider');
    }
}?>

this is my home.php
Answer: Home is your class name and first try to remove index.php using .htaccess and your url should be like this
src="<?php echo site_url('home/slider'); ?>"

removing index.php use this code in your .htaccess
<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^(.*)$ index.php?/$1 [L]
</IfModule>

Comment: when you use site_url, you no need to worry about the htaccess or index.php
Answer: use site_url() in source (src)
example :-
site_url('home/slider');


Let M, K, and L be points on line (AB), (BC), and (CA), respectively. Find the maximum area of smallest the three triangles MAL, KBM, and LCK?

Question: Let M, K, and L be points on line (AB), (BC), and (CA), respectively. Find the maximum area of smallest the three triangles  MAL,  KBM, and  LCK in respect to ABC?
I try to guess the answer and then prove it, however it doesn't work to randomly guess.
I draw some pictures, but it hardly tells me anything
Comment: The question as written is not clear.
Comment: @AndresCaicedo, randomly guessing to find the answer...
Comment: In other words: Find the minimum area of $\triangle KLM$ inscribed in $\triangle ABC$, correct? (Maximizing the areas of the three corner triangles minimizes the area of the center triangle.) That's easy: Take $K=L=C$ and $M=B$.
Comment: What does not work?
Comment: Why wouldn't it be the triforce?
Answer: We shall denote the area of a triangle $ABC$ with $S_{ABC}$. We shall prove that $\min(S_{MAL}, S_{KBM}, S_{LCK}) \leq \frac{1}{4}S_{ABC}$.
Without loss of generality assume that $S_{MAL}=\max(S_{MAL}, S_{KBM}, S_{LCK})$. Clearly if $\frac{S_{MAL}}{S_{ABC}} \leq \frac{1}{4}$, we are done. Otherwise consider $\frac{S_{MAL}}{S_{ABC}}=\frac{AM}{AB} \cdot \frac{AL}{AC}>\frac{1}{4}$. Let $\frac{AM}{AB}=x, \frac{AL}{AC}=y, 0 \leq x, y \leq 1$. Then $xy>\frac{1}{4}$. Also, we have $\frac{MB}{AB}=1-x, \frac{LC}{AC}=1-y$. Clearly if any of $K, L, M$ are equal to $A, B$, or $C$, then $\min(S_{MAL}, S_{KBM}, S_{LCK})=0 \leq \frac{1}{4}S_{ABC}$. Thus $0<x, y<1$.
Let $K'$ be on $BC$ s.t. $\frac{BK'}{CK'}=\frac{1-y}{1-x}$. Then $$\frac{S_{K'BM}}{S_{ABC}}=\frac{BK'}{BC} \cdot \frac{BM}{AB}=\frac{(1-x)BK'}{BC}=\frac{(1-y)CK'}{BC}=\frac{CK'}{BC} \cdot \frac{LC}{AC}=\frac{S_{LCK'}}{S_{ABC}}$$
If $BK \leq BK'$, then $$\frac{S_{KBM}}{S_{ABC}}=\frac{BK}{BC} \cdot \frac{BM}{AB} \leq \frac{BK'}{BC} \cdot \frac{BM}{AB}=\frac{S_{K'BM}}{S_{ABC}}$$
Otherwise $BK>BK'$ so $CK<CK'$, so $$\frac{S_{LCK}}{S_{ABC}}=\frac{CK}{BC} \cdot \frac{LC}{AC}<\frac{CK'}{BC} \cdot \frac{LC}{AC}=\frac{S_{LCK'}}{S_{ABC}}=\frac{S_{K'BM}}{S_{ABC}}$$
In any case, we have $$\min(\frac{S_{KBM}}{S_{ABC}}, \frac{S_{LCK'}}{S_{ABC}}) \leq \frac{S_{K'BM}}{S_{ABC}}=\frac{(1-x)BK'}{BC}=\frac{(1-x)(1-y)}{1-x+1-y}$$
It thus suffices to prove that $\frac{(1-x)(1-y)}{1-x+1-y} \leq \frac{1}{4}$, or equivalently, $\frac{1}{1-x}+\frac{1}{1-y} \geq 4$.
Note that $x>xy>\frac{1}{4}$ so $4x-1>0$. Thus
\begin{align}
\frac{1}{1-x}+\frac{1}{1-y}-4 & =\frac{1}{1-x}+\frac{4x}{4x-4xy}-4 \\
& >\frac{1}{1-x}+\frac{4x}{4x-1}-4 \\
& =\frac{(4x-1)+4x(1-x)-4(1-x)(4x-1)}{(1-x)(4x-1)} \\
& =\frac{12x^2-12x+3}{(1-x)(4x-1)} \\
& =\frac{3(2x-1)^2}{(1-x)(4x-1)} \\
& \geq 0
\end{align}
Therefore $\min(S_{MAL}, S_{KBM}, S_{LCK}) \leq \frac{1}{4}S_{ABC}$. Furthermore, equality holds when $M, K, L$ are the midpoints of $AB, BC, AC$ respectively, so $\max(\min(S_{MAL}, S_{KBM}, S_{LCK}))=\frac{1}{4}S_{ABC}$.


I need a numpy vector with the shape (N,1) and not (N,) for multiple inputs, __data_generator XY problem i need my X

Question: I need to have X[0].shape be (N, 120, 160, 3) which works but i also need X[1].shape = (N, 1, 1) but i only get (N,)
I have tried reshaping it but i didn't manage to make it work.
I am working on a data_generator. I am trying to load inputs from a camera on a car into XY to be able to train a model on it (goal make an self driving car).
I am struggling with it.
Here is the part that makes my head hurt.
image_data = {
    "image": np.zeros((120, 160, 3), np.float32),
    "speed": 3.4,
    "throttle": 0.4,
    "steering": 0.14,
}
inputs=["image", "speed"]
outputs=["steering", "throttle"]
batch_size = 64

X = []
Y = []
for j in range(len(inputs)):
    L = []
    for i in range(batch_size):
        data = np.array(list(image_data.items()))
        L.append(data[j][1])
    X.append(np.array(L))

Comment: To turn an array of shape `(n,)` into `(n,1)`, simply: `a_n1 = a_n[:, None]`. That being said, I have absolutely no idea what it is you are trying to accomplish. The code is strange enough that I can't infer what the intent is, and it raises a warning (rightly so) about "Creating an ndarray from ragged nested sequences". Sounds like an [XY problem](https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem). What are you actually trying to do?
Comment: indeed it is an X Y problem, I am trying to load inputs from a camera on a car into X and Y. For the car we can have multple inputs ranging from only the image to image the steering or even the throttle.
It is my first time doing __data_generator.
thanls for there help
Answer: Based on your current question, if you want to have a (64,1) shape, you can manually reshape it with np.reshape
X[1]=np.reshape(X[1],(64,1))

X[1].shape
Out[59]: (64, 1)

Again, it's inefficient to convert a list to numpy array and to list again. Do everything in a list first, only then, convert your X[0] and X[1] into numpy array.
for j in range(len(inputs)):
    L = []
    for i in range(batch_size):
        data = list(image_data.items())
        L.append(data[j][1])
    X.append(L)

Answer: Here is the fix I found, i wasn't shearching for the correct solution.
def __data_generation(self):
 X = [[] for _ in range(len(self.inputs))]
        Y = [[] for _ in range(len(self.outputs))]

        rdm_paths = np.random.choice(self.paths, size=self.batch_size)
        for path in rdm_paths:
            try:
                image_data = io.load_image_data(path)
                self.augm(image_data)
                for i, inp in enumerate(self.inputs):
                    data = np.array(image_data[inp])
                    if len(data.shape) < 2:
                        data = np.expand_dims(data, axis=0)
                    X[i].append(data)

                for i, out in enumerate(self.outputs):
                    data = np.array(image_data[out])
                    if len(data.shape) < 2:
                        data = np.expand_dims(data, axis=0)
                    Y[i].append(data)
            except Exception:
                logging.debug(f"Error processing {path}")

        X = [np.array(x) for x in X]
        Y = [np.array(y) for y in Y]

        return X, Y ```


How to fix: "Switch" statement in Python doesn't recognise input string

Question: I need to parse some action given by a client. The action is a simple string contained the word action: "load", "start", "pause",....
I come from C world and I am a newbie in Python. I need a switch statement and I did it with the switcher.get() function (see code below).
The problem is that this switcher doesn't recognize only the string 'load', the other strings works correctly (see output example below).
Why?
To analyze correctly the problem I give you only the switcher case beacuse the rest of the code works and it is useless for this part.
I try to give directly the string 'load' to the function but it goes directly to the except zone "Command not found"
switcher={
        'load': partial(load_wav,message_tocheck),
        'start': partial(start_wav,message_tocheck),
        'pause': partial(pause_wav,message_tocheck),
        'resume': partial(resume_wav,message_tocheck),
        'stop': partial(stop_wav,message_tocheck),
        'reset': partial(reset_ch,message_tocheck),
        'mqtt': partial(mqttrun),
        'help': partial(help),
        'zero':lambda:'lambda'
    }
    try:
        func=switcher.get('load','INVALID')
        return func()
    except:
        print('-------- COMMAND NOT FOUND --------')

OUTPUT:

load (DOESN'T WORK):

-------- COMMAND NOT FOUND --------

start (WORK):

Limits:        A = 0, B = 8, C = 0, D = 8
Wait sample = 690
LED MATRIX ON CHANNEL 0. STIMULATION RUNNING...

help (WORK):

---------------- help ----------------
The possible commands are:
INSERT ALL POSSIBLE TOPIC TO SUBSCRIBE
---------------- help ----------------
As you can see the only string that doesn't work is load. The problem is that I can't change the 'load' word with another one.
Answer: There's no way that switcher.get('load') generates an exception, so it must be the function call below.
Try this instead:
func = switcher.get('load')
if func is None:
    raise ValueError("Command not found")

func()  # at this point `func` is a valid member of `switcher`, but it still can raise exceptions

Why the code with try/except doesn't work:
The try block contains the call to func, which may be raising the exception. Also, probably at some point the dictionary doesn't contain the key you're looking for, so get returns a string, which you end up calling, which isn't possible, so you get an exception.
If you would like to use try/except, add an else clause:
try:
    func = switcher['load']
except KeyError:
    raise ValueError("Command not found")
else:
    # no exception was raised
    func()


Understanding SSL for consuming .Net webservice from Android

Question: I am developing an Android app which need to consume .Net webservices over SSL which I have no  experience in. Now I am looking for some guidance and explanation on SSL handshake and certificates.
Note: the server is using IP address and NOT domain name. It is an intranet application.
So far I have created a certificate(called self-signed?) in web server from IIS 7.
To consume it from Android app, I found two ways of doing it :
1). Embedded the certificate in the app (Which certificate? How do I get it?)
2). Trust all the certificates ( ppl said there is security issue with this approach, could you elaborate more? Does it still do the handshake?)
CERTIFICATES:
How many type of certificates are there in the handshake and what are they?
Does self-signed certificate have root certificate? If yes, how can i get them?
Is it possible to move/copy the self-signed certificate from one server to another?
HANDSHAKE:
First of all, is this process correct?
The SSL handshake process(copied from a website) is described below:

The client initiates the SSL handshake process by sending a URL
starting with the following: https:// to the server.
The client initially sends the Web server a list of each encryption
algorithm which it supports. Algorithms supported by SSL include RC4
and Data Encryption Standard (DES). The client also sends the server
its random challenge string which will be utilized later in the
process.
Will the embedded cert be sent in here?
The Web server next performs the following tasks:
Selects an encryption algorithm from the list of encryption
algorithms supported by, and received from the client.
Sends the client a copy of its server certificate.
Sends the client its random challenge string
The client utilizes the copy of the server certificate received from
the server to authenticate the identity of the server.
The client obtains the public key of the server from the server
certificate.
The client next generates a premaster secret. This is a different
random string which will in turn be utilized to generate the session
key for the SSL session. The client then encrypts a different value
called the premaster secret using the public key of the server, and
returns this encrypted value to the server. This is accompanied with
a keyed hash of the handshake messages, and a master key. The hash
is used to protect the messages exchanged in the handshake process.
The hash is generated from the former two random strings transmitted
between the server and the client.
What is a master key?
The server sends the client a keyed hash of all the handshake
messages exchanged between the two parties so far.
What is this keyed hash made from?
The server and the client then generate the session key from the
different random values and keys, and by applying a mathematical
calculation.
The session key is used as a shared secret key to encrypt and
decrypt data exchanged between the server and the client.

The session key is discarded when the SSL session either times-out or is terminated.
Comment: Unfortunately wour question is way too large for a good SO answer. First and foremost you should read [RFC 2246](http://tools.ietf.org/html/rfc2246). Also, this is a protocol question, not a programming question. By my understanding of the SO rules it is off-topic.
Answer: I'll try to answer to the best of my knowledge here

Embedded the certificate in the app (Which certificate? How do I get it?)
This the certificate identifying the client's/app identity. You can either get it through CA or self signed. This certificate will be used by the server to verify the client's/app identity
Trust all the certificates ( ppl said there is security issue with this approach, could you elaborate more? Does it still do the handshake?)
It still does the handshake but it doesn't do the certificate validation which is dangerous unless you are connecting internally (which seems you are). Trusting all certificate means an entity can claim as someone who they are not and thus could obtain confidential information from the users.
How many type of certificates are there in the handshake and what are they? In handshake you have the server's certificate and optionally the client certificate (for two factors authentication)
Does self-signed certificate have root certificate? If yes, how can i get them? Root certificate as far as I know means the ones that identifies by CA itself and thus it has no else to sign it. As your identity can still be verified and needs to be signed by CA, yours would not be classified as root certificate
Is it possible to move/copy the self-signed certificate from one server to another? The short answer is yes though the procedures from one platform to the others are different. Check [this link)(http://www.sslshopper.com/how-to-move-or-copy-an-ssl-certificate-from-one-server-to-another.html), it has instructions to copy certificate for few platforms
Will the embedded cert be sent in here? No, the embedded (client's) certificate is sent after validation of the server's identify is complete
What is a master key? Master key is the key that is used to derived the session key for later communication. It is also used to hash the messages and to verify authenticity of the messages in the next set of stages
What is this keyed hash made from? It's made from the master key sent by the client. In order to verify all messages, the server sent all messages that have been passed and hashed it with the master key. The client will hashed its messages as well with the same key and then compared with the data sent by the server. Only when the hash matches then we could be sure we are still communicating with the same server
Comment: thank you so much for your complete answer. As I mentioned, I am using IP address. Does it make any impact on the two methods (Embedded and Trust all)


Maximum number of spanning trees of a planar graph with a fixed number of edges

Question: Let $\mathcal{G}_m$ be the set of planar graphs with exactly $m$ edges. In this question, graphs are allowed to have multiple edges and/or loops.
I want to know what the maximum number of spanning trees of any graph in $\mathcal{G}_m$ is, as a function of $m.$ I suspect this question is too hard to have an exact formula, and so I am also interested in upper bounds for the maximum number of spanning trees of any graph in $\mathcal{G}_m$.
For small values of $m$, my (possibly incorrect) computations give me the following.

When $m=1$, the maximum number of spanning trees is $1$, realized by any connected graph with $1$ edge.
When $m=2$, the maximum number of spanning trees is $2$, realized by the graph with two vertices connected by two edges.
When $m=3$, the maximum number of spanning trees is $3$, realized by a $3$-cycle.
When $m=4$, the maximum number of spanning trees is $5$, realized by a $3$-cycle with one edge doubled.
When $m=5$, the maximum number of spanning trees is $8$, realized by a $3$-cycle with two edges doubled or by the complete graph $K_4$ with one edge deleted.
When $m=6$, the maximum number of spanning trees is $16$, realized by the complete graph $K_4$.

I could not find anything relevant in OEIS with respect to my computations so far. This is what leads me to believe that an exact formula may not be known.
Answer: This is a very, very tough question. It is obvious that for any graph $G$ with $n$ edges the number of spanning trees $t(G)$ does not exceed $2^n$ (each edge is either included in or excluded from a subtree; this is also the upper bound of the number of connected subgraphs of $G$). We can somewhat improve this - if $G$ has $m$ vertices ($m \leqslant n+1$) then we have
$$
t(G) \leqslant \binom{n}{m-1} < 2^n ,
$$
since we need to choose $m-1$ edges out of $n$ (not arbitrarily, of course).
It is a bit easier for the planar graphs but you are correct that the exact formula is not known. I will say more, there is no exact formula even for such a "simple" planar graph as $Z_{n,n}$, which represents $n \times n$ rectangular lattice.
However, there are a few upper and lower bounds, most of them pretty complicated. I suspect there should be an elementary proof for the following conjecture.
Conjecture. For any finite connected planar graph $G$ with $n$ edges we have
$$
t(G) < \tau^n,
$$
where $\tau$ is... say, $1.8$.
Perhaps I am a bit optimistic about 1.8 but there has to be some value of $\tau < 2$ for which an elementary proof exists. I am actually doing some low-tech research into that area right now...
An example: for large values of $n$ it is known that $t(Z_{n,n})$ is pretty close to $\tau^n$, where $\tau = e^{2C/\pi} \approx 1.7916...$, where $C$ is the so-called Catalan constant
$$
C = 1 - 1/3^2 + 1/5^2 - 1/7^2 \pm ...
$$
Comment: As a matter of fact, the conjecture above has a relatively elementary proof (found by yours truly) for $\tau \approx 1.96$. Of course, that is not very close to the hypothetical upper bound of $e^{2C/\pi}$, but at least it is something...
Comment: 1.9328... is the new $\tau$ - with an elementary proof. :)


Recommendations for an open-source project to help an experienced developer practice C++

Question: I'm looking for recommendations for open-source projects written in C++ that will help me "get my chops back".  A little background:

I've been working heavily in Java for the last three years, doing a lot of back-end development and system design, but with a fair amount of work in the presentation layer stuff, too.
The last C++ projects I worked on were a Visual C++ 6 project (designed to interact with Visual Basic) for mobile devices and several projects using the GNU toolchain circa gcc versions 2.x to 3.2
I'm looking to get back up to speed on the language and learn some of the popular frameworks, specifically the basics of boost (although boost seems fairly sprawling to me, similar to the kitchen-sink feel of Spring in the java space) and test driven development in C++.

What I'm looking for:
Specific recommendations for small to mid-size open source projects to poke through and perhaps contribute to as I level my C++ skills back up.  The problem domain isn't important, except that I would like to work on something in a new area to broaden my experience.
Edit:
A few people have commented that it's difficult to provide a recommendation without some indication of the problem domain I'd like to work in.  So, I've decided that I'm most interested in graphics applications or games, two areas which I haven't worked in before.
Answer: I would personally be working on Unladen Swallow if I wasn't absurdly busy starting my own personal venture. Dynamic language optimisation looks pretty cool to me.
Answer: If you like visual stuff, openFrameworks is a C++ Framework for doing Processing-type applications. http://www.openframeworks.cc/  I'm not sure how viable it still is, but it looked pretty cool.
It's hard to suggest something like this, you really don't have any itches you want to scratch??
Comment: I know that my request is a bit vague.  What's most important to me is getting up to speed on the language itself and learning new frameworks in a new problem domain.
Comment: Cool software, I'll check it out.
Answer: You could also look at Wt
Answer: Why not Boost itself? It's a very active project, it's right at the core of what C++ is about, and it could need some help.
You mentioned test driven development. The Boost Unit Test Framework, for example, is powerful, but IMHO suffers from extremly bad documentation. That'd be a place to start, would teach you everything there is to know about that particular part of Boost, and I am sure you could find your way into one of the Boost modules from there.
Answer: I think you're going to have to be more specific. As a quick check, I did an apt-cache showpkg libstdc++6 on my Debian squeeze system, to find all the packages that depend on the C++ library — and found 4,537 of them. Obvious examples include:

most of KDE
Firefox, Thunderbird, etc.
apt-get itself

It'd really help if you specified what field you're interested in.
Answer: You can find many projects on GitHub. If you find a nice project, you can fork it (it's like creating a local copy you can work on) and start coding. Once you have done something nice, you can make a "Pull request" to ask the guy you made your fork from to merge your work.
I like being able to commit without having to ask for an access and be able to make smalls contributions to many projects without having to contact anybody, simply with a couple of clicks.
You can also check Gitorious and Bitbucket, both site work a bit like Github.


Problems with DeserializeObject with an json array

Question: So I have a problem with DeserializeObject with an json array and I cant find what I am doing wrong here:
{"name":"Pannbiff n\u00f6tf\u00e4rs stekt","number":1128,"nutrientValues":
  {"energyKj":694,"energyKcal":166,"protein":17.2,"fat":7.6,"carbohydrates":7}}

My model looks like this:
And my code looks like:

var responseText = streamReader.ReadToEnd();
var jsonSerializer = JsonConvert.DeserializeObject(responseText);
public class Asware
{
    public IEnumerable<NutrientValues> nutrientValues { get; set; }

}

public class NutrientValues
{
    public int energyKcal { get; set; }
    public double protein { get; set; }
    public double carbohydrates { get; set; }
    public int fat { get; set; }
}

Can't see what can be wrong here I have also tried:
JsonConvert.DeserializeObject>(responseText)
Comment: It seems like C#.Please, add the language tag.
Comment: what is the error you're getting?
Answer: The problem here is that in your source JSON, nutrientValues is a single object, not an array of objects.
If you change your model as follows it should serialise correctly:

public class Asware
{
    public NutrientValues nutrientValues { get; set; }
}

Alternatively, if you have control of the JSON, then you can modify it to contain an array of nutrients as follows, the [ ] characters indicate multiple items.

{"name":"Pannbiff n\u00f6tf\u00e4rs stekt","number":1128,"nutrientValues":
  [{"energyKj":694,"energyKcal":166,"protein":17.2,"fat":7.6,"carbohydrates":7}]}


syntax error when to join or concat mysql

Question: I want to retrive the mysql result, but my query didn't work because I am new and computer programming or computer database.
SELECT guid, post_name
FROM `wp_posts`
WHERE `post_parent` = 0 and `post_type` = 'post' and post_title != 'Auto Draft'

Returns:
guid                    post_name
http://localhost/?p=21  post-2-title
http://localhost/?p=12  post-4-title

And
SELECT guid as children_url, post_parent as post_parent
FROM `wp_posts`
WHERE `post_parent` != 0 and `post_type` = 'attachment' and post_title != 'Auto Draft'

Returns:
children_url                               post_parent
http://localhost/attachment-post-1            12
http://localhost/attachment-post-2            12
http://localhost/attachment-post-3            12
http://localhost/attachment-post-4            12
http://localhost/attachment-post-5            12
http://localhost/attachment-post-6            12
http://localhost/attachment-post-7            12
http://localhost/attachment-post-8            12
http://localhost/attachment-post-9            21
http://localhost/attachment-post-10           21
http://localhost/attachment-post-11           21
http://localhost/attachment-post-12           21
http://localhost/attachment-post-13           21
http://localhost/attachment-post-14           21
http://localhost/attachment-post-15           21
http://localhost/attachment-post-16           21

I have tried several query but didn't succeed,
SELECT guid as children_url, post_parent as post_parent
FROM `wp_posts`
WHERE `post_parent` != 0 and `post_type` = 'attachment' and post_title != 'Auto Draft'
  and SELECT guid, post_name FROM `wp_posts`
      WHERE `post_parent` = 0 and `post_type` = 'post' and post_title != 'Auto Draft'

Raises the error:

1064 - You have an error in your SQL syntax; check the manual that
  corresponds to your MySQL server version for the right syntax to use
  near 'SELECT guid, post_name FROM wp_posts WHERE post_parent = 0
  and post_type =' at line 1

What I want the result like :
 children_url                              post_parent              post_paraent_guid       post_parent_title
http://localhost/attachment-post-1            12                    http://localhost/?p=12  post-2-title
http://localhost/attachment-post-2            12                    http://localhost/?p=12  post-2-title
http://localhost/attachment-post-3            12                    http://localhost/?p=12  post-2-title
http://localhost/attachment-post-4            12                    http://localhost/?p=12  post-2-title
http://localhost/attachment-post-5            12                    http://localhost/?p=12  post-2-title
http://localhost/attachment-post-6            12                    http://localhost/?p=12  post-2-title
http://localhost/attachment-post-7            12                    http://localhost/?p=12  post-2-title
http://localhost/attachment-post-8            12                    http://localhost/?p=12  post-2-title
http://localhost/attachment-post-9            21                    http://localhost/?p=21  post-4-title
http://localhost/attachment-post-10           21                    http://localhost/?p=21  post-4-title
http://localhost/attachment-post-11           21                    http://localhost/?p=21  post-4-title
http://localhost/attachment-post-12           21                    http://localhost/?p=21  post-4-title
http://localhost/attachment-post-13           21                    http://localhost/?p=21  post-4-title
http://localhost/attachment-post-14           21                    http://localhost/?p=21  post-4-title
http://localhost/attachment-post-15           21                    http://localhost/?p=21  post-4-title
http://localhost/attachment-post-16           21                    http://localhost/?p=21  post-4-title

Any help would appreciate.
Thank you
Comment: You want four columns, and asking for only two columns. Or did I just misread your question?
Comment: you are right, I am sorry because of my limited knowledge about database query
Answer: Try this
SELECT
    pc.guid as children_url,
    pc.post_parent as post_parent,
    pp.guid as post_paraent_guid,
    pp.post_title as post_parent_title
FROM
    wp_posts pc
    left join wp_posts pp on pp.ID=pc.post_parent
WHERE
    pc.post_type = 'attachment'
    and pc.post_title != 'Auto Draft'
ORDER BY
    pc.guid

Comment: anyway also how to limit retrieve from only categoryId 2?
Comment: add where condition `WHERE
    pc.post_type = 'attachment'
    and pc.post_title != 'Auto Draft' and categoryId=2`
Comment: I am sorry but Unknown column 'categoryId' in 'where clause', I use wordpress database
Comment: I don't have wordpress DB, so I can't say how it is organized


Atualização (Insert) dinâmico com ajax

Question: Pesquisei e ainda não consegui resolver este problema.
é um evento onclick que envia uma requisição ao arquivo update.php, que faz um update na tabela notificações.
Segue código abaixo:
Aciona o evento onclick:
<input type="hidden" name="id" id="id" value="'.$id.'">

Ajax dessa página:

Trecho do arquivo update.php, código:
$id = ($_POST['id']);
$sql = "UPDATE notif SET status = 1 WHERE id = :id";
$res = $pdo->prepare($sql);
$res->bindParam(':id',$id);
$res->execute();
$pdo->close();

O que pode estar errado?
Agradecido pela atenção.
Comment: Qual é o problema que te dá? O que é o `'#id'`? um `input`?
Comment: Ele não apresentava erro. Revi o código e removi "contentType:False"  "processData: False" e funcionou somente o método GET. O que pode estar errado pra funcionar o POST? O #id vem do value de um input
Answer: Quando passas um objeto como { id: id_n }, no data do ajax, o que o jQuery faz é converter em query string: id=oValorDe_id_n com o jQuery.param(). Tendo a opção processData: false ele impede isso. Removendo ele assume processData: true.
Podes ler mais sobre isso aqui (em Inglês)
Comment: Grato.
Mas ele só está passando via GET.

Outra coisa, como faço pra passar uma varíavel que varia por esse código?

tipo:

var id_n = $(  ).val();

tem jeito?

Agradeço
Comment: @AdrianoLeal daí a minha pergunta "O que é o `#id`".
Comment: É um input que é gerado por um laço.
São 8.
input type hidden id=idnot name=idnot value=$id

Atualização (Insert) dinâmico com ajax


Detect if all children are hidden and hide parent div using vanilla JS

Question: As the title suggests, I wwant to build a filter that hides elements. If all children are hidden then the paretn should also set itself to display none only I can't quite figure out how to approach it. I've tried the below with no luck.
https://jsfiddle.net/6wt0jndp/1/
function filter(e){
  search = e.value.toLowerCase();
  console.log(e.value)
  document.querySelectorAll('.kb-item').forEach(function(row){
     text = row.innerText.toLowerCase();
     if(text.match(search)){
        row.style.display="block"
     } else {
        row.style.display="none"
     }

      // need to count hidden items and if all instances of .kb-items are hidden, then hide .kb-item
     var countHidden = document.querySelectorAll(".kb-item[style='display: none;']").length;
     var children = document.querySelectorAll(".kb-items").length;

     if(countHidden > children){
       row.style.display="none"
     }

      console.log(countHidden);
  })
}

HTML

fruits

apple

banana

vegetables

lettuce

onion

carrot

Comment: Count the number of items you're hiding with `display: none`. And when the number of items is the same as the length of the collection you're iterating over (third parameter of the `.forEach()` callback) then all are hidden and you can hide the parent.
Comment: Please remove jquery tag from the question. You are asking about vanilla javascript and tagging jquery.
Answer: may be you can trigger two function on keypress . One would detect the elements state in a group which will detect whether all the  element is hidden or not. We can edit the below code a bit for dom efficency.
Hope this is the result what you are expecting
fiddle link : https://jsfiddle.net/binaryslate/2z1ptnao/1/
        <input type="text" onkeyup="filter(this);detectParent();"/>

        function detectParent()
        {
            var collectionref=document.querySelectorAll(".kb-items");
            collectionref.forEach(group=>{
            var itemcollection=group.getElementsByClassName("kb-item");
            var hidecounter=0;
            for(var j=0;j<itemcollection.length;j++)
            {

                if(itemcollection[j].style.display==='none')
                {
                    hidecounter++;
                }
            }
            if(hidecounter===itemcollection.length)
            {
                group.style.display="none";
            }else{
                group.style.display="block";
            }

            });
        }

Answer: You need to do things to parent after iterating children, not during doing it.

Get children for each parent they have, not whole .kb-item elements.
Compare the length of children and length of them with display: none style.

function filter(e) {
  // ...
  var parents = document.querySelectorAll(".kb-items");
  parents.forEach(parent => {
    if (parent.querySelectorAll(".kb-item").length == parent.querySelectorAll(".kb-item[style='display: none;']").length) {
      parent.style.display = "none"
    } else {
      parent.style.display = "block"
    }
  })

Complete code snippet:

function filter(e) {
  search = e.value.toLowerCase();
  console.log(e.value)
  document.querySelectorAll('.kb-item').forEach(function(row) {
    text = row.innerText.toLowerCase();
    if (text.match(search)) {
      row.style.display = "block"
    } else {
      row.style.display = "none"
    }

  })

  var parents = document.querySelectorAll(".kb-items");
  parents.forEach(parent => {
    if (parent.querySelectorAll(".kb-item").length == parent.querySelectorAll(".kb-item[style='display: none;']").length) {
      parent.style.display = "none"
    } else {
      parent.style.display = "block"
    }
  })

}
<input type="text" onkeyup="filter(this)" />

fruits

apple

banana

vegetables

lettuce

onion

carrot


Gauss-Newton local convergence

Question: Is it possible for the Gauss-Newton algorithm to converge to a local minima? How does convergence of Gauss-Newton to the correct minima compare with gradient decent and Levenberg-Marquardt?
Answer: All three of those are "local" methods, which means that they will be attracted to local minima if they start close enough to them even if they are not global minima.
Non-convex optimization is just difficult in general. There is no general recipe to follow to guarantee getting the correct minimum in a reasonable amount of computation time. (Certain stochastic methods will always work eventually, but keeping runtime down is difficult.)
Comment: Are there existing methods that will converge to a course global minimum? After that, one could switch to one of the above approximations.
Comment: @JohnM The hard part is getting anywhere near the global minimum, sharply resolving it from inside a neighborhood is usually easy.

Gauss-Newton local convergence


Using Matlab to obtain data from a graph

Question: I currently have a large number of 1D graphs that i would like to use to calculate a value. I would like the code to take the y values at 20 and 100 on the X axis, and then do the log10 of the x value at 20 divided by the x value at 100.
Answer: Here is some example code that you can modify for your problem:
% Data
X = (1:100)';
Y = X*5 + 10;

% Calculation
result = log10(X(Y == 20)) / X(Y == 100);

The expression Y == 20 returns a logical array of the indices of Y for which this is true. Putting this in X gives the X values at those indices. In the case of the simple function plotted here, there is exactly one such point so we get a scalar value. For more complex value searching inside arrays you should use the find function.


JSON API Callback

Question: Tenho uma dúvida em como filtrar resultados provenientes de uma API, e gostaria de saber se alguém já teve este problema anteriormente.
Imaginemos que temos que aceder a uma API que está num servidor diferente do nosso e que retorna uma reposta em JSON com uma estrutura semelhante à seguinte
[
{
"nome": "Joshua",
"sex": "M"
},
{
"name": "Marie",
"sex": "F"
},
{
"name": "Frank",
"sex": "M"
}
]

Claro que isto é apenas um exemplo, pois a resposta poderia ser de milhões de resultados. O parametro do callback para iniciar a comunicação JSONP é ?callback=...?.
O que eu gostaria de saber é se há uma forma de filtrar estes resultados, imaginemos que queremos apenas retornar pessoas do sexo masculino (M), sem ter que se fazer uma filtragem do lado do cliente. Lembro que para fazer esta chamada, apenas pode ser feita através de Javascript sem recorrer a outro tipo de linguagem.
A minha primeira ideia seria fazer uma chamada com recurso a jQuery desta forma:
$.ajax({
type: 'GET',
url: "https://url-to-api?callback=?",
async: false,
jsonpCallback: 'jsonCallback',
contentType: "application/json",
data:{'sex':'M'},
dataType: 'jsonp',
success: function(json) {
console.dir(json);
},
error: function(e) {
console.log(e.message);
}

Alguém sabe uma forma de se fazer uma filtragem ao fazer o request?
Desde já agradeço a disponibilidade.
Comment: Esse é o [pt.so], traduza sua pergunta ou poste no [so].
Comment: Peço desculpa, nem tinha dado conta disso.
Comment: Tranquilo cara.
Comment: Já agora, se souberes como resolver o meu problema... ;)
Comment: Estou tentando entender, comecei há pouco com javascript. Do jeito que você tentou não funcionou?
Comment: Da forma que fiz, apenas retorna a lista toda. Aquilo que queria era filtrar essa lista logo no request., passar parametros. Mas como não tenho controlo na api não sei como passar esses parametros. Não queria fazer loop por todos os objects e ver qual deles é do sexo masculino (M)
Answer: Se o site onde vais buscar o JSON não permitir parâmetros de filtragem então tens de fazer isso no lado do cliente.
Dá uma olhada na API desse site.
Fazendo a filtragem no lado do cliente podes usar o .filter(). Verifica se o JSON que o site ter passa é processado como JSON ou já como array, vou incluir essa verificação no exemplo em baixo:
var parametroFiltragem = 'M';
$.ajax({
    type: 'GET',
    url: "https://url-to-api?callback=?",
    jsonpCallback: 'jsonCallback',
    contentType: "application/json",
    dataType: 'jsonp',
    success: function (json) {
        if (typeof json == 'string') json = JSON.parse(json);
        var filtrados = json.filter(function(obj){
            return obj.sex == parametroFiltragem;
        });
        // fazer algo somente com os "filtrados"
    },
    error: function (e) {
        console.log(e.message);
    }
});

Comment: A tua solução funciona. E foi aquilo q tinha pensado inicialmente. A questão é que aqui há até 6 paramentros de pesquisa.E a pesquisa pode até ser algo complexa.Por exemplo, é necessário filtrar por preço (maior,menor,entre) e mais outros tipos de combinação. Será uma boa solução em termos de performance?A única informacao que tenho da API é a seguinte:
The tool itself should allow for the user to perform simple filtering based on the criteria listed.The filtering options should be appropriate for its type (numerical etc.).The callback parameter to initiate JSONP communication is "?callback="
Comment: @Ma1990 por essa descrição em Inglês dizem que dá para fazer filtragem. Podes mostrar o link para a documentação?
Comment: Não tenho qualquer documentação. O único que tenho é o URL da API.
Comment: @Ma1990 e qual é o url?
Comment: @Ma1990, estive a dar uma olhada pelo site da ndivia e não encontro nada que indique parametros para filtrar. Como descobriste essa API? não tens onde perguntar?
Comment: @Ma1990 podes partilhar essa documentação?  a ver se diz lá alguma coisa sobre os filtros...
Comment: O que tem foi aquilo partilhei mais acima. Depois tem o seguinte:

The callback parameter to initiate JSONP communication is "?callback=…".
Invalid or missing callbacks will invoke a 400 Bad Request
The user should be able to filter against these criterias
• Series number
• Has PhysX
• Has SLI
• Is In Stock
• Is Not A Preorder
• Price Is Below, Above, or Between
Comment: @Ma1990 e recebeste informação que isso dá para fazer no url? ou é para fazeres um filtro no cliente? Fazendo no cliente faz-me sentido, senão vais ter de adivinhar e isso parece-me estranho que te tenham dado uma tarefa para "adivinhares" o que a API faz.
Comment: É para fazer o filtro no cliente O que para mim não faz sentido, é ter que fazer o request de tudo e depois implementar um filtro. Ainda para mais o filtro pode ser bastante complexo, tendo em conta que é para filtrar por imensos parametros.

"We require a javascript-based widget that can be dropped onto a NVIDIA owned property. The widget should pull a JSON feed from a determined location. The JSON feed contains product information, and some purchasing data.
The tool itself should allow for the user to perform simple filtering based on the criteria listed."
Comment: At a minimum, the user should be shown the technologies inside the graphics card, the specifications, the graphics card "image", and a link to a detail page.
The filtering options should be appropriate for its type (numerical, boolean, etc.)
https://www.nvidia.eu/developer-test/buy.php?callback=
The callback parameter to initiate JSONP communication is "?callback=…"
Invalid or missing callbacks will invoke a 400 Bad Request
The user should be able to filter against these criterias
• Series number
• Has PhysX
• Has SLI
• Is In Stock
• Is Not A Preorder
• Price Is Below, Above, or Between
Comment: Esta é a documentação do problema, nada mais. O que me leva a crer que é para fazer filtro no lado do cliente depois de fazer o request.
Comment: @Ma1990 exato. Acho que tens de fazer selects no HTML populados com o que o JSON tem baseado nas especificações "Series number • Has PhysX • Has SLI • Is In Stock • Is Not A Preorder • Price Is Below, Above, or Between". Sabes como fazer isso? Se não posso ajudar/adaptar a resposta mais tarde.
Comment: Agradecia a tua ajuda para isso :)
Comment: Olá Sergio. Sempre dá para me auxiliares nesta filtragem? Outra questão. Tendo em conta que se tem que fazer a manipulação depois do success. Como posso fazer fazer o styling do conteúdo? Faço isso na resposta e depois append a um elemento que já exista na página? Há alguma forma de passar o array de objectos para o HTML e fazer lá a manipulação? Como é feito em AngularJS com o ng-repeat.
Comment: @Ma1990 o código para fazer isso não é assim tão simples. Perdi um bom tempinho a montar um exemplo que precisa ser afinado: http://jsfiddle.net/gfrsLx92/ Imagino que é isso que procuras... isso demorou algum tempo e não está a 100%. Saber fazer o resto?
Comment: Obrigado por isto. Estou a pegar a na tua ideia e fazer com AngularJS. Acho que remove a complexidade de "construir" o HTML.
Answer: Acho que o código abaixo pode ser o que você está procurando:
$.ajax({
    type: 'GET',
    url: "https://url-to-api/pagina",
    data: {
        sex: "M"
    },
    dataType: "jsonp",
    crossDomain: true,
    cache: false,
    success: function (json) {
        alert(json);
    },
    error: function (e) {
        alert(e.statusText +": "+ e.status);
    }
});

No seu comentário você falou que a requisição vai ser feita para outro domínio, para isso ativamos o crossDomain, recurso que permite realizar requisição ajax para outros domínios.
Neste caso por default desativei o cache, porém, fica a seu critério utilizar ou não.
No parametro data apenas retirei as aspas da palavra "sex".

Obs: "o seu filtro por sexo só vai funcionar se a API que está do outro
  lado tiver implementado este parâmetro como filtro, do contrário você
  terá que retornar todos os dados e criar o filtro do lado do cliente."

JSON API Callback


Custom Framework with Swift and SpriteKit: can't access custom class

Question: I created my custom framework in swift, let says MyCustomFramework.
Within this project, I added a new swift file: XYZCustomClass which looks like this:
public class XYZCustomClass: SKNode {
    // variables declaration

    public override init() {
        super.init()
        // make my custom init here
    }

    ...
}

I build my project as iOS Generic Device and get my MyCustomFramework.framework location.
Then I import MyCustomFramework.framework within a personal project and I import it in the good file:
import SpriteKit
import MyCustomFramework

class GameScene: SKScene {
    override func didMoveToView(view: SKView) {
        let test = XYZCustomClass()    // Error
    }
}

And I finally get the following error:

"path"/MyProject/GameScene.swift:44:20: XYZCustomClass' is unavailable: cannot find Swift declaration for this class

As an additional information, the project has been built with SpriteKit in swift language.
Thank you in advance,
Answer: Check that the framework is included under 'General'->'Linked Frameworks and Libraries' and/or under 'Build Phases'->'Target Dependencies', and add it if necessary.
Comment: The framework is indeed, automatically added to "General/Linked Frameworks" while added to the project. However, "Build Phases/Target Dependencies" only accept : "MyProjectTests" and "MyProjectUITests" as inputs.


Sync Two IIS 8.5 Server configurations only excluding bindings

Question: We have two IIS 8.5 web servers, Server 2012 R2
Server1
Server2
I am trying to find a powershell command that will sync only changes made on Server1 to Server2
I tried shared configurations however that will sync the bindings as well and I do not want that as they are load balanced. Also I am trying to avoiding adding unneeded bindings to servers to make it work.
I found a couple webdeploy powershell commands however that looks like it wants to sync files as well, we use DFS to sync the files.
All I want to be able to do is sync changes from the Server1 applicationhost.config or web.config to Server2
Answer: Got it (Make sure you are using CMD ADMIN and Powershell ADMIN)
Using CMD, it will not work in powershell not sure why it doesn't.
msdeploy -verb:sync -source:webserver,computerName=acd-pv01 -dest:webserver,computerName=acd-pv02 -skip:skipAction=Delete,objectName=binding -skip:skipAction=AddChild,objectName=binding

A little overview
There are a couple posts online about a custom rule replaceipbindings
However the type is not valid, this is a bug that has not been fixed yet.
So you have the add the -skip:skipAction to the command line to make it work and use the objectName=binding
1 problem is if you created a new site, the configuration is brought over however the binding info in not because you told it not to
So the fix that use powershell
Add-WebConfigurationProperty -pspath 'MACHINE/WEBROOT/APPHOST'  -filter "system.applicationHost/sites/site[@name='SITENAME']/bindings" -name "." -value @{protocol='http';bindingInformation='IPADDRESS:80:SITENAME'}


How to determine sample size prior to designing a prospective cohort study research of 2 groups?

Question: How do I use  the a priori test to determine a sample size for my prospective cohort research that compares vaccinated males versus non vaccinated males. I am looking at the effect of vaccination on disease prevalence in the future.
Answer: First, you will need to decide on the desired power and expected effect size in order to determine sample size. http://en.wikipedia.org/wiki/Estimating_sample_sizes#Estimating_sample_sizes


What's the EntryPoint in AppxManifest.xml for C++/WinRT console UWP apps?

Question: This blog post about command line UWP apps says "The Executable is the name of your UWA app EXE, and the EntryPoint is the fully qualified name of your App class."
That makes sense for C# apps, but what about the C++/WinRT console UWP app template? The only code we have there is this:
int main()
{
    // You can get parsed command-line arguments from the CRT globals.
    wprintf(L"Parsed command-line arguments:\n");
    for (int i = 0; i < __argc; i++)
    {
        wprintf(L"__argv[%d] = %S\n", i, __argv[i]);
    }

    wprintf(L"Press Enter to continue:");
    getchar();
}

and the mainfest says:
...
<Application Id="App"
  Executable="$targetnametoken$.exe"
  EntryPoint="UWPConsoleApp.App"
...

I called the project UWPConsoleApp, so that's what VS set as the entry point, but where is this class? Does the compiler generate it, is it some obscure vcruntime init code controlled by macros or something entirely different?
Answer: Those manifest values are basically unused here, so don't worry about it. There's no difference in the Package.appxmanifest for C++/CX vs. C++/WinRT.
The start-up differences are in your code entry-point:
// C++/CX
[Platform::MTAThread]
int __cdecl main(Platform::Array<Platform::String^>^ /*argv*/)
{
    auto viewProviderFactory = ref new ViewProviderFactory();
    CoreApplication::Run(viewProviderFactory);
    return 0;
}

vs.
// C++/WinRT
int WINAPI wWinMain(
    _In_ HINSTANCE /*hInstance*/,
    _In_ HINSTANCE /*hPrevInstance*/,
    _In_ LPWSTR    /*lpCmdLine*/,
    _In_ int       /*nCmdShow*/
)
{
    ViewProviderFactory viewProviderFactory;
    CoreApplication::Run(viewProviderFactory);
    return 0;
}

Comment: So there is no hidden WinRT class with that name that does some init logic? Alright, that's what I wanted to know, thanks.
Comment: Just verified, after changing EntryPoint to random gibberish the app still launches correctly.


How can I reset render cache on an entity for current user in hook_entity_view_alter()?

Question: I have Commerce products for which I'm showing or hiding the add-to-cart link, if that product is or isn't in the current cart.  In my code:
<code>function mymodule_commerce_product_view_alter(array &$build, EntityInterface $entity, EntityViewDisplayInterface $display) {
    $myservice = \Drupal::service('myservice');
    if ($myservice->isProductInCurrentCart($entity->id()) {
        $build['add_to_cart_link']['#access'] = FALSE;
    }
}
</code>
That works fine, however, when the product entities are rendered, they retain their cache and will continue to display, or not display, the add-to-cart link until the cache is cleared.
In my view_alter hook, how can I clear the cache for the current user for that entity before it's rendered?  Can I set a cache tag?
Answer: At first I disabled the cache for the link, but the entity was cached, preventing the link from being shown or hidden.  Therefore, I disabled the cache for the entity and that worked.
In the alter hook:
<code>$build['#cache']['max-age'] = 0
</code>
The entity is now rendered with the proper state of the cart link.


Why in general is early stopping a good regularisation technique?

Question: Early stopping means stopping gradient descent when the validation error starts to increase.
This is commonly used for neural networks, but can also be used for any model trained by gradient descent, such as a high degree polynomial.
Usually when we regularise, we put some kind of penalty on the parameters, and then look for the optimum of this modified cost function. We think of this as balancing goodness of fit, and high variance, which is controlled by the original cost function, against model simplicity, and high bias, which is controlled by the penalty.
But this isn't what we do with early stopping. We're not seeking the optimum of anything -- by definition we are stopping only "part way" to the optimum of the cost function. And we don't seem to have made the model any simpler; we initialise the model randomly, so we can end up anywhere in the parameter space, not in some restricted "simpler" region. Why then is this a good choice of parameters for reducing overfitting? How, intuitively, should we conceptualise what early stopping is doing?
Comment: Actually, the answer likely resides from my experience from my adventures in my Numerical Analysis course. Repetitive procedures either quickly converge with the right starting values, or run into a singularity and just crash. Hence, a rule of thumb.
Comment: An analogy,  you are attempting to drive home in a thick fog. You know approximately how long it should take. Taking longer likely means you are lost.  It is wiser to park then find the lake.
Comment: Personally, early stopping is more or less related to bias - variance decomposition. At the early training stage, both bias and variance are reduced, meaning that the (ensemble of) models are fitted to the data. However, as the training progresses, bias continues to go down, while variance, at one point, starts to go up, meaning that the models start to overfit. That is why we should stop training at that point, and hence, it is coined "early stopping"
Answer: This is not a rigorous answer, but just to try to give some intuition behind the concept of early stopping.
We know that neural networks have a very high flexibility, which means that they can model extremely complex functions. The more complex a function gets, the more likely is that it will overfit the data.
Searching for that perfect minimum increases the complexity of the function. You start with a relatively smooth function and start tweaking every point of it until it gets you the best performance on the training data. Which means you have overfitted it.
Instead, you can stop early, to a simpler function. Think of it as something in between a smooth function and a highly complex function. It still gets the general shape you want, but didn't have time to fine tune all the small variations needed for a perfect error.
Comment: Thanks -- could you elaborate on in what sense a neural network is initialised to a "smooth" function? In the polynomial example, I'd have guessed that almost all randomly chosen initial parameters give "unsmooth" functions.
Comment: Perhaps I oversimplified my example for illustration purposes. Indeed, the function might not be smooth as we start, but if will definitely be "wrong" (in the sense that is different from our target). The core idea is to stop before the function has learnt the small intricacies of our dataset, before it overfits. This is again, based more empirical evidence than supported by a mathematical argument: we have simply observed that the generalization error decreases, then increases again when overfitting.
Comment: you initialise to *small* weights (normal around zero  at least for sigmoid) where function is linear and small variance.  you have to check exactly what is done for relu (which is nonlinear only around zero).
Answer: Early stopping is very similar to regularisation like Lasso or Ridge. It is similarly reducing the size of the parameters.
Below is a sketch for the situation of ordinary least squares (OLS) regression. It shows the cost as function of parameters $\beta_1$ and $\beta_2$ which has a shape of ellipses around the optimal OLS solution.
The sets of potential solutions for Lasso, Ridge and gradient descent are similarly creating a descending path towards the optimal OLS solution. In the case of LASSO one of the algorithms to solve the problem, least angle regression (LARS), is even literally following a path down towards the OLS solution.

The reason that early stopping is mostly used with Neural Networks is probably practical. The optimisation is anyways using gradient descent.
The reason that LASSO and Ridge regression are mostly used with linear regression is probably because these methods are more particularly punishing the inclusion of multiple regressor variables (especially LASSO prefers a sparse solution). This can relate to plausible prior assumptions that a solution with few parameters should be preferable (one does not know which regressors are important, but one may have the idea that only a few should be sufficient andany others are just rubbish).