Automated Testing for Oracle APEX Web Application

Question: I'm currently working on a new web application and it's being developed using Oracle APEX.  It's basically a ten page wizard-style web form that gets filled out and submitted.  In nearly all cases, only three or four of these pages will be used and the other exist to present special-case information to the user.
Anyway... I'm currently writing a test plan to ensure all the validation and processes are working as expected and I would like to try automating this testing if at all possible.
Does anyone know any good automated testing tools (preferable open source) that I can put to use for this purpose? Also, as it might be relevant, I'm limited to Java and/or APEX for tailoring these tools to meet my testing needs.
Comment: I'd argue that the fact that the app is Oracle/Apex should be irrelevant, so you may get more feedback if you tag it "web application" or similar
Answer: Selenium - http://seleniumhq.org/
Answer: Cucumber with headless driver such as capybara-webkit.
Here you can find how to do it for non rails apps like APEX http://github.com/pshapoval/cucumber-norails
Answer: Selenium web driver and RSPEC if you want something straightward. I use it in a legacy classic ASP application and used it with Oracle Apex as well. Best to use ruby rather than the Firefox Selenium IDR.
Follow the below steps
Tested with ruby 2.0.0p481
Installed the following gems
childprocess-0.5.3.gem
diff-lcs-1.2.5.gem
ffi-1.0.11.gem
ffi-1.0.11-java.gem
multi_json-1.10.1.gem
rspec-3.0.0.gem
rspec-core-3.0.4.gem
rspec-expectations-3.0.4.gem
rspec-mocks-3.0.4.gem
rspec-support-3.0.4.gem
rubyzip-1.1.6.gem
selenium-webdriver-2.42.0.gem
To install run
gem install selenium-webdriver --local
You will be asked to install dependencies..follow instructions.
To run tests
rspec RecordAdminTests.rb
You will need selenium server running
java -jar selenium-server-standalone-2.42.2.jar

require 'rubygems' require "selenium-webdriver" require "rspec"
describe "Admin ABC" do
before(:each) do        @vcntPg = 20    end
before(:all) do         @driver = Selenium::WebDriver.for :firefox      @wait
  = Selenium::WebDriver::Wait.new(:timeout => 15)       @driver.navigate.to "whateverurl"                   end
after(:all) do          @driver.quit    end
            describe "Admin Project/User/Events" do
                it "Should Edit CDE" do
<code>              @wait.until {
                  @driver.find_element(:css ,"a[href*='Home.asp?GroupId=2']")
              }
</code>
end
end
Answer: JMeter can also be used, particularly for load testing. Chris Muir has a good breakdown here
http://one-size-doesnt-fit-all.blogspot.com.au/2010/05/configuring-apache-jmeter-for-apex.html
Answer: You could use Cypress, which has an easy learning curve and interactive test runner right out of the box. This is my goto tool for automated browser testing now.
https://www.cypress.io


How to solve maximum likelihood estimates with inequality constraint?

Question: For example, let $ r_i \sim \operatorname{Binomial} (n, p_i)$, where $i \in [1,m]$. Assume that $ r_i $ are independent and also, put an inequality, $ p_1 < p_2 < \cdots < p_m $.
How to find the maximum likelihood estimates of $ p_1, \ldots,p_m$ in such setting?
I know the joint likelihood can be written as,
$$ \sum_{i=1}^m \big(r_{i} \log p_{i} + (n-r_{i})\log(1-p_{i})\big)+ \text{constant}.$$
But how can I continue to derive the MLE with the constraint?
Comment: If you're looking for a point in the space $\{\,(p_1,\ldots,p_n) : 0 \le p_1 < p_2 < \cdots < p_m\le 1\}$ that maximizes a likelihood function, there may not be one since in some cases the maximizing value will be on the boundary. Thus you may want to look in the space $\{\,(p_1,\ldots,p_n) : 0 \le p_1 \le p_2 \le \cdots \le p_m\le 1\}. \qquad$
Comment: I've deleted my answer. I may edit it further and then undelete it.
Comment: yep, i make a mistake.
Comment: An MLE is always within the closure of the parameter space, so the MLE must satisfy the same weak inequalities.
Comment: So, if it is the non-strict inequality, for example m = 2, then the MLE of p1 is r1/n, p2 = r2/n if r1 < r2 and p1 = p2 = r2/n if r2< r1. Am I right?
Answer: Constrained maximum-likelihood is just a particular application of constrained optimisation more generally, and so it falls within the field of nonlinear programming.  There are many methods of solving nonlinear optimisation problems constrained by inequality constraints, including the Karush–Kuhn–Tucker method or simply transforming the problem into an unconstrained one.
An example applicable to your problem: In the present case, it is possible to transform the constrained vector $\boldsymbol{p} = (p_1, \ldots, p_m)$ from an unconstrained vector $\boldsymbol{u} = (u_1, \ldots, u_m) \in \mathbb{R}^m$.  There are lots of ways to do this, but one way is to define the transformation using nested logistic functions as follows (the parameter $\alpha$ is a control parameter):
$$p_k = T_k(\boldsymbol{u}) \equiv \frac{1}{1 + \sum_{i=k}^m \exp(- \alpha u_i)} \quad \quad \text{for } k = 1,2,\ldots,m.$$
This yields a transformation $T: \mathbb{R}^m \times \mathbb{R} \rightarrow \{ \boldsymbol{p} \in \mathbb{R}^m \mid 0 < p_1 < \cdots < p_m < 1 \}$, which means that it maps an unconstrained parameter $\boldsymbol{u}$ to the constrained parameter $\boldsymbol{p}$.  (I have also allowed for a control parameter $\alpha$ that lets you adjust the steepness of the logistic functions; you can remove this part by setting $\alpha = 1$ if you want to.)
Re-parameterising your optimisation problem into the new unconstrained parameter $\boldsymbol{u}$ yields the log-likelihood function (which also includes the logistic control parameter $\alpha$):
$$\ell_\boldsymbol{r}(\boldsymbol{u} \mid \alpha) = \sum_{k=1}^m \Big( (n_k-r_k) \log \Big( \sum_{i=k}^m \exp(- \alpha u_i) \Big) - n_k \log \Big(1 + \sum_{i=k}^m \exp(- \alpha u_i) \Big) \Big).$$
The maximum-likelihood estimator $\hat{\boldsymbol{u}}$ can be obtained by maximising this function over the unconstrained space $\boldsymbol{u} \in \mathbb{R}^m$, which requires numerical methods.  If this MLE exists, we then obtain the corresponding MLE for your desired parameter vector as $\hat{\boldsymbol{p}} = T(\hat{\boldsymbol{u}}, \alpha)$.
Note: In your problem the strict inequality constraints mean that the MLE will not exist for most data vectors.  If you change these to non-strict inequality constraints then the constrained MLE will exist.  In this case the transformation does not allow values with equality between adjacent $p_k$ values, but it allows you to come arbitrarily close to this.  Hence, standard numerical methods to maximise the above likelihood should still converge towards the MLE.
Comment: So, if it is the non-strict inequality, for example m = 2, then the MLE of p1 is r1/n, p2 = r2/n if r1 < r2 and p1 = p2 = r2/n if r2< r1. Am I right?


multi value fetch in style tag in html php

Question: <select name="organization" id="orgId" style="<?php echo $_POST['report_type'] == 'org_participation' ? '' : 'display:none'; ?>">

I have 3 values: org_participation, monthly, daily.
I have tried all three include in style like
<select name="organization" id="orgId" style="<?php echo $_POST['report_type'] == 'org_participation','monthly','daily' ? '' : 'display:none'; ?>">

But not get any result i know it wrong way but tried something like this.
Please help me to solve this issues.
Answer: Use
in_array($_POST['report_type'], ['org_participation', 'monthly', 'daily'])

to check whether report_type is one of 'org_participation', 'monthly', 'daily'.
So
<select name="organization" id="orgId" style="<?php echo in_array($_POST['report_type'], ['org_participation', 'monthly', 'daily']) ? '' : 'display:none'; ?>">

Comment: ty so much it woked for me


Implicit Differentiation for calculating area of a circle

Question: I am working on a implicit differentiation equation of a circle where the radius grows by 1/per sec.
Can someone advise if I have differentiate the equation correctly?
The radius of the circle grows by 1/s given:
$$\frac{dr}{dt} = 1$$
The area of the circle given:
$$A = \pi r^2$$
Differentiate both sides of the equation with respect to the third variable: time
$$\frac{dA}{dt} = 2\pi r \frac{dr}{dt}$$
The differentiation of the left hand side of the equation:
$$\frac{d}{dt}[A] = \frac{dA}{dt}$$
The differentiation of the right hand side of the equation:
$$\frac{d}{dt} [\pi r^2] = [f(x)g'(x)+g(x)f'(x)]\frac{dr}{dt}$$
$$= [\pi\frac{d}{dr}[r^2] + r^2 \frac{d}{dr}[\pi]]\frac{dr}{dt}$$
$$= 2\pi r \frac{dr}{dt}$$
$$= 2\pi r$$ (since dr/dt = 1)
Comment: @BCLC OP means one per second ie $1 s^{-1}$
Comment: its correct. Continuing with the given values will give the answer you require
Comment: @TheIntegrator "A" should not be treated as a constant since it is dependent on $$A = \pi r^2$$ Am I right?
Comment: Yes , if you want you can write it as $A(r)$ to be more clear
Comment: What's $\frac 1 s$ ?
Answer: Since $\pi$ is a constant, all you have to do is $$ \frac {dA}{dt} =   2 \pi r\frac{dr}{dt}$$
You do not need to do the product rule in this case.
Comment: yes, the derivative of a constant is zero and anything multiply by it ends up as zero. =)


Proving the dimension of a manifold is well defined

Question: Show that if $M \subseteq \Bbb R^n$ is a $k$-dimensional manifold, then there is no $x \in M$ and $U_x$ a neighborhood of $x$ such that $M \cap U_x$ has a good parametrization from $V_x \subseteq \Bbb R^m$ where $k \neq m$.
The definition of "good parametrization" of $M$ is as follows: there exists a smooth, regular homeomorphism $r:V_x \to \Bbb R^n $ such that $r(V_x) =M$ where $V_x \subseteq \Bbb R^m$ is an open set.
I'm having a hard time approaching this one, any guidance will be appreciated
Comment: If you have charts $\phi: U \to \Bbb R^n$ and $\psi : U \to \Bbb R^m$, then $\psi^{-1}\circ \phi$ is a homeomorphism between open sets of $\Bbb R^n$ and $\Bbb R^m$. So you just need to prove it for open sets in $\Bbb R^n$ and $\Bbb R^m$ for it to be true for all manifolds.
Answer: If  $\phi$, $\psi$ are two good parametrizations (i.e. smooth immersions into $M$ which are homeomorphisms onto their images) with the same non-empty image, then the transition map  $\tau=\psi^{-1}\circ\phi$ is a homeomorphism between non-empty open subsets of $\mathbb R^k$ and  $\mathbb R^l$ and one can use tools from algebraic topology to show that this implies $k=l$. However in the differentiable setting this is easier:
Assume for a moment that we knew that $\tau$ is in fact a diffeomorphism. Then by the chain rule for all $x$ in the domain of $\tau$ we have
$$id_{\mathbb R^k}=D(id)(x)=D(\tau^{-1}\circ\tau)(x)=D(\tau^{-1})(\tau (x))\circ D(\tau)(x)$$
so $D(\tau)(x)$ is a linear isomorphism between $\mathbb R^k$ and  $\mathbb R^l$ which implies $k=l$.
It remains to show that $\tau$ is a diffeomorphism. For this we can use the following lemma:

$\textbf{Lemma:}$
Assume $\psi:\tilde V \to\mathbb R^n$ is a smooth immersion, with $\tilde V\subset\mathbb R^k$ open. Then for all $x\in \tilde V$ there  are open neighbourhoods $V\subset\tilde V$ of $x$ and $U$ of $\psi(x)$ with $\psi(V)\subset U$ and a smooth map $\Gamma:U\to V$ such that $\Gamma\circ\psi_{|V}=\text{id}_{|V}$.

