Show that $\int_{S}x^2 d\sigma = \frac{a^{4} \pi}{4}$ where $S$ is a disk of radius $a$ centered at the origin in the plane $z=0$.

Question: Show that $$\int_{S}x^2 d\sigma = \frac{a^{4} \pi}{4}$$ where $S$ is a disk of radius $a$ centered at the origin in the plane $z=0$.
Deduce that, $$\int_{S}(x^2 + y^2)d\sigma = \frac{a^4 \pi}{2},$$ And, $$ \int_{S}(x^2 + z^2)d\sigma = \int_{S}(y^2 + z^2)d\sigma = \frac{a^4 \pi}{4}$$
Know where to go with this problem after the initial setup, but as there is no height given, do you assume a height?
Also would i be correct in saying you use polar coordinates?
Thank you in advance.
Comment: For instance in $$\iint_{x^2+y^2\leq a^2}x^2\,dx\,dy = \int_{-a}^{a}2\sqrt{a^2-x^2}x^2\,dx = 4a^4\int_{0}^{1}u^2\sqrt{1-u^2}\,du = \frac{\pi}{4}a^4 $$ there is no angle ranging over $[0,2\pi]$.
Comment: Forget $z$, it is useless. You are asked to compute $$\iint_{x^2+y^2\leq a^2}x^2\,dx\,dy\qquad\text{and}\qquad \iint_{x^2+y^2\leq a^2}(x^2+y^2)\,dx\,dy$$ and they are clearly related by symmetry.
Comment: You may easily solve them through polar coordinates or just by Cavalieri's principle.
Comment: @JackD'Aurizio What would my boundaries for each integral be then in this case. I understand that the one will be $[0,2\pi]$.
Comment: The boundaries depend on the parametrization you choose for the disk $x^2+y^2\leq a^2$.
Answer: With polar coordinates, the first integral becomes
$$\int_0^a\int_0^{2\pi}(r\cos (t))^2 (r)drdt $$
$$=\int_0^ar^3dr \int_0^{2\pi}\cos^2 (t)dt $$
$$=\frac {a^4}{4}\Bigl [\frac {t}{2}+\frac {1}{4}\sin(2t)\Bigr]_0^{2\pi} $$
$$\frac{\pi a^4}{4} $$
for the second, by symetry,
$$\int_Sx^2d\sigma=\int_Sy^2d\sigma $$
for the third
$$\int_Sz^2d\sigma =0$$


Oracle 11gR2 exp does not export some tables

Question: I have an Oracle 11g (220.127.116.11) Database running on Linux (x64). Within the database I have a schema and 33 tables for it (all in the same tablespace). When I log in via sqlplus I can list all the tables via
SELECT OBJECT_NAME FROM USER_OBJECTS WHERE OBJECT_TYPE = 'TABLE';

But when I export the Tablespace using
exp ... BUFFER=65536 FULL=N COMPRESS=N CONSISTENT=Y TABLESPACES=... FILE=...

Then it only exports 24 of the 33 tables.
I have tried to export the missing tables via
exp ... TABLES=<missing_table> ...

But then I get an error:
 EXP-00011: <schema>.<missing_table> does not exist

How can I find out what's wrong here?
How can I export all the tables?
UPDATE:
After following Gary's advice I found the following difference between the exported and missing tables. DDL of an exported table:
CREATE TABLE "MY_SCHEMA"."EXPORTED_TABLE" ( ... ) TABLESPACE "MY_TS" PCTFREE 10 INITRANS 1 MAXTRANS 255 STORAGE ( INITIAL 64K BUFFER_POOL DEFAULT) LOGGING NOCOMPRESS

And now the DDL of a not exported table:
CREATE  TABLE "MY_SCHEMA"."MISSING_TABLE" ( ... ) TABLESPACE "MY_TS" PCTFREE 10 INITRANS 1 MAXTRANS 255 STORAGE ( BUFFER_POOL DEFAULT) LOGGING NOCOMPRESS

The above DDLs were generated by the Enterprise Manager. The ones created with sqlplus contained no STORAGE section at all for the missing tables.
I found out that the tables get exported when I reorganize them and set the STORAGE INITIAL value to 64K.
Problem solved. (Hopefully ;))
Comment: I am getting the same issue. I have issued the command for two tables one which is working and for one which is not exported: For the one which is not workin: SQL> SELECT DBMS_METADATA.GET_DDL('TABLE','DR$XMLDOCIX5_TX$I') from dual; DBMS_METADATA.GET_DDL('TABLE','DR$XMLDOCIX5_TX$I')
-------------------------------------------------------------------------------- CREATE TABLE "SDE_RIYADH"."DR$XMLDOCIX5_TX$I" ( "TOKEN_TEXT" VARCHAR2(64) For the one which is getting exported: SQL> SELECT DBMS_METADATA.GET_DDL('TABLE','CHAINED_ROWS') from dual; DBMS_METADATA.GET_DDL('TABLE','CHAINED_ROWS')
-------
Answer: Starting from Oracle 11gR2 (184.108.40.206) there is a new feature:
Deferred Segment Creation: the creation of a table sent is deferred until the first row is inserted.
This results as empty tables not being listed in dba_segments and not being exported by exp utility.
The easiest solution is to use expdp utility.
If you have to use exp utility, you must run this command for all your empty tables:
ALTER TABLE tablename ALLOCATE EXTENTS

Answer: Do a SELECT DBMS_METADATA.GET_DDL('TABLE','yourTableName') for one of the tables that works, and one that doesn't. Then play spot the difference.  (Note that yourTableName is case-sensitive.)
Could be something like BLOBs/CLOBs or partitions in a different tablespace, a dependency on a TYPE that is owned by another schema that isn't being exported...
Comment: I am not that deep into Oracle. What has to be inserted at the "..."?
Comment: So now I know more (and less ;)):
The missing tables do NOT have a 'STORAGE' section in the output of SELECT DBMS_METADATA.GET_DDL.

I will edit the question to contain the new information.
Answer: Table exist in the DB but you cannot export it unless you allocate a extent to this table….
Elapsed: 00:00:00.04
14:44:54  PIMUSER @ mdmqa > alter table RECORDAPPROVALHISTORY allocate extent ;
Answer: I'm getting similar error and think it has something to do with synonyms also.
I can describe the specific table in the database and select from it (zero rows).
I can also describe select from the public synonym
But when I export that table, I get the 011 does not exist error, name or synoynm.
When I insert a row (that solves one problem), I can export via table name but not via the synonym.
Of course, all this used to work in 11.1
First I've heard of expdp. Will look at that
Answer: are the tables in the same tablespaces you export ? Check with this query:
SELECT table_name, tablespace_name FROM user_tables

Comment: Yes, all tables are within the same tablespace.
Answer: It is a new Oracle11 feature. only in Enterprise edition. Empty table will not be exported.
Answer: Yes the tables exist in the same schema. Some tables which are not exported contain data, only a few tables are there whose count is zero, rest all have data in them.
Regards
Answer: The allocate extent works. You can find the tables with this statement:
select 'alter table '||table_Name||' allocate extent;' from user_Tables where temporary='N' and table_name not in (select segment_name from user_segments)


PHP session variable not being saved

Question: I am creating a survey based on a PHP script. The script re-loads itself with a different set of videos to be rated and a set of radio buttons to choose from after clicking a "submit" button.
I have the problem that my scores are not being saved in the Session variable. When I print it, it is empty.
Here is an excerpt of my code:
<?php
session_start();

if (isset($_POST['submit2'])) {
    $_SESSION['rating2'] = $_POST['score2'];
}
?>

  <?PHP echo "<embed src='$video1' width='400' height='400'>"; ?>

  <input type="radio" name="score2" value="A"> <?php echo "A"; ?>

  <?PHP echo "<embed src='$video2' width='400' height='400'>"; ?>

  <input type="radio" name="score2" value="B"> <?php echo "B"; ?>

<form action="setup2.php?video=<?php echo $nextvideo; ?>" method="post">
<input type="submit" name="submit2" value="Submit">

Apologies if that looks messy, I'm very new to PHP and hope that someone can point me into the right direction. Thanks!
Comment: I don't  see your radio buttons between the form element why is that?
Comment: Do you get any errors?
Comment: can you add the code where you actually try to access $_SESSION['rating2'] and where you post the current score? You are currently saving the value of a radio button as score - correct?
Comment: First step: Do `var_dump()`'s of the variables involved and then you will probably see that the problem is not related to the session.
Answer: Pull your radios into the form
<form action="setup2.php?video=<?php echo $nextvideo; ?>" method="post">
<input type="submit" name="submit2" value="Submit">
  <input type="radio" name="score2" value="A"> <?php echo "A"; ?>

  <?PHP echo "<embed src='$video2' width='400' height='400'>"; ?>

  <input type="radio" name="score2" value="B"> <?php echo "B"; ?>
</form>

Answer: I'm not sure why you are calling it 'score' since you are saving Chars - but here is what i would expect it to do:
<?php
session_start();

if (isset($_POST['submit2'])) {
    $_SESSION['rating2'] = $_POST['score2'];
}
?>
<form action="setup2.php?video=<?php echo $nextvideo; ?>" method="post">

      <?PHP echo "<embed src='$video1' width='400' height='400'>"; ?>

      <input type="radio" name="score2" value="A"> <?php echo "A"; ?>

       <?PHP echo "<embed src='$video2' width='400' height='400'>"; ?>

       <input type="radio" name="score2" value="B"> <?php echo "B"; ?>

<input type="submit" name="submit2" value="Submit">
</form>

PHP session variable not being saved


Transfer iOS app name from one Apple account to other

Question: I have ios app in AppStore Connect. This app not published in the store (only TestFlight). This is OldAccount. then I will work with the application in a new account - NewAccount.
The app has no downloads, I don't need the package id(bundle id), I only need the app name.
Now I have two solutions:

Transfer full app from OldAccount to NewAccount.
To do this, I need to publish the application, now it has comments.

Create a completely new application on a new account. I like this option better, but I cannot use the old name. I get an error - this name is already taken.

I tried changing the name. It was "appname" now "app name" (I added a space in name in oldAccount). But I still get this error when create new app in new account with name "appName".
Is it possible? How can I transfer the application name from the old account to the new one?
Answer: I solved this issue. I renamed name in old account to "app name1", then "app name"  became available in the new account. Just adding a space in the name is not enough.


Estimating error bounds for proportion estimation for a given sample size

Question: Given an error bound, I can calculate the sample size to estimate proportion. E.g. for 10% the sample size is 100. But this relies on maximum variance being $\sqrt{\frac{0.25}{n}}$ which is achieved when p=0.5. Now say the result on the sample is 1%. So the actual p can be in the range (0%, 11%). But for this range, the variance is lower than the above and is $0.11*0.89/n=0.0979$. This yields that the error bound is in fact lower, leading to a lower maximum variance etc.
What is the formula to determine the actual error bound given a sample size and estimated proportion?
Answer: $1.96 \times \sqrt{1/4n}$ is the correct upper bound of the margin of error with 0.95 confidence.  In some ways your search is futile because if $p$ is far from 0.5, no one would accept a large absolute margin of error, but would instead insist that you achieve a reasonable relative margin of error.  The net result is that the needed sample size doesn't change very much as you lower $p$ and in fact can increase drastically. BBR discusses both the absolute and relative (odds) scales.


How can I eliminate duplicate Drupal nodes in a View when one CT references the other?