So if $z$ is in the domain of $\tau$ we can set $x=\tau(z)$, find $V$, $U$ and $\Gamma$ as above and then  $\tau=\Gamma\circ\phi$ on $\tau^{-1}(V)$ which is smooth. In the same way $\tau^{-1}$ will then be smooth.
proof of the Lemma:
Let $T$ be the image of the differential of $\psi$ at $x$ which is a $k$-dimensional subspace of $\mathbb R^n$ and let $L:\mathbb R^n\to\mathbb R^k$ be any linear map which maps $T$ onto $\mathbb R^k$. Then by the chain rule
$D(L\circ\psi)(x)=DL(\psi(x))\circ D\psi(x)=L\circ D\psi(x) $
is surjective and linear and hence invertible. By the inverse function theorem there are open neighbourhoods $V\subset\Omega$, $W\subset\mathbb R^k$ of $x$ and $L(\psi(x))$ such that $L\circ\psi:V\to W$ is a diffeomorphism.
Now set $U=L^{-1}(W)$ and $\Gamma = (L\circ\psi)^{-1}\circ L$. $\square$


Save comment dynamically

Question: I've made my own module to add commenting to a node (it opens modally in a colorbox - really nice). The form works great, but how do I save the comment?
I know it's got to be done using comment_save. But, as usual, drupal.org is great at showing the code for the function without giving an example...
Has anyone done this before?
I'm guessing it's something like:
<code>$comment = new stdClass();

$comment->nid = $the_node_the_comment_is_for;
$comment->title = $my_comment_title;
$comment->body = $my_comment_body;

comment_save($comment);
</code>
Answer: Yes you can save comment dynamically using comment_save() function, a working example is given below
<code><?php

$comment = new stdClass();

$comment->nid = 28; // nid of a node you want to attach a comment to
$comment->cid = 0; // leave it as is
$comment->pid = 0; // parent comment id, 0 if none
$comment->uid = 1; // user's id, who left the comment
$comment->mail = 'email@example.com'; // user's email
$comment->name = 'User name'; // If user is authenticated you can omit this field, it will be auto-populated, if the user is anonymous and you want to name him somehow, input his name here
$comment->thread = '01/'; // OPTIONAL. If you need comments to be threaded you can fill this value. Otherwise omit it.
$comment->hostname = '127.0.01' ;// OPTIONAL. You can log poster's ip here
$comment->created = time(); // OPTIONAL. You can set any time you want here. Useful for backdated comments creation.
$comment->is_anonymous = 0; // leave it as is
$comment->homepage = ''; // you can add homepage URL here
$comment->status = COMMENT_PUBLISHED; // We auto-publish this comment
$comment->language = LANGUAGE_NONE; // The same as for a node
$comment->subject = 'Comment subject';
$comment->comment_body[$comment->language][0]['value'] = 'Comment body text'; // Everything here is pretty much like with a node
$comment->comment_body[$comment->language][0]['format'] = 'filtered_html';
$comment->field_custom_field_name[LANGUAGE_NONE][0]['value'] = 'Some value'; // OPTIONAL. If your comment has a custom field attached it can added as simple as this // preparing a comment for a save

comment_submit($comment); // saving a comment
comment_save($comment);
?>
</code>

Save comment dynamically


Is there a way to add items from an array to each row in a container using jQuery?

Question: I've been trying to add items from an array to rows within a container. Essentially, each row is supposed to contain a time text, input field, and a button. I'm pretty sure for loop is the way to go, but I'm getting each row repeated in the container. Where do you think I'm going wrong?
// array for time range
var timeArr = [
  "9 am",
  "10 am",
  "11 am",
  "12 pm",
  "1 pm",
  "2 pm",
  "3 pm",
  "4 pm",
  "5 pm",
];

// loop through time range array, creating hours, input fields, and text lock buttons
for (i = 0; i < timeArr.length; i++) {
  var eachRow = $("
").addClass("row");
  $(".container").append(eachRow);
  var eachHour = $("<textarea>").text(timeArr[i]).addClass("hour col-md-2");
  var userInput = $("<input>")
    .attr("placeholder", "Add your notes here..")
    .addClass("time-block col-md-8");
  var textLock = $("<button>").text("lock/unlock").addClass("saveBtn col-md-2");
  $(".row").append(eachHour);
  $(".row").append(userInput);
  $(".row").append(textLock);
}

Comment: `$(".row").append(eachHour)` etc.  will find ALL elements with `.row` class and append to them. So will grow exponentially. Here you only want to append to the new element.
Answer: You need to modify the last 3 lines. When using $(".row"), you are selecting all the elements with class "row". You just need the current row where you are iterating. Hence, using eachRow instead is a right way:
        var timeArr = [
        "9 am",
        "10 am",
        "11 am",
        "12 pm",
        "1 pm",
        "2 pm",
        "3 pm",
        "4 pm",
        "5 pm",
    ];

    // loop through time range array, creating hours, input fields, and text lock buttons
    for (i = 0; i < timeArr.length; i++) {
        var eachRow = $("
").addClass("row");
        $(".container").append(eachRow);
        var eachHour = $("<textarea>").text(timeArr[i]).addClass("hour col-md-2");
        var userInput = $("<input>")
        .attr("placeholder", "Add your notes here..")
        .addClass("time-block col-md-8");
        var textLock = $("<button>").text("lock/unlock").addClass("saveBtn col-md-2");
        eachRow.append(eachHour);
        eachRow.append(userInput);
        eachRow.append(textLock);
    }

Demo: https://jsfiddle.net/lotusgodkk/co8r4hks/3/

        var timeArr = [
          "9 am",
          "10 am",
          "11 am",
          "12 pm",
          "1 pm",
          "2 pm",
          "3 pm",
          "4 pm",
          "5 pm",
        ];

        // loop through time range array, creating hours, input fields, and text lock buttons
        for (i = 0; i < timeArr.length; i++) {
          var eachRow = $("
").addClass("row");
          $(".container").append(eachRow);
          var eachHour = $("<textarea>").text(timeArr[i]).addClass("hour col-md-2");
          var userInput = $("<input>")
            .attr("placeholder", "Add your notes here..")
            .addClass("time-block col-md-8");
          var textLock = $("<button>").text("lock/unlock").addClass("saveBtn col-md-2");
          eachRow.append(eachHour);
          eachRow.append(userInput);
          eachRow.append(textLock);
        }

Comment: This worked perfectly. I see the logic error now. Thanks!!


Reading only specific rows from a CSV file using Python 3

Question: I am learning how to read CSV files using Python 3, and have been playing around with my code and have managed to read either the whole document or certain columns, however I am trying to now read only certain records that contain a certain value.
For example I want to read all records where the car is blue, how would I make it read only those records? I can't figure this out and would be grateful for any help or guidance!
import csv

with open('cars.csv') as csvfile:
    reader = csv.DictReader(csvfile)
    for row in reader:
        print(row['ID'], row['Make'], row['Colour'])

Comment: Possible duplicate of [How do I read and write CSV files with Python?](http://stackoverflow.com/questions/41585078/how-do-i-read-and-write-csv-files-with-python)
Answer: A simple "if" statement should suffice.  See control flow docs.
import csv

with open('Cars.csv') as csvfile:
    reader = csv.DictReader(csvfile)
    for row in reader:
        if row['Colour'] == 'blue':
            print(row['ID'] ,row ['Make'],row ['Colour'])

Answer: You can check the values while reading the rows.
with open('Cars.csv') as csvfile:
    reader = csv.DictReader(csvfile)
    for row in reader:
     // check your values here - if car = blue
     // do something with blue cars.
     print(row['ID'] ,row ['Make'],row ['Colour'])

Answer: You read each row one by one and use an explicit check to filter those that you want to deal with. Then add them to an array for example, or process it in place.
Comment: How would I do this?


Advice on how to fix Workbench Moderation error messages

Question: (n00b drupal person)
I seem to be suffering the problems described in https://drupal.org/node/1966908 and https://drupal.org/node/1966920.
Basically I have installed the following:
drupal-7.26.tar.gz
media-7.x-1.4.tar.gz
views-7.x-3.7.tar.gz
ctools-7.x-1.3.tar.gz
workbench-7.x-1.2.tar.gz
workbench_access-7.x-1.2.tar.gz
workbench_media-7.x-1.1.tar.gz
workbench_moderation-7.x-1.3.tar.gz

It all seems to be configured OK, but when I switch to My Workbench -> Create Content I get the following warning/error message:

Notice: Undefined index: #contextual_links in
  contextual_pre_render_links() (line 140 of
  /home/apache/drupal-7.26/modules/contextual/contextual.module).
Warning: Invalid argument supplied for foreach() in
  contextual_pre_render_links() (line 140 of
  /home/apache/drupal-7.26/modules/contextual/contextual.module).
Notice: Undefined index: #contextual_links in
  contextual_pre_render_links() (line 140 of
  /home/apache/drupal-7.26/modules/contextual/contextual.module).
Warning: Invalid argument supplied for foreach() in
  contextual_pre_render_links() (line 140 of
  /home/apache/drupal-7.26/modules/contextual/contextual.module).
Notice: Undefined index: #contextual_links in
  contextual_pre_render_links() (line 140 of
  /home/apache/drupal-7.26/modules/contextual/contextual.module).
Warning: Invalid argument supplied for foreach() in
  contextual_pre_render_links() (line 140 of
  /home/apache/drupal-7.26/modules/contextual/contextual.module).

Would very much appreciate some help with:

Confirmation I've got the right bugs
Some advice on fixing it... should really be using git patch rather than installing the updated modules to fix ?
Answer: OK, so I found a workaround, which is good enough for the timebeing... enable Views UI modules - https://drupal.org/comment/6971496#comment-6971496
Answer: certainly enabling views UI solve the problem but a more suitable solution is provided in this patch [#1727284-1]
Answer: Enable Views UI and error goes away.


How do I make batch callbacks as class methods?

Question: This is the code I am using.
$serviceClass = \Drupal::service('abcclass.service');
$batch = array(
  'title' => t('Pushing updated.'),
  'init_message' => t('Start Pushing.'),
  'progress_message' => t('Completed @current step of @total.'),
  'error_message' => t('Pushing has encountered an error.'),
  'operations' => array(
    array(array($serviceClass , 'ebook_push_single_pdf'), $node->id()),
  ),
  'finished' => array($serviceClass , 'ebook_push_finished'),
);
batch_set($batch);

But it doesn't work. I checked log file and I get:

Settings can not be serialized. This probably means you are serializing an object that has an indirect reference to the Settings object. Adjust your code so that is not necessary.

Note that if I implement batch callbacks in same file, it works.
How can I fix the code?
Answer: When I use a callback function what live in a class I use, for example:
'finished' => array('\Drupal\my_batch\Form\MyBatchForm', 'finish_function'),

The same with 'operations':
'operations' => array(array('\Drupal\my_batch\Form\MyBatchForm', 'operation_function'), array($node->id())),

Comment: Your example of operations makes no sense. There are more closing brackets than opening brackets and it looks like the whole thing should be wrapped in another array to allow for multiple operations.
Comment: @FelixEve thank you, fixed the closing brackets xD
Answer: A $serviceClass cannot be passed through the form to a batch file like this. It has to be passed as an array of arguments inside the operations.
Fixed Code is here -
$serviceClass = \Drupal::service('abcclass.service');
$batch = array(
  'title' => $this->t('Pushing updated.'),
  'init_message' => $this->t('Start Pushing.'),
  'progress_message' => $this->t('Completed @current step of @total.'),
  'error_message' => $this->t('Pushing has encountered an error.'),
  'operations' => array(
    array(
      array('Drupal\module_name\Batch_file','run'),
      array($serviceClass , 'ebook_push_single_pdf', $node->id(),'import'),
    ),
  ),
  'finished' => array('Drupal\module_name\Batch_file','finished'),
);
batch_set($batch);

where, "Batch_file" is the Batch_file.php where we get those arguments.
'run' and 'finished' are the two static functions of Batch_file.


Compare whether one group are significantly closer to real observations than other

Question: I have two groups consisting of non-parametric estimated data of a phenomenon. I want to compare these two groups of estimations with a third group of real observations of the same phenomena. Basically, I want to check whether one group is significantly closer to the real observations than the other. After a little search, I ended up identifying Wilcoxon paired test (or Wilcoxon Signed Rank test) as my way to go, but couldn't quite figure out how to interpret its results. Since I'm a newbie to non-parametric statistics, I need a little help on how use the Wilcoxon paired test to test the hypothesis that Group A is significantly closer to real observations than Group B, for example.
I came out with two approaches:

Apply a Wilcoxon paired test directly between the two groups and the real observations. Therefore, the group who have the lower p-value (if < 0,05) in comparison to the real observations is significantly more different than the other at 5% of significance.

Calculate the absolute errors |N observed - N estimated| and perform a one-tailed Wilcoxon paired test between the two error groups to check whether the absolute errors of group A are significantly lower than group B. Therefore if p-value < 0.05 group A has significantly less errors than group B, i.e. is closer to real observations at 5% significance.

Which one of them do you consider most appropriate to test my hypothesis?
Answer: Overview.
If you use method (1), then you will have no information
to make a direct comparison between the two methods of estimation.
It is not appropriate to interpret a larger P-value to mean
that $H_0$ is "more true."
[Under $H_0,$ P-values of exact tests
on continuous data are uniformly distributed. However, the nonparametric Wilcoxon signed rank test is based on (discrete) ranks and uses normal approximations when sample sizes are large. The
test is calibrated to have correct error probabilities for usual
significance levels (say, below 10%), but P-values should be used
for deciding whether to reject $H_0.]$
If you use method (2), then you can see how well each kind of estimate performs.
Simulated results for sample median vs. sample midrange of normal data
as estimates of population mean.
To illustrate, consider whether the sample median or the sample midrange is the more reliable estimate of the center $\mu$ of a sample from a normal population. [Of course, we know the sample mean has nice properties. It turns out that the median is generally better than the midrange.]
We choose normal samples of size $n = 50$ from normal populations
with means $\mu$ in $(30,60)$ and SDs $\sigma=3.$ Then we do paired
Wilcoxon (signed rank) tests to assess the properties of sample medians and midranges as estimates of $\mu.$
# fictitious data simulated in R
set.seed(2022)
mu = runif(50, 30, 60)  # various centers for normal samples
mean(mu)
[1] 45.16524

h = mr = numeric(50)
for(i in 1:50){
 x = rnorm(50, mu[i], 3)
 h[i] = median(x)
 mr[i] = mean(range(x)) }
mean(h); sd(h)
[1] 45.14566    # average median nearly matches avg of means
[1] 8.562685    # SD of medians slightly smaller than SD
                # of midranges
mean(mr); sd(mr)
[1] 45.19334
[1] 8.63267     # slightly larger than above.

A large component of the variance of medians and of midranges
is due to the variety of values of $\mu$ used in the simulation.
Method (1)
pv.h.mu = wilcox.test(h,mu, pair=T)$p.val; pv.h.mu
[1] 0.8620549  # Medians not significantly biased
wilcox.test(h,mu, pair=T, conf.int=T)

     Wilcoxon signed rank test
     with continuity correction

data:  h and mu
V = 619, p-value = 0.8621
alternative hypothesis:
  true location shift is not equal to 0
95 percent confidence interval:
 -0.1467199  0.1214599
sample estimates:
(pseudo)median
   -0.01538954

pv.mr.mu = wilcox.test(mr,mu,pair=T)$p.val; pv.mr.mu
[1] 0.6922641
wilcox.test(mr,mu, pair=T)

        Wilcoxon signed rank test
        with continuity correction

data:  mr and mu
V = 679, p-value = 0.6923
alternative hypothesis:
 true location shift is not equal to 0

Method (2). Absolute errors for the median tend to be smaller than absolute errors
for the midrange.
pv.d = wilcox.test(abs(h-mu),abs(mr-mu), pair=T)$p.val; pv.d
[1] 0.0003293868
wilcox.test(abs(mr-mu),abs(h-mu), pair=T, conf.int=T)

        Wilcoxon signed rank test
        with continuity correction

data:  abs(mr - mu) and abs(h - mu)
V = 1010, p-value = 0.0003294
alternative hypothesis:
 true location shift is not equal to 0
95 percent confidence interval:
 0.1554304 0.5230677
sample estimates:
(pseudo)median
     0.3184359

mean(abs(mr-mu));  sd(abs(h-mu))
[1] 0.7289042
[1] 0.3220564

Paring of sample medians with population means and of sample midranges with population means allows
us to focus on the smaller absolute errors for medians.


Difference between polynomial and power series

Question: My lecture notes say:

A polynomial on $\mathbb{R}$ is a function $f: \mathbb{R} \to \mathbb{R}$ with $x \mapsto \sum_{k=0}^n a_k x^k$ with $n \in \mathbb{N}$ and $a_k \in \mathbb{R}$.
A power series in $x \in \mathbb{R}$ is the expression $\sum_{k=0}^\infty a_k x^k$ with $a_k \in \mathbb{R}$.

I don't really understand the difference here. What should "expression" mean in this case? Except that the second sum goes to infinity the definitions look the same to me.
Can somebody explain me the differences?
Comment: The difference is simply that a polynomial has a largest power of x while a power series can have all positive integers as powers.
Comment: I upvote you now that I understand...but stackexchange won't let me do it...I agree with your observations so my comment will upvote you in principle
Comment: Is it correct to say that every polynomial is a (terminating) power series? (But the converse is NOT always true.)
Answer: The formal polynomial expression is a function because you can always substitute a numerical value for $x$ and get a number. That's not necessarily the case for a power series, since there may well be values for $x$ for which the infinite series does not converge. When restricted to the values of $x$ for which it does converge, it defines a function.
That's why your instructor was careful to call the formal power series just an expression.
Related, possibly helpful: What actually is a polynomial?
Comment: "When restricted to the values of $x$ for which it does converge, it defines a function."  Yes, but that function doesn't determine the series, if $0$ is the only value of $x$ for which it converges.
Comment: @RobertIsrael True, but a power series converging only at $0$ does define a function with domain $\{0\}$.
Answer: It's an expression rather than a function because the series might not converge anywhere except at $x=0$.
Answer: There's, strictly speaking, a difference between a polynomial and a polynomial function. Polynomials are expressions also (look up polynomial rings). But when you're dealing with a polynomial ring over an infinite field, then there's a natural bijection between the polynomials and the polynomial functions. Since $\mathbb{R}$ is an infinite field, this distinction is often not made. A power series is an expression just like polynomials are an expression (to not be understood as a function). However, with the topological structure on $\mathbb{R}$, you can use convergence (either pointwise or compact convergence) of functions to assign a power-series to a function defined on some interval of $\mathbb{R}$.
Comment: The distinction between polynomial and a polynomial function is absolutely correct, however in this context I think we are talking about polynomial as function.
Comment: The OP said he didn't understand the difference. Extra context sometimes helps.
Comment: I've pointed out this only because maybe he is looking for something simpler. By the way your answer is absolutely ok!
Comment: That's a bit assumptive. If the OP wants clarification, that's what the comment sections are for. Also, answers on MSE do not have to appease the OP, they just have to answer the question. They are also meant for future readers. My answer might not be sensible to someone now, but it could be what someone in the future needs.
Answer: In short terms polynomials are a kind of (regular and smooth) functions, whereas power series can converges (in a given domain) to others functions or not converge at all.
EG
$$e^x=1+x+\frac{x^2}{2!}+\frac{x^3}{3!}...$$
Answer: Polynomials can be defined in this way:
A polynomial is a power series such that there is $k_0 \in \mathbb N_0$ for which we have $a_k=0$ for every $k \geq k_o$.
Now you can see that polynomials can be seen as a special subset of a set of all power series, such that only a finite number of coefficients is non-zero.


Proof ceiling function monotonocity?

Question: Is there any indication about the proof of the following statement:
$\forall x,y. x \le y \Rightarrow \left \lceil x \right \rceil \le \left \lceil y \right \rceil$
Yes it's $\le$. Sorry.
Thanks
Comment: It's false. What if $x=\frac12$ and $y=1$?
Comment: Not quite true. We have $\lceil 1.5\rceil=\lceil 1.8\rceil =2$.
Comment: Perhaps you mean $\left \lceil x \right \rceil \leq \left \lceil y \right \rceil$?
Answer: We need only one counterexample to show that the conjecture is false.
Take $x = 1.5$ and $y = 2$: $$1.5 \lt 2,\;\;\text{but} \;\; \lceil 1.5 \rceil = \lceil 2\rceil = 2$$
However, if you replace the second $\lt$-sign to $\leq$, then it is true that$$\forall x,y. x < y \Rightarrow \left \lceil x \right \rceil \leq \left \lceil y \right \rceil$$ This conjecture $(1)$ can easily be proven using a proof by contradiction: assume $x \lt y$ AND that $\left \lceil x \right \rceil \gt \left \lceil y \right \rceil,$ and you'll soon find a contradiction!.
If you are interested in whether the ceiling function  is monotonic: Monotonicity is still preserved by the ceiling function, given that it is non-decreasing.
Comment: This needs a TU --..+1
Answer: As noted in the comments, the assertion is false.
What is true is that if $x\le y$, then $\lceil x\rceil\le\lceil y\rceil$. Suppose, on the contrary, that $\lceil x\rceil>\lceil y\rceil$. For convenience let $n=\lceil x\rceil$ and $m=\lceil y\rceil$. Then $n-1<x\le n$ and $m-1\le y<m$, by the definition of the ceiling function. But we also know that $n>m$, where $n$ and $m$ are integers, so $n-1\ge m$, and therefore $x>n-1\ge m>y$, contradicting the hypothesis that $x\le y$.

Proof ceiling function monotonocity?


Activation function at output layer for multi label classification

Question: I have read that it is generally better to use sigmoid function than softmax function at output-layer with cross entropy error function as the output of the node in the output layer should be independent of other nodes present in the output layer.
I am not able to think of an usecase or an example where sigmoid function outperforms softmax function. How does the output being independent help sigmoid function to perform better than softmax?
Answer: If each data point has exactly one output label, then the output node in fact should be depending on each other. We want the probability to sum to one over the output nodes.
If the data point has multiple output labels in the sense that there are multiple tasks, we want to predict if a picture has an apple and to predict if a picture has a table. Then there isn't a need for the probability to sum to $1$. The probability of an apple and the probability of a table appearing could be independent of each other.


How to compare predictive accuracy of various predictors

Question: In my dataset, I have one dependent variable and 6 explanatory variables and I am interested in the question which predictor is the best. The relationship between the explanatory variables and the dependent variable is linear.
My initial idea was to fit one linear model for each of the predictors and compare the resulting RMSEs. In order to take the uncertainty into consideration my idea was to obtain quantiles for the RMSE by bootstrapping.
Now I was told that I can compare the predictive accuracy of the covariates by fitting one multiple regression model that contains all the 6 explanatory variables and looking at the p-values from the t-Tests. In my case this resulted in only one significant Test-result. However I believe that this is not really the correct way to proceed as I have read e.g. here that p-values should not be used to assess feature importance.
My questions are:

Which of the two ways I suggested are legitimate
What would be another (maybe even standard) procedure to solve this task?
Comment: I have used the "leave-one-out" technique, where each predictor is iteratively removed from the regression one at a a time to determine if it has any effect on the fitting results. This can sometimes be useful to weed out the less useful predictors that are not contributing to the regression model.
Answer: One-at-a-time regressions can suffer from omitted-variable bias. This is true in linear regressions when the omitted variable is correlated both with outcome and with the included predictors, as discussed on this page.*
So one should be highly skeptical of results with one-at-a-time analysis.
Of the 2 methods you propose, multiple regression is the better way to go, provided that you have enough cases that you aren't overfitting. When your multiple regression returns only 1 coefficient significantly different from a value of 0, that means that you only have 1 predictor that is significantly associated with outcome when the other predictors are taken into account by the multiple regression, given the size of your data sample.
That does not mean, however, that the single "significant" predictor is the only (or even most) "important" feature. In particular, you shouldn't just go ahead blindly with a model based solely on that predictor. When predictors are correlated (as they generally are) the issue of which are "most important" becomes quite tricky and the particular choice can depend heavily on the particular data sample at hand. This page discusses the problems with trying to automate feature selection.
There are 2 other approaches that you might consider.
One is LASSO, which provides a principled way to identify a set of features most useful for prediction. Coefficients of retained features are penalized to absolute values lower than they would be in a standard regression based on them, to reduce overfitting. The retained features might not be the "most important" in some theoretical sense, but they can often work well for prediction.
The second is boosted regression trees. That approach can allow for non-linearities and for interactions among features. Measures of feature importance are then based on the difference that omitting a feature makes in terms of model performance. Those measures of importance can be difficult to interpret, however, as they include both direct and interaction terms involving each feature. And again, the importance measure is only in the context of the entire model.
So think carefully about what you mean by "which predictor is the best." There might be no single, simple answer to that question.

*For other types of regressions like logistic or Cox proportional hazards regressions, omitting any predictor associated with outcome will lead to bias in the regression coefficients for the included predictors, regardless of correlations with the included predictors. See this page for a nice analytic proof in the case of profit regressions.
Comment: yes, if he wants to do "model" comparisons, DM test is not the thing to use. I tried to stress that but you did a better job.  It's purely a tool for saying that "this set of forecasts is better than that set of forecasts".  The forecasts could come from anywhere including a crayon.Thanks.
Comment: See the Diebold-Mariano for a totally different way of looking at your problem. It's  non-parametric in the sense that, given the forecasts of each model, you don't need to know anything about the original models. Note that the test is purely for evaluating predictive ability. Nothing else.
Comment: @mlofton note that Diebold-Mariano was designed for comparing forecasts, not comparing models per se. See [Diebold 2012](https://www.nber.org/papers/w18391) for extensive discussion of application to model comparison, which is what the OP seems to be getting at.


SQL Server Report Builder Field Formatting

Question: I am creating Reports in SQL Server Report builder.
When I set format of any number fields, in design it is displaying sample value.
For e.g. If I set format 0.00 to one numeric field, it started to display 12345.00
I have 10-12 fields in design, it caused very much confusion.
Is there any solution to change this?
When I open report in Visual Studio, it doesn't display like that.
Check Following screenshots:
In Report Builder:

In Visual Studio:
Comment: Earlier this question was asked as http://stackoverflow.com/questions/24631762/sql-server-report-builder-number-formatting/24774623
but, no valid answers received.
and, I am still facing this formatting issue.
Comment: Bounty is the SO way to attract more attention and more answers for your questions. http://stackoverflow.com/help/bounty
Answer: Finally, I got solution:
There is option in toolbar


Expectation of a function of a binomial distribution

Question: I have a question that is:
Given n iid Bernoulli(p) distributions: $X_1, X_2, \ldots, X_n$ and $S_n=\sum X_i$. Find $E[(S_n-np)^3]$. Hint: $S_n-np= \sum (X_i-p)$.
So far, I have gotten that $S_n$ is a Binomial$(n,p)$ distribution. I have also tried the Binomial expansion of $(S_n-np)^3$, and calculating the overall expectations as the sum of the expectations of each term, but that didn't appear to be too helpful. Given the hint that $S_n-np= \sum (X_i-p)$, I am assuming I need to use that.
So, using the formula for expectation, I found $E \left[(\sum(X_i-p))^3 \right]=\sum_{k=1}^n(k-p)^3\frac{n!}{k!(n-k)!}p^k(1-p)^{n-k}$
I can't see what I should do next though (if this is even on the right track)
Any help would be much appreciated
Thanks!
Comment: Please add the `self-study` tag and read its [tag wiki](http://stats.stackexchange.com/tags/self-study/info).
Comment: For the binomial it's generally easier to find the factorial moments.

For $Y\sim \text{binomial}(n,p)$ find $E[Y(Y-1)(Y-2)]$ -- the expectation simplifies nicely; from there the third central moment is readily calculated
Answer: A possible way to go is to use the moment-generating function.
By expanding $(S_n-np)^3$ you see that $E\bigl[(S_n-np)^3\bigr]$ can be obtained from the first three moments $E[S_n]$, $E[S_n^2]$ and $E[S_n^3]$.
The moments $E[S_n^k]$ can be derived with the help of the moment-generating function $M_{S_n}(t)=E(e^{tS_n})$ by the relation $\boxed{E[S_n^k] = M^{(k)}_{S_n}(0)}$ (the $k$-th derivative at $0$).
Since $S_n=\sum_{i=1}^n X_i$, one has $M_{S_n}(t)=E(e^{tX_1}\ldots e^{tX_n})$ and since the $X_i$ are independent this gives $M_{S_n}(t)=E(e^{tX_1})\ldots E(e^{tX_n})$. Now $M_{S_n}(t)={E(e^{tX_1})}^n$ because the $X_i$ have the same distribution. It is easy to get $E(e^{tX_1})=1-p+pe^t$ and finally $\boxed{M_{S_n}(t)={(1-p+pe^t)}^n}$.
Now it remains to calculate $M_{S_n}'$, $M_{S_n}''$, $M_{S_n}'''$, to take the values at $0$, and to inject the results in the expansion of $E\bigl[(S_n-np)^3\bigr]$. I agree this is not really funny.
Comment: As Stephane notes, we are just seeking the $3^{rd}$ central moment of a Binomial random variable. That is straight forwards with a computer (or just look it up). If one is calculating by hand, then, along the same lines – but perhaps simpler – might be to derive the _central_ mgf. i.e. $\text{cmgf} = E\left[e^{t \left(S_n-\mu \right)}\right]=e^{-t \mu} M_{S_n}(t)$ where $\mu = n p $. Taking the third derivative etc will then yield the $3^{rd}$ central moment directly, side-stepping the substitution.


Get the middle scoped value of variable

Question: Say this is an chunk of code to demonstrate how to use local and global variables. I was trying to explain this to one junior guy and he asked me this question.
In the below code, what should you do to get the value of 'x' from outer loop. In this case, how to access 'x' which has its value as 2.
#include<iostream>
using namespace std;
int x = 1;
void fun() {
  int x = 2;
  {
    int x = 3;
    cout << x << endl; // This will give 3
    cout << ::x << endl; // This will give 1
    // What should I write here to get x = 2.
  }
}
int main() {
  fun();
}

Comment: You can't. Rename one of the variables.
Comment: Why  make life difficult and code unreadable? Having multiple variables with the same name will make errors  more  likely
Answer: You can't. The name of the first x has been hidden by the second x. Since the first x does not belong to a namespace (including the global namespace), class or enum, you cannot qualify its name, so it is inaccessible.

Get the middle scoped value of variable


The trigonometrical properties of a triangle

Question: I want to prove that $$\text{area}=\frac{1}{2}a^2\frac{\sin B\sin C}{\sin(B+C)}$$
Since $a^2$ this must be an isosceles triangle, I wrote $\;\text{area}=\frac{1}{2}a^2\sin x$ I squared both sides and the cosine became $\sin^2x=(1-\cos x)(1+\cos x)$ Does it possible to get the part $\frac{\sin B\sin C}{\sin(B+C)}$
Comment: It is unclear what the quantities $B,C$ are in relation to $x$. Could you explain?
Comment: I tried to prove from the formula
Comment: See also: [Alternative area of a triangle formula](https://math.stackexchange.com/q/1394560). Found [using Approach0](https://approach0.xyz/search/?q=%24%5Cfrac%7B1%7D%7B2%7Da%5E2%5Cfrac%7B%5Csin%20B%5Csin%20C%7D%7B%5Csin(B%2BC)%7D%24&p=1)
Answer: In fact this works for any triangle. The usual area formula is $\frac{1}{2}ab\sin{C}$, with the standard labelling of the capital letter as the angle opposite the side with length the small letter. So if we can show that $b = \sin{B}/\sin{(B+C)}$, we're done. But we have
$$ \frac{\sin{A}}{a} = \frac{\sin{B}}{b} $$
from the sine rule, and since $A=\pi-B-C$ and $\sin{(\pi-\theta)}=\sin{\theta}$, we find the required expression for $B$ after rearranging.


Showing the BFGS Update

Question: Hi guys I was reading a paper and it was left as easy to show that (for $y_k,s_k \in \mathbb R^n$ and $B_k \in \mathbb R^{n \times n}$)
$$B_{k+1} = B_k + \frac{ y_k  (y_k-B_k s_k)^T+  (y_k-B_k s_k) y_k^T }{y_k^Ts_k } -\frac{\langle  y_k- B_k s_k, s_k  \rangle}{(y_k^Ts_k)^2 } y_k y_k^T $$
implies
$$B_{k+1} = B_k -\frac{B_ks_ks_k^TB_k}{s_k^TB_ks_k}+ \gamma y_k y_k^T$$
For $\gamma = \frac{1}{y_k^T s_k}$. Where this has the assumptions that $s_k = x_{k+1}-x_k$ and $y_k = \nabla f(x_{k+1})- \nabla f(x_{k})$. $B_k$ is symmetric positive definite matrix.  Also I think we can assume $B_{k+1}s_k = y_k$
I want to show this is true:
My attempt
$$B_{k+1} = B_k + \frac{ y_k  y_k^T-y_ks_k^TB_k+  y_k y_k^T-B_k s_k y_k^T }{y_k^Ts_k } -\frac{\langle  y_k, s_k  \rangle}{(y_k^Ts_k)^2 } y_k y_k^T +\frac{\langle  B_k s_k, s_k  \rangle}{(y_k^Ts_k)^2 } y_k y_k^T$$
Where I just distributed and used the prop of inner product. Now
$$B_{k+1} = B_k + \frac{ y_k  y_k^T-y_ks_k^TB_k+  y_k y_k^T-B_k s_k y_k^T }{y_k^Ts_k } -\frac{  y_k^Ts_k  }{(y_k^Ts_k)^2 } y_k y_k^T +\frac{  s_k^T B_k  s_k  }{(y_k^Ts_k)^2 } y_k y_k^T$$
Using the inner product.
$$B_{k+1} = B_k + \frac{ y_k  y_k^T-y_ks_k^TB_k+  y_k y_k^T-B_k s_k y_k^T - y_k y_k^T}{y_k^Ts_k }  +\frac{  s_k^T B_k  s_k  }{(y_k^Ts_k)^2 } y_k y_k^T$$
Now I am left with
$$B_{k+1} = B_k + \frac{ y_k  y_k^T-y_ks_k^TB_k+  -B_k s_k y_k^T }{y_k^Ts_k }  +\frac{  s_k^T B_k  s_k  }{(y_k^Ts_k)^2 } y_k y_k^T$$
Now I am unsure how to cancel the last term because it has a square term I need to get rid off.
Answer: The first update formula is not BFGS. It is DFP update. They are different algorithms, it is not possible to rewrite one to another. However, there is a certain symmetry between them: if you look at the DFP update for the inverse Hessian $H_k=B_k^{-1}$ in the link above, you may notice that the BFGS update for $B_k$ looks very similar - you just need to replace all $B$ with $H$, $y$ with $s$ and $s$ with $y$. In this sense, it is easy to get the BFGS update, but from the inverse Hessian DFP update.
Comment: @Kori Derivation of DFP update for $B$ is [here](https://math.stackexchange.com/questions/2091867/quasi-newton-methods-understanding-dfp-updating-formula). Derivation of BFGS update for $H$ is [here](https://math.stackexchange.com/questions/2271887/how-to-solve-the-matrix-minimization-for-bfgs-update-in-quasi-newton-optimizatio). Update for inverses is done via [Woodbury matrix identity](https://en.wikipedia.org/wiki/Woodbury_matrix_identity). It is an exercise in Nocedal, Wright book *Numerical Optimization*.
Comment: Correct this is the DFP, and I was reading the proof of it, I wanted to understand how to derive it (Not assuming it is true for the inverse and substantiate)

Showing the BFGS Update


A confession and a conjecture $\gcd(a-b,a+b)|2\gcd(a,b)$

Question: A long time ago I studied mathematics at the University of Stockholm. I was mostly interested in algebra and topology but as everybody interested in math I was fascinated by the most famous problems and results in number theory. However, I never took a course in number theory since I considered it as too complicated for me. There was an introductory course 'Algebra 1' which included some elementary number theory, as the greatest common divisor, but instead of joining the lectures of 'Algebra 1' I made self-studies in 'Algebra 2' containing the first half of Hersteins 'Topics in Algebra'. Today I'm trying to learn elementary number theory from the first two chapters of 'Introduction to Analytic Number Theory' by Apostol. But as we say in Sweden "You can't learn old dogs to sit".
A couple of years ago I started to develop number theoretical facilities to ANS Forth (which is a wonderful language created with the ambition "Keep it simple"). Then I implemented sets and vectors of numbers, sets and vectors, more general than needed in mathematics, really. Entering
{ 1 2 3 ( 4 5 { 6 7 } 8 ) 9 }
put the set $\{1,2,3,9,(4,5,\{6,7\},8)\}$ on a stack. The set algebra is managed by postfix operations on the items on the stack. Using these implementations I've started a semi random search for arithmetical conjectures/theorems. My ignorance make the search more random, but I do understand the language of mathematics and I do have some intuition left for mathematics. And even a blind dog can search using it's noose.
I guess I have posted almost hundred of conjectures in number theory on MSE, some better and some not. One of my last conjectures could be formulated
$$\gcd(a,b)|\gcd(a+b,ab)|\gcd(a,b)^2$$
which has a form reminding of lower and upper bound inequalities. The right part wasn't to easy to prove and I couldn't make it on my own. My most recent conjecture may be easy for the experienced MSE users to prove, I guess so but I don't know. Also this has the form of inequalities:
$$\gcd(a,b)|\gcd(a-b,a+b)|2\gcd(a,b)$$
I manage the left side of the chain but want help to prove the right side:
$$\gcd(a-b,a+b)|2\gcd(a,b)$$
I have convinced myself there is no counter-examples by testing millions of pseudo random pairs $a,b$.
$a,b$ are positive integers such that $a\ge b$.
Comment: Special case $\,\det A = 2\,$ in [this answer](https://math.stackexchange.com/a/32894/242) in the dupe. Also reduces to the first dupe's question if you reduce to the case $\,a,b\,$ coprime, by cancelling $\gcd(a,b)$ throughout, cf. [homogeneous reduction](https://math.stackexchange.com/a/3658798/242)
Answer:
I manage the left side of the chain but want help to prove the right side:
  $$\gcd(a-b,a+b) \mid 2\gcd(a,b)$$

Hint:   write it as $\,\gcd(a+b,a-b)\mid \gcd(2a,2b)\,$ then it reduces to the left side, which you proved.
Answer: Show, for positive integers $a$, $b\ge1$, $a\ge b$, that
$$
\gcd(a,b)\mid\gcd(a-b, a+b)\mid2\gcd(a,b)\tag{1}
$$
If $m=\gcd(a,b)$ then $m\ge1$. Let $a=a_1m$, $b=b_1m$, for some positive integers $a_1$, $b_1\ge1$; so
$$\gcd(a_1m-b_1m, a_1m+b_1m)=m\gcd(a_1-b_1, a_1+b_1)$$
proving the LHS of $(1)$.
Now for the RHS; note that $\gcd(a_1-b_1, a_1+b_1)=1$, for if not we should have some integer $m_1>1$ s.t. $a_1=a_2m_1$, $b_1=b_2m_1$ and so the mid $\gcd$ of $(1)$ becomes
$$\gcd(a_2m_1-b_2m_1, a_2m_1+b_2m_1)=m_1\gcd(a_2-b_2, a_2+b_2)$$
But $m=\gcd(a,b)=\gcd(a_1m,b_1m)=\gcd(a_2m_1m,b_2m_1m)=m_1m\gcd(a_2,b_2)>m$, a contradiction. Hence $\gcd(a_1-b_1, a_1+b_1)=1$ as required.
Now the RHS gives
$$\gcd(a-b, a+b)=m\gcd(a_1-b_1, a_1+b_1)=m\mid2\gcd(a,b)=\gcd(2a,2b)=2m$$


How to estimate parameters for a Kalman filter

Question: In a previous question, I inquired about fitting distributions to some non-Gaussian empirical data.
It was suggested to me offline, that I might try the assumption that the data is Gaussian and fit a Kalman filter first.  Then, depending on the errors, decide if it is worth developing something fancier.  That makes sense.
So, with a nice set of time series data, I need to estimate several variable for a Kalman filter to run.
(Sure, there is probably an R package somewhere, but I want to actually learn how to do this myself.)
Answer: Max Welling has a nice tutorial that describes all of the Kalman Filtering and Smoothing equations as well as parameter estimation. This may be a good place to start.
Comment: Link is dead, here is an alternate https://web.archive.org/web/20120915073205/http://www0.cs.ucl.ac.uk/staff/S.Prince/4C75/LaceyThackerTutorial.pdf
Comment: I found the refered tutorial here https://pdfs.semanticscholar.org/3e9f/d115f7d13880d0aa515ee7ac45311c78f857.pdf
Answer: The usual method is to use Maximum Likelihood Estimation. Basically, you need a Likelihood function and then run a standard optimizer (such as optim) to maximize your Likelihood.


Fill matrix with function values in Matlab

Question: I've got 3 functions, oe1(n), oe2(n) and oe3(n).
I want to create a matrix representing the function values.
The structure of the matrix should be like this:
A = [oe1(0) oe2(0) oe3(0); oe1(1) oe2(1) od3(1); ...... ; oe1(N-1), oe2(N-1), oe3(N-1)];

I've tried filling it with a for loop, but it does not work.
Is there a standard Matlab operation for this? I really can't figure out how to do it.
Anders.
oe1(n1) = sin(2*pi*F*n1+phi)
oe2(n1) = ones(length(n1),1);
oe3(n1) = n1*Ts

pol = (oe2)'

vector_x = [a; b; c];
vector_veardier = [oe1(n1), 1, oe3(n1)]
xi = 1:N-1;

for i = 2:N-1;
   for j = 1:3
      vector_veardier(i, j) = oe1(j);
   end
end

Comment: What does not work? What error message do you get?
Answer: Do your functions accept vectors? If so you can use:
A = [oe1((1:N)'), oe2((1:N)'), oe3((1:N)')];

but otherwise you might have to use arrayfun:
A = [arrayfun(@oe1, (1:N)'), arrayfun(@oe2, (1:N)'), arrayfun(@oe3, (1:N)')];

Note that in your provided code you have not defined oeN as functions, but as some kind of array with a value inserted at position n1.
One way to do it with a for loop would however be:
A = zeros(N,3);
for i = 1:N,
  A(i,:) = [oe1(i), oe2(i) oe3(i)];
end


Chave estrangeria não está exibindo corretamente na tela, mesmo com o método __ str __ DJANGO 3.2

Question:

Mesmo com o método  colocado na classe CARGO, não está aparecendo como deveria quando mostra na identidade funcionários, como resolver esse problema? obg
Comment: Olá Humberto, boas-vindas ao site. É importante **[edit]** e adicionar **um [mcve] do problema (NÃO delete e NÃO repita a pergunta)** ([NÃO use imagens para mostrar códigos e logs](https://pt.meta.stackoverflow.com/a/7817/3635)), com um passo a passo do que já fez e explicar de forma clara e objetiva e então aguarde o processo de reabertura (que será avaliado por outros usuários). Para aproveitar melhor o site, entender e evitar fechamentos vale a pena ler o [Guia de sobrevivência do Stack Overflow em Português](https://pt.meta.stackoverflow.com/q/8045). Obrigado por compreender.
Answer: Tente colocar o def str fora da classe meta


Quantidade de caracteres do CPF, CNPJ e RG

Question: Estou fazendo um programa que precisa validar uma série de documentos - CPF, CNPJ e, se possível, RG.
Minhas questões são as seguintes:

Existem CNPJs válidos com número de caracteres menor que 14?
(ex: empresas antigas).
Formato comum: xx.xxx.xxx/xxxx-xx
Caso sim, qual número mínimo de caracteres para um CNPJ ser válido?
Existem CPFs válidos com número de caracteres menor que 11?
    (ex: pessoas idosas) Formato comum: xxx.xxx.xxx-xx Caso sim,
    qual número mínimo de caracteres para um CPF ser válido?
Existem RGs válidos com número de caracteres menor(1) ou
    maior(2) que 9?(ex: pessoas idosas(1) ou crianças (2)) Formato
    comum: xx.xxx.xxx-x Caso sim, qual número mínimo e qual número
    máximo de caracteres para um RG ser válido?
Comment: RG depende do UF. Cada UF tem um formato. O resto é fixo (prefixado com zero se for o caso). Um RG 98.236 é válido.
Comment: Imagino que não. Mas o lugar dos pontos e se vai ter digito ou não, pode ser diferente. Melhor coisa pra RG é campo livre, e um campo separado para emissor.  Melhor ainda é ter um campo "documento de identidade" e um campo "órgão emissor", pois pode nem ser um RG a identificação da pessoa. De repente é um registro de estrangeiro.
Comment: @CuriousElf Alguma das respostas resolveu sua dúvida? Acha que pode aceitar uma delas? Veja o [tour] como fazer isso, se ainda não o fez. Você ajudaria a comunidade identificando qual foi a melhor solução para você. Pode aceitar apenas uma delas. Mas pode votar em qualquer pergunta ou resposta que achar útil no site todo.
Comment: Um RG pode ser maior que um CPF?
Comment: O RG da minha mãe, da Bahia, nascida em 64, tinha mais de 10 digitos até recentemente.
Comment: @PabloAlmeida se esse mais de dez for também mais de onze, realmente é maior que um CPF.
Comment: Erros comuns na implementação da validação desses dados cadastrais: permitir apenas números na máscara do RG (alguns dígitos verificadores são X, o certo é não usar máscara); proibir CPF 000.000.000-00 e o mesmo com outros números repetidos (esses CPFs são válidos).
Comment: @vnbrs a pergunta é sobre validação, se for colocar tag brasil em toda as perguntas de validação de cpf e cnpj, essa tag seria uma das mais utilizadas. Não vejo sentido algum colocar nessa pergunta apenas.
Comment: Segue validador Java no seguinte [link](https://github.com/jereztech/validation-br-api)
Answer:
Existem CNPJs válidos com número de caracteres menor que 14? (ex: empresas antigas)

O formato é este para todas empresas nacionais. Um dia pode mudar, mas hoje é sempre assim.
Alguns sistemas podem ter que lidar com empresas estrangeiras, aí é bem diferente. Mas isto é algo secundário em sistemas, não tem base em operações brasileiras e mesmo em sistemas que fazem operações internacionais é essencialmente descritivo.

Existem CPFs válidos com número de caracteres menor que 11? (ex: pessoas idosas)

Não existe nada diferente.
O que pode ocorrer é um dia mudar. Pode ser que o CPF até deixe de existir um dia e dar lugar a outra documento. Está em curso o documento único. Mas por enquanto não é uma substituição.

Existem RGs válidos com número de caracteres menor(1) ou maior(2) que 9?(ex: pessoas idosas(1) ou crianças (2))

Sim, cada estado é de um jeito, pode ter diferenças entre órgãos de emissão diferentes no mesmo estado e dependendo da época pode diferir também. É difícil criar uma máscara.
A Receita Federal tem um documento indicando que o máximo é 11, mas não é oficial, eu acho que tem maior.
Existem critérios de validação do CNPJ e CPF. Alguns estados possuem fórmulas de validação de seu Registro Geral (irônico nome).
Em geral o RG precisa ser deixado bem livre. Me parece que 13 ou 14 é seguro.
Pode ser útil. E sobre máscaras.
Coloquei no GitHub para referência futura.
Answer: Sobre CPF e CNPJ
CPF 11 digitos e o nono digito é referente a localidade

A Região Fiscal onde emitido o CPF (definida pelo nono dígito) tem a
  seguinte abrangência: 1 (DF-GO-MS-MT-TO), 2 (AC-AM-AP-PA-RO-RR), 3
  (CE-MA-PI), 4 (AL-PB-PE-RN), 5 (BA-SE), 6 (MG), 7 (ES-RJ), 8 (SP), 9
  (PR-SC) e 0 (RS)

CNPJ 14 digitos

No passado, os números eram agrupados por Estado. Hoje está tudo
  misturado e por isso XX.XXX.XXX os 8 primeiros números são emitidos
  sequencialmente a partir dos números já criados. Desta forma, qualquer
  pessoa com mais de 10 neurônios consegue chegar ao CNPJ das empresas
  novas. É assim que algumas pessoas pegam o seu CNPJ e enviam malas
  diretas e boletos falsos.

Referencia(e recomendo a leitura): https://atendimento.contadorx.com/hc/pt-br/articles/205698465-O-que-%C3%A9-CNPJ-
RG é mais complicado, por que cada estado tem um formato diferente e existe a possibilidade de de duas pessoas de estados diferentes possuirem a mesma numeracao, para validar um rg é necessario saber a regra de criacao de cada estado.
Answer: A quantidade de dígitos de CNPJ e CPF são fixas, como os colegas já apontaram.
O RG é complicado mas a sugestão do @Bacco, de utilizar também o campo 'Emissor',  é boa.
Acrescente também a UF de emissão pois não é ilegal que uma pessoa tenha RGs emitidos em mais de uma UF.
fonte ([http://portalcatalao.com/cbcaixa/painel/upload/manuais/manual_caixa.pdf])


Is it right to run crontab service and wsgi within a single docker container

Question: Currently, I have a Django wsgi to handle web traffic. (I have a nginx as front end to forward traffic to wsgi)
Now, I would like to start a crobtab service, to run periodic background job.
This is what I had done

django\Dockerfile
FROM python:3.6.4-alpine3.4
...

RUN chmod +x entrypoint.sh

ENTRYPOINT ["sh", "entrypoint.sh"]

CMD /usr/local/bin/gunicorn web.wsgi:application -b django:5000 --log-level=info --error-logfile=/var/log/gunicorn3.err.log

django\entrypoint.sh
#!/bin/sh

...

python manage.py crontab add

# https://stackoverflow.com/questions/37015624/how-to-run-a-cron-job-inside-a-docker-container
#
# "crond -help" yields:
#
# -f      Foreground
# -b      Background (default)
# -S      Log to syslog (default)
# -l N    Set log level. Most verbose:0, default:8
# -d N    Set log level, log to stderr
# -L FILE Log to FILE
# -c DIR  Cron dir. Default:/var/spool/cron/crontabs

# start cron
/usr/sbin/crond -f -l 8

exec "$@"

docker-compose.yml
  django:
    build:
      context: ./django
      dockerfile: Dockerfile
    restart: always
    depends_on:
      - pgbouncer
    expose:
      - "5000"
    volumes:
      - static_data:/app/static

If I use the above setup, I notice that.

My schedule cron worker is running periodically.
But, wsgi unable to serve web traffic.

First, I try to change in django\entrypoint.sh
# start cron
/usr/sbin/crond -f -l 8

to
# start cron
/usr/sbin/crond -b -l 8

After making above change,

My schedule cron worker is no longer running. Not sure why.
wsgi can serve web traffic.

May I know why is it so? How can I make my django container to serve web traffic, and run cron job at the same time?
Or, is it not the right way to do such thing in Docker? I should use 2 containers?
Answer: I'd run a full on second container naming the service in the compose file cron or something of the likes (maybe more specific to the actual job in the event you have multiple crons). 1 process per container is general practice. In the "cron" container I wouldn't even run it via crond I'd have whatever I'm using on the host machine to handle the scheduling of the container. I'd change your job from being a django-cron to a custom django-admin command since you won't be managing the running of it with the django app anymore. You could still build the second container off the django one image just change the CMD with the docker-compose.yml file command: ["django-admin", "mycommand"]. Likely would be unnecessary to expose the ports on the second container. Invoke as a normal service docker-compose run mycronservice


Linkit Module - Pointing the link's title attribute to a custom field. Hook available?

Question: Currently the Linkit module delivers the link's title attribute by pulling the related node's title field.
We would like it to point to another field in the node.
How can we achieve this?
I looked into Editor Advanced Link module, but I need this to be automatic, and my custom field changes based on content type.
Maybe someone has a hook idea?
Answer: There are (at least) 2 options:

Write a custom filter plugin, basing it on the LinkitFilter plugin included with the Linkit module. In the process() method, where the title is currently set, introduce you own logic to set the title field instead of the existing $entity->label().This method has the benefit of auto-updating when a referenced node's title changes, but does mean you'll have to maintain your filter alongside the Linkit module's releases. The process() method does a lot more than just setting the title, and new features/bug fixes in the module will need to be incorporated into your code.

Alter the link dialog form (like Editor Advanced Link does), and get the title into the markup while it's still in the editor. This method is a bit easier, and less maintenance, but the title attribute won't update when the node title does. It will only update when the link dialog form is saved again.If that's acceptable, this is a rough but working example to get started:
use Drupal\Core\Form\FormStateInterface;
use Drupal\node\NodeInterface;

function custom_module_form_editor_link_dialog_alter(&$form, FormStateInterface $form_state, $form_id) {
  array_unshift($form['#validate'], '_custom_module_link_dialog_validate');
}

function _custom_module_link_dialog_validate(array &$form, FormStateInterface $form_state) {
  $attributes = $form_state->getValue('attributes');

  if (isset($attributes['data-entity-type']) && $attributes['data-entity-type'] == 'node') {
    $node = \Drupal::service('entity.repository')
      ->loadEntityByUuid('node', $attributes['data-entity-uuid']);
    if ($node instanceof NodeInterface) {
      $override_title = '';
      switch ($node->getType()) {
        case 'page':
          $override_title = $node->field_title_override->value;
          break;
        case 'foo':
          // ...
          break;
      }
      if (strlen($override_title)) {
        $form_state->setValue(['attributes', 'title'], $override_title);
      }
    }
  }
}

Comment: Thanks for these!
Comment: Thanks for these! And for editing my question to make it clearer.
We would need this to only apply on the front end. And not all content type will have this field available.
Is there a hook in the Linkit module that would allow for the filter to check if the node has a certain field existing and filled and replace it on the fly on the front end?
Comment: No, unfortunately it's hard coded into the middle of the process method at the moment. You would need to replicate the whole filter for that approach


How to use std::function using variadic template

Question: There is a template for constructing std::function:
template< class R, class... Args >
class function<R(Args...)>;

I have not figured out how to invoke it. (VC++, if that matters.)
Question: How can I use std::function with a variadic list without using std::bind?
#include <functional>
#include <iostream>
using vfunc = std::function<void()>;
using namespace std; // I know, I know.

template<class F, class... Args>
void
run(F&& f, Args&&... args) {
    vfunc fn = bind(forward<F>(f), forward<Args>(args)...); //OK
    //vfunc fn = vfunc(forward<F>(f), forward<Args>(args)...); // COMPILER ERROR
    fn();
}

void foo(int x) {
    cout << x << " skidoo\n";
}
int main() {
    run(foo, 23);
    return 0;
}

Comment: What are you actually trying to achieve? Because you can implement `run` without using `std::function` just do `f(std::forward(args)...);`
Comment: I mean something like `vfunc fn = []{f(std::forward(args)...);};`
Comment: @ChisDrew - It's for a thread-pool class. I need a `std;:function` for the worker threads. Thank you for your concern. :-)
Comment: @xskxzr - I do not understand your comment and question. The template to which I refer is on the cppreference page that's clickable in the question. Do you know the answer to my question? Is it not possible, and if not, why not?
Comment: What about using a lambda?
Comment: @xskxzr - Lamda's have no utterable type. Really folks,I appreciate that you are trying to help, but the real application requires an `std::function`. Really it does.  The question is only how to forego the `bind` if possible - as much out of curiosity as anything.
Comment: @xskxar - Yes, that would work, but it's hardly an improvement on using `bind`.
Answer:
There is a template for constructing std::function.
template< class R, class... Args >
class function<R(Args...)>;

That's not what that declaration means. It's not declaring a constructor or a "template for constructing" anything; it's a specialization for the template class std::function. The specialization is the only definition of std::function; the base template is never defined. I think the point of this has something to do with using a function signature in the template declaration. That is, being able to use the template via function rather than as function.
You want to take a callable object and some number of values and create a new callable object that stores those values, which has an operator() overload that calls the given function with those values. std::function does not do that; it has no constructors for doing so.
This is exactly what std::bind is for. Basically, your code is fine as is: storing the result of bind within function is entirely valid.
Comment: @JiveDadson: Think of it just as "a thing people have to do in C++ to make it work right". Deep metaprogramming has all kinds of esoteric issues with it. But you don't have to understand it to *use* it.
Comment: What is that template for for?
Comment: I need a function object that has a well-known type, hence `std::function`. I think I am hearing that I must do the `bind` first, although I am still puzzled by that template from cppreference.com
Comment: The specialization is the *only* definition of `std::function`; the base template is never defined. I think the point of this has something to do with using a function signature in the template declaration. That is, being able to use the template via `function` rather than as `function`.
Comment: I guess I do not understand these things well enough to, uh, understand. I am just going to use `bind` and not worry my pretty little head about it.  The  thread pool is working just fine that way, and it is blazing fast.
Comment: Tell me about it. I delved into the Dinkum implementation - always an adventure. What a hot mess!  It is full of MACROs for deduction guides and other imponderables. It seems to depend on the function object having an `operator()`.  As usual, I ran away in horror.  As I said, the thread pool is working great, and whoa is it fast.
Comment: Ah. Light dawns over Dunderhead!
Answer: In that case, you can just wrap the function in a lambda and construct your std::function from it.
template<class F, class... Args>
void run(F&& f, Args&&... args) {
    auto fn = vfunc{
        [=]() mutable {
            std::invoke(std::forward<F>(f), std::forward<Args>(args)...);
        }
    };

    fn(); // fn is of type std::function<void()>
}

I made the lambda mutable so std::forward will not silently not move.
Note however that the [=] capture will copy everything. To support move only types, you can use a tuple:
[f = std::forward<F>(f), args = std::tuple{std::forward<Args>(args)...}]() mutable {
    std::apply(std::forward<F>(f), std::move(args));
}

In C++20, this becomes easier:
[f = std::forward<F>(f), ...args = std::forward<Args>(args)...]() mutable {
    std::invoke(std::forward<F>(f), std::forward<Args>(args)...);
}

Comment: With all due respect, this does not answer the question. A lambda has no advantage over bind that I can see. The use of `std::functions` is A REQUIREMENT of the problem. Thanks for the effort.
Comment: @JiveDadson please look more carefully. I assign the lambda into an `std::function` of the type you defined `vfunc`. As far as I know, it respects the specified requirements.
Comment: @JiveDadson this shows exactly how to construct a`std::function` from a callable. Is there something I can clarify?
Comment: I think the confusion is due to my confusion. Bind and lambda both work just fine. I thought there was a way to get the `std::function` without a `bind` or `lambda` or other wrap'em up thing. Apparently I was wrong.


Probability of an experience giving the same outcome n times

Question: Lets assume I have a distributions of outcomes $A=\{a_1, a_2, a_3, \ldots, a_n\}$. I also have a probability function $P$, with $\forall a\in A, P(a)\in[0,1]$ and $\sum_{a\in A}P(a) = 1$.
Now let assume I run my experiment $n$ times. I'm talking a REAL experiment where I don't know the full range of $A$ nor the details of $P$ ... those are what I am trying to reconstruct. I am trying to estimate the probability of $A$ containing a single element $\alpha$ such that $P(\alpha)=1$
If after $n$ runs I have at least $2$ different outcomes, I know that my experiment in not deterministic and that is good for me. But what if I do have $n$ time the same result ? What can I conclude ? What is the probability of my experiment being deterministic ? Can I achieve a lower bound on $P(a')$, the probability of the most probable event ($\forall a\in A, a\neq a' \implies P(a)\leq P(a')$)
Answer: You can't ever prove the experiment is deterministic because there could always be some possible but improbable event.  You could think of buying lottery tickets and the event being not winning the grand prize.  After $1000$ tries you (very likely) have every try with the same result.
You can put a lower bound on the chance of the most probable event.  If the chance of the most probable event is $p$ and you do $n$ trials, the chance you get the same result on every trial is $p^n$.  For a $90\%$ confidence lower bound on $p$ you can say $p^n \gt 0.1, p \gt \sqrt [n]{0.1}$
Comment: I know I cannot prove that the experiment is not deterministic, I just want an estimation of something that never happened happens.
And If I have two events, one with $P(a)=90\%$ and the other with $P(b)=10\%$, the probability of having $n$ times the same is $0.9^n+0.1^n$, not $0.9^n$ ... so things are a bit more complicated then you say
Comment: The $0.9^n+0.1^n$ is strictly true, but $0.1^n$ is so much smaller that for any reasonable $n$ you can ignore it.
Comment: If I have $n$ events with proba $1/n$ I cannot ignore any of those. That is my issue here, I'd like to simplify the $\sum_{a\in A}P(a)^n$ by having an upper bound which removes some terms I don't want to carry ... but I don't find the way to do so without any assumptions on $A$


How to delete from 3 tables with one query using where exists

Question: I have four tables Monitoring, Participant, Participant validation group, Validation group,
I would like to delete all monitorings, and there particpants also each particpant possibly (not always) has participant validation group.

Blockquote

but i have the error sql command not properly ended.
NOTE: I am on oracle database and inner joins would not work here.
I would like to achieve an optimized query
that could take only the application number of monitoring and delete all monitorings, participants for each monitoring and participant validation group.
I am not sure if its actually possible in a single query if its not then what could be the optimized way to do this. and I cant use jpa for this at the moment.
Expected results, both monitorings are deleted, and there particpants as well as participant validation groups
Comment: Whenever you have a question, please post a little sample data (CREATE TABLE and INSERT statements for all tables involved, relevant columns only) so the people who want to help you can recreate the problem and test their ideas. Also post the exact results you want from that data, and explain why you want those results from that data. Lastly, don't post any images as they cant be cut and pasted.
Comment: Please, minimize you sample model: keep only columns used in filters/relationships and remove physical properties of the table (it doesn't necesary to specify what is the table space and initial extent for your exact issue)
Answer: You can define foreign keys on child tables to "ON DELETE CASCADE". So when you delete a parent table it will delete associated rows from child tables.
<code>create table parent (
  id NUMBER(10),
  value      varchar2(30),
constraint parent_pk primary key (id)
);

CREATE TABLE child
( id NUMBER(10) not null,
value NUMBER(10) not null,
constraint child_pk primary key (id,value),
CONSTRAINT parent_child_fk
FOREIGN KEY (id)
REFERENCES parent(id)
ON DELETE CASCADE
);

CREATE TABLE grandchild
( id NUMBER(10) not null,
value NUMBER(10) not null,
constraint grandchild_pk primary key (id,value),
CONSTRAINT child_grandchild_fk
FOREIGN KEY (id,value)
REFERENCES child(id,value)
ON DELETE CASCADE
);

insert into parent values (1,'a');
insert into parent values (2,'b');
insert into parent values (3,'c');

insert into child  values (1,1);
insert into child  values (1,2);
insert into child  values (1,3);
insert into child  values (2,1);
insert into child  values (2,2);
insert into child  values (2,3);
insert into child  values (3,1);
insert into child  values (3,2);
insert into child  values (3,3);

insert into grandchild  values (1,1);
insert into grandchild  values (1,2);
insert into grandchild  values (1,3);
insert into grandchild  values (2,1);
insert into grandchild  values (2,2);
insert into grandchild  values (2,3);
insert into grandchild  values (3,1);
insert into grandchild  values (3,2);
insert into grandchild  values (3,3);

SELECT  (
        SELECT COUNT(*)
        FROM   parent
        ) AS parent_cnt,
       (
        SELECT COUNT(*)
        FROM   child
        ) AS child_cnt,
        (
        SELECT COUNT(*)
        FROM   grandchild
        ) AS grandchild_cnt
FROM    dual

DELETE from parent where value = 'a';

SELECT  (
        SELECT COUNT(*)
        FROM   parent
        ) AS parent_cnt,
       (
        SELECT COUNT(*)
        FROM   child
        ) AS child_cnt,
        (
        SELECT COUNT(*)
        FROM   grandchild
        ) AS grandchild_cnt
FROM    dual

PARENT_CNT    CHILD_CNT    GRANDCHILD_CNT
2    6    6

</code>
Comment: @valik `DELETE` does not support multiple tables. You must use `CASCADE` or execute multiple `DELETE` statements. See the documentation: https://docs.oracle.com/en/database/oracle/oracle-database/19/sqlrf/DELETE.html#GUID-156845A5-B626-412B-9F95-8869B988ABD7
Comment: i have posted the DDL we already have cascade delete on them, but i want to achieve deletion by a query that could be delete from monitoring, participant, pvg ....
Comment: I dont see on DELETt E CASCADE clause on the ddl you posted.
Comment: Did my post answer your question


Generic Comparator warnings

Question: I have this:
import java.util.*;
import java.io.*;

class MyComparator<K,V> implements Comparator<Map.Entry<K,List<V>>> {

    public int compare(Map.Entry<K,List<V>> me1, Map.Entry<K,List<V>> me2) {

                List<V> v1 = me1.getValue();
                List<V> v2 = me2.getValue();

                if(v1.size() > v2.size())
                    return 1;
                else if(v1.size() < v2.size())
                    return -1;
                else
                     return 0;
    }
}

public class Anagrams1 {
    public static void main(String[] args) {
        int minGroupSize = Integer.parseInt(args[1]);

        // Read words from file and put into a simulated multimap
        Map<String, List<String>> m = new HashMap<String, List<String>>();

        try {
            Scanner s = new Scanner(new File(args[0]));
            while (s.hasNext()) {
                String word = s.next();
                String alpha = alphabetize(word);
                List<String> l = m.get(alpha);
                if (l == null)
                    m.put(alpha, l=new ArrayList<String>());
                l.add(word);
            }
        } catch (IOException e) {
            System.err.println(e);
            System.exit(1);
        }

        // Print all permutation groups above size threshold
        Collection<Map.Entry<String,List<String>>> c = m.entrySet();
        Object[] arr = c.toArray();
        Arrays.sort(arr, new MyComparator());
        for(Object o : arr) {
            if(m.get(o).size() >= minGroupSize)

                System.out.println(o + " : " + m.get(o).size() + ": " + m.get(o));

        }
    }

    private static String alphabetize(String s) {
        char[] a = s.toCharArray();
        Arrays.sort(a);
        return new String(a);
    }
}

This is giving me two warnings:
  javacode$ javac -Xlint:unchecked Anagrams1.java

  Anagrams1.java:45: warning: [unchecked] unchecked method invocation: method sort in class Arrays is applied to given types
          Arrays.sort(arr, new MyComparator());

                     ^
    required: T[],Comparator<? super T>

    found: Object[],MyComparator

    where T is a type-variable:

      T extends Object declared in method <T>sort(T[],Comparator<? super T>)

  Anagrams1.java:45: warning: [unchecked] unchecked conversion

          Arrays.sort(arr, new MyComparator());

                           ^
    required: Comparator<? super T>

    found:    MyComparator

    where T is a type-variable:

      T extends Object declared in method <T>sort(T[],Comparator<? super T>)

Help needed. Thanks.
Comment: Well, since this is the third question (including the deleted one) about generics and (almost) the same code: have you ever read something about generics? How they work and how one can use them?
Comment: @Tom I read the tutorial and I am reading it again. I felt getting tips from people to supplement with my reading would be a good and quick way to learn. I am currently reading this: http://docs.oracle.com/javase/tutorial/extra/generics/subtype.html
Answer: You've defined class MyComparator<K,V>.
You're calling new MyComparator(). With an Object[].
This should give you the exact warning it's giving you - it's expecting to be defined new MyComparator<String, String>() based on your code.
I'd also recommend passing in a properly typed List instead of an Object[] as the first argument, and using Collections.sort instead.
Answer: There are two approaches to this that I'd suggest:

Use Collection#toArray(T[]) to get an array of the elements of type T[]. This is tricky and icky because you'd need T to be Map.Entry<K,List<V>>, and you can't create one of those directly since generics are non-reifiable types.
Copy the elements into an ArrayList (e.g. using new ArrayList<>(m.entrySet())) and then call Collections.sort on that.

The latter would be my preferred approach, since Collections have type safety advantages over plain arrays.
Comment: "and you can't create one of those directly since generics are non-reifiable types." What does that mean ? Can you please explain in simplistic terms ?
Comment: http://stackoverflow.com/questions/2927391/whats-the-reason-i-cant-create-generic-array-types-in-java
Answer: This would still give you a warning in the assignment of the Map.Entry[] to Map.Entry<String,List<String>>[], but the Arrays.sort call won't give any warning :
    Map.Entry<String,List<String>>[] arr = c.toArray(new Map.Entry[0]);
    Arrays.sort(arr, new MyComparator<String,String>());

I don't think you can get away with that warning if you want to use an array for the sorting, since you can't create an instance of a generic array, so c.toArray(new Map.Entry<String,List<String>>[0]) won't pass compilation.
Comment: Using `Collections.sort` will eliminate the need to use an array (and that extra warning)
Comment: I could not compile after the changes: javacode$ java Anagrams1 ./dictionary.txt 8
Exception in thread "main" java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to [Ljava.util.Map$Entry;
 at Anagrams1.main(Anagrams1.java:44)

Trying Collections.sort approach now.
Comment: Why could not I do the cast, why the error as above ?
Comment: @abc Try the new code. I tried multiple versions of this code and ended up posing a version I didn't check that didn't work. Sorry about that.
Comment: @Eran It worked, but gave two warnings
code : http://pastebin.com/zE3vM5uk
Warnings: http://pastebin.com/9f9FqxRv

Generic Comparator warnings


Botao FAB não fica no lugar

Question: Não sei o que está acontecendo o botão FAB sobe em cima de outro componente na hora de compilar, mas no preview ele fica certo.
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    tools:context="com.rbxsoft.rbxsalesforce.CaixaDeEntradaActivity">

    <RelativeLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        tools:layout_editor_absoluteY="0dp"
        tools:layout_editor_absoluteX="0dp">

        <TextView
            android:id="@+id/textView"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:padding="10dp"
            android:text="@string/caixaDeEntrada"
            tools:layout_editor_absoluteX="0dp"
            tools:layout_editor_absoluteY="0dp" />

        <android.support.v7.widget.RecyclerView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="10dp"
            android:layout_marginRight="10dp"
            android:paddingTop="30dp"
            tools:layout_editor_absoluteX="8dp"
            tools:layout_editor_absoluteY="8dp">

        </android.support.v7.widget.RecyclerView>

    </RelativeLayout>

    <android.support.design.widget.FloatingActionButton
        android:id="@+id/fabNovoPedido"
        android:layout_width="48dp"
        android:layout_height="53dp"
        android:layout_gravity="end|bottom"
        android:elevation="0dp"
        android:padding="4dp"
        android:src="@drawable/ic_plus"
        app:elevation="0dp"
        app:fabSize="normal"
        tools:layout_editor_absoluteX="292dp"
        tools:layout_editor_absoluteY="439dp" />

</android.support.constraint.ConstraintLayout>

Answer: Ele não fica no lugar porque tu não aplicou nenhuma constraint para ele. E o editor deve te avisar isto com um sinal de warning. Os atributos editor_absoluteY/X só servem pra dar um efeito visual no editor, eles não vão posicionar tua view como você quer que ela fique.
Leia um pouco sobre ConstraintLayout, porque para posicionar as suas views, você vai precisar conectar elas uma às outras, criando nodes. No próprio editor você consegue fazer isso.
Outra coisa, nenhuma das suas views estão conectadas corretamente, porque você apenas jogou elas no seu Layout.
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    tools:context="com.rbxsoft.rbxsalesforce.CaixaDeEntradaActivity">

    <RelativeLayout
        android:layout_width="0dp"
        android:layout_height="0dp"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintBottom_toBottomOf="parent">

        <TextView
            android:id="@+id/textView"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:padding="10dp"
            android:text="@string/caixaDeEntrada" />

        <android.support.v7.widget.RecyclerView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="10dp"
            android:layout_marginRight="10dp"
            android:paddingTop="30dp">

        </android.support.v7.widget.RecyclerView>

    </RelativeLayout>

    <android.support.design.widget.FloatingActionButton
        android:id="@+id/fabNovoPedido"
        android:layout_width="48dp"
        android:layout_height="53dp"
        android:elevation="0dp"
        android:padding="4dp"
        android:src="@drawable/ic_plus"
        app:elevation="0dp"
        app:fabSize="normal"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent" />

</android.support.constraint.ConstraintLayout>

O código acima deve funcionar como desejado. Abaixo explicarei algumas coisas importantes que eu adicionei no seu layout.
Observação: o valor 0dp é como mach_parent.

layout_constraintStart
Esse atributo vai alinhar o começo da sua view com outra parte de outra view ou do parent (que no caso é o próprio Constraint Layout).
Pode usar ela com os seguintes atributos: _toStartOf e _toEndOf.

layout_constraintEnd
É a mesma coisa do atributo anterior, mas ele alinha a parte direita da sua view com outra view/parent.
Pode ser usada com: _toStartOf e _toEndOf

layout_constraintTop
Também é a mesma coisa da anterior, mas alinha a parte superior e lembra muito o atributo layout_below do RelativeLayout se combinada com _toBottomOf.
Pode ser usada com: _toTopOf e _toBottomOf.

layout_constraintBottom
Alinha a parte inferior e lembra o atributo layout_above do RelativeLayout se combinada com _toTopOf.
Pode ser usada com: _toTopOf e _toBottomOf.

Botao FAB não fica no lugar


remove duplicate list after using zip()

Question: one=['nlo_90', 'nlo_90', 'nhi_88']
two=['12', '12', '84']
three=[['a','a','b','c'], ['a','a','b','c'], ['b','g','g','b']]
new_three=[list(dict.fromkeys(q)) for q in three]

z=zip(one,two,new_three)
for a,b,c in z:
        c_str = ', '.join(c)
        print(f'{a}, {b}, {c_str}')

I need to remove duplicate data after i combine the lists using zip()
the output from above code is
nlo_90, 12, a, b, c
nlo_90, 12, a, b, c
nhi_88, 84, b, g

my desired output is
nlo_90, 12, a, b, c
nhi_88, 84, b, g

I tried to code  this  new=list(dict.fromkeys(z))  to remove duplicate but it shows error
TypeError: unhashable type: 'list'
Comment: The issue is you are using `list()` in `new_three=[list(dict.fromkeys(q)) for q in three]`, just change this to a `tuple()` and you will be able to do `dict.fromkeys(z)`
Answer: This Will Surely At Any Cost Give The Desired Output.
one = ['nlo_90', 'nlo_90', 'nhi_88']
two = ['12', '12', '84']
three = [['a', 'a', 'b', 'c'], ['a', 'a', 'b', 'c'], ['b', 'g', 'g', 'b']]
new_three = [list(dict.fromkeys(q)) for q in three]

z = zip(set(one), two, new_three)

res = []

for a, b, c in z:
    c_str = ', '.join(c)
    res.append(f'{a}, {b}, {c_str}')

for res in reversed(sorted(res)):
    print(res)

Output
nlo_90, 12, a, b, c
nhi_88, 12, a, b, c

Comment: `set(one)` doesn't guarantee, you could use `dict.from_keys(one)` but then this only uses `one` to determine duplicate data.
Comment: thanks but it seems the output is not the same like my desired output
Comment: @qwe what's the diff ?
Comment: the second line in your output does not match with what i want.  here is the 2nd line of my desired output 'nhi_88, 84, b, g' meanwhile yours is 'nhi_88, 12, a, b, c'
Comment: @qwe i have updated my answer please check if the answer gives the desired output.
Comment: @qwe did you check my given answer ? it solves that problem
Comment: PLEASE! Check the answer that has been posted @qwe.

remove duplicate list after using zip()


Renovação AppStore

Question: Olá,
Eu queria lançar uma aplicação mas quando fui ao membership da Apple dizia que estava expirado....então eu renovei e agora não consigo adicionar a aplicação.
Alguém sabe quanto tempo tenho que esperar para que o meu Developer Membership fique atualizado ou renovado?
Answer: O prazo maximo que eles dao pra renovacao 'e de 48 horas e, quando demora mais que isso (ou quando voce precisa agilizar o processo), da pra mandar email ou ligar pra Apple que os atendentes resolvem rapidinho. Os dados pra contato voce pode encontrar nessa pagina aqui: Apple contact
Comment: Obrigado pela resposta

Renovação AppStore


multiple regression log transformed how do i see initial values

Question: I log transformed my dependent variable and all 5 independent variables to get a better fit. The dependent variable is sale price in dollars. Before I logged it, the intercept and all coefficients made sense. The intercept was 452,000 dollars. Now the intercept is really low - 3.2, which, if I exp it, is 24.97. I am completely new to this, can someone please explain how to see the values in $ and what is the reason the values are so much lower now? Or am I wrong in thinking that simply exponenting coefficients would give the correct result? Thank you!
Answer: The intercept is the predicted value of the dependent variable when all independent variables have values of 0 (continuous variables) or are at their reference values (categorical variables)—after they have been transformed.
So after you log-transformed your continuous independent/predictor variables, their values of 0 in the transformed scale presumably represented values of 1 in their non-transformed scales. So it's not clear that the intercept as calculated from your regression will be of much practical use. That's probably true both for the original and for the log-transformed regressions in your case: how often do your continuous independent variables actually take on values of 0?
Working with intercepts can be tricky. It's usually better to examine predicted values of the dependent/response variable at some "typical" values of the independent/predictor variables, for example their median values. Those should make a lot more sense both for the non-transformed and the log-transformed analyses.


Simplify $\int \frac{1}{\sqrt{2-x^2}}\, dx$

Question: Somewhere in the provided answer:
$$\int \frac{1}{\sqrt{2-x^2}} dx = \sin^{-1}{\frac{x}{\sqrt{2}}}$$
How did they get that? What I have:
$$\frac{1}{\sqrt{2-x^2}} = \frac{1}{\sqrt{2(1-\frac{x^2}{2})}} = \frac{1}{\sqrt{2} \sqrt{1-\frac{x^2}{2}}}$$
$$\frac{1}{\sqrt{2}} \int \frac{1}{\sqrt{1-(\frac{x}{\sqrt{2}})^2}} = \frac{1}{\sqrt{2}} \sin^{-1}{\frac{x}{\sqrt{2}}}$$
So I have an extra $\frac{1}{\sqrt{2}}$ ... I probably had some stupid mistakes?
Comment: Leaving out the $dx$ sounds like a good idea, save some time, save some paper. But people who leave out the $dx$ often make mistakes during the substitution process.
Comment: HINT: $u=x/\sqrt{2}$ then $dx=?$ (which is missing in your last line (and the title) and is probably the source of the error!)
Comment: You're making change of the variable in your integral $t=x/\sqrt{2}$. This implies that you need to change your differential: $dx=\sqrt{2}dt$. And this will take care of your extra $\sqrt{2}$
Answer: You made a mistake in the last step. To see why, let $u = \frac{x}{\sqrt{2}}$, $du = \frac{dx}{\sqrt{2}}$.
\begin{align*}
\frac{1}{\sqrt{2}} \int \frac{dx}{\sqrt{1-\left(\frac{x}{\sqrt{2}}\right)^2}} &= \frac{1}{\sqrt{2}} \int \frac{\sqrt{2}du}{\sqrt{1-u^2}} \\
&= \int \frac{du}{\sqrt{1-u^2}} \\
&= \arcsin{u} + c \\
&= \arcsin\left({\frac{x}{\sqrt{2}}}\right) + c
\end{align*}
Basically, you made an implicit variable substitution, but forgot that $dx$ also changes when you change the variable.
Answer: $$\int \frac{dx}{\sqrt{a^2-x^2}} = \sin^{-1}\frac{x}{a}$$
$$\int\frac{dx}{\sqrt{2-x^2}}=\int\frac{dx}{\sqrt{{(\sqrt2})^2-x^2}} = \sin^{-1}\frac{x}{\sqrt2}$$
or, doing it other way
$$\int\frac{1}{\sqrt{2-x^2}}dx=\frac{1}{\sqrt{2}} \int \frac{1}{\sqrt{1-(\frac{x}{\sqrt{2}})^2}}dx$$
now put , t=$\frac{x}{\sqrt2}$
$$\frac{1}{\sqrt{2}}\int \frac{\sqrt2 \, dt}{\sqrt{1-t^2}}= \int\frac{dt}{\sqrt{1-t^2}}=\sin^{-1}t+c = \sin^{-1}\frac{x}{\sqrt2}+c$$
Comment: You forgot the $+c$
Answer: I'm going to use a $u$-substitution to make it clearer why this is the case. Let $x = \sqrt{2}\sin \theta$ so $dx = \sqrt{2} \cos \theta d\theta $. We have that
\begin{eqnarray}
\int \dfrac{dx}{\sqrt{2-x^2}} &=& \int\dfrac{\sqrt{2}\cos \theta d\theta}{\sqrt{2 - (\sqrt{2}\sin \theta)^2}} \\
&=& \int\dfrac{\sqrt{2}\cos \theta d\theta}{\sqrt{2 - (\sqrt{2}\sin \theta)^2}} \\
&=& \int\dfrac{\sqrt{2}\cos \theta d\theta}{\sqrt{2 - 2\sin^2 \theta}}\\
&=& \int\dfrac{\cos \theta d\theta}{\sqrt{1 - \sin^2 \theta}} \\
&=& \int\dfrac{\cos \theta d\theta}{\sqrt{\cos^2\theta}} \\
&=& \int\dfrac{\cos \theta d\theta}{cos\theta} \\
&=& \int d\theta = \theta+C.
\end{eqnarray}
Since $x = \sqrt{2}\sin \theta$, we have $\sin \theta = \dfrac{x}{\sqrt{2}}$ and so $\theta = \sin^{-1}\left(\dfrac{x}{\sqrt{2}}\right)$. Therefore
$$
\int \dfrac{dx}{\sqrt{2-x^2}} = \theta+C = \sin^{-1}\left(\dfrac{x}{\sqrt{2}}\right) + C.
$$


Como definir um atributo com valor fixo no ASP.Net MVC?

Question: Eu tenho uma classe usuário que possui o atributo permissão, que deve ser sempre 1. Onde e como eu faria pra fixar esse valor? Na pasta models, controller ou na própria view de cadastro?
Answer: No Model, mais especificamente no construtor:
public class Usuario
{
    ...
    public int Permissao { get; set; }

    public Usuario() {
        Permissao = 1;
    }
}

Para impedir a modificação do valor (propriedade somente leitura), você pode fazer da seguinte forma:
public class Usuario
{
    ...
    public int Permissao { get { return 1; } }
}

Para evitar que o valor seja mapeado no Entity Framework (caso esteja usando), use [NotMapped]:
public class Usuario
{
    ...
    [NotMapped]
    public int Permissao { get { return 1; } }
}

Comment: Obrigado! Irei testar quando chegar em casa. Tinha tentado fazer na view,  mas não deu certo. Posso dizer então que classes de validação e atributos fixos devem ser feitos na pasta models? Ex. Uma classe para validar cpf
Comment: Sim, toda e qualquer informação de validação precisa ficar no *Model*. As validações devem ser feitas ou fazendo a classe implementar `IValidatableObject` ou usando atributos de validação.
Answer: eu usaria:
public class Usuario
{
...
 public const int Permissao = 1;
}

se ele sempre for apenas um número sem regras, sem validações sem nada, então faz todo o sentido ser uma constante e pronto :)
Comment: No contexto do MVC, isto é fora do padrão, por mais que funcione.
Comment: sim você tem razão, mas ainda assim preferiria dessa forma, uma vez que de uma forma elegante eu não colocaria nenhuma das duas formas na minha classe de domínio.