Question: Drupal 7 with relevant Modules: Views & Entity Reference
I have a view that simply shows the "Teaser" display type of two different Content Type records, we'll say they are Article and Page. This is built into a Views Page.
My Article CT has some simple fields that are shown.
My Page CT has a few fields, but also an Entity Reference field (unlimited entries). The Entity Reference field points to other Article nodes.
My View then, as expected, shows each record's Teaser display and of course when a Page record references another Article record, that Article's teaser is shown as part of the Page teaser.
This is great. The problem is, I do not want to show duplicate Article teasers. That means, if a Page references an Article, I don't want to show that same Article teaser as an individual listing.
Think of it like this, I have these Articles:

Article 1
Article 2
Article 3

And I have these Pages:

Page 4
Page 5
Page 6

Page 4 points -> at Article 1 and Article 2
Page 6 points -> at Article 2
TL;DR
Right now the view would show something like:

Article 1
Article 2
Page 4

Article 1
Article 2

Page 5
Page 6

Article 2

Article 3

What I want is this:

Page 4

Article 1
Article 2

Page 5
Page 6

Article 2

Article 3

Here's a Diagram:
https://i.stack.imgur.com/2joEr.jpg
Comment: i also got the same problem before.
Comment: Check out the answer I posted to the question then, it's working well.
Answer: My guess would be to use fields instead of teasers, first. Then, use filter to undisplay Articles that are nodereferenced by pages - you then would only have pages and unreferenced articles showing up.
You might be able to do that with the relationship entityreference - reverse, or with views PhP if it doesn't work.
Comment: I can't really make use of fields without going through a whole lot of pain, as mentioned previously:

Unfortunately this isn't using fields due to the method by which the content has to be rendered (very differently when shown as a child), as it's handled in node-tpl files.

But, this is on the right track. As I managed to solve it using a 2-way relationship that didn't exist without another module. My answer is posted...
Comment: I see that ; that's right, you actually didn't need to use fields, as fields filtering still works with teaser display :)

I'm glad I helped. Thx for noting best answer !
Answer:
Go and edit your view
In Advanced » OTHER section by enabling Use aggregation: Yes
In FIELDS or FILTER CRITERIA section, select and apply Aggregation settings for which fields you want to group by or distinct.
Comment: Unfortunately this isn't using fields due to the method by which the content has to be rendered (very differently when shown as a child), as it's handled in node-tpl files.
Answer: I ended up knocking this out by making use of the Corresponding Entity Reference module (CER). This creates a 2-way relationship that is sync'd between the parent<->child. Using that, I could simply filter all children which have a parent from the View.


Interrupted time series analysis with log transformed data

Question: I want to conduct an assessment of the annual citation rates for a group of patents before and after a particular intervention (namely the decision of the Supreme Court in Alice v CLS Bank, which I represent with a dummy value 0 or 1). Unfortunately, from the dataset I have collected, I have a fair amount of positive skew in the raw citation rate for each patents (some patents have 100 citations, others have 10). I have tried to filter out those patents that do not have any citations. Accordingly, I have log transformed those values as follows:
+------+-------+-----------+--------------+
| year | alice | citations | logcitations |
+------+-------+-----------+--------------+
|    1 |     0 |         6 |        0.778 |
|    2 |     1 |         3 |        0.477 |
|    3 |     1 |         1 |        0.301 |
+------+-------+-----------+--------------+

I then wanted to conduct a time series analysis to see whether there was a relative change in the number of LogCitations before and after Alice using the following model:
model1 = lm(logcitations ~ alice, data)

Is this model too simplistic for assessing the effect of the change in citations? Is there another test that I could use for assessing the effect of the time series? Thank you.
EDIT: I should mention that I am attempting to measure these effects over a 20 year period. I have adopted the lm model described above because I have read that using an ARIMA model requires at least 30 data points (which unfortunately I don't have, because patents only remain in force for 20 years).
EDIT: In response to Chris Haug's question below, I've added the acf and pacf values for the model1 residuals:
Comment: Using an ARIMA model does not require any particular number of observations in general. What does the ACF/PACF of the residuals of `model1` look like?
Comment: Hi Chris Haug, I have edited my post and added the ACF and PACF outputs from the residuals. Hopefully they demonstrate that my data is stationary. Thanks!
Answer: When you have count data like this, it is generally better to model it with a GLM using a negative binomial distribution (also known as negative binomial regression).  This model operates directly on the count values and has its support on the non-negative integers, so it allows any counts of zero and also positive integer counts.  The standard form of the negative-binomial regression uses a log-link function, so you still effectively use an implicit logarithmic transformation in your model, but you still allow counts of zero in your outcome.  This is a major advantage over the model you have used, since removing count values of zero is almost certain to bias your analysis.
You can implement negative binomial regression using the glm.nb function in the MASS package.  The syntax for a model using the same explanatory variable as your model would be as follows:
library(MASS);

Model2 <- glm.nb(citations ~ alice, data, link = log);

There is no guarantee that this model form will fit your data well, but it is the place I would start if I were looking at count data.  In your existing model you have a simple binary comparison where the only explanatory variables is the indicator alice.  If you have a reasonable amount of data (with non-overlapping years) and you want a richer model, you might consider adding factor(year) as another explanatory variable.  To see if your model fits the data appropriately you should look at the residuals using diagnostic plots, and undertake model comparisons.  In many cases you will find that the negative binomial regression gives good results.
Comment: Dear Ben, thank you for your reply. I have a few questions to ask about using negative binomial regression. Firstly, is it possible to use negative binomial regression with non-integer data (that is, the log transformed data)? Secondly, what would you define as a reasonable amount of data? I have citation details from about 100 patents over 10 years, with a citation count at each interval of that 10 year period. Is this a sufficient amount of data to be able to draw conclusions? Thank you.
Comment: (There is no "negative logistic regression" so I'm going to assume you meant to refer to negative binomial regression.)  Negative binomial regression can deal with non-negative non-integer data (since the NB distribution can be extended to the non-negative reals), but the data should **not** be log-transformed prior to input into the model.  The logarithmic transformation is already dealt with in the link function for the model, so the response variable should be the raw count values.
Comment: As to the sample size, any regression model you use is going to have the same issues here.  Having approximately 1,000 data points is a reasonable sample size and it should allow you to fit models that are not too complicated (i.e., not too many parameters).
Comment: Sorry, negative binomial regression was what I meant! Thank you very much Ben! Just one other question - when you mention non-overlapping years, do you mean the year from patent citation expressed as a linear value (1 year since publication, 2 years, 3 years) or the actual raw year (2001,2002)? I have found an article here that describes a method for normalising the decline in patent citations over time: https://www.tandfonline.com/doi/pdf/10.1080/10438590500510459. Should I use a similar normalisation factor to account for a decline with my data set? Thanks once again!
Comment: I mean that you would want data from patents with differences in their initial year (e.g., some starting in 2001, some starting in 2002, etc.).  That way you will be able to "identify" the coefficient for ```alice``` in your model, separately from the coefficients for ```factor(year)```.


when is the maximum likelihood estimator measurable

Question: For a random variable $X$, a class of probability measures $P_\theta$ for $\theta\in \Theta$ and their densities $f_{\theta}$ w.r.t. some common measure $\mu$, we can define the maximum likelihood estimate:
$$\hat{\theta}^{*} = \hat{\theta}^{*} (X) = \arg
\max_{\theta \in \Theta} f_{\theta} (X)$$
In order for this to be a statistic, it needs to be measurable. When is it so? I can see the case where $\mu$ is the counting measure and $\Theta$ is finite in particular.
Answer: It's an interesting question. Usually, a discussion on measurability of estimators is (deliberately) avoided in statistical applications...
In the following I assume the i.i.d. case; $(X,\mathcal{F},P)$ is a probability space, and $\Theta$ is a parameter space. The MLE is a special case of M-estimator $\hat\theta_n=\hat\theta_n(X_1,...,X_n)$ which is defined by
$$\tag{1}\label{1}
P_n h(\cdot,\hat\theta_n)=\inf_{\theta\in\Theta}P_nh(\cdot,\theta)
$$
for some measurable function $h:X\times\Theta\rightarrow \mathbb{R}$; ($P_n$ is the empirical measure/sample average). In the parametric likelihood case $h(x,\theta)=-\ln f_\theta(x)$.
The main issue with measurability of $\hat\theta_n$ is the measurability of the infimum in \eqref{1}. In particular, if $\Theta$ is compact and $h$ is continuous in $\theta$ for each $x\in X$, then there is enough structure to ensure that the relevant infimum is measurable (compactness implies separability so that we can consider the infimum over a countable dense subset of $\Theta$).
I found a more general discussion on the issue in "High Dimensional Probability, Vol. 1" on pages 34-58. First, let $\hat\theta_n^*$ denote an approximate M-estimator. A sequence of approximate estimators satisfies
$$P_nh(\cdot,\hat\theta_n^{*})-\inf_{\theta\in\Theta}P_nh(\cdot,\theta)\to 0$$
in (outer) probability (or a.s.). Imposing some structure on $(\Theta,\mathcal{S})$ (measurable space associated with $\Theta$) it can be shown that although a Borel-measurable approximate estimator need not exist, this structure ensures the existence of universally measurable (u.m.) estimator.
Here is Theorem A.2 on page 55 (which uses a version of the measurable selection theorem):

If $(X,\mathcal{F})$ is any measurable space and $(\Theta,\mathcal{S})$ is Suslin, and if a sequence of approximate M-estimators exists, then such estimators can be chosen to be u.m.

You can find even more discussion on measurability in chapter 7 of "Stochastic Optimal Control: The Discrete-Time Case" (it's available online).
Answer: The book Mathematical Foundations of Infinite-Dimensional Statistical Models by Giné and Nickl contains the following result as instructive excercise 7.2.3:
Lemma. Let $(X,\mathcal{A})$ be a measurable space, $\Theta$ a compact metric space and $u:X\times\Theta \rightarrow \mathbb{R}$ a function that is measurable in the first argument for fixed $\theta \in \Theta$ and continuous in the second argument for fixed $x\in X$. Then there exists a Borel measurable function $\hat \theta: X\rightarrow \Theta$ such that $u(x,\hat \theta(x)) = \sup_\Theta u(x,\theta)$ for all $x\in X$.
The crux is to make the choice of estimator canonical in some way. This is easiest illustrated for $\Theta\subset \mathbb{R}$, in which case one can always choose the largest maximiser. To show measurability one can then take a sequence $F_n\subset \Theta$ of finite subsets such that $\bigcup_n F_n\subset \Theta$ is dense and define $\hat \theta_n(x)$ to be the largest maximiser of $u(x,\cdot)\vert_{F_n}$. This is clearly measurable and hence $\hat \theta = \sup_n\hat \theta_n $ is measurable.
Comment: Interesting. When you consider the case $\Theta\subset\mathbb{R}$ are you assuming that $\Theta$ is compact or you just need the separability of $\mathbb{R}$?
Comment: $\Theta$ is assumed to be compact throughout to ensure that each $u(x,\cdot)$ assumes its maximum at some point in $\Theta$.
Comment: Thank you for your answer. If I understand correctly, provided that the maximum uniquely exists, one could drop the compactness assumption and just assume separability for $\Theta$ in order to ensure measurability of the maximizer. Is this right?
Comment: Probably; you have to check that $\hat \theta =\sup_n \hat \theta_n$ still holds true.


Convert Generated output html/css using php to pdf - Year 2017

Question: I produce php output like the following
<code>$.fn.getPDF = function(folder_suffix){
  var fullurl = folder_suffix+"/superimpressivereport.php";
  $.ajax({
     url: fullurl,
     dataType:'html'
      }).done(function(data) {
         $.fn.converthtmltopdf(data):
      });
 };
$.fn. fn.converthtmltopdf = function(htmlcssoutput){
   //TODO
}
</code>
I want to convert the generated output html that uses bootstrap and css to a neat pdf file. Is there a library that I can use to generate pdf on the fly so that users can generate and download the pdf file in their local computer?
Thanks a ton!
Answer: You can't do this in Javascript
for pdf , you can use http://www.fpdf.org/
it's very easy to use, below is the sample to create a ticket with barcode for an event:
<code>$pdf = new FPDF();

$pdf->AddPage("H",array(100,160));
$pdf->AddFont('code128',"", 'code128.php');
$pdf->AddFont('3of9',"", '3of9.php');

$pdf->Image('img/'.$alias.'/ticket.gif', -20, 0, 180, 100);

//blank
$pdf->SetFont('arial','',6);
$pdf->Cell(145,10,'', 0,1,'R');

// EVENT DATE
$pdf->SetFont('arial','',6);
$pdf->Cell(145,3,'Event Date:', 0,1,'R');

$pdf->SetFont('arial','B',8);
$pdf->Cell(145,5,$event_date, 0,1,'R');

// EVENT TIME
$pdf->SetFont('arial','',6);
$pdf->Cell(145,3,'Event Time:', 0,1,'R');

$pdf->SetFont('arial','B',8);
$pdf->Cell(145,5,$event_time, 0,1,'R');

// TICKET SERIAL
$pdf->SetFont('arial','',6);
$pdf->Cell(145,5, "Class: $class_code | Serial Number: $serial_number", 0,1,'R');
$pdf->SetFont('3of9','',10);
$pdf->Cell(145,5, "*$serial_number*", 0,1,'R');

// TICKET PASS
$pdf->SetFont('arial','',6);
$pdf->Cell(145,5, "Passcode: $passcode", 0,1,'R');
$pdf->SetFont('3of9','',10);
$pdf->Cell(145,5, "*$passcode*", 0,1,'R');

// PURCHASE BY
$pdf->SetFont('arial','',6);
$pdf->Cell(145,3, "Purchased by : $purchased_by", 0,1,'R');

// Payment Method
$pdf->SetFont('arial','',6);
$pdf->Cell(145,3, "Payment Method : $payment_method", 0,1,'R');

// Transaction ID
$pdf->SetFont('arial','',6);
$pdf->Cell(145,3, "Transaction ID : $transaction_id", 0,1,'R');

if ($method == "display") {
    header('Content-type: application/pdf');
    header('Content-Disposition: inline; filename="the.pdf"');
    header('Content-Transfer-Encoding: binary');
    return $pdf->Output();
} else {
    return $pdf->Output("$filename", "S");
}
</code>
Answer: In your AJAX you can call PHP script and inside this PHP you can put this code:
<code><?php
$url = 'http://example.com/document.html';
$data = json_decode(file_get_contents('http://api.rest7.com/v1/html_to_image.php?url=' . $url . '&format=pdf'));

if (@$data->success !== 1)
{
    die('Failed');
}
$pdf = file_get_contents($data->file);
file_put_contents('rendered_page.pdf', $pdf);
</code>
This example uses URL to the HTML file but you can use CURL extension in PHP to perform a HTTP POST to http://api.rest7.com/v1/html_to_image.php
Comment: what does these lines do - $pdf = file_get_contents($data->file);
file_put_contents('rendered_page.pdf', $pdf);
Comment: `$pdf = file_get_contents($data->file); ` get's the PDF file from the API. `file_put_contents('rendered_page.pdf', $pdf);` saves what it got to the file rendered_page.pdf


Como habilitar o CORS em projetos Java com a implementação do JWT?

Question: Estou fazendo um projeto web service, onde eu implementei o JWT e para consumir usando Reactjs eu habilitei o CORS, porem quando faço uma requisição que precisa ter o token, esta retornando isso: Access to fetch at 'http://localhost:8080/teste/' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.
Se for uma requisição GET, mas não precisa do token, ele consome normal.
Quando usa o JWT precisa ser feito algo alem de criar a classe de filtros (ContainerResponseFilter)?
@Provider
public class CORSResponseFilter implements ContainerResponseFilter {
@Override
public void filter(ContainerRequestContext containerRequestContext,
ContainerResponseContext containerResponseContext) throws IOException {
containerResponseContext.getHeaders().add(
"Access-Control-Allow-Origin", "http://localhost:3000");
containerResponseContext.getHeaders().add(
"Access-Control-Allow-Credentials", "true");
containerResponseContext.getHeaders().add(
"Access-Control-Allow-Headers",
"origin, X-Requested-With, content-type, accept, Authorization");
containerResponseContext.getHeaders().add(
"Access-Control-Allow-Methods",
"GET, POST, PUT, DELETE, OPTIONS, HEAD");
}
}

Answer: O erro do browser Response to preflight request doesn't pass access control check: It does not have HTTP ok status indica o endpoint http://localhost:8080/teste/ não está retornando o código HTTP 200 OK para a chamada do método HTTP OPTIONS.
Verifique o log da sua aplicação por erros nesse endpoint, corrija os erros encontrados e teste novamente.
Comment: Ao debugar o web server feito em java, me deperarei que classe na JWTFilter  no trecho; String authorizationHeader = requestContext.getHeaderString(HttpHeaders.AUTHORIZATION); Esta Null, será que o problema ta na forma que eu to enviando o token?
Comment: É possível sim. Editar a pergunta, adicionando o request que está sendo enviado, vai auxiliar a melhorar a resposta :)
Comment: Tem como por citar um exemplo usando reactjs por favor?


Bound variance proxy of a subGaussian random variable by its variance

Question: If I know $X$ is a sub-Gaussian random variable, and I know it has finite variance $\sigma^2$. Can I assert that $\sigma^2$ is a valid variance proxy for $X$?
Definition (sub-Gaussian Random Variable)
A random variable $X$ is called sub-Gaussian with variance proxy $\sigma^2$, if

$E[X] = 0$
$E[\exp(sX)] \leq \exp(s^2\sigma^2/2), \quad \forall s\in\mathbb{R}$

Note the variance proxy is not unique. Any larger number than a valid variance proxy is still a valid variance proxy.
I can easily show using the moment generating function that the variance proxy of a sub-Gaussian random variable is greater than or equal to its variance. But I'm not sure about the inverse direction.
Comment: @MichaelHardy sorry for making it confusing. I have edited the text. The variance proxy is not unique. I just wonder if the variance could be *one* valid variance proxy.
Answer: The answer is no. Here is an example. For $p\in(0,1)$, define the random variables
$$X_p = \begin{cases}1&\text{with probability $p/2$;}\\-1&\text{with probability $p/2$;}\\0&\text{with probability $1-p$.}\end{cases}$$
Clearly $\mathbb E[X_p]=0$. Since $X_p$ is bounded, you have that it is subgaussian by Hoeffding's lemma.
You can evaluate the variance $\mathbb V[X_p] = p$. Moreover you have
$$\mathbb E[e^{\lambda X_p}] = 1 + (\cosh\lambda-1)p\,.$$
For $p$ small enough you can find some $\lambda$ such that $$e^{\lambda^2p/2}< 1 + (\cosh\lambda-1)p$$
and hence conclude that $X_p$ is not subgaussian with variance proxy $p$.
Indeed, Taylor expanding in $p$ you get
$$e^{\lambda^2p/2} = 1 + \frac{\lambda^2}{2}\,p + o(p)$$
and for $\lambda$ large enough we have $\frac{\lambda^2}{2}< \cosh\lambda -1$.


When to use the (|) in Bellman's equation

Question: I was reading the Reinforcement Learning book by Sutton and Barto but I have problems in understanding when to include the term $\sum_{a}^{} \pi (a|s) $, because they handle the different evaluation policy in two parts of the book when updating V(s).

Thank you in advance
Comment: There are lots of places in the posted algorithms where you *might* add the policy or where the policy is used differently between the two algorithms. Could you clarify which specific lines you are concerned about, and why?
Comment: When updating V(s) in both cases (both images), I'm trying to understand why in one pseudocode it appears (the one above) and in the other(below), which is supposed to do the policy evaluation, it is no longer there.
Answer: Important to know: When you select an action $a$ you actually draw it from the policy $\pi(a|s)$ and the notation is $\pi(s)$. How is that important ?

To compute $V$ you then do the average over all possibles actions (expected value of V), that is why in the first image you see the term $\pi(a|s)$

In the second image you can notice that $p$ is now conditioned on $\pi(s)$ and not $a$, because you are looking at a specific action that was taken at random from $\pi(a|s)$, and which is noted $\pi(s)$

The 2 images actually do not serve the same purpose as their titles indicates. Mainly, in the second image one can see that the policy $\pi(a|s)$ is actually unknown (or uniform) at the beginning because this is the algorithm to find it.
Finally, the answer: the second image (policy iteration) describes a deterministic policy which simply assign 1 action to 1 state through $\pi(a|s)$. Thus there is no need for an average because all other terms, the ones that do not correspond to the action assigned to state s, are 0. So the sum is not there, simply because there is no distribution over $a$.
Hope this helps !
Comment: Thanks Romain!!


Running system command from C++ application differs from commandline

Question: I want to execute a command from a C++ application. I do so using:
system("sendEmail.exe -f email@example.com -t ...");

This works on Windows Server 2008 and also on other systems. However, it does not work the same on my new server (Windows Server 2012), it seems to call the command but never completes. If I type the exact same command in a command window it works just fine.
I tried using
system("cmd.exe /C \"sendEmail.exe -f email@example.com -t ...\"");

but that did not help.
Anyone has an idea whats the difference between calling from C++ with system and running in a cmd?
Edit: The problem is not reproducible any more. Thanks for the fast answers
Comment: Different environment (Path) ?
Comment: Maybe its executed in different user context.
Comment: This seems more like a scripting job.
Comment: Thanks for all the comments, unfortunately the problem is now not reproducible any more. In the meantime I integrated the email client frome [here](http://www.codeproject.com/Articles/98355/SMTP-Client-with-SSL-TLS) into my code.
Answer: Try with
system("cmd.exe");

without parameters
This will just open a cmd window and leave it open. From that window you can call sendMail.exe and see what's happening. Perhaps there's just a different path setting or a permission issue.
As an alternative you can use the Windows Api function CreateProcess
Comment: This should help you - most likely windows UAC giving you problems.
Comment: What does CreateProcess() return? If false, what does GetLastError() return?
Did you try with system("cmd.exe") and calling your program manually from that window? What happened?
Comment: doing it in the window created by _system("cmd.exe")_ worked.
Comment: Now it also works directly. It is not reproducible any more. Thanky for all the comments.


Remove Panel from layout only

Question: I have a frame where the layout is null. There is a panel attached to it that has a flow layout.
My code has it so that a button press creates a new panel that gets added to the first panel (the one attached to the frame). Then I have a mouse listener that lets you drag the newly created panel around.

<code>panel.addMouseListener(new MouseAdapter() {
    @Override
    public void mousePressed(MouseEvent me) {
            x = me.getX();
            y = me.getY();
    }
});
panel.addMouseMotionListener(new MouseMotionAdapter() {
    @Override
    public void mouseDragged(MouseEvent me) {
        me.translatePoint(me.getComponent().getLocation().x-x, me.getComponent().getLocation().y-y);
        panel.setLocation(me.getX(), me.getY());
    }
});
</code>

However, when I press the button for it to create a new panel, it creates a new panel while returning the it to the flow layout. I've tried removing the panel but when I drag the new panel over it, it gets erased. While if I revalidate and repaint the panel after removing it, it vanishes.
So how do I prevent it from getting erased or remove it from the layout only?
Comment: Please create and post your [mcve]
Comment: `"frame where the layout is null"` -- note that this is usually a very bad idea. Usually it's better to use layouts and to drag images or shapes, not components. Also don't forget to call `repaint()` on the container after changing any components within it. You would also call `revalidate()` if the container uses a layout manager.
Comment: You verbal description of the problem isn't clear to me. If you have a JPanel with buttons that uses a FlowLayout, then the layout of the frame should be a BorderLayout. Then you add this panel to the NORTH/SOUTH depending on your requirement. Then you create a second panel with a null layout that you add to the CENTER of the frame. Then when you click the button you add the new panel to this panel in the center.
Comment: You may want to consider using the [Drag Layout](https://tips4java.wordpress.com/2011/10/23/drag-layout/) for the CENTER panel. It provides some layout functionality while allowing you to drag components to a new location.
Answer: Try changing the layout to null, I don't think what you're asking is possible.

Remove Panel from layout only


2/4 time signature, miscounting?

Question: I'm trying to to practice my 2/4 time signature. Am I just making a stupid mistake with the attached image? They are 1/16th notes? so shouldn't there only be 8 of them to make up two beats and not 12? I am pretty out of practice, so am sure it is just me!
Answer: Each of the four groups of 3 sixteenth notes has a "3" under them. This indicates that each group of 3 notes is a "triplet" and so is played in the same time as 2 such notes. That makes the arithmetic add up.
Comment: @Mathlearner traditionally, the three notes to which the *3* applies would be under a curved line.  More recently, the triplet-grouping-line might be a square bracket so as to avoid the confusion with a slur or other articulation mark.  Here, the engraver relies on the beaming for this purpose, which makes the *3* harder to notice (and, in some contexts, could create ambiguity with fingering marks).  In some older scores, the *3* might be absent entirely, the performer being left to infer the triplet from the fact that there are 50% more of them than there normally ought to be.

2/4 time signature, miscounting?


Mongo-Go-Driver Failing to Connect

Question: So I am trying to use https://github.com/mongodb/mongo-go-driver to connect to a mongo database in golang.
Here is my connection handler:
var DB *mongo.Database

func CreateConnectionHandler()(*mongo.Database, error){
    fmt.Println("inside createConnection in database package")
    godotenv.Load()
    fmt.Println("in CreateConnectionHandler and SERVER_CONFIG: ")
    fmt.Println(os.Getenv("SERVER_CONFIG"))
    uri:=""
    if os.Getenv("SERVER_CONFIG")=="kubernetes"{
        fmt.Println("inside kubernetes db config")
        uri = "mongodb://patientplatypus:SUPERSECRETPASSDOOT@
               mongo-release-mongodb.default.svc.cluster.local:27017/
               platypusNEST?authMechanism=SCRAM-SHA-1"
    }else if os.Getenv("SERVER_CONFIG")=="compose"{
        fmt.Println("inside compose db config")
        uri = "mongodb://datastore:27017"
    }
    ctx, _ := context.WithTimeout(context.Background(), 10*time.Second)
    client, err := mongo.Connect(ctx, uri)
    if err != nil {
        return nil, fmt.Errorf("mongo client couldn't connect: %v", err)
    }
    DB := client.Database("platypusNEST")
    return DB, nil
}

And the error I am getting:
api         | database/connection.go:29:30: cannot use uri (type
string) as type *options.ClientOptions in argument to mongo.Connect

So I tried replacing uri with the connection string like this:
client, err := mongo.Connect(ctx, "mongodb://datastore:27017")

But I still got the error.
Compare this with what is in the documentation:

ctx, _ := context.WithTimeout(context.Background(), 10*time.Second)
client, err := mongo.Connect(ctx, "mongodb://localhost:27017")

And it is exactly the same! I'm really not sure why there is this error. Any ideas?
Answer: To those who come searching - the docs are out of date as of this posting, but their latest push here: https://github.com/mongodb/mongo-go-driver/commit/32946b1f8b9412a6a94e68ff789575327bb257cf has them doing this with the connect:
client, err := mongo.NewClient(options.Client().ApplyURI(uri))

You will also now need to import the options package. Happy hacking.
EDIT: thanks vcanales for finding this -  you're a gentleman and a scholar.
Comment: Answer outdated either
Comment: The up-to-date answer can be found here: https://stackoverflow.com/questions/55157890/mongo-go-driver-error-new-client-error-clientoptions-in-argument-to-mongo-newcli
Comment: Followed latest steps from github. After using import "go.mongodb.org/mongo-driver/mongo" , getting error "options.Client().ApplyURI undefined (type *options.ClientOptions has no field or method ApplyURI)" ... options is taking from github.com/mongodb/mongo-go-driver/mongo/options
Answer: In addition to the accepted answer - this snippet below may be improved by using an environment variable to pass in the Mongodb URL.
package main

import (
   "context" //use import withs " char
   "fmt"
   "time"
   "go.mongodb.org/mongo-driver/mongo"
   "go.mongodb.org/mongo-driver/mongo/options"
   "go.mongodb.org/mongo-driver/mongo/readpref"
)

func ConnectMongo() {

   var (
       client     *mongo.Client
       mongoURL = "mongodb://localhost:27017"
   )

   // Initialize a new mongo client with options
   client, err := mongo.NewClient(options.Client().ApplyURI(mongoURL))

   // Connect the mongo client to the MongoDB server
   ctx, _ := context.WithTimeout(context.Background(), 10*time.Second)
   err = client.Connect(ctx)

   // Ping MongoDB
   ctx, _ = context.WithTimeout(context.Background(), 10*time.Second)
   if err = client.Ping(ctx, readpref.Primary()); err != nil {
       fmt.Println("could not ping to mongo db service: %v\n", err)
       return
   }

   fmt.Println("connected to nosql database:", mongoURL)

}

func main() {

   ConnectMongo()
}

More information on options and readpref respectively:
https://docs.mongodb.com/manual/reference/method/cursor.readPref/index.html
https://docs.mongodb.com/manual/core/read-preference/

Mongo-Go-Driver Failing to Connect


Fast search within strings in PostgreSQL

Question: Which is the fastest way to search within string in PostgreSQL (case insensivity):
SELECT col FROM table WHERE another_col ILIKE '%typed%'

or
SELECT col FROM table WHERE another_col ~* 'typed'

How can I turn on showing the time which query need to return results? Something like is on default in mySQL (I am thinking about CLI client).
Answer: Both queries are the same, PostgreSQL rewrites ILIKE to ~*. Check the results from EXPLAIN to see this behaviour.
I'm not sure about your question, but the psql-client can show you some timing of the query, using \timing.
Comment: This is not the same.
If I write sth like that:
ilike '%[text]%' this not the same as ~* '[text]'. I think this is something with regex.
Comment: This example is different, you have to escape the brackets in the regex if you want to search for brackets.
Answer: Regarding the timing:
One solution is to use the switch for psql that Frank has already mentioned.
When you use EXPLAIN ANALZYE it also includes the total runtime of the query on the server.
I prefer this when comparing the runtime for different versions of a query as it removes the network from the equation.


jQuery form doesn't send

Question: I have this weird situation where my form doesn't send any data, but the page (which should only be displayed when the data is send) is shown.
I have this code now:

     [..]
     if(form == true){
      var gender = $("input[@name='rgender']:checked").val();
      var data = "name="+$("#name").val()+"&gender="+gender+"&country="+$("#country").val()+"&address="+$("#address").val()+"&zip="+$("#zip").val()+"&city="+$("#city").val()+"&mail="+$("#mail").val()+"☎="+$("#phone").val()+"&checkin="+$("#checkin").val()+"&guests="+$("#guests").val()+"&time="+$("#time").val()+"&nights="+$("#nights").val()+"&remarks="+$("#remarks").val();
      $.ajax({
       url: "http://www.domain.nl/tmp/process.php",
       type: "GET",
       data: data,
       cache: false,
       success: function(){
        $("#content").empty();
        $("#content").load('http://www.domain.nl/tmp/process.php');
       }
      });
      f.preventDefault();
     }
     [..]

I checked the data string with an alert() before and that one is working well
My php file looks like this, but I don't get any values

<?php
echo("GET: ".$_GET['name']);
?>

Comment: Are you doing a GET on a remote domain?  If that's the case your response will be empty due to the same origin policy.
Comment: No it's on the same server/domain, but if i use ../../process.php nothing happens
Answer: Change it as follows:
url: "http://www.cherrytrees.nl/tmp/process.php?" + data,

In your original request you were sending it via POST, rather than GET.
Comment: its sending via GET... `type: "GET"`
Comment: i've just tested same ajax request - it works for me. so that's not the problem.
Answer: maybe this will help:
   success: function(result){
    $("#content").html(result);
   }

In your code you are sending 2 ajax request. First with $.ajax and with some GET parameters, and second with $().load, but without any parameters.
So actually you can simplify your code to this:
if(form == true){
   var gender = $("input[@name='rgender']:checked").val();
   var data = "name="+$("#name").val()+"&gender="+gender+"&country="+$("#country").val()+"&address="+$("#address").val()+"&zip="+$("#zip").val()+"&city="+$("#city").val()+"&mail="+$("#mail").val()+"&phone="+$("#phone").val()+"&checkin="+$("#checkin").val()+"&guests="+$("#guests").val()+"&time="+$("#time").val()+"&nights="+$("#nights").val()+"&remarks="+$("#remarks").val();
   $("#content").load('http://www.cherrytrees.nl/tmp/process.php', data);
   f.preventDefault();
}

Comment: I don't think that is the problem, because i get the following output: GET: Just as it is empty
Comment: it is the problem :) i've edited my post with some explanation
Comment: Hmm.. i tried your solution, but i'm still getting empty values..
process.php loads, but there is no data in it
Comment: oh sorry, i made a mistake in first code snippet. there should be $("#content").html(result);. try changing your success: function to the one i've posted.
Comment: Ok, maybe i'm retarded but those two options both don't work here :( The second one actually sends my form (so preventDefault) somehow don't work and the first one still gives me no data (allthough process.php loads)
Comment: try alert($("#name").val()); are you sure it's not empty?
Comment: I'm sorry, IT WORKS!! You're my hero!! I still used the GET method, but i changed it to POST en everything is allright! Thanks!
Answer:  url: "http://www.cherrytrees.nl/tmp/process.php",
       type: "GET",
       data: data,

the option "data" ist only for POST type, if you wont to GET paratmeeters, write them in your URL
url.com?name="+$("#name").val()+"&gende....

Comment: read my comment to xil3 post. I think Nick Craver posted right asnwer in OP post's comments.

jQuery form doesn't send


CodeIgniter - create library or package that can be extended by other developer

Question: i am trying to create library or package (i don't know which on is good ) so that me/other team member can extend it and  can add their functionalists.
in general term i want to create library/package that can be extended (not use). there must be abstract class which have to be extended by other user
here my abtract class
<code>abstract class BaseTable{
    abstract function createQuery();
    abstract function render();
    /*
    there are other concrete function but i did not mentioned here
    */
}
</code>
so the aim is to allow me or other person to extend this class.
Comment: Refer this Question

[http://stackoverflow.com/questions/5097969/how-do-you-add-abstract-class-library-in-the-codeigniter-framework][1]

  [1]: http://stackoverflow.com/questions/5097969/how-do-you-add-abstract-class-library-in-the-codeigniter-framework
Answer: In Codeigniter  load the library
here this tutorial will help
http://ellislab.com/codeigniter%20/user-guide/general/creating_libraries.html
Comment: i know this manual and i also know how to create library. as i already told in post that i want to create library that can be extended by other user not to use


How to get SUM of a column with number of affected rows

Question: How to get SUM of  a column with number of affected rows
I am trying to get the sum of a column and I will also like to return the number of affected columns.
Example:
orders table

id    customer_id       name      amount
----------------------------------------
1      2                burger    5.00
2      2                pizza     6.00
3      2                grape     1.00
4      1                sandwich  4.00

Now I want to SUM the amount column for a particular customer(customer_id) and also return number of items(count rows affected)
I am doing this but it only gets the sum of the amount, I would also like to get number number affected rows (count) from this single query:
SELECT SUM(amount) AS amount
FROM orders
WHERE customer_id = 2

Answer: Just do a COUNT as well:
SELECT SUM(amount) AS amount, COUNT(*) AS cnt
FROM orders
WHERE customer_id = 2

If amount is a nullable field and you want to only count NOT NULL rows, then do a COUNT(amount) instead of COUNT(*).
Answer: SELECT SUM(amount) AS amount, COUNT(1) AS cnt
FROM orders
WHERE customer_id = 2


Ajax InvokeCommand with custom Callback Primary tabs View(active tab)

Question: I tried to do a what described in https://api.drupal.org/comment/56868#comment-56868, but for Drupal 8.
Drupal.behaviors.corsFileAutoUpload = {
  attach: function (context) {
    $(context).find('input[type="file"].s3fs-cors-upload').once('auto-s3file-upload').on('uploadToS3', Drupal.s3fs_cors.uploadToS3);
    },
}

To invoke this from PHP, I used the following code.
$response->addCommand(new InvokeCommand($selector, 'uploadToS3');

But I got an error from core/misc/ajax.js line number of 1266, as the method for the element is not available. On inspecting eventlistener in Chrome, it was very well visible and I was also able to fire it from Browser Console.
I am missing something here. How do we call a custom jQuery function using InvokeCommand?
Answer: In the JS side try with this:
(function($) {
  $.fn.uploadToS3 = function() {
    // Your code here.
  };
})(jQuery);

the PHP part looks ok to me.
Answer: What's your selector, where you're trying to trigger the method ?? This won't be available according to your error. I guess you have an event/method mixup.
To trigger a custom event do something like:
new InvokeCommand('html', 'trigger', array(
  'your_bound_event',
  array('param1', 'param2'),
)));

And in your behavoir:
$(document).on('your_bound_event', function(ev, param1, param2) {
  console.log('hit');
});

Comment: It's not wrong .. it's a different approach. I'm triggering ("invoking") an event. You invoke a function.
Comment: The InvokeCommand object in your example is wrong.

And is correct how Ankit used it.


Pegar data atributo de último elemento de uma lista

Question: Bom dia pessoal, estou montando um sisteminha que ao clicar em um botão eu adiciono um
 no último registro da linha, porém cada
 possui um data-id numérico para diferenciação, ou seja, eu precisaria saber qual o último data-id para poder adicionar + 1 ao clicar no botão.
Tentei como código abaixo, mas não funcionou, ele só pega o primeiro data-id (eu preciso do último) e não adiciona + 1 no segundo clique, apenas no primeiro.
$("#botaoexemplo").on("click", function() {
    var contagem = $('.dd-item').attr('data-id');
    contagem++;
    $("#dd-list-geral").append('

 Item 100

');
    console.log(valor, dado);
});

Answer: Você pode usar last para pegar o último item de um array de elementos no seu seletor:
var ultimoId = $('.dd-item:last').data('id');

Referência: https://api.jquery.com/last/
Answer: Use a função .last()
$("#botaoexemplo").on("click", function() {
    var contagem = $('.dd-item').last().attr('data-id');
    contagem++;
    $("#dd-list-geral").append('

 Item 100

');
    console.log(valor, dado);
});

Answer: Para pegar o ultimo elemento você pode utilizar o seletor :last
Por exemplo, para pegar a ultima linha de uma table:
$('table tr:last')
Nota que o seu append já insere na ultima posição, então o :last depois do append será a linha recém inclusa.


O que é deadlock no SQL Server?

Question: Estou tentando resolver um problema com um erro no SQL Server e vendo uma pergunta no SO, na resposta é citado um possível 'deadlock' no SQL Server. O que é isto?
Answer: Isso ilustra bem o que é um deadlock:

Existem quatro condições para a ocorrência de deadlock:

Condição de exclusão mútua:  Em um determinado instante, cada recurso está em uma de duas situações: ou associado a um único processo ou disponível.
Condição de posso e espera:  Processos que, em um determinado instante, retêm recursos concedidos anteriormente podem requisitar novos recursos.
Condição de não preempção:  Recursos concedidos previamente a um processo não podem ser tomados a força desse processo, eles devem ser explicitamente liberados pelo processo que os retém.
Condição de espera circular:  Deve existir um encadeamento circular de dois ou mais processos; cada um deles encontra-se à espera de um recurso que está sendo usado pelo membro seguinte dessa cadeia.

Todas essas condições devem ocorrer simultaneamente para que ocorra um deadlock.

Em relação ao seu problema, verifique se alguma transação não está retendo algum recurso que outra transação precisa.
Referência:
 Introdução ao DeadLock - DevMedia
Comment: Essa aqui merece ser a resposta aceita só por causa da foto. +1.
Comment: Deixo aqui uma experiência: Recentemente tivemos um problema com isso aqui na empresa. Um usuário estava fazendo alguma alteração em uma pré-venda, enquanto outro tentou transformá-la em venda. Os devs optaram por criar um campo 'lock' e, quando/enquanto algum user estiver alterando algum dado na pré-venda, ela não poderá ser transformada em venda.
Comment: @CiganoMorrisonMendez - Lembro que, quando fui apresentar um trabalho sobre Sistemas Operacionais, usei essa imagem para explicar o que era deadlock. Acho que 100% da turma entendeu. kkkk
Comment: Eu era admin de uma página chamada Computação Depressão. Lembro de ter pego essa imagem e ter colocado em um desmotivado. O resultado foi [este](https://scontent-gru.xx.fbcdn.net/hphotos-xpa1/v/t1.0-9/1654130_486866364752309_1619390936_n.jpg?oh=ddf7fff26d17d31528e9fc92fbd7019f&oe=5606F928)
Comment: Ótima representação (foto)!
Answer: Um deadlock acontece quando duas ou mais tarefas bloqueiam uma à outra permanentemente, sendo que cada uma tem o bloqueio de um recurso, que a outra tarefa está tentando bloquear. Por exemplo:

A transação A adquire um bloqueio compartilhado da linha 1.
A transação B adquire um bloqueio compartilhado da linha 2.
A transação A agora solicita um bloqueio exclusivo na linha 2 e é
bloqueado até que a transação B termine e libere o bloqueio
compartilhado que tem na linha 2.
A transação B agora solicita um bloqueio exclusivo na linha 1 e é
bloqueado até que a transação A termine e libere o bloqueio
compartilhado que tem na linha 1.

A transação A não pode terminar até que a transação B termine, mas a transação B está bloqueada pela transação A. Essa condição é também chamada de dependência cíclica: a transação A tem uma dependência da transação B, e a transação B fecha o círculo tendo uma dependência da transação A.
Neste post no fórum do Technet fala mais sobre os processos de solução do deadlock.
Answer: Deadlock não é um conceito exclusivo de banco de dados, mas sim de aplicações concorrentes. Em poucas palavras:

É uma situação em que duas ou mais ações concorrentes estão cada uma esperando que a outra termine, e, portanto, isto nunca ocorre.

Para o caso de um banco de dados, um deadlock é provocado normalmente havendo transações, e envolvendo travas exclusivas. Travas exclusivas normalmente aparecem em operações de modificação.
Suponha duas transações, A e B. A precisa modificar as mesmas tabelas que B, mas B já pediu trava exclusiva em alguma das tabelas que A precisa modificar. O resultado é que A pode pedir trava exclusiva em outras tabelas que B também irá utilizar, resultando no deadlock.
O próprio banco de dados possui alguns mecanismos internos para evitar deadlock, mas o mecanismo não é infalível e normalmente demanda ações do usuário.

O que é deadlock no SQL Server?


How to programmatically disallow some users to comment on some nodes?

Question: I've been asked to implement the following:

I have a content type with a user reference field from the References module;
a user creates a node and references another user using that field;
only that user and the node's author are allowed to add comments to that node;
at some point the author closes comments, but that's part of another question :)

I've browsed the API of node (both module and API itself) and comment, and couldn't find anything useful. In fact I tried with two of the most promising functions (hook_node_view and hook_node_view_alter) without success.
I'd appreciate pointers to look at.
(yes, I know I said "complex", but this is just the starting point :)
EDIT: Partial solution ahead
<code>function _comment_access_check_permission(&$node) {
    if(user_is_logged_in()) {
        global $user;
        $account = user_load($user->uid);
        $account_uid = intval($account->uid);
        $asker = field_get_items('node', $node, 'field_asker');
        $asker_uid = intval($asker[0]['uid']);
        $author_uid = intval($node->uid);

        if($account_uid == 1 or $account_uid == $asker_uid or $account_uid == $author_uid) {
            return true;
        } else {
            return false;
        }
    } else {
        return false;
    }
    return true;
}

function comment_access_preprocess_comment_wrapper(&$vars) {
    if(!_comment_access_check_permission($vars['node'])) {
        $vars['content']['comment_form'] = array();
    }
}

function comment_access_preprocess_comment(&$vars) {
    if(!_comment_access_check_permission($vars['node'])) {
        unset($vars['content']['links']['comment']['#links']['comment-reply']);
    }
}
</code>
This code effectively hides the comment form for those users that are not supposed to comment on a given node.
BUT. If one goes to comment/reply/$nid or comment/reply/$nid/$cid the form is still shown, which is not acceptable. Another overview of the API didn't ring any bell to me, so if you have any suggestion…
Comment: I think it may help if you phrase the above into a question. Without question marks I'm guessing as to where you're looking for help.  Programmatically closing comments is generally a simple task on its own.
Answer: I would hook_form_alter the comment form, and use your logic to set #access on the form.  You may need to explicitly call menu_get_item to get your node to use in the logic.
You could also use a template_preprocess_node that would perform your logic, and hide or show the comment form in the node's render array based on your logic (this assumes it is in that render array, which I am not 100% positive about).
Comment: I actually thought of going via the preprocess_node and hiding the comment form (I think you can actually hide it and possibly render it in another place) but I was trying to avoid confusing presentation (theme) with logic (module). Thank you for you reply, though: at least I know I wasn't going crazy :)
Comment: You can preprocess in a module, which helps with the separation of duties.  Your situation is a grey area.
Answer: If you're looking to automate the closing of comments based on potentially complex logic the Rules module may be exactly what you're looking for. Managing the comments status of a given node is built in Rules functionality.
If using a contrib module is not an option, seeing how Rules would accomplish this could save you time developing your custom code.
Using nothing more than Rules and maybe the Flag and References modules, you can accomplish everything you mentioned in your original question and it would still allow for additional, possibly more complex logic in the future without needing to write custom code.
Comment: Would hook_menu_alter() be useful here to modify the access callbacks on the `comment/reply` paths?  Rules isn't the solution for sure.
Comment: Hey, I'm definitely going to check this module. How could I miss it? I've been searching for two days in a row…
Comment: I checked the Rules module and it's great. The only problem is that I need to "temporarily hide" the comment form (and possibly "temporarily block" comment saving) on a per request basis, while Rules seems to only allow me to change [node:comment] value permanently, thus making it persistent across requests.
Comment: Rules can be triggered in both directions.  You can unset settings just as easily as you set them.  This would require the creating of a new rule to handle the 're-enabling' of the feature.  At what points specifically do comments need to be disabled and at what point specifically do the need them to be re-enabled?  The 'specific conditions' that must be met to trigger each transition would be necessary to help further.
Comment: Ok, bad phrasing. I don't really need to open/close comments, I just need to show them open or closed depending on which user views a node. I think I've explained the "specific conditions" but here they are: a node has an author (obviously) and another user referenced via a field_asker user reference field. The condition is: disallow comments on the node if the user viewing it is not admin, the author, or the asker referenced by field_asker. I thought it was quite clear in the code I pasted above.
Comment: It doesn't seem to get called on every request but only when you clear the menu cache. Plus I have no access to the node object (if any).
Comment: Uh. I misunderstood something, mostly the purpose of that function :) I set an access callback and now I can do all the checks I need. Now, If only I had an answer to mark as accepted…
Answer: Implement hook_menu_alter() and use your custom access function to control access to the comment system.
<code>// Minimalist Example
function MYMODULENAME_menu_alter($items) {
  $items['<path known to hook_menu()>']['access callback'] = 'your_callback_function';
  $items['<path known to hook_menu()>']['access arguments'] = array('your args');
}
</code>


$p^{th}$ root of an analytic function $f$.

Question:
Suppose that a function f is analytic and free of zeroes in a domain $D$.  Under the assumption that a branch $g$ of the $p^{th}$-root of $f$ exists in $D$, show that there are exactly $p$ distinct branches of the $p^{th}$-root of $f$ in $D$ each having the form $cg$ for some $p^{th}$-root of unity $c$.

How would I start this proof?  I'm aware that if $g$ is a branch of the $p^{th}$ root function, then each branch has the form $cg$ where $c$ is a root of unity.
Answer: If $h(z)$ is another $p$-th root then for each $z$ you have $h(z) = e^{2\pi i k\over p} g(z)$ for some $k$ since they have to have the same $p$th power. So the issue is why the same $k$ works for all $z$. For a given $k$ the set $D_k = \{z \in D: h(z) = e^{2\pi i k\over p} g(z)\}$ is closed so you have $D$ as a union of finitely many closed sets. Since $D$ is connected all but one of them are empty.
Comment: Why would all but one of them be empty?
Comment: A connected set can't be written as the union of two disjoint closed sets. So if $D_{k_1}$ and some other $D_{k}$ are nonempty you could write $D = D_{k_1} \cup (\cup_{k \neq k_1} D_k)$ in this way


PDFSharp inverted text

Question: I'm trying to use PDFSharp to add 2 text strings to a document - one as normal and 1 upside-down. How do I add the inverted text?
This is the code I'm using to add the normal text:
<code>PdfDocument doc = PdfReader.Open(_path, PdfDocumentOpenMode.Modify);
PdfPage pdfPage = doc.Pages[0];
XGraphics gfx = XGraphics.FromPdfPage(pdfPage);
//
XTextFormatter tf = new XTextFormatter(gfx);
XFont fontHeader = new XFont("Arial", 24, XFontStyle.Bold);
//
XRect topRect = new XRect(200, 0, 200, 100);
tf.Alignment = XParagraphAlignment.Center;
tf.DrawString(_reference, fontHeader, XBrushes.Black, topRect, XStringFormats.TopLeft);
//
doc.Save(_path);
doc.Close();
doc=null;
</code>
Answer: You'll have to use transformation, presumably RotateTransform.
See this thread on the PDFsharp forum for an example:
http://forum.pdfsharp.net/viewtopic.php?p=5413#p5413
Comment: I haven't actually tried it yet, but the point raised in that question is a good one: you specify the pivot point relative to the page, so it's easier if the pivot point is where the text is going to go. It actually makes a lot of sense thinking back to my earlier attempts. Will give it another go soon. Thanks Thomas.

PDFSharp inverted text


How to deal with non-uniform data density in regression?

Question: I have a program that can detect an object in an image. It will either output a confidence in [0, 1], or "no detection" (which can be interpreted as 0 confidence). I have collected a bunch of images where the distance to the object varies.
The problem I'm trying to solve is to fit a curve to the expected detection confidence, given the distance to the object -- a regression problem. Now, there's the issue that the data I have collected does not cover all distances equally -- I have several "hot spots", distances where I have a lot of images, relatively.

Is it necessary to normalize the data density for regression? I would say yes.
How should I go about dealing with the issue?

What I tried so far is to create a histogram of distances, and divide the confidence by the nearest histogram value. However, there is too much noise for distances which are rarely observed (histogram value close to 0). Also, the discontinuities of the histogram carry over to the adjusted data.
What I am considering to do is to do some resampling of the data to achieve a more uniform spread. Any other ideas?
Here is a screenshot that shows, from left to right, the original data (confidence vs. distance), the histogram of distances, and the the normalized data (confidence divided by histogram value for that distance vs. distance):
Answer: The statistical method you need is simple linear regression. For simple linear regression, there is no special requirement on the covariate (distance in your case).
But simple linear regression requires that variance of response variable (confidence in your case) be homogeneous, i.e., the variation of the response variable does not change along the x. In you case, the variation of confidence is large (from 0 to 1) when x is near zero and is small (0 to 0.4) when X is near 0.7 (based on the first graph). So you need to consider the transformation of confidence (maybe log or square root) so that the transformed confidence has the homogeneous variance along the distance. Then you can fit the simple linear regression on transformed variable.
Comment: Your question is not problem. The frequency of covariates has no relation with bias (bias in statistical meaning). For example, $Y$ being weight, and $X$ being height of a person. The proportion of people in your sample with height >5.8` would have no relation with bias of the estimate of regression coefficients (intercept and slop). But this frequency has effect on the precision. Good design will give you higher precision of the estimate comparing with bad design giving the sample size are the same.    You can refer to regression book to check the requirements of linear regression.
Comment: This does not address my question. I can do a linear regression, however it has several disadvantages, such as sensitivity to outliers. My question was about how to deal with there being more data points in certain ranges of my independent variable(s). My intuition is that it will bias the regression in a way that leads to wrong results, given the experiment setup.


Finding the Lateral Distances between two GPS Points

Question: I have two Set of GPS Points recorded from High Precision GPS Receivers which travels from Point A to Point B . please see the Image attached.
Black Point is the GPS points of Vehicle 1 and its path... Blue Point is the GPS Points of Vehicle 2 and its path.  Vehicle 2 should follow the same path as Vehicle 1 , But there exists some deviation in pratcical scenerios. So. I need to Caluculate how much deviation it has .
I am trying to find the lateral distance between the vehicle 1 and nearest vehicle 2 GPS Point.
What I did till now ?
*)  Since vehicle 1 is ahead of vehicle 2  and , vehicle 2 reaches vehicle1 (approx)  after some time (say buffer as 5 ~10 seconds )....
   I am calculating the arc distance between  Vehicle 1 GPS Point and a set of Vehicle 2 GPS Points (buffer)  and finding the minimum of those Arc Distances.
*) By finding the Minimum of Arc Distance , I am finding the GPS Point which is nearest to the vehicle 1 GPS Point.. now , I am stuck at finding the Lateral Distance between these two GPS Points in an effecient manner.
Please let me know if u have any questions or comments on my procedure..
Answer: I assume both routes start from the same position. so i would do the  following:

Resample each route to get a new set of points with a known sampling step from on another (You can interpolate the new points from the old see for example https://www.mathworks.com/matlabcentral/answers/278615-how-to-create-points-set-on-2d-polyline)
Once i have two sets of points that start from the same location and are in a constant sampling step just calculate the distance between each corresponding points.


Lodash _.filter - filter array to return most occurences

Question: I have the following array:
{ id: 19531285,
   domain: 'fjuhsd.org',
   alexa_rank: 458835,
   country: 236,
   employees: '0',
   revenue: '0',
   industry_id: '0' },
 { id: 2657031,
   domain: 'deporlovers.
   alexa_rank: 470687,
   country: 209,
   employees: '0',
   revenue: '0',
   industry_id: '0' },
 { id: 1846092,
   domain: 'lehighsports
   alexa_rank: 477376,
   country: 236,
   employees: '0',
   revenue: '0',
   industry_id: '0' },
 { id: 41443846,
   domain: 'blacklightsl
   alexa_rank: 477964,
   country: 0,
   employees: '0',
   revenue: '0',
   industry_id: '0' },
 { id: 3881608,
   domain: 'audubonportl
   alexa_rank: 478643,
   country: 236,
   employees: '2',
   revenue: '2',
   industry_id: '39' },
 { id: 32704527,
   domain: 'lowryparkzoo
   alexa_rank: 488859,
   country: 236,
   employees: '0',
   revenue: '0',
   industry_id: '0' },
 { id: 1907473,
   domain: 'citymb.info'
   alexa_rank: 490285,
   country: 236,
   employees: '4',
   revenue: '4',
   industry_id: '53' },
 { id: 8716166,
   domain: 'terrainracin
   alexa_rank: 490404,
   country: 0,
   employees: '0',
   revenue: '0',
   industry_id: '0' },
 { id: 935439,
   domain: 'triatlonchan
   alexa_rank: 491953,
   country: 83,
   employees: '0',
   revenue: '0',
   industry_id: '0' }

I am using Lodash _.filter() function to try and sort the following array to return only the elements that have value equal to the most occurences of revenue, industry_id and employees.
In this case the number that appears the most for these (based off looking at the array )
Is revenue: 0, industry_id: 0 and employees: 0
How would I filter the array to do this with _.filter? I haven't managed to figure out a way to do this.
Thanks.
Answer: You need to find the most frequent values of necessary fields first. You can check this to find out how to do that.
Once you have the most frequent fields you can do this -
_.filter(records, record => {
    return record.revenue === mostFrequentRevenue &&
        record.industry_id === mostFrequentIndustryId &&
        record.employees === mostFrequentEmployees;
})

Answer: You can use a map to keep a tally of occurrences.

function sortExtract(data) {
  var sorted = data.sort((a, b) => {
    return a.revenue > b.revenue || a.industry_id > b.industry_id || a.employees > b.employees;
  })

  var count = new Map();
  for (let l of sorted) {
    var m = l.revenue + l.employees;
    if (count.has(m)) {
      var val = count.get(m);
      val.push(l)
    } else count.set(m, [l]);
  }
  var len = 0;
  var obj = 0
  var len = Array.from(count, (x, y) => {
    if (x[1].length > len) {
      len = x[1].length;
      obj = x[1]
    }
  })
  return obj[0];
}

var data = [{
    id: 19531285,
    domain: 'fjuhsd.org',
    alexa_rank: 458835,
    country: 236,
    employees: '0',
    revenue: '0',
    industry_id: '0'
  },
  {
    id: 2657031,
    domain: 'deporlovers',
    alexa_rank: 470687,
    country: 209,
    employees: '0',
    revenue: '0',
    industry_id: '0'
  },
  {
    id: 1846092,
    domain: 'lehighsport',
    alexa_rank: 477376,
    country: 236,
    employees: '0',
    revenue: '0',
    industry_id: '0'
  },
  {
    id: 41443846,
    domain: 'blacklights',
    alexa_rank: 477964,
    country: 0,
    employees: '0',
    revenue: '0',
    industry_id: '0'
  },
  {
    id: 3881608,
    domain: 'audubonport',
    alexa_rank: 478643,
    country: 236,
    employees: '2',
    revenue: '2',
    industry_id: '39'
  },
  {
    id: 32704527,
    domain: 'lowryparkzoo',
    alexa_rank: 488859,
    country: 236,
    employees: '0',
    revenue: '0',
    industry_id: '0'
  },
  {
    id: 1907473,
    domain: 'citymb.info',
    alexa_rank: 490285,
    country: 236,
    employees: '4',
    revenue: '4',
    industry_id: '53'
  },
  {
    id: 8716166,
    domain: 'terrainraci',
    alexa_rank: 490404,
    country: 0,
    employees: '0',
    revenue: '0',
    industry_id: '0'
  },
  {
    id: 935439,
    domain: 'triatloncha',
    alexa_rank: 491953,
    country: 83,
    employees: '0',
    revenue: '0',
    industry_id: '0'
  }
];

console.log(sortExtract(data));
Answer: Create an "id" for each item by combining the revenue, industry_id and employees values, count the occurrences in the data, and get the "id" of the highest one.
Filter the data using this id.

const data = [{"id":19531285,"domain":"fjuhsd.org","alexa_rank":458835,"country":236,"employees":"0","revenue":"0","industry_id":"0"},{"id":2657031,"domain":"deporlovers","alexa_rank":470687,"country":209,"employees":"0","revenue":"0","industry_id":"0"},{"id":1846092,"domain":"lehighsport","alexa_rank":477376,"country":236,"employees":"0","revenue":"0","industry_id":"0"},{"id":41443846,"domain":"blacklights","alexa_rank":477964,"country":0,"employees":"0","revenue":"0","industry_id":"0"},{"id":3881608,"domain":"audubonport","alexa_rank":478643,"country":236,"employees":"2","revenue":"2","industry_id":"39"},{"id":32704527,"domain":"lowryparkzoo","alexa_rank":488859,"country":236,"employees":"0","revenue":"0","industry_id":"0"},{"id":1907473,"domain":"citymb.info","alexa_rank":490285,"country":236,"employees":"4","revenue":"4","industry_id":"53"},{"id":8716166,"domain":"terrainraci","alexa_rank":490404,"country":0,"employees":"0","revenue":"0","industry_id":"0"},{"id":935439,"domain":"triatloncha","alexa_rank":491953,"country":83,"employees":"0","revenue":"0","industry_id":"0"}];

const getId = ({ revenue, industry_id, employees }) => `${revenue}-${industry_id}-${employees}`; // create the id of the element by combining the required properties

const mostOccurring = _.get(_(data)
  .countBy(getId) // count the number of items that have the same "id"
  .entries() // get the entries
  .maxBy(([_, v]) => v), 0); // find the maximum, and use get to take the id

const result = data.filter((o) => getId(o) === mostOccurring); // filter all items by the most occuring id

console.log(result);


Create a custom template for displaying a custom content type - and Views in Drupal 7

Question: I'm creating custom templates for my Drupal 7 site. There is a custom content type called flowers.

Which template file (.tpl.php) should I put under templates directory of my theme's folder for displaying a single flower-type node?
Can I use the Views module to create different views (i.e displaying picture of a flower in a view & displaying species of the flower in another view) for displaying only a single flower-type node? So far I can create pages that displays list of flower-type nodes. I want to display just a single (perhaps providing it's node-id) flower-type node. How do I do that?
2.1. For displaying different types of views to display a single flower-type node, which template files (.tpl.php) should I edit?

Thanks in advance for caring :)
Answer: Create node--flowers.tpl.php, put the default code from modules/node/node.tpl.php, and edit it.
Comment: Thanks @ram4nd. Would you please take some time and answer the 2nd problem  - creating Views using `Views` module to display just one flower?

Thanks
Comment: You can do this under pager settings. Instead of pager select display specific number of items. And you can configure the number of displayed items and offset.
Comment: Your answer is incomplete, so I answered it after creating a fully detailed tutorial on my blog. Thanks & +1 for helping


Possible values of "p" in positive semi-definite matrix

Question: I have a problem that's asking me for the maximum and minimum possibilities of "p" for this positive semidefinite matrix:
$$\begin{bmatrix}
1 & 0.8 & 1 \\
0.8 & 1 & p\\
0.8 & p & 1 \\
\end{bmatrix}$$
The answer uses the fact that the determinant must be positive. Hence they arrive 0.28 <= p <= 1 which is obvious.
My question is, how do we know there is no other restriction on p? There are many other things to consider like submatrices, eigenvalues, etc. that could be adding additional restrictions to p.
Answer: One approach is to use Sylvester's criterion. In particular, we know that the matrix will be positive definite iff the $3$ leading principal minors are positive. Those minors are given by $1$ (which is positive), $1^2 - 0.8^2 = 0.64$ (which is positive), and the determinant of the entire matrix.  Thus, if the determinant of the matrix as a whole is positive, then the matrix must be positive definite.
Incidentally, this criterion is one that you may have already encountered for $2 \times 2$ matrices when studying local extrema in multivariate calculus.
The catch to this approach is that things get a bit tricky when we consider whether or not the matrix is positive semi-definite. In particular, we know from the previous paragraph that the values $0.28<p<1$ make the matrix positive definite, but we don't know when the matrix might be positive semidefinite. In this case, there is a convenient approach: because the limit of positive semidefinite matrices is positive semidefinite, we can be sure that the matrix at $p = 0.28$ (i.e. the limit as $p \to 0.28^+$) must also be positive semidefinite. Similarly, it must be positive semidefinite at $p = 1$. In order for a matrix to be positive semidefinite without being positive definite, it must have determinant zero, so because there are no other values of $p$ for which the determinant of the matrix is zero, there are no other values that need to be considered.
More generally, we could test cases where the determinant is zero directly (i.e. test for whether the matrix is positive semidefinite) by considering every principal minor of the matrix (as opposed to the leading ones only). Unfortunately, this means that instead of considering $3$ values, we would be considering $7$.
Comment: A more direct approach might be to use the [Cauchy interlacing theorem](https://en.wikipedia.org/wiki/Min-max_theorem#Cauchy_interlacing_theorem): because the eigenvalues of a size $2$ submatrix are positive, the eigenvalues of the whole matrix (which must "interlace" with these submatrix eigenvalues) must consist of at least two positive eigenvalues and at most one eigenvalue that can be negative. Thus, the matrix has a negative eigenvalue if and only if its determinant is negative.


what is the difference between multiple select and single select Query

Question: I like to know difference between multiple and single select Query
single Query
SELECT name,age,country FROM user

Multiple Query
SELECT name FROM user
SELECT age FROM user
SELECT country FROM user

I am having functions to get values for each column in user table... That why this question
arises.. This may be silly but i like to know
Comment: ha ha ha ... sometime my mind is witch
Answer: In the first case you'll go to the grocery 1 time and back to home with a big bag, in the second case you'll go to the grocery 3 times and back to home with a small bag. If your are late you should prefere the first way...
Answer: The second query is pointless. It would be more worthwhile explaining the difference if it's a UNION join:
(SELECT name FROM user) UNION
(SELECT age FROM user) UNION
(SELECT country FROM user)

Difference? It takes longer for no real gain or reason. Pointless again.
SELECT name, age, country FROM user

This is ineffective as well. You should only select data you want, this selects for ALL users -- bad bad bad.

A better way to optimize a query
SELECT name, age, country FROM user WHERE username IN ('gary', 'john')

Select only the data you want. Don't:

don't: SELECT *
don't: select all record
don't: do multiple selects that are pointless.

DO: think logically about your data, what information you really want. Always use the EXPLAIN query to get a real idea of the performance of each query.
Comment: Across your whole page you just get one piece of information i.e. country, that's it? I find that hard to believe. Your best bet is to create a `User` class that will get all the fields you want, cache them so they can be output anywhere you like across your pages. You interact with this class i.e. `$user->get('country, age')` -- this is a nice pattern because that way you can add easily add filters onto it, using an Active Record Pattern: `$user->limit(3)->country('uk')->get('username')` it's fairly straight forward creating such a class.
Comment: did you read my question ? Mr green all is well ... But my question is different... i am having functions for each column like get_user_name($id),get_user_country($id) and etc ... some time i am only looking to get country only in that case i will use it... suppose i use the three functions in same page, is this good or bad.. bad means y
Answer: In the first example you get all the data you need in a single query, whereas in the second you'll have to do three queries (this is bad) and get three different datasets.
Answer: Exactly what it looks like.
With a single query you get everything in one go.
With multiple queries you get one thing. Then you ask for another thing and get that. Then you ask for another thing and get that.
i.e. asking three separate times is slow and wasteful and will, when computers get sentience, result in unhappy robots beating you up.
Answer: Why you'd want to run three queries with statically defined column headers, instead of picking out:
SELECT name, age, country FROM user

Is beyond me!
Unions are useful if you have two tables with the same table structure, but definitely not needed for this case.


round to nearest multiple of 5 in a range in php

Question: I have this if statement:
if($_GET["angle_1"] > 39) {
    $markers["###ANGLE###"] = "45";
} elseif($_GET["angle_1"] > 29 && $_GET["angle_1"] < 40) {
    $markers["###ANGLE###"] = "35";
} elseif($_GET["angle_1"] < 30) {
     $markers["###ANGLE###"] = "25";
} else {
     $markers["###ANGLE###"] = "45";
}

Is there a better / simpler way to do this check, f.x. with round that will round the integer to the nearest 5, i.e. 28 -> 25 or 34 -> 35 etc. and in that, if the integer is less than 25, it will always be 25 and if the integer is higher than 45, it will always be 45 and again if the integer is between 30 and 40 it will always be 35.
That returned value will be used to display an image.
EDIT:
I have 3 images: image_25, image_35 and image_45, therefore the need to round.
Comment: See this answer: http://stackoverflow.com/a/4133893/1726343
Answer: Let say $x has the number:
$x = 39;

If you want the closest multiple of 5 (39 --> 40):
$x = round($x / 5) * 5;

If you want to round up (36 --> 40):
$x = ceil($x / 5) * 5;

If you want to round down (39 --> 35):
$x = floor($x / 5) * 5;

After defining $x, you can use the following to make sure its in the 25-45 range:
$x = ($x > 45) ? 45 : ($x < 25) ? 25 : $x;

Comment: This works almost as it should, but if X is 48 the returned value will be 50, but if X is 48 I need the returned value to be 45, X cannot be less than 25 and higher than 45
Comment: Then why don't you add a statement for this particular case for yourself?
Comment: Add the following: `$x = ($x > 45) ? 45 : ($x < 25) ? 25 : $x;`
Comment: Arh.. thanks.. This I can work with! :) Answer accepted! Thanks!
Answer: Give this a try:
$var = 5 * round($n / 5);

Taken from here


Plotting results having only mean and standard deviation

Question: I am trying to visualize an appropriate plot for the observations in this table of means and standard deviations of recall scores:
\begin{array} {c|c c|c c|}
& \text{Control} & & \text{Experimental} &  \\
& \text{Mean} & \text{SD} &\text{Mean} &\text{SD} \\
\hline
\text{Recall} & 37 & 8 & 21 & 6 \\
\hline
\end{array}
What is is the best way to do that? Is bar chart a good way to do it? How can I illustrate the standard deviation in that case?
Comment: If you don't have more data, I would not create a graph. It would be a waste of space.
Comment: If you don't have more than this, a full analysis is difficult, as these means and SDs are compatible with many different distributions.
Answer: Standard deviation on bar graphs can be illustrated by including error bars in them.
The visualization(source) below is an example of such visualization:

From a discussion in the comments below, having only the error whiskers instead of the error bars setup seems a better way to visualize such data. So, the graph can look somewhat like this:
Comment: The principle is clearly along the  right lines, but I'd suggest refinements to your graph. If bins are for touching intervals, then the bars should touch too and indicating bin boundaries alone is sufficient. Regardless of that, the cross-hatching is, in my view, just a distraction here. BTW, how would you denote error for a zero observed count?
Comment: I think bars can be fine for small counts, as in this example, and for some other measured quantities also with natural origin and reference level zero, so long as they don't occlude error bars. But bars can be silly and distracting (rather than bad) when it's not an issue whether  values are or aren't zero.
Comment: At least this example has the error bars on both sides, the worst "[dynamite plots](http://biostat.mc.vanderbilt.edu/wiki/pub/Main/TatsukiKoyama/Poster3.pdf)" don't even have those, see [here](http://stats.stackexchange.com/q/1173/1036) for one example.
Comment: Another possibility is a Cleveland dot plot ([pdf](https://www.perceptualedge.com/articles/b-eye/dot_plots.pdf)), which is essentially the same as your dot & whisker version, except they go horizontally. Error bars are less common on dot plots, but are certainly acceptable.
Comment: No! I meant plotting error whiskers without plotting the bars. Bars are bad.
Comment: @NickCox I'd let them be there, as people can look at the edit history and learn why poor images shouldn't be used in answers  :D
Comment: @NickCox I just lifted it up from the web. And yeah, the bins should touch for touching intervals(but here they aren't, so I think it's alright here). And yeah, the hatching is distracting.  I need to plot one for getting my head around how to get a zero observed count on it.
Comment: @AndyW After reading that article, I too hate dynamite plots now :D

These are good enough then.  So, are these dynamite plots with less opacity?  (Maybe ;-) )
Comment: This plot comes with a HUGE caveat that it is only meaningful if the zero mean has some special meaning! Because yellow bars all stretch down to zero and so emphasize it immensely. An (often preferred) alternative is to remove the bars altogether, leaving only points and whiskers.
Comment: Me and Nick touched upon the points I think are the most noteworthy. Even ignoring the show the data point and just discussing showing the point estimates and the standard errors, the bars are generally superfluous, and they are even worse when they "cover up" half of the interval. Also bar conventions like anchoring to zero and having discrete bins can impede the viz. as well. Tukey has a great example of that in EDA.
Comment: @amoeba So, you mean having only the error bars, instead of the _error whiskers + bars_ setup?
Comment: @amoeba Yeah, I meant _whiskers_.  That should look neat, but you need to have the dotted lines in the graph though.
Comment: @NickCox Replaced Image-1 with a better one.
Comment: Thanks for removing the cross-hatching. Cutting out comments that are now irrelevant is (mostly) too difficult,
Answer: I'd suggest a dot plot:

Although there is still some room for improvement (perhaps dimming the edges of the big rectangle surrounding the data), almost all of the ink is being used to display information.
Comment: @kjetilbhavlorsen: The mean is the dot, and the standard deviation (or optionally, standard error of the mean) is shown using the length of the lines adjacent to the dot.
Comment: (+1) The term "dot plot" is rather overloaded, my first thought was that you were going to suggest drawing dots for each data point (which of course the OP can't do, not having the raw data). I suspect this is what @kjetil wondered too. Does this variety of "dot plot" have a more specific name which distinguishes it from the "dot for each data point" type of plot?
Comment: How does this answer the OP's question? How do you use dotplot with means and standard deviations?
Comment: [This Stack Overflow page](http://stackoverflow.com/a/18207651/5044791) discusses how to generate dotplots from means and SDs.
Answer: Perhaps the best way to visualise the kind of data that gives rise to those sorts of results is to simulate a data set of a few hundred or a few thousand data points where one variable (control) has mean 37 and standard deviation 8 while the other (experimental) has men 21 and standard deviation 6.  The simulation is simple enough in a spreadsheet or your favourite stats package.  You can then graph the two distribitions to get an impression of the extent that the two sets of recall scores vary.

With a simuated data-set you can also easily construct summary graphs like box-plots or histograms with error bars.


Para usar o Admob é obrigatório publicar o app em loja oficial?

Question: Estou terminando um aplicativo que apresenta banners vindos do Admob. Não ficou claro (para mim) se o aplicativo tem que ser, obrigatoriamente, distribuído numa loja oficial (Google Play ou Apple App Store), ou se posso distribuir por outros meios, como email, website, etc.
Comment: Não, não precisa publicar na loja oficial.
Answer: Não é obrigatório sua aplicação estar na loja do Google para que seja monetizada, no entanto você tem que assinar seu APK e não distribuir em modo de depuração. Caso você publique em modo de depuração, este mesmo é considerado que está em teste. De acordo com as políticas do AdMob:

É contra a política da AdMob clicar nos próprios anúncios ativos.
  Durante o desenvolvimento e os testes, use anúncios de teste. Se você
  não precisa renderizar anúncios ativos antes do lançamento, evite
  clicar neles. Se você clicar em anúncios ativos, sua conta na AdMob
  poderá ser suspensa.

Para saber mais detalhes veja na documentação e também conferir as Políticas da AdMob e do Google AdSense.
Observação: Verifique o ID do anúncio, caso não esteja inserido corretamente, você não será monetizado.


Can't store data fetched with jQuery JSONP

Question: I'm trying to fetch a bunch of photo data from Flickr via a jQuery AJAX call using JSONP, but I don't want to use the data right away. Instead, I'd like to preserve it for use later. In a complicated case, I'd like to let users perform different queries on the prefetched data. In a simpler case, I'd like to just load the next n images each time the user clicks a button.
Right now, I'm testing just the most basic functionality below, which is adapted from the best answer to this question: JQuery - Storing ajax response into global variable
However, the retrieved JSON data is not getting stored in the jsonData variable as it should. I put the alert statements to debug, and the strange thing is that the getData() alert is triggered before the alert in the callback function. Why is this happening?
var dataStore = ( function() {
  var jsonData;

  $.ajax({
    type: "GET",
    url: "http://api.flickr.com/services/feeds/photos_public.gne?jsoncallback=?",
    dataType: "json",
    data: {
      tags: "dog",
      tagmode: "any",
      format: "json"
    },
    success: function(data) {
      jsonData = data;
      alert(jsonData);
    }
  });

  return { getData : function()
  {
      if (jsonData) return jsonData;
      else alert("no data!");
  }};
})();

var stuff = dataStore.getData();

$.each(stuff.items, function(i,item) {
  $("").attr("src", item.media.m).appendTo("#images");
  if ( i == 3 ) return false;
});

Comment: It's best to ask **one** question in each question here on Stack Overflow. In the above, you're asking two quite distinct questions: 1) Why is your code not working as you expect, and separately 2) Should you be doing this or putting in hidden images. Conflating questions reduces the quality of both the question and its answers, best to split them up.
Comment: I see, thanks for the tip. Should I split it up now, after the fact?
Comment: `@stchangg`: I probably would, yeah. Since the other answer here addresses the "why doesn't this code work right" aspect, I'd leave that part here and ask the image best practices question separately. I can copy over the part of my answer that relates to that.
Comment: Cool, just extracted out the other question here: http://stackoverflow.com/questions/8353733/is-it-better-to-use-the-hidden-css-attribute-or-fetch-each-set-of-new-images
Answer:
...and the strange thing is that the getData() alert is triggered before the alert in the callback function. Why is this happening?

Because ajax calls in general are, by default, asynchronous — and JSONP calls are always asynchronous by their nature (other kinds of ajax calls can be made synchronous, but it's generally a bad idea).
This means your
var stuff= dataStore.getData();

line executes before the JSONP request completes. This is also why it doesn't see anything in jsonData.
You need to move any processing of the JSONP call result into something called from the success callback of the request.
Comment: Thanks! I wish I could upvote but I don't have enough rep points yet.
Answer: The problem is that stuff is undefined when $.each runs because stuff hasn't finished running yet. Everything needs to be in a callback. There's numerous ways to get around it from the most ugly and hacky of doing a setInterval() that checks if stuff === undefined and if NOT then it does the $.each to a more JS native way of just using callbacks.
Personally, I highly suggest you just use callbacks more effectively. Here's what i'd do. This should put you on the right track. Obviously a lot of this is faux code, but can easily be modified to your needs.
var cachedImageData = {}; //To check if data exists for the search term

var displayImages = function(stuff){
  $.each(stuff.items, function(i,item) {
    $("").attr("src", item.media.m).appendTo("#images");
    if ( i == 3 ) return false;
  });
}

$('button').bind('click',function(){ //Triggers the ajax...
  if(cachedImageData[$('input').val()] === undefined){ //If this search doesn't exist...
    $.ajax({
      url:''
      data:{ tag: $('input').val() }, //Get the value however
      success: function(data){
        cachedImageData[$('input').val()] = data; //Save for later
        displayImages(data); //Run the display images function which is your $.each()
      }
    });
  }
});

Comment: Thanks for the answer. But... where does cachedImageData get added to?
Comment: Updated. You'd save once you got the data.


Controlling for categorical variables

Question: I have 8 independent variables which may be nominal or ordinal, and I want to see how each of them affect a numeric dependent variable $Y$, so that the effect of $X_{1}$ is controlled by the rest of variables $X_{2}$ through $X_{8}$.
How can I do this?
Answer: You could create a dummy variable (https://en.wikipedia.org/wiki/Dummy_variable_(statistics) ) for each category.
For example, if you have variable $X_1$ that can attain three values, say, $X_1 = 1$ or $X_1 = 2$ or $X_1=3$. Then create 3 new dummy variables, $d_1, d_2, d_3$, such that $$d_i = \begin{cases} 1 & \text{if } \  X_1 = i \\ 0 & \text{otherwise} \end{cases}$$
and regress
$$
Y  = \delta_1 d_1 + \delta_2 d_1 +  \delta_3 d_1 + \epsilon,
$$
in order to estimate $\delta_i$. These parameters are equal to average $Y$ in the group of observations with $X_1 = i$. If there are other regressors, then $\delta_i$ correspond to a conditional mean,  conditional on the impact of the other variables on the right-hand side.

Controlling for categorical variables


What is the difference between $i=(1+r)^{m}-1$ and $i=(1+\frac{r}{m})^{m}-1$?

Question: If I put say $P$ amount of money in my account at the beginning of the year and the yearly interest rate is $i$ (as a decimal) then at the end of the year I will have $P(1+i)$ in my account.
If I put $P$ in my account and the interest was compounded $m$ times per year at a rate $r$ which is equivalent to a yearly rate of $i$ I would have to work out $r$.
I would do: $$(1+i)=(1+r)^{m}$$
I could write this in terms of $i$ as: $$i=(1+r)^{m}-1$$
But in my booklet of formulae I see the formula: $$i=(1+\frac{r}{m})^{m}-1$$
Where did that extra $m$ come from?
I suspect these two formulae are used for slightly different problems.
What is the difference between these two formulae?
Comment: Typically, compund interested is computed using the *periodic* rate $r/m$ instead of the *annual* rate.
Comment: If an annual interest rate of, say, $r=3\%$ is compunded monthly, the interest rate applied each month would be $r/m=3\%/12=0.25\%$.
Comment: Can you give me an example amd13 ? I'm not fully sure what that means.
Comment: Ok I think I have it. Thanks amd13.
Answer: (Rolling comments into an answer)
Compound interest calculations generally use a periodic interest rate, which is the annual rate divided by the number of periods, i.e., $r/m$. For example, if an annual rate of $3.00\%$ were to be compunded monthly, the rate used for the interest computation would be $$\frac rm={3.00\%\over12}=0.25\%.$$