distribute list to buckets by window or cycle for processing

Question: In SQL Server I have a source list of id's that I want to re-order in a specific way for processing. My original table has a list of ids like 10,10,10,10,10,20,20,20,20,30,40,40,50,50,60 and a unique key associated with each one. They can be in any order. I want to distribute them to buckets by window or cycle so that they won't conflict. I'm familiar with the aggregate functions, I'm having trouble with the math to get it distributed. I could do it with a loop but for performance reasons I would like to do it in a single query if possible.
I have a query to get a count and priority like
Count   Id  Priority
5       10  1
4       20  2
2       40  3
2       50  4
1       30  5
1       60  6

The # of buckets is arbitrary although decided ahead of time. If it was 3 I want id's 10,20,40 in the first cycle then 10,20,50 in the second cycle. If the bucket was 4 then 10,20,40,50 in first and 10,20,40,50 again in second.
Another way for me to express the problem is I want to grab the first x from the new table by count, decrement the count and then grab the next x until exhausted.
Took the solution suggested and re-wrote it but I'm still looking for a single sql query solution if possible.
I've updated the suggested loop a bit which should be a little more optimized haven't yet updated it to my real workload
declare @bucket int, @b int, @maxrows int
declare @buckets table (fstrEntityHash varchar(100), bucket int)
declare @count table (flngCount int, fstrEntityHash varchar(100))
declare @bucketTemp table (fstrEntityHash varchar(100), bucket int)

select @bucket = 3, @maxrows = 20

insert into @count
select  COUNT(1) as flngCount,
    fstrEntityHash
from tblTest
group by fstrEntityHash
order by COUNT(1) desc

set @b = 1
while (1 = 1)
begin
insert into @bucketTemp
select top (@bucket) fstrEntityHash, @b
from @count
where   flngCount > 0
order by flngCount desc;

if @@rowcount = 0
   break

 update C
 set    C.flngCount -= 1
 from   @count C, @bucketTemp I
 where  C.fstrEntityHash = I.fstrEntityHash

insert into @buckets
select  *
from        @bucketTemp

if (select count(1) from @buckets) >= @maxrows
   break

 select @b = @b + 1
 delete from @bucketTemp

end

select * from @buckets

Answer: Well I don't know if it's possible with CTE, cause there are some restrictions (you cannot use top in the recursive part and cannot use aggregates in the recursive part).
So for the moment I got this semi cycle:
UPDATE:
SQL FIDDLE EXAMPLE
I've changed a query a little bit, so it will not count all over the table all the times. I also deleting from table @counts all unnecessary records and calculate minimum priority with which I can get records.
declare @bucket int, @b int, @Priority int
declare @buckets table (Id int, bucket int)
declare @bucketsTemp table (Id int primary key, [Count] int, Priority int)
declare @counts table (Id int primary key, [Count] int, Priority int)

select @bucket = 3, @b = 1
select @Priority = min(Priority) from temp

while (1 = 1)
begin
   insert into @bucketsTemp (Id, [Count], Priority)
   select top (@bucket)
       t.Id,
       isnull(c.[Count], t.[Count]) - 1 as [Count],
       t.Priority
   from temp as t
       left outer join @counts as c on c.Id = t.Id
   where t.Priority >= @Priority and isnull(c.[Count], t.[Count]) > 0
   order by t.Priority

   if @@rowcount = 0
       break

   insert into @buckets
   select b.Id, @b
   from @bucketsTemp as b

   update @counts set
       c.[Count] = b.[Count]
   from @counts as c
       inner join @bucketsTemp as b on b.Id = c.Id

   insert into @counts
   select b.Id, b.[Count], b.Priority
   from @bucketsTemp as b
   where b.Id not in (select c.Id from @counts as c)

   delete @counts
   from @counts as c
   where
       c.[Count] = 0 and
       not exists (select * from @counts as t where t.Priority < c.Priority and t.[Count] <> 0)

   delete from @bucketsTemp

   select @Priority = min(Priority) from @counts
   select @b = @b + 1
end

select * from @buckets

First try was
SQL FIDDLE EXAMPLE
declare @bucket int, @b int
declare @buckets table (Id int, bucket int)

select @bucket = 3, @b = 1

while (1 = 1)
begin
  insert into @buckets
  select top (@bucket)
     t.Id,
     @b
  from <your table> as t
     left outer join
     (
         select t.Id, count(*) as [Count]
         from @buckets as t
         group by t.Id
     ) as B on B.Id = t.Id
  where t.[Count] - isnull(B.[Count], 0) > 0
  order by t.Priority asc

  if @@rowcount = 0
     break

  select @b = @b + 1
end

select * from @buckets

Comment: Thanks but I was hoping for a single query solution because in my original I have millions or id's. I'll try it out and see though.
Comment: For millions you need to optimize solution a bit. I'll edit my post later, Ihave a pair of ideas but have no time right now
Comment: I've updated the query a bit which should be a little more optimized haven't yes updated it to my real workload
Comment: I've added another query. It should work faster than first one. It's possible to create a formula for nth backet by calculating and then write a query, but I doubt that such a query will be faster than iterating, because you'll need to read through the table for all buckets.


Why is $\lim\limits_{x \to \infty} \frac{(\sqrt{x})!}{(\sqrt{x+1})!}$ = 1 and not 0?

Question: Wouldn't we expect it to be equal to 0? I suspect that $\lim\limits_{x \to \infty} \frac{1}{\sqrt{x+1}}$ should be equal to $\lim\limits_{x \to \infty} \frac{(\sqrt{x})!}{(\sqrt{x+1})!}$. And the limit of the former is 0. Why is this not the case for the latter?
Comment: $0$ is  the correct answer.
Comment: Is the factorial done *after* the square root on top and bottom?
Comment: What you have written is not clear.  $(\sqrt x)!$ is very different from $\sqrt {x!\,}$  Please edit for clarity.
Answer: Note that $(\sqrt{x+1})!\neq \sqrt{(x+1)!}$. In the former case note that
$$
\sqrt {x + 1}  = \sqrt x \sqrt {1 + \frac{1}{x}}  = \sqrt x  + \frac{1}{{2\sqrt x }} + \mathcal{O}\!\left( {\frac{1}{x}} \right).
$$
Now for fixed $a$ and $b$,
$$
\frac{{(z + a)!}}{{(z + b)!}} = \frac{{\Gamma (z + 1 + a)}}{{\Gamma (z + 1 + b)}} \sim z^{a - b}
$$
as $z\to +\infty$ (see here). Thus,
$$
\frac{{(\sqrt x )!}}{{(\sqrt {x + 1} )!}} \!=\! \frac{{\Gamma (\sqrt x  + 1)}}{{\Gamma (\sqrt {x + 1}  + 1)}} \!=\! \frac{{\Gamma (\sqrt x  + 1)}}{{\Gamma \left( {\sqrt x  + 1 + \frac{1}{{2\sqrt x }} + \mathcal{O}\!\left( {\frac{1}{x}} \right)} \right)}} \sim (\sqrt x )^{ - \frac{1}{{2\sqrt x }}}  \!=\! \mathrm{e}^{ - \frac{1}{4}\frac{{\log x}}{{\sqrt x }}}  \to 1
$$ as $x\to +\infty$.


Constraints on choice of marginal distribution and likelihood

Question: For some time I have been reading into Bishop's Pattern Recognition and Machine Learning. Coming back to some earlier chapters the following got me confused and I am interested where, formally I go wrong.
Bishop states in chapter 1 that Bayes' Theorem
\begin{equation}
p(C\mid x) = \frac{p(x \mid C)p(C)}{p(x)}
\end{equation}
holds for probability densities (as well as probability masses and cont/discrete mixed densities). The core problem is at the meaning of the denominator $p(x)$. Is it an arbitrary prob. density or does the normalization constraint need to hold? What are the constraints for the choice of the RHS terms?
Consider the following example:
Assume $x\in \mathbb{R}$ to be a continuous variable and $C$ a class label $C \in \{0,1\}$.
As an example, could we imagine a situation with a marginal density given by a Gaussian
\begin{equation}
p(x) = N(x\mid \mu,\sigma) \\
\end{equation}
and where at the same time the class-conditional probabilities (likelihood) are given by Gaussians
\begin{align}
p(x\mid C=0) &= N(x\mid \mu-\epsilon,\sigma) \\
&and\\
p(x\mid C=1) &= N(x\mid \mu+\epsilon,\sigma) \\
\end{align}
that are shifted by $\delta$ from the mode of the marginal distribution?
Assuming equal priors $p(C=0)=p(C=1)=0.5$ I am tempted to simply evaluate the LHS of the first equation, e.g. for an $x$ on the far LHS of $\mu$ I find
\begin{equation}
p(C=0\mid x) = 0.5\frac{N(x\mid \mu -\epsilon,\sigma)}{N(x\mid \mu,\sigma)}=...\propto \exp(\frac{\delta(-x+(\mu-\epsilon/2)}{\sigma^2})
\end{equation}
This expression diverges towards smaller $x$. We know that the posterior does not have to be normalized with respect to $x$, and also I presume it can be $>1$ as it is a probability density.
But, I think it still has to hold that $\sum_C p(C\mid x) = \sum_C \frac{p(x,C)}{p(x)} = \frac{\sum_C p(x,C)}{p(x)}=\frac{p(x)}{p(x)}=1$. Which cannot be with the posterior at hand (direct consequence of not choosing a normalizing marginal).
TL;DR: "Why" can is start with "apparently arbitrary" expressions for the RHS $p(x)$ and $p(x\mid C)$ and find an expression for the LHS, when it turns out that the densities are not consistent?
Answer: First, the identity$$\begin{equation}p(c\mid x) = \frac{p(x \mid c)p(c)}{p(x)}
\end{equation}\tag{1}$$is not open to options or debate. It is a theorem, meaning that it holds when used with the proper definitions of the terms within it. (In continuous cases, it holds almost everywhere.) This means that, given a joint probability density $p(x,c)$ for the pair of rv's $(X,C)$, wrt a dominating measure, say $\text d\lambda(x)\text d\mu(c)$, the marginal densities$$p(x)=\int p(x,c)\text d\mu(c)\qquad p(c) = \int p(x,c)\text d\lambda(x)$$are (almost surely) uniquely defined. And thus that the conditional densities$$p(x|c)=\dfrac{p(x,c)}{p(c)}\qquad p(c|x)=\dfrac{p(x,c)}{p(x)}$$are also (almost surely) uniquely defined. The theorem (and theory) does not apply when some of the four elements in (1) are arbitrarily chosen.
Second, the example does not apply for the reason above: $p(x)$ as chosen is not compatible with $p(x|c)$ as chosen. If $X|C=c\sim\mathcal N(\mu+(-1)^c\epsilon,\sigma^2)$ and $\mathbb P(C=0)=\mathbb P(C=1)=1/2$, then
$$X\sim 1/2\mathcal N(\mu+\epsilon,\sigma^2)+1/2\mathcal N\mathcal (\mu-\epsilon,\sigma^2)$$which is not a $\mathcal N(\mu,\sigma^2)$ distribution.
Comment: Thank you. Recap: Say the joint probabilty is known --> conditionals and marginals follow by definition --> all expressions in Bayes Theorem are defined, the theorem itself is provable consequence. Making an Ansatz for any term(s) in (1), the other terms have to be consistent (likely unique) w.r.t. definitions of marginal and  conditional. Only then Bayes theorem (1) holds. @ Xi'an: In case you read this, a dashing question: Would you mind having a look at this post: https://stats.stackexchange.com/questions/406113/logistic-regression-understanding-convergence-towards-coefficients-from-synthet


How to make existing public files private?

Question: Let's say I have a node type "Article" which has a field "File" which is set to handle public files. A lot of articles and files get added.
Now the specs suddenly change and the "Article" will move behind a login and therefore also the attached files must be changed to be not publicly accessible anymore.
I already found out how to change the file system for the file field from public to private pretty easily by reimporting the manually updated field.storage.node.field_file.yml config. But: this only affects new files that will be added after the switch. It doesn't work for existing files. They still are accessible publicly. Many thousand existing files would need to be manually reuploaded to also make them private.
Does anybody of you have solved that in D8 before? If so, then how?
As all I can think of right now is to programmatically query all "Article" nodes, then foreach through all nodes, get the files, temporarily store them somewhere else, empty the field out, then try to reupload the files programmatically (probably my next question) and then resave each node.
Does that sound reasonable? Or can you think of any other approach that might work here (in D8)?
Comment: Interesting question.  This may be affected (complicated?) by https://www.drupal.org/node/2891902
Answer: Thanks a lot for the answers! FileField Paths definitely is the way to go.

Update the file field's field storage to handle private files.
Run FileField Paths' Retroactive update on your content type's file field.

Step 1. can be accomplished from within hook_update_N (if you use configuration management do that locally and then export the updated configuration and deploy the resulting *.yml):
$field_type = 'file';
$field_name = 'field_file';

if (!$field_storage_configs = \Drupal::entityManager()
  ->getStorage('field_storage_config')
  ->loadByProperties(['type' => $field_type])) {
  return;
}

foreach ($field_storage_configs as $field_storage) {
  // Note: These settings apply to the field_file field everywhere it is
  // used.
  if ($field_storage->getName() == $field_name) {
    $field_storage->setSetting('uri_scheme', 'private');
    $field_storage->enforceIsNew(FALSE);
    $field_storage->save();
  }
}

Alternatively, follow the manual config update and reimport as suggested in the question.

Step 2. is to go to your file field's edit screen and fire the Retroactive update upon saving the form:
Answer: It's quite simple, I tested this myself and it works.
1) With PHPMyAdmin or some DB managing application, you'll need to look at node__field_NAME that has your files. Record all the field_NAME_target_id numbers that belong to your content type.
2) Go to to file_managed table.
3) Export table as .sql file
4) Open .sql file with some text editing app. Rename all public:// to private:// for the ones that have the fid number that you recorded.
5) Import .sql and override table file_managed. OR you could clear the table and then import.
6) Move the files to the private folder.

Important: make sure that it has the same parent folder structure. If it was previously under /files/2018-06/some.jpg, in private it needs to be /private/2018-06/some.jpg

Also, no need to move image style image files, these will get auto created. Thus, you only need to grab the original.

7) Flush all caches.

I'm sure you could use SQL query to do 1 to 5. Basically all you gotta do is update the specific values of the uri column in the field_managed table.
Comment: Or just do a query: `UPDATE file_managed SET file_managed.uri = REPLACE(file_managed.uri, 'public://', 'private://');`
Comment: Thanks a lot for your detailed answer! As always a pleasure. Although I must admit I find it gets quite complex pretty fast when you want to automate that.
Answer: I did this for Drupal 7, but haven't tried it in Drupal 8.
I believe that it should work similarly since there is already a D8 release for the required module: FileField Paths. I first installed and enabled the module before following the steps below:

just in case someone is looking to do this, here are the steps:

backup your site and db
copy the table for your field to make a backup (in my case i copied: field_data_field_attachments to
  field_data_field_attachments_bk)
empty table field_data_field_attachments
go to drupal and the option to change the file system should be available, so change it
copy all data from field_data_field_attachments_bk back to field_data_field_attachments
go to drupal, select your content type, select your file field, in file path settings select retroactive update
click save and it will move all your files to the right place in file system and update your db to the new path

— A Romka

Full thread
Comment: FileField Paths definitely is the way to go! Though steps 1 to 5 are invalid in D8.
Comment: You don't have to empty the table to change the file system setting. For Drupal 7, you can just run this (this is for all fields, you can change the WHERE for a specific one): `UPDATE field_config SET data = REPLACE(field_config.data, 's:10:"uri_scheme";s:6:"public";', 's:10:"uri_scheme";s:7:"private";') WHERE data LIKE '%s:10:"uri_scheme";s:6:"public";%';`
Comment: FileField Paths didn't work for me. No idea why.
Answer: With my Drupal 8.6.3 the retro-active update doesn't work.
You still need to achieve step 1, to update the field storage of your field.
Then you need to update all existing files via the database with:
UPDATE file_managed SET uri = REPLACE(
    uri,
    'public://',
    'private://'
)
WHERE filemime like 'application%';

In my case I'm updating only the files, that's why I'm using this where clause.
Don't forget to clear the cache after this SQL query.
Answer: I was able to resolve this without using contrib. @leymannx's answer using FileField Paths is great, but I didn't want to install a contrib module for a one-time script. If you're familiar with batch processing items in hook_post_update_NAME(), it's a piece of cake.
Step 1: Update your field to use private files. (See step 1 of @leymannx's answer)
Step 2: Make sure the new private files directory (or directories) exists (the subdirectory where you want to move your files)
Here's my example:
/**
 * Make sure the private files directory exists.
 */
function mymodule_update_9001(&$sandbox) {
  $directory = 'private://MY-SUBDIRECTORY';

  /** @var \Drupal\Core\File\FileSystemInterface $file_system */
  $file_system = \Drupal::service('file_system');

  $success = $file_system
    ->prepareDirectory($directory, FileSystemInterface::CREATE_DIRECTORY);

  if (!$success) {
    throw new UpdateException('The required directory does not exist (or exists and is not writable) or could not be created.');
  }
}

Step 3: Move existing files to the new directory.
The code to do this is straightforward for a single file:
use Drupal\file\FileInterface;

// Move file to the private files directory.
$file = loadMyFileEntitySomehow();
if ($file instanceof FileInterface) {
  // Note: $destination must be the full file uri, including file name.
  // Additionally, the directory must exist and be writable.
  $destination = 'private://MY-SUBDIRECTORY/' . $file->getFilename();
  \Drupal::service('file.repository')
    ->move($file, $destination);
}

Example post_update to update all files in a specific field on a specific node type:
use Drupal\file\FileInterface;

/**
 * Move files to the private files directory.
 */
function mymodule_post_update_make_files_private(&$sandbox) {
  $batch_size = 25;
  $entity_type = 'node';
  $bundle = 'MY_BUNDLE';

  if (!isset($sandbox['num_processed'])) {
    $sandbox['num_processed'] = 0;
  }

  if (empty($sandbox['entity_ids'])) {
    $sandbox['entity_ids'] = \Drupal::entityTypeManager()
      ->getStorage($entity_type)
      ->getQuery()
      ->condition('type', $bundle)
      ->exists('field_MY_FILE_FIELD')
      ->execute();

    if (is_array($sandbox['entity_ids'])) {
      $sandbox['total'] = count($sandbox['entity_ids']);
    }
  }

  if (!empty($sandbox['entity_ids'])) {
    $current_batch_ids = array_slice($sandbox['entity_ids'], $sandbox['num_processed'], $batch_size);
    $current_batch_entities = \Drupal::entityTypeManager()
      ->getStorage($entity_type)
      ->loadMultiple($current_batch_ids);

    foreach ($current_batch_entities as $entity) {
      // Move files to the private files directory.
      $files = $entity->field_MY_FILE_FIELD->referencedEntities();
      foreach ($files as $file) {
        if ($file instanceof FileInterface) {
          \Drupal::service('file.repository')
            ->move($file, 'private://MY-SUBDIRECTORY/' . $file->getFilename());
        }
      }

      $sandbox['num_processed']++;
    }
  }

  if (!empty($sandbox['total'])) {
    $sandbox['#finished'] = $sandbox['num_processed'] / $sandbox['total'];
  }
  else {
    $sandbox['#finished'] = 1;
  }

}

Answer: Thank you everybody. I combined the previous answers into two update hooks that you can mostly copy and paste. Only use this if you want to move ALL files that are currently public into private.
The only change you need to make is to the function/hook implementation names, and to the $field_names array in the first hook.
The first hook will cause config changes if you have not already set your fields to use the private directory. I would recommend making that change and exporting config locally, but including this update hook as well so that when deploying to another environment the fields are set to use the private directory before the second hook is run, which will be before config is imported (if your deploy script is in the correct order).
use Drupal\Core\File\FileSystemInterface;
use Drupal\Core\Utility\UpdateException;
use Drupal\file\FileInterface;

/**
 * Set file fields to use private files directory.
 */
function my_module_update_9007(&$sandbox) {
  $field_types = [
    'file',
    'image',
  ];
  $field_names = [
    'field_document',
    'field_media_image',
  ];

  foreach ($field_types as $field_type) {
    if (!$field_storage_configs = \Drupal::entityTypeManager()
      ->getStorage('field_storage_config')
      ->loadByProperties(['type' => $field_type])) {
      continue;
    }

    foreach ($field_storage_configs as $field_storage) {
      if (in_array($field_storage->getName(), $field_names)) {
        $field_storage->setSetting('uri_scheme', 'private');
        $field_storage->enforceIsNew(FALSE);
        $field_storage->save();
      }
    }
  }
}

/**
 * Move files from public directory to private.
 */
function my_module_update_9008(&$sandbox) {
  $batch_size = 25;

  if (!isset($sandbox['num_processed'])) {
    $sandbox['num_processed'] = 0;
  }

  if (empty($sandbox['entity_ids'])) {
    // Get an array of all file ids.
    $sandbox['entity_ids'] = \Drupal::entityQuery('file')
      ->execute();

    if (is_array($sandbox['entity_ids'])) {
      $sandbox['total'] = count($sandbox['entity_ids']);
    }
  }

  if (!empty($sandbox['entity_ids'])) {
    $current_batch_ids = array_slice($sandbox['entity_ids'], $sandbox['num_processed'], $batch_size);
    $current_batch_entities = \Drupal::entityTypeManager()
      ->getStorage('file')
      ->loadMultiple($current_batch_ids);

    foreach ($current_batch_entities as $file) {
      if ($file instanceof FileInterface) {
        $uri = $file->get('uri')->getValue()[0]['value'];
        // Only proceed if file is in public directory.
        if (str_contains($uri, 'public://')) {
          // Check that file actually exists.
          // If it doesn't there's nothing we can do.
          if (file_exists($uri)) {
            // Get the current subdirectory and recreate
            // it within the private files directory.
            $uri = str_replace('public://', '', $uri);
            $subdirectory = str_replace('/' . $file->get('filename')->getValue()[0]['value'], '', $uri);
            $subdirectory_path = 'private://' . $subdirectory;
            /** @var \Drupal\Core\File\FileSystemInterface $file_system */
            $file_system = \Drupal::service('file_system');
            $success = $file_system
              ->prepareDirectory($subdirectory_path, FileSystemInterface::CREATE_DIRECTORY);

            if (!$success) {
              throw new UpdateException('The required directory does not exist (or exists and is not writable) or could not be created.');
            }
            else {
              // Move file from public to private.
              // Note: $destination must be the full file uri,
              // including file name.
              // Additionally, the directory must exist and be writable.
              $destination = $subdirectory_path . '/' . $file->getFilename();
              \Drupal::service('file.repository')
                ->move($file, $destination);
            }
          }
        }
      }

      $sandbox['num_processed']++;
    }
  }

  if (!empty($sandbox['total'])) {
    $sandbox['#finished'] = $sandbox['num_processed'] / $sandbox['total'];
  }
  else {
    $sandbox['#finished'] = 1;
  }
}


UMVUE $g(\lambda)$ = $e^\lambda$ when $x_i \sim Pois(\lambda)$

Question: Let $x_1 ... x_n$ be $Pois(\lambda)$
Find UMVUE of $e^\lambda$
From a previous question, I found the UMVUE of $e^{-\lambda}$ to be $(\frac{n-1}{n})^{t}$ where $t = \sum_{i=0}^n(x_i)$.  $\sum_{i=0}^n(x_i)$ is our complete and sufficient statistic for $\lambda$ and has the distribution $Pois(n\lambda)$.
So I considered the estimator $(\frac{n-1}{n})^{-t}$ and took its expected value to see how close I got.
$$E((\frac{n-1}{n})^{-t}) = \sum_{i=0}^\infty\frac{(\frac{n-1}{n})^{-i}e^{-n\lambda}(n\lambda)^{i}}{i!}.$$
Which my calculator says is $$e^{\frac{n\lambda}{n-1}}$$  This seems close.
I have three questions regarding this result,
1) How did my calculator come up with this answer?
2) Can I get to the umvue by modifying my estimator? How?
3) Is there a different estimator I should consider instead? ETA:  Not necessary,  answering 1 and 2 were sufficient!
Answer: For 1, You're interested in $E[a^t]$ where $t$ is poisson with rate $n\lambda$. Explicitly:
$$E[a^x]=\sum_{x=0}^\infty a^x\frac{1}{e^{n\lambda}}\frac{n\lambda^x}{x!}=\frac{1}{e^{\lambda}}\sum_{x=0}^\infty \frac{(na\lambda)^x}{x!}=e^{na\lambda-n\lambda}=e^{n\lambda(a-1)}.$$
Now plug in $a=\left(\frac{n-1}{n}\right)^{-1}$. You should get $e^{n\lambda/(n-1)}$.
Answer:
1) How did my calculator come up with this answer?

Alex R. has already explained this.

2) Can I get to the umvue by modifying my estimator? How?

Using Alex R. 's answer, clearly you don't have an unbiased estimator. However, if you can find $a$ such that,
$$E[a^t] = e^{\lambda}, $$
then you will have an unbiased estimator. So you solve for $a$ in the equation $e^{n\lambda (a-1)} = e^{\lambda}$. This should lead you to a UMVUE.

3) Is there a different estimator I should consider instead?

Don't know if there can be a different estimator or not here.


Limit $\lim_{n \to \infty}\frac{n!-\sin(2n)}{\sqrt{(n+1)!}-\ln(n^2+3n)}$

Question: My professor of Analysis has said that to simplify the factorial I can use Stirling's formula, but I don't know very well what it is or how to apply it.
$$\lim_{n \to \infty}\dfrac{n!-\sin(2n)}{\sqrt{(n+1)!}-\ln(n^2+3n)}$$
I have tried with Stolz but it doesn't work.
Comment: There is no need for Stirling's approximation, such limit is clearly $+\infty$ by elementary inequalities.
Comment: You don't need Stirling's formula (as @MichaelRozenberg pointed out). Anyway, the formula is:$n!\sim\sqrt{2\pi n}\left(\frac{n}{e}\right)^n$
Answer: Stirling Formula gives an good approximation of how $n!$  behaves when $n \rightarrow +\infty$, it is given by
$$
n! \underset{(+\infty)}{\sim}\sqrt{2\pi n}\left(\frac{n}{e}\right)^n
$$Indeed you can use it here, but careful, you cannot sum the $\sim$ relation.
However you can use that
$$
\frac{n!-\sin\left(2n\right)}{n!}=1-\frac{\sin\left(2n\right)}{n!} \underset{n \rightarrow +\infty}{\rightarrow}1
$$
And
$$
\frac{\sqrt{(n+1)!}-\ln\left(n^2+3n\right)}{\sqrt{(n+1)!}}=1-\frac{\ln\left(n^2+3n\right)}{\sqrt{(n+1)!}}\underset{n \rightarrow +\infty}{\rightarrow}1
$$
Hence

$$
\frac{n!-\sin\left(2n\right)}{\sqrt{(n+1)!}-\ln\left(n^2+3n\right)}\underset{(+\infty)}{\sim}\frac{n!}{\sqrt{(n+1)!}}
$$
Comment: For example, when I tried $20!$ with the formula is a negative number, why?
Comment: The expression $$ \sqrt{2n \pi}\left(\frac{n}{e}\right)^n$$ is positive so it is impossible. Or you have used it directly in the limit you were searching but as i said you cannot " sum " this relation.
Answer: $$\lim_{n \to \infty}\dfrac{n!-\sin(2n)}{\sqrt{(n+1)!}-\ln(n^2+3n)}=\lim_{n \to \infty}\dfrac{\sqrt{\frac{n!}{n+1}}-\frac{\sin(2n)}{\sqrt{(n+1)!}}}{1-\frac{\ln(n^2+3n)}{\sqrt{(n+1)!}}}=\infty$$
Answer: The idea is that $\sin$ and $\ln$ are irrelevant in the computation. Thus, the limit dependens only on the ratio between the two factorial expressions, the one at the denominator  being "almost" the square root of the other one. Formalizing:
$\begin{align}\lim_{n \to \infty} \frac{n!-\sin(2n)}{\sqrt{(n+1)!}-\ln(n²+3n)}\sim\\ \sim\lim_{n \to \infty} \frac{n!}{\sqrt{(n+1)}n!^{\frac{1}{2}}}=\\ =\lim_{n \to \infty} \sqrt{\frac{n!}{n+1}} \to +\infty\end{align}$
Answer: For this kind of limits the key point is to recognize that $n!$ and $\sqrt{(n+1)!}$ are "bigger" than all others terms, thus an efficent way to solve is to collect them
$$\dfrac{n!-\sin(2n)}{\sqrt{(n+1)!}-\ln(n^2+3n)}=\frac{n!}{\sqrt{(n+1)!}}\dfrac{1-\frac{\sin(2n)}{n!}}{1-\frac{\ln(n^2+3n)}{\sqrt{(n+1)!}}}\to+\infty\cdot\frac{1-0}{1-0}=+\infty$$
Answer: $ \dfrac{n!-\sin(2n)}{\sqrt{(n+1)!} - \log(n^2+3n)} \gt$
$\dfrac{n! -1}{\sqrt{(n+1)!}} \gt$
$\dfrac{n!}{\sqrt{(n+1)n!}} -\dfrac{\sqrt{n+1}}{\sqrt{(n+1)!}}=$
$\sqrt{n!}\dfrac{1}{\sqrt{(n+1)}} -\dfrac{1}{\sqrt{n!}} \gt$
$\sqrt{(n-2)!} - \dfrac{1}{\sqrt{n!}}.$
The limit $n \rightarrow \infty$  is ?
Used: $n(n-1) \gt n+1$, for $n\ge 3.$


TouchableOpacity onLongPress not working on android

Question: i have been trying to use a TouchableOpacity inside a react-native-maps Marker heres the code:
<MapView.Marker
     coordinate={{
     latitude: marker.lat,
     longitude: marker.lng
     }}
     anchor={{ x: 0, y: 0 }}
     centerOffset={{ x: 0, y: 0 }}
     calloutOffset={{ x: 0, y: 0}}
     title={marker.title}
     description="Sample Description"
                >
<TouchableOpacity
     onLongPress={() => {console.log("MARKER LONG PRESSED")}}
     delayLongPress={1000}
     onPress={()=>{console.log("MARKER PRESSED")}}
>
     // here i have a custom image for the marker
</TouchableOpacity>
</MapView.Marker>

now the problem is this works fine on ios both the onPress and onLongPress events get invoked but on android none of them gets called this is so confusing and i dont know why. is there something i am missing here or something i should be adding?
and also i am importing ToucahbleOpacity from react-native-gesture-handler. i tried importing it from react-native but that just doesnt work on both platforms
Answer: android will have limitations here. Android renders the markers and the callout as bitmaps directly, and they don't have interactivity. So as far as I know you you can not
use long press functionality inside marker all you can use is onPress functionality which can be called inside marker component
<Marker onPress={() => {console.log('in')}}>
  <View>
    <TextWithStyle style={styles.markerText}>{'Home'}</TextWithStyle>
  </View>
</Marker>

Or if this is not helpful. Checkout this answere if that helps
Marker click event on react native maps not working in react ios


How To Do MySQL Data Actions in A Function With PDO

Question: My php version is 5.6.11.
I'm using PDO for mysql actions.
I'll use functions for select any data from my database. Like this;
function select_post($id) {
$result = $db->prepare('SELECT * FROM posts WHERE id = ?');
$result->execute(array($id));
return $result->fetch(PDO::FETCH_ASSOC);
}

But it doesn't work. Then I tried include my connnection file in function. It worked. But do I have to include this file to all of my functions ? Or do we have a different solution for this problem ?
My working code is this;
function select_post($id) {
require "config.php";
$result = $db->prepare('SELECT * FROM eb_settings WHERE setid = ?');
$result->execute(array($id));
return $result->fetch(PDO::FETCH_ASSOC);
}

Comment: You have a variable scope issue - `$db` isn't in scope inside `select_post`. You need to either pass it in as an extra parameter, or add it as a `global`
Comment: How can i add it as global ? The $db variable is in config.php file. I including config.php into functions file but it doesnt work.
Comment: You need to include `config.php` at the start of your code; and inside your function, a line of `global $db;`. That will let you use the `$db` variable inside a function
Comment: Thanks a lot, it works.
Answer: The best is to use a connexion.php file that you'll include at the beginning of every file where you'll proceed to a database connexion. This way you'll only have to change the information at one place if the password or the username changes for example.


Getting Duplicates in Person ID and ASSIGNMENT_ID

Question: This is the query I'm using:
select  DISTINCT  "HRG_GOAL_ACCESS"."PERSON_ID" as "PERSON_ID",
     "HRG_GOAL_ACCESS"."BUSINESS_GROUP_ID" as "BUSINESS_GROUP_ID",
     "HRG_GOALS"."GOAL_ID" as "GOAL_ID",
     "HRG_GOALS"."ASSIGNMENT_ID" as "ASSIGNMENT_ID",
     "HRG_GOALS"."GOAL_NAME" as "GOAL_NAME",
     "HRG_MASS_REQ_RESULTS"."ORGANIZATION_ID" as "ORGANIZATION_ID",
     "HRG_MASS_REQ_RESULTS"."RESULT_CODE" as "RESULT_CODE",
     "HRG_GOAL_PLN_ASSIGNMENTS"."CREATED_BY" as "CREATED_BY"
 from   "FUSION"."HRG_GOAL_PLN_ASSIGNMENTS" "HRG_GOAL_PLN_ASSIGNMENTS",
    "FUSION"."HRG_MASS_REQ_RESULTS" "HRG_MASS_REQ_RESULTS",
    "FUSION"."HRG_GOALS" "HRG_GOALS",
    "FUSION"."HRG_GOAL_ACCESS" "HRG_GOAL_ACCESS"
 where   "HRG_GOAL_ACCESS"."PERSON_ID"="HRG_GOALS"."PERSON_ID"
 and     "HRG_MASS_REQ_RESULTS"."PERSON_ID"="HRG_GOALS"."PERSON_ID"
 and     "HRG_GOAL_PLN_ASSIGNMENTS"."PERSON_ID"="HRG_MASS_REQ_RESULTS"."PERSON_ID"

Output
PERSON_ID        BUSINESS_GROUP_ID GOAL_ID          ASSIGNMENT_ID  GOAL_NAME RESULT_CODE          CREATED_BY
---------------- ----------------- --------------- --------------- ------------------ -------------------- -------------------
300000048030404  1                 300000137711224 300000048033078 NANO_CLASS            SUCCESS anonymous  G_1
300000048030404  1                 300000137637946 300000048033078 INCREASE SALES BY 40% SUCCESS REDDI.SAREDDY G_1
300000048030404  1                 300000137637946 300000048033078 INCREASE SALES BY 40% SUCCESS CURTIS.FEITTY

Comment: A more useful Tip Of The Day: please **edit your question** to include additional information. Comments are for comments.
Comment: What is your expected result, and what result do you get?
Comment: I need to avoid duplicates ...? can I add any thing..
Comment: Tip of today: Switch to modern, explicit `JOIN` syntax! Easier to write (without errors), easier to read, and easier to convert to outer join if needed.
Comment: Also you do not Need to define aliasses if the Name is equals to the table Name. Which makes it more readable
Comment: Are you having duplicated values in a query with DISTINCT? are you sure?
Comment: Please add the ddl and some sample data
Comment: You have to decide which other values to return for each distinct person id/assigbment id.
Comment: I have added DISTINCT then also getting some duplicates so please any modification is there please modify it and share me back
Comment: @Sudakar DISTINCT only removes rows where all columns are equal.
Comment: Yes Person Id & ASSIGNMENT_ID  im getting duplicates
Comment: @Sudakar Show a table with example of these duplicate, that way you have a chance to get an answer.
Comment: Output:-PERSON_ID (300000048030404)
BUSINESS_GROUP_ID (1)
GOAL_ID (300000137711224)
ASSIGNMENT_ID (300000048033078)
GOAL_NAME (NANO_CLASS)
RESULT_CODE (SUCCESS)
CREATED_BY (anonymous)
G_1
PERSON_ID (300000048030404)
BUSINESS_GROUP_ID (1)
GOAL_ID (300000137637946)
ASSIGNMENT_ID (300000048033078)
GOAL_NAME (INCREASE SALES BY 40%)
RESULT_CODE (SUCCESS)
CREATED_BY (REDDI.SAREDDY)
G_1
PERSON_ID (300000048030404)
BUSINESS_GROUP_ID (1)
GOAL_ID (300000137637946)
ASSIGNMENT_ID (300000048033078)
GOAL_NAME (INCREASE SALES BY 40%)
RESULT_CODE (SUCCESS)
CREATED_BY (CURTIS.FEITTY)
Comment: can u please check Above Output getting Person ID & A_Id duplicates
Answer: Your output does not contain duplicates. You have more than one row for PERSON_ID (300000048030404) but that's because the master table (? HRG_GOAL_ACCESS ?) has multiple rows in its child tables.
Each row has different details, so the set is valid. There are different values of  HRG_GOALS.GOAL_ID, HRG_GOALS.GOAL_NAME and HRG_GOAL_PLN_ASSIGNMENTS.CREATED_BY.
If this response does not make you happy you need to explain more clearly what your desire output would look like. Alternatively you need to figure out your data model and understand why your query returns the data it does. Probably you have a missing join condition; the use of distinct could be hindering you in finding that out.


Using Async V3 without installing it

Question: I've problem installing VS-SP1 and Async CTP V3 on my machine. For some reason it cause any .NET application I run on that machine to crash. (good thing I'm using virtual machine and I can roll-back).
I've copy the update csc.exe file into .NET framework 4 directory in my Windows directory.
When I build my project with msbuild from command line everything build and works great.
When I compile the same project from within VS2010 I get compile time error that the async keyword is unknown.
I don't care that VS does not highlight the syntax of async and await but it does bother me that I have to build the project from command line.

How come the command line csc works but when using VS it does not?
How can I change VS to compile the async code properly (without installing Async CTP itself)?

Thank you,
Ido.
Comment: Async targetting pack for .Net 4 doesn't work for you?
Comment: My guess for question 1 is that VS doesn't really shell out to call `csc`, but invokes the compiler from its own DLLs programatically.
Comment: I didn't want to get into the targeting pack but I guess I have no choice.
Comment: Why don't you use VS2012 instead?
Comment: VS use MSBuild which should use csc. I've also turn the log level to diagnostics and it show that it use the right csc.exe
Comment: I don't use 2012 because it has the problem of targeting .NET 4 using the old CTP. I will do that if no other solution will be found.
Comment: @IdoRan - anything about the async targeting pack you didn't like?  I used it for a couple of projects and loved it. :)
Answer: VS2012 and the Async targeting pack is the best option, for the following reasons:

The syntax is the same as in C#5, making upgrade to C#5 easier. The Async CTP has enough differences (TaskEx instead of Task classes, TaskAsync instead of Task suffixes, token parameters etc), that make upgrade a nuisance. Not difficult, just a nuisance
Await/async behavior is much better and closer to C#5. In the Async CTP, an exception that occurs inside a loop will cause the entire loop to silently fail. See Retry a task for a scenario that is affected by this.
There are no installation issues. The Async CTP and VS 2010 SP1 had to be installed in a certain order to avoid problems.
You can expect some sort of support from MS for the targeting pack, while you can expect none for the Async pack.

A small caveat is that installing VS2012 on a machine with VS2010 + Async CTP breaks the Async CTP. You won't be able to use the VS2010 version to compile Async code anymore.
As an example where the async behavior is important, consider the following very simple way of retrying a task. While the function compiles with the Async CTP, it fails SILENTLY (as in application termination silently) if an exception occurs:
<code>private static async Task<T> Retry<T>(Func<T> func, int retryCount)
{
    while (true)
    {
        try
        {
            var result = await Task.Run(func);
            return result;
        }
        catch
        {
            if (retryCount == 0)
                throw;
            retryCount--;
        }
    }
}
</code>
That said, I've been using the Async CTP for over a year now and the only issue was the installation order after adding Visual Studio 2010 SP1. If you get the order wrong the Asycn CTP won't install and you will have to remove SP1 and reinstall everything in the proper order.
Still, I would move to 2012 and the targeting pack as soon as is practical (ie the entire team is ready to switch), to avoid multiple code versions and the annoying exception behavior.
Comment: thank you for the detailed answer. I guess I'll be moving to VS2012 now

Using Async V3 without installing it


Using x509 cert public key in a Java servlet

Question: I can use some help.
I've got some very sketchy requirements to build Single Sign On to 3rd party website.
The documentation I have says that I need to :
Create an X509 Certificate Public Key
Send a SAML post with some basic info to a specific URL
Use plain ( ASCII/UTF8 ) text
In the sample SAML assertion, the X509 certificate is supposed to look like this :
<code> .....
 <ds:KeyInfo>
    <ds:X509Data>
        <ds:X509Certificate>xxxxxxxxxxxxxxxx</ds:X509Certificate>
     </ds:X509Data>
     <ds:KeyValue>
        <ds:RSAKeyValue>
           <ds:Modulus>xxxxxxxxxxxxxxxx</ds:Modulus>
           <ds:Exponent>xxxx</ds:Exponent>
        </ds:RSAKeyValue>
      </ds:KeyValue>
 ...
</code>
So I've created my self-signed certificate, and if I use the command

openssl x509 -noout -text -in ca.crt

I see the public key, but it's got 8 line breaks in it and looks something like this :
<code> Subject Public Key Info:
      Public Key Algorithm: rsaEncryption
           RSA Public Key: (1024 bit)
             Modulus (1024 bit):
                01:a6:26:44:13:cb:ab:5d:37:83:b4:9f:25:a4:8f:
                73:b8:e3:8c:a6:8a:58:13:a8:4f:af:43:8f:13:4a:
                96:75:63:ba:8d:6a:43:9c:31:... etc
</code>
How can I use the public key in my Java servlet, running on tomcat, on RedHat linux.  And how is it going to work inside and XML document ?
Or have I taken a wrong turn somewhere ?
Thanks for your help
Answer: I normally use something like:
<code><KeyDescriptor use="signing">
            <ds:KeyInfo xmlns:ds="http://www.w3.org/2000/09/xmldsig#">
                <ds:X509Data>
                    <ds:X509Certificate>    ...hRWRV+DyfQc9nO
                    </ds:X509Certificate>
                </ds:X509Data>
            </ds:KeyInfo>
        </KeyDescriptor>
</code>
In other words, turn "01:a6:26:44:13:" into "01a6264413" with no linebreaks.


Using glm() as substitute for simple chi square test

Question: I am interested in changing the null hypotheses using glm() in R.
For example:
x = rbinom(100, 1, .7)
summary(glm(x ~ 1, family = "binomial"))

tests the hypothesis that $p = 0.5$.  What if I want to change the null to $p$ = some arbitrary value, within glm()?
I know this can be done also with prop.test() and chisq.test(), but I'd like to explore the idea of using glm() to test all hypotheses relating to categorical data.
Comment: +1.  $p$ evidently refers to the Binomial parameter *expressed as a probability.*  Since the natural link (and the one used by `glm` by default) is the logit, to avoid confusion it's important to distinguish $p$ from its logit, which is the log odds $\log(p/(1-p))$.
Answer: You can use an offset: glm with family="binomial" estimates parameters on the log-odds or logit scale, so $\beta_0=0$ corresponds to log-odds of 0 or a probability of 0.5. If you want to compare against a probability of $p$, you want the baseline value to be $q = \textrm{logit}(p)=\log(p/(1-p))$. The statistical model is now
\begin{split}
Y & \sim \textrm{Binom}(\mu) \\
\mu & =1/(1+\exp(-\eta)) \\
\eta & = \beta_0 + q
\end{split}
where only the last line has changed from the standard setup. In R code:

use offset(q) in the formula
the logit/log-odds function is qlogis(p)
slightly annoyingly, you have to provide an offset value for each element in the response variable - R won't automatically replicate a constant value for you. This is done below by setting up a data frame, but you could just use rep(q,100).

x = rbinom(100, 1, .7)
dd <- data.frame(x, q = qlogis(0.7))
summary(glm(x ~ 1 + offset(q), data=dd, family = "binomial"))

Comment: (+1) this will give you the Wald test. A LRT can be done fitting the null model `glm(y ~ offset(q)-1, family=binomial, data=dd)` and using `lrtest` from the `lmtest` package. Pearson's chi-square test is the score test for the GLM model. Wald/LRT/Score are all consistent tests and should provide equivalent inference in reasonably large sample sizes.
Comment: maybe `anova(.,test="Chisq")` ?
Comment: I think you can also use `anova()` from base R on the glm to get a LR test
Comment: Interesting, I've lost the habit of using ANOVA. However, I observe anova refuses to print the pvalue for the test whereas `lrtest` does.
Answer: Look at confidence interval for parameters of your GLM:
> set.seed(1)
> x = rbinom(100, 1, .7)
> model<-glm(x ~ 1, family = "binomial")
> confint(model)
Waiting for profiling to be done...
    2.5 %    97.5 %
0.3426412 1.1862042

This is a confidence interval for log-odds.
For $p=0.5$ we have $\log(odds) = \log \frac{p}{1-p} = \log 1 = 0$. So testing hypothesis that $p=0.5$ is equivalent to checking if confidence interval contains 0. This one does not, so hypothesis is rejected.
Now, for any arbitrary $p$, you can compute log-odds and check if it is inside confidence interval.
Comment: You can ask for any level of confidence in `confint`. So it is not only for $p<0,05$. Of course your solution is much better when it comes to calculation of p-value
Comment: this is useful, but only works for checking whether $p<0.05$. If you want the actual p-value my answer will be more useful.
Answer: It is not (entirely) correct/accurate to use the p-values based on the z-/t-values in the glm.summary function as a hypothesis test.

It is confusing language. The reported values are named z-values. But in this case they use the estimated standard error in place of the true deviation. Therefore in reality they are closer to t-values.  Compare the following three outputs:
1) summary.glm  2) t-test  3) z-test
> set.seed(1)
> x = rbinom(100, 1, .7)

> coef1 <- summary(glm(x ~ 1, offset=rep(qlogis(0.7),length(x)), family = "binomial"))$coefficients
> coef2 <- summary(glm(x ~ 1, family = "binomial"))$coefficients

> coef1[4]  # output from summary.glm
[1] 0.6626359
> 2*pt(-abs((qlogis(0.7)-coef2[1])/coef2[2]),99,ncp=0) # manual t-test
[1] 0.6635858
> 2*pnorm(-abs((qlogis(0.7)-coef2[1])/coef2[2]),0,1) # manual z-test
[1] 0.6626359

They are not exact p-values. An exact computation of the p-value using the binomial distribution would work better (with the computing power nowadays, this is not a problem). The t-distribution, assuming a Gaussian distribution of the error, is not exact (it overestimates p, exceeding the alpha level occurs less often in "reality"). See the following comparison:
# trying all 100 possible outcomes if the true value is p=0.7
px <- dbinom(0:100,100,0.7)
p_model = rep(0,101)
for (i in 0:100) {
  xi = c(rep(1,i),rep(0,100-i))
  model = glm(xi ~ 1, offset=rep(qlogis(0.7),100), family="binomial")
  p_model[i+1] = 1-summary(model)$coefficients[4]
}

# plotting cumulative distribution of outcomes
outcomes <- p_model[order(p_model)]
cdf <- cumsum(px[order(p_model)])
plot(1-outcomes,1-cdf,
     ylab="cumulative probability",
     xlab= "calculated glm p-value",
     xlim=c(10^-4,1),ylim=c(10^-4,1),col=2,cex=0.5,log="xy")
lines(c(0.00001,1),c(0.00001,1))
for (i in 1:100) {
  lines(1-c(outcomes[i],outcomes[i+1]),1-c(cdf[i+1],cdf[i+1]),col=2)
#  lines(1-c(outcomes[i],outcomes[i]),1-c(cdf[i],cdf[i+1]),col=2)
}

title("probability for rejection as function of set alpha level")

The black curve represents equality. The red curve is below it. That means that for a given calculated p-value by the glm summary function, we find this situation (or larger difference) less often in reality than the p-value indicates.
Comment: This answer is interesting but problematic. (1) the OP didn't actually ask about the difference between score, chi-squared, "exact", or GLM-based approaches to testing hypotheses about binomial responses (they *might* actually know all this stuff already), so this doesn't answer the question that was asked; (2) the estimates of residual variance etc. have a different set of assumptions and sampling distributions from linear models (as in @AdamO's question), so use of a t-test is debatable;  ...
Comment: (3) 'exact' confidence intervals for binomial responses are actually tricky ('exact' [Clopper-Wilson] intervals are conservative; score tests may perform better over some ranges
Comment: @BenBolker, I believe the exact test is indeed conservative, but... only because in reality we are not sampling from perfect binomial distributions. The alternative z-test, is only better from an *empirical* point of view. It is that the two "errors" cancel each other 1) the binomial distribution not being the real distribution of residuals in practical situations, 2) the z-distribution not being an exact expression for a binomial distribution. It is questionable whether we should prefer the *wrong* distribution for the *wrong* model, just because in practice it turns out 'ok'.
Comment: Hmm.. I may be confused about the rationale for using the T distribution for a GLM. Can you take a peak at a related question I just asked [here](https://stats.stackexchange.com/questions/320812/should-degrees-of-freedom-corrections-be-used-for-inference-on-glm-parameters)?
Comment: @Ben You are right that the z-test si actually better than the t-test. The graph displayed in the answer is for the z-test. It uses the output of the GLM function. The bottom-line of my answer was that the "p-value" is a tricky thing. Therefore, I find it better to compute it explicitly, e.g. using the normal distribution, rather than extracting the p-value from a glm function, which has very conveniently been shifted with the offset but hides the origins of the calculations for the p-value.


Square summable consescutive differences and boundedness imply convergence.

Question: Let $\{x_k\}_{k\in\mathbb{N}}$ be a sequence of vectors in $\mathbb{R}^n$ which is bounded (say, in a ball at the origin of radius $b$) and which satisfies,
$$\sum\limits_{k=1}^\infty\|x_{k+1}-x_k\|^2<\infty$$
Must $x_k$ converge? I don't think so but I cannot provide a counter example. I know that, if you remove the assumption of boundedness, then it's not true as the sequence can have summable consecutive differences but be unbounded.
Comment: This is equivalent to say that every coordinate has a sum of squares of differences convergent. We can assume $n = 1$.
Comment: As a counterexample take harmonic series as $x_k$.
Comment: the harmonic series isn't bounded.
Comment: Can you explain why it should be Cauchy?
Answer: No, the claim is false.
Take for example $x_k=\cos(\log(k))$ for $k>1$. Then $(x_k)_k$ is bounded, but it is not convergent (see Analyse of a simple trigonometric sequence)
Moreover, by the MVT
$$x_{k+1}-x_k=-\frac{\sin(\log(t_k))}{t_k}$$
with $t_k\in (k,k+1)$
and therefore
$$|x_{k+1}-x_k|\leq \frac{1}{k}$$
which implies that
$$\sum_{k=1}^\infty|x_{k+1}-x_k|^2<\infty.$$
Comment: Very nice, +1$\,\,$


confidence about range of standard deviation

Question:
Suppose $X_1, X_2$ is a random sample of size 2 from a normal population known to have mean $0$ and variance $\sigma^2$; further assume $x_1 = -0.75$, $x_2=0.16$. How sure (or confident) would you be that:
(a) $\sigma^2 \ge 1.0221$ ?
(b) $\sigma^2 \ge 0.4242$ ?
(c) $\sigma^2 \ge 2.7908$ ?

I reason that this problem should be able to be solved using the following logic:
We know that if $Z_i$ is a standard normal random variable, $(Z_i - \bar{Z})$ is also an independent random variable with normal distribution, and therefore $(Z_i - \bar{Z})^2$ is $\chi^2$. However, we can use the definition of sample variance $S^2 = \frac{1}{n-1}\sum{(X_i - \bar{X})^2}$ to show that:
$$\sum_{i=0}^n{(Z_i - \bar{Z})}^2 = \frac{(n-1)S^2}{\sigma^2}$$
So, $\frac{(n-1)S^2}{\sigma^2}$ is $\chi^2$ with $n-1$ degrees of freedom.

I used the above reasoning to try and solve this problem in the following manner:
$$P(\sigma^2 \ge t) =
P\left(\frac{\sigma^2}{S^2} \ge \frac{t}{S^2}\right) =
P\left(\frac{S^2}{\sigma^2} \le \frac{S^2}{t}\right) =
F_{\chi^2_{df=1}} \left(\frac{S^2}{t}\right)$$
Using the values in the problem to solve for $S^2$:
$$S^2 = \frac{1}{2-1}\left((-0.75-\bar{x})^2 + (0.16 - \bar{x})^2\right) = 0.41405$$
(since $\bar{x} = \frac{0.16-0.75}{2} = -0.295$ )
Therefore the answers should be:
(a) $F_{\chi^2_{df=1}}(\frac{0.41405}{1.0221}) = F_{\chi^2_{df=1}}(0.4051) = 0.48$
(b) $F_{\chi^2_{df=1}}(\frac{0.41405}{0.4242}) = F_{\chi^2_{df=1}}(0.976) = 0.68$
(c) $F_{\chi^2_{df=1}}(\frac{0.41405}{2.7908}) = F_{\chi^2_{df=1}}(0.148) = 0.3$
However, the solutions in the back of the book gives the following answers:
(a) 0.25
(b) 0.5
(c) 0.1
Answer:
$\dfrac{(n-1)S^2}{\sigma^2}$ is $\chi^2$ with $n-1$ degrees of freedom.

That much is true.  But at the outset you said this is from a population that is KNOWN to have expectation $0$.  Unrealistic perhaps, but it is clearly intended that you would use that information, and you did not.
You defined the sample variance: $\displaystyle S^2 = \frac{1}{n-1}\sum{(X_i - \bar{X})^2}$. This uses the sample mean $\bar X$ as an estimator of of the population mean. There is no reason to do that when the population mean is known with certainty.  Instead, the appropriate thing is
$$
S^2 = \frac 1 n \sum_{i=1}^n (X_i - 0)^2,
$$
so you have
$$
\frac{nS^2}{\sigma^2} \sim \chi^2_n.
$$
Your confidence intervals should be based on that.
Comment: $$ \phantom{mnnn}\frac 1 {\sigma^2} \sum_{i=1}^n (X_i - \bar X)^2 \sim \chi^2_{n-1}, $$ $$\text{but } \frac 1 {\sigma^2} \sum_{i=1}^n (X_i - \mu)^2 \sim \chi^2_n,$$ where $\mu$ is the population mean and $\bar X$ is the sample mean. $\qquad$
Comment: $\ldots\,$so you reduce the number of degrees of freedom from $2$ to $2-1$ when you use $\bar X$ as an estimator $\text{of } \mu$, but not when $\mu$ is known and used. $\qquad$
Comment: Very good point, thank you. The answer comes out to be correct when you use $\bar{X} = 0$ and assume 2 degrees of freedom. I'm very confused by the latter point, however. Since there are only 2 values, the degrees of freedom should only be 1...
Comment: I see. Essentially because we know the value for $\mu$, the $\chi^2$ distribution is just defined as a linear combination of each random variable $X$. Therefore, the degrees of freedom just follows the typical pattern of how many normal random variables are squared (i.e. 2). THANKS!


Importing methods from Python class into another class instance

Question: Let's say I've got python object A, that is an instance of class A.  Every instance of class A has an attribute SubType.
I've also got classes SubType_B, SubType_C, and SubType_D, each of which has a method called ingest().  The ingest() method was previously using (self) to get all the parameters it needed, but that self is now the instance of class A.
What is the most elegant way to inherit / use the method ingest() from a SubType class (e.g. SubType_A), using the self from object A?
Previously, the ingest() method was defined in class A, but I would like to break that out into separate classes.  Class A is instantiated, and based on the SubType parameter, that object would inherit the correct ingest() method from the corresponding SubType class.
In real simple terms, I'd like one object to grab a method from another object, as if it were its own.
Comment: [If you have an instance of `A`, then how would a child's method be relevant to it?](http://meta.stackexchange.com/questions/66377/what-is-the-xy-problem)
Comment: Keep the relationship well defined - make a new controlling class which passes the instance of `A` as necessary to the instance of `SubType` and remove the `SubType` attribute from `A`. That is, the new class will have an instance of `A` and an instance of `SubType` which is deals with as it should.
Comment: Why not creating a metaclass which will return a class with the proper ingest method based on the subclass type? This metaclass would have direct access to any of your subclasses bases and would be able to take the decisions, in its new method.
Comment: @HenryGomersall, a controlling class is a good thought, thank you, will look into that.
Comment: @IgnacioVazquez-Abrams, you're right, it's not.  The question was perhaps too loosely defined, stating not my end goal, but how to perform something ill-conceived.  The idea of a controlling class, as suggested in other comments, intuited my intent despite the incoherence.  Thanks for the XY problem link though, good to keep in mind.
Answer: UPDATE
Final solution was to make a factory function that returns instances of the SubType classes.  This factory reads information in parameters passed to it, that determine which SubType class to instantiate.  The SubType classes all extend Class A.
I had envisioned things backwards, thinking I started with the most general class, then incorporated attributes and methods from sub-classes.  This factory-like-function does the requisite information gathering, then instantiates the appropriate sub-class.
Thanks to @HenryGomersall and @IgnacioVazquez-Abrams for ideas and clarification.


ava.lang.NullPointerException: null at org.apache.catalina.loader.WebappClassLoader.findResources(WebappClassLoader.java:1368) ~[na:na]

Question: I am getting this error in one of my web app. After restarting the tomcat server everything went perfect.Can anybody help to identify the root cause of the issue.
2016-07-01 09:29:13,529 ERROR [http-bio-8080-exec-42] c.a.w.c.s.Caller [Caller.java:88] Couldn't get request Handler
java.lang.NullPointerException: null
    at org.apache.catalina.loader.WebappClassLoader.findResources(WebappClassLoader.java:1368) ~[na:na]
    at java.lang.ClassLoader.getResources(ClassLoader.java:1040) ~[na:1.6.0_45]
    at org.apache.commons.discovery.jdk.JDK12Hooks.getResources(JDK12Hooks.java:150) ~[commons-discovery-0.2.jar:0.2]
    at org.apache.commons.discovery.resource.DiscoverResources$1.getNextResources(DiscoverResources.java:153) ~[commons-discovery-0.2.jar:0.2]
    at org.apache.commons.discovery.resource.DiscoverResources$1.getNextResource(DiscoverResources.java:129) ~[commons-discovery-0.2.jar:0.2]
    at org.apache.commons.discovery.resource.DiscoverResources$1.hasNext(DiscoverResources.java:116) ~[commons-discovery-0.2.jar:0.2]
    at org.apache.commons.discovery.resource.names.DiscoverNamesInFile$1.getNextClassNames(DiscoverNamesInFile.java:186) ~[commons-discovery-0.2.jar:0.2]
    at org.apache.commons.discovery.resource.names.DiscoverNamesInFile$1.getNextClassName(DiscoverNamesInFile.java:170) ~[commons-discovery-0.2.jar:0.2]
    at org.apache.commons.discovery.resource.names.DiscoverNamesInFile$1.hasNext(DiscoverNamesInFile.java:157) ~[commons-discovery-0.2.jar:0.2]
    at org.apache.commons.discovery.resource.names.NameDiscoverers$1.getNextIterator(NameDiscoverers.java:143) ~[commons-discovery-0.2.jar:0.2]
    at org.apache.commons.discovery.resource.names.NameDiscoverers$1.hasNext(NameDiscoverers.java:126) ~[commons-discovery-0.2.jar:0.2]
    at org.apache.commons.discovery.resource.classes.ResourceClassDiscoverImpl$1.getNextResource(ResourceClassDiscoverImpl.java:159) ~[commons-discovery-0.2.jar:0.2]
    at org.apache.commons.discovery.resource.classes.ResourceClassDiscoverImpl$1.hasNext(ResourceClassDiscoverImpl.java:147) ~[commons-discovery-0.2.jar:0.2]
    at org.apache.axis.configuration.EngineConfigurationFactoryFinder$1.run(EngineConfigurationFactoryFinder.java:120) ~[axis-1.2.1.jar:na]
    at java.security.AccessController.doPrivileged(Native Method) ~[na:1.6.0_45]
    at org.apache.axis.configuration.EngineConfigurationFactoryFinder.newFactory(EngineConfigurationFactoryFinder.java:113) ~[axis-1.2.1.jar:na]
    at org.apache.axis.configuration.EngineConfigurationFactoryFinder.newFactory(EngineConfigurationFactoryFinder.java:160) ~[axis-1.2.1.jar:na]
    at org.apache.axis.client.Service.getEngineConfiguration(Service.java:812) ~[axis-1.2.1.jar:na]
    at org.apache.axis.client.Service.getAxisClient(Service.java:103) ~[axis-1.2.1.jar:na]
    at org.apache.axis.client.Service.<init>(Service.java:112) ~[axis-1.2.1.jar:na]
    at com.amadeus.winaproach.connector.soap.Caller.<init>(Caller.java:81) ~[winaproach_connector-2.1.0.jar:2.1.0]
    at com.amadeus.qlm.rndrequest.handler.WinaproachRequestHandler.<init>(WinaproachRequestHandler.java:73) [WinaproachRequestHandler.class:na]
    at com.amadeus.qlm.rndrequest.Request.handlRequest(Request.java:128) [Request.class:na]
    at com.amadeus.qlm.rndrequest.SupportRequestCreatorServlet.doPost(SupportRequestCreatorServlet.java:57) [SupportRequestCreatorServlet.class:na]
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:646) [tomcat-servlet-api-3.0.jar:na]
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:727) [tomcat-servlet-api-3.0.jar:na]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303) [tomcat-catalina-7.0.52.jar:7.0.52]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208) [tomcat-catalina-7.0.52.jar:7.0.52]
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:369) [spring-security-web-3.0.7.RELEASE.jar:3.0.7.RELEASE]
    at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:109) [spring-security-web-3.0.7.RELEASE.jar:3.0.7.RELEASE]
    at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:83) [spring-security-web-3.0.7.RELEASE.jar:3.0.7.RELEASE]
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:381) [spring-security-web-3.0.7.RELEASE.jar:3.0.7.RELEASE]
    at org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:97) [spring-security-web-3.0.7.RELEASE.jar:3.0.7.RELEASE]
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:381) [spring-security-web-3.0.7.RELEASE.jar:3.0.7.RELEASE]
    at org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:100) [spring-security-web-3.0.7.RELEASE.jar:3.0.7.RELEASE]
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:381) [spring-security-web-3.0.7.RELEASE.jar:3.0.7.RELEASE]
    at org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:54) [spring-security-web-3.0.7.RELEASE.jar:3.0.7.RELEASE]
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:381) [spring-security-web-3.0.7.RELEASE.jar:3.0.7.RELEASE]
    at org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:35) [spring-security-web-3.0.7.RELEASE.jar:3.0.7.RELEASE]
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:381) [spring-security-web-3.0.7.RELEASE.jar:3.0.7.RELEASE]
    at com.amadeus.qlm.rndrequest.auth.OAuth2Filter.doFilter(OAuth2Filter.java:77) [OAuth2Filter.class:na]
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:381) [spring-security-web-3.0.7.RELEASE.jar:3.0.7.RELEASE]
    at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:79) [spring-security-web-3.0.7.RELEASE.jar:3.0.7.RELEASE]
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:381) [spring-security-web-3.0.7.RELEASE.jar:3.0.7.RELEASE]
    at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:168) [spring-security-web-3.0.7.RELEASE.jar:3.0.7.RELEASE]
    at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:237) [spring-web-3.0.7.RELEASE.jar:3.0.7.RELEASE]
    at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:167) [spring-web-3.0.7.RELEASE.jar:3.0.7.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241) [tomcat-catalina-7.0.52.jar:7.0.52]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208) [tomcat-catalina-7.0.52.jar:7.0.52]
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:220) [tomcat-catalina-7.0.52.jar:7.0.52]
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122) [tomcat-catalina-7.0.52.jar:7.0.52]
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:501) [tomcat-catalina-7.0.52.jar:7.0.52]
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:170) [tomcat-catalina-7.0.52.jar:7.0.52]
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:98) [tomcat-catalina-7.0.52.jar:7.0.52]
    at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:950) [tomcat-catalina-7.0.52.jar:7.0.52]
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116) [tomcat-catalina-7.0.52.jar:7.0.52]
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408) [tomcat-catalina-7.0.52.jar:7.0.52]
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1041) [tomcat-coyote-7.0.52.jar:7.0.52]
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:607) [tomcat-coyote-7.0.52.jar:7.0.52]
    at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:313) [tomcat-coyote-7.0.52.jar:7.0.52]
    at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:895) [na:1.6.0_45]
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:918) [na:1.6.0_45]
    at java.lang.Thread.run(Thread.java:662) [na:1.6.0_45]

Comment: Welcome to SO! Please read http://stackoverflow.com/help/how-to-ask and http://stackoverflow.com/help/mcve
Comment: can you put your code please?
Answer: I've once seen this error occur when included commons-discovery.jar in Tomcat/lib folder.
If you are using commons-discovery.jar   put it in the WEB-INF/lib folder of your project and not the Tomcat/lib folder of your project and that should resolve your issue.
Comment: Commons-discovery.jar is in WEB-INF/lib folder only.Can there be any other issue.Please help.
Comment: I would suggest to check your classpath for the jar's you are using and if they exist in Tomcat/lib too, move them to WEB-INF/lib. There must be some dublicated jar there...


Converting Object received using SOAP from (C# .net) web service to a String array in Android

Question: I am trying to send string array from web service to android application using kSOAP2.
Using kSOAP2, I receive an response in Object format at android end. Now i want to convert this object in String Array format so that i can pass this array directly to GridView.
My Web Service Method is as follows:
[WebMethod]
public string[] getit(string status)
{
   string[] result;
   if (status == "blue")
      result = new string[] { "One", "Two", "Three", "Four" };
   else
      result = new string[] { "five", "six", "Seven", "Eight" };
   return result;
}

My Android Code is as follows:
public void call(String status)
{
   try {
       SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);

       request.addProperty("status",status.toString());

       SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
       envelope.dotNet=true;
       envelope.setOutputSoapObject(request);

       HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
       androidHttpTransport.call(SOAP_ACTION, envelope);

       Object result = (Object)envelope.getResponse();

       array1=(String []) result;   //This statement does not work
   }
}

In android code array1 is globally declared string array. String array1[];
I want to convert Object result to be converted into array1 String array.
Thanks in advance.
Answer: right now I can't think of a good example. You should examine the object that is returned. But I guess that it is a SoapObject with properties inside
SoapObject result = (SoapObject)envelope.getResponse();

then I guess if you call
String s = (String)result.getProperty(0);

you will get the first element of the returned array.
And ofcource, you should do the necessery error handling.
Answer: first print the "result" object using result.toString().... and see what it returns and after that it will not directly convert into the string[] first it should convert into the Object[] array... and one by one it will convert into the string[] array... so your code should be like....
Object[] objArr=(Object[])result;
String[] strArr=new String[objArr.length];
for(int i=0;i<=objArr.length;i++)
{
  strArr[i]=objArr[i].toString();

}
Thats how u can do it....
Comment: not exactly. With kSOAP2 you get SoapObjects, which contain attributes and properties. The rest is easy to handle.
Comment: @mihail Thanks for the input, can you please explain me or refer to a simple straight forward example for fetching the data in string array.


What is the relationship between training-test split and shifting window for time series?

Question: I have created a stock trend prediction model with sentiment analysis but I am confused of the relationship between training test split and shifting window for time series.
Is the shifting window used for validation and train-test split separates the data for the model? Or are the two interchangeable?
I know the train-test split procedure is used to estimate the performance of machine learning algorithms when they are used to make predictions on data not used to train the model. But I don't understand why a sliding window is used in existing literature?
Thank you for the help :)
Comment: Are you asking why researchers use shifting windows instead of ordinary cross-validation? Does this thread answer your question? https://stats.stackexchange.com/questions/14099/using-k-fold-cross-validation-for-time-series-model-selection
Comment: I am trying to find out if I need to do a train-test split and sliding window or is it just one them I need to deploy?
Answer: You don't want the test data to contain information that is more recent than the train data. If that were the case the model has a free peak into the future which is never the case in the real world. That is why you need the sliding window.
Comment: So do I need both train-test split and sliding window for time series stock prediction?


Prove $(a,b,c)=((a,b),(a,c))$

Question: The notation is for the greatest common divisor.  I know that
$$(a,b,c)=((a,b),c)=((a,c),b)=(a,(b,c))$$
Suppose $g=(a,b,c)$.  Then $g\mid a,b,c$.  Also, $g\mid(a,b),c$ and $g\mid(a,c),b$.  Thus there exist integers $k,m$ such that
$$(a,b)=gk, (a,c)=gm$$
Then
$$((a,b),(a,c))=(gk,gm)=g(k,m)$$
Therefore, since $(k,m)=1$ (otherwise $g$ would not be the greatest common divisor of $(a,b)$ and $(a,c)$), $g=((a,b),(a,c))$.
Is this proof okay?
Answer: It's much simpler using the identities you already know (associativity, commutativity, etc)
$$((a,b),(a,c))\, =\, ((a,b),a,c)\, =\, (a,b,a,c)\, =\, (a,b,c)$$
Remark $\ $ By induction, in the same way, one can always "flatten" such gcd expressions.
Answer: Your proof seems okay. This is probably the shortest one. But gonna be large because I am oversimplifying.
Let
$$a=\prod_{i=1}^{k}p_i^{\alpha_i},b=\prod_{i=1}^{k}p_i^{\beta_i},c=\prod_{o=1}^{k}p_i^{\gamma_i}$$
Now $\displaystyle \text{gcd}(a,b,c)=\prod_{i=1}^{k}p_i^{\min(\alpha_i,\beta_i,\gamma_i)}$
and $\displaystyle \text{gcd}(a,b)=\prod_{i=1}^{k}p_i^{\min(\alpha_i,\beta_i)},\text{gcd}(a,c)=\prod_{i=1}^{k}p_i^{\min(\alpha_i,\gamma_i)}$
So prove the equality we need to prove the fact :
for arbitrary integers(also true for reals) $\alpha,\beta,\gamma$
$$\min(\alpha,\beta,\gamma)=\min (\min(\alpha,\beta),\min(\alpha,\gamma))$$
Which is obvious since we may WLOG assume $\alpha\ge \beta\ge \gamma$ and both sides equal $\gamma$. Hope this proof satisfies you.
Comment: Nice.  I actually did a similar proof for a lcm this way, and considered it, but I thought mine would suffice.  I appreciate the response.
Comment: I know what you meant.  I was pretty confident I was right to begin with, but to see it done another way (especially a way that I also feel comfortable using) was definitely awesome.  Thanks for the help!
Comment: @Lalaloopsy You'll gain greater general insight (and a simpler proof) if you use the gcd laws - see my answer.
Comment: Yours surely suffices, this one is something I heart. I didn't mean to say your is wrong or something. Nevermind.
Comment: Oh you are welcome!!
Answer: Your proof seems OK. A more elegant proof would be to show that $m$ divides $a,b$ and $c$ if and only if $m$ divides $(a,b)$ and $(a,c)$, which is fairly routine. Then of course $(a,b,c)=((a,b),(a,c))$.
Answer: You can use just the one identity you know along with symmetry, and  nothing else, to simplify
$$ ((a,b),(a,c)) = ((a,b),a,c) = (((a,b),a), c) = ((a,a,b),c) = (((a,a),b),c) = ((a,a),b,c)$$
In fact, the associative identity for a binary operator $((a,b),c) = (a,(b,c))$ -- or in its more common expression for operators with infix notation $(a \cdot b) \cdot c = a \cdot(b\cdot c)$ -- is enough to prove that if you operate on an arbitrary number of things, it doesn't matter how you group them: e.g. if you know that binary gcds are associative, then it automatically follows, e.g., that
$$ ((a,(b,c)),d) = ((a,b),(c,d)) $$
without any fuss. And it means that extending the operator to any positive, finite number of terms is unambiguous: if I write
$$ (a,b,c,d) $$
then it doesn't matter how I group the terms into pairwise gcds, I have to get the same value.
If the operator is also symmetric (more commonly called "commutative" when talking about operations, but "symmetric" -- that is, $(a,b) = (b,a)$ or for infix operations $a\cdot b = b \cdot a$ -- that means you can rearrange the terms arbitrarily.
And thus, I immediately know that it makes sense to just say
$$ ((a,b),(a,c)) = (a,a,b,c) $$
and furthermore, if I instead write it as
$$ ((a,b),(a,c)) = ((a,a),(b,c))$$
this could be proven without ever resorting to ternary or quaternary gcds, just by using the associative and commutative laws.
Comment: Already mentioned - see my answer 5 mins prior.
Comment: I felt it worthwhile to completely avoid the quaternary operator. But I had planned on adding some more content anyways
Comment: Whoops, I forgot to ping @Bill
Answer: It's worthwhile to consider a proof that resides entirely within the algebra of divisibility.
The main trick in this regard is that if $x$ and $y$ are nonnegative numbers and you can show $x \mid y$ and $y \mid x$, then it follows that $x = y$
Thus, to prove $((a,b),(a,c)) = (a,b,c)$, you need to prove

$((a,b),(a,c)) \mid (a,b,c)$
$(a,b,c) \mid ((a,b),(a,c)) $

To get you started on both points, observe that the definition of gcd means that the second statement is equivalent to

$(a,b,c) \mid (a,b)$ and $(a,b,c) \mid (a,c) $

The entire proof ultimately boils down to repeatedly writing down statements equivalent to what you're trying to prove until you're left with something obviously true.

Prove $(a,b,c)=((a,b),(a,c))$


Ionic change image on click?

Question: I would like to change an image when I click on a button.
I made this:
home.html

    <ion-button (click)="logEvent($event)">
      <ion-icon slot="icon-only" name="checkmark-outline"></ion-icon>
    </ion-button>
</ion-content>

and my home.ts
export class HomePage implements OnInit {
  cards;
  constructor() {
    this.cards = [];
  }

  ngOnInit() {}

  logEvent(event) {

    console.log("click");

    this.cards = [
      {
        img: "https://placeimg.com/300/300/people",
      },
      {
        img: "https://placeimg.com/300/300/animals",
      },
    ];
  }
}

but that's as far as I can go.
Comment: your cards variable is an array, do you intend to display multiple image or just one?
Answer: The problem is here . You are trying to read .img of an array, instead of a single card.
Have a selectedCardIndex variable on your class and on button click, you need to set the selectedCardIndex value.
You can change your code to below to make it work:

<ion-button (click)="logEvent($event)">
  <ion-icon slot="icon-only" name="checkmark-outline"></ion-icon>
</ion-button>

export class HomePage implements OnInit {
  cards;
  selectedCardIndex = 0;

  constructor() {
    this.cards = [
      {
        img: "https://placeimg.com/300/300/people",
      },
      {
        img: "https://placeimg.com/300/300/animals",
      },
    ];
  }

  ngOnInit() {}

  logEvent(event) {
    const newIndex = this.selectedCardIndex + 1;

    if (newIndex === this.cards.length) {
      this.selectedCardIndex = 0;
    } else {
      this.selectedCardIndex = newIndex;
    }
  }
}

Ionic change image on click?


Disable email to admin on new user registration

Question: When a new user registers, an email is sent to the admins. I can't work out how to turn this off. There doesn't seem anywhere where I can alter it.
In Home » Administration » Configuration » People » Account settings
Who can register accounts? "Visitors" is checked (not "Visitors, but administrator approval is required")
Comment: I check the rules (if installed) to see if there's some other configuration sending out email on user signup.
Answer: There are a module for control this emails sendings:
MailControl


Sorting answers, given overvotes and undervotes

Question: At many question-and-answer sites, like StackExchange, people can upvote or downvote each answer.  These sites also typically try to use the votes to sort answers, so the answers that are most likely to be helpful or accurate tend to appear nearest the top.  Given the number of upvotes and downvotes for each answer, how should one sort the answers?

Examples. To illustrate why I think this question might have some non-trivial statistical content, let me survey a handful of methods one might consider and some shortcomings of them.  In each method, we compute a score for each answer from its upvotes and downvotes, and then sort the answers by score, so the only question is what method to use to compute the score.

Upvotes minus downvotes. The additive difference is simple to compute.  Limitations. Is an answer with 121 upvotes and 100 downvotes really better than an answer with 20 upvotes and 0 downvotes?
Upvotes divided by total number of votes. This estimates the fraction of voters who held a positive opinion of the answer, which is arguably natural and meaningful in its own right. Limitations. Is an answer with 1 upvote and 0 downvotes really better than an answer with 8 upvotes and 1 downvotes?
Compute a confidence interval. I suppose we could compute, for each answer, a confidence interval for the true fraction of people who would vote positively if they voted.  But it is not clear how to extend this to a complete sorting scheme; what do we do when two answers have overlapping confidence intervals?
Laplace smoothing. We could apply Laplace smoothing (additive smoothing) to the counts of upvotes and downvotes, then estimate the fraction of votes that are positive.  If we have $u$ upvotes and $d$ downvotes for an answer, its score will be $(u+1)/(u+d+2)$.  (For instance, this would declare that an answer with 3 upvotes and 1 downvote is equivalent an answer with 1 upvote and 0 downvotes.  Does that seem reasonable?  Hard to say.)
Comment: It should be noted, that in this particular site, downvotes are a bit rare.
Comment: @mpiktas, OK.  I'm most interested in the general question, as downvotes are more common at some sites than others.  But if you have a good answer that is specialized to the case where downvotes are rare, that'd be great, too.
Answer: I recently learned about Bayesian rating.  Bayesian rating computes a weighted average of the naive uncorrected rating for this answer and the average rating for all answers.  The fewer the votes for this answer, the more we weight things towards the average rating.  The intuition is that if we have no votes on this answer, then the average rating (across all answers) is our best guess at the rating of this answer; as we gain more votes on this answer, they start to move our estimate away from the average rating.
The scheme apparently works like this.  The naive uncorrected rating for an answer is $r = u/n$, where $u$ is the number of upvotes and $n$ the total number of votes for that answer (i.e., $n=u+d$, where $d$ is the number of downvotes).  Let $r^*$ denote the average uncorrected rating, averaged over all answers, i.e., the average of $r$ over all answers.  Also, let $n^*$ the average number of votes per answer, over all answers, i.e., the average value of $n$.
With these definitions, the Bayesian rating for an answer is $r'$, defined as follows:
$$ r' = \frac{n}{n+n^*} r + \frac{n^*}{n+n^*} r^*. $$
Notice how if we have no votes on this answer, then $r'=r^*$ (the Bayesian rating is the average rating across all answers); whereas as $n \to \infty$, we have $r' \to r$ (the Bayesian rating for an answer converges to the naive uncorrected rating, as the number of votes on the answer becomes large).  These seem like appealing properties.
For a generalization that can be used if items can be rated from 1-5 stars, instead of upvoted/downvoted, see the answers to How to find confidence intervals for ratings?, the essay Bayesian sorting by rank (which appears to use a slightly different formula), and Bayesian Ratings: Your Salvation for User-Generated Content.
Answer: I found an essay (How Not To Sort By Average Rating) which argues that you should compute a 95% confidence interval for the true fraction of people who would vote positively, and then sort ratings by the lower end of the confidence interval.
This is an interesting approach.  It is hard for me to judge whether this is in some sense the "right" way to do it, but it seems to behave better than some of the more naive alternatives.  Worth noting: @raegtin gives a cogent criticism of this approach, in his answer to a related question.  The short version of the criticism is that using the lower limit of a confidence interval pushes items with few ratings towards a very low rating, where it's probably better to push them towards the average rating over all items (as Bayesian rating does).


Can we have multiple WITH Clauses in BigQuery and then SELECT by joining

Question: Is it possible to have multiple WITH clause statements in the BigQuery editor with #standardSQL
e.g:
#StandardSQL

#features
WITH features AS (
SELECT
fullVisitorId,
IFNULL(totals.bounces, 0) AS bounces,
IFNULL(totals.timeOnSite, 0) AS time_on_site
FROM
`data-to-insights.ecommerce.web_analytics`
WHERE
totals.newVisits = 1
AND date BETWEEN '20160801' AND '20170430');

# features labels
WITH features_label AS (
SELECT
fullvisitorid,
IF(COUNTIF(totals.transactions > 0 AND totals.newVisits IS NULL) > 0, 1, 0) AS will_buy_on_return_visit
FROM
`data-to-insights.ecommerce.web_analytics`
GROUP BY fullvisitorid);

# Combine features with feature labels for model training
SELECT * EXCEPT(fullVisitorID)
FROM features
JOIN features_label
USING (fullVisitorId);

I am getting errors Syntax error: Unexpected ";" at [13:44] but not sure whether the multiple with clause works or not.
Answer: use below
WITH features AS (
  SELECT
  fullVisitorId,
  IFNULL(totals.bounces, 0) AS bounces,
  IFNULL(totals.timeOnSite, 0) AS time_on_site
  FROM `data-to-insights.ecommerce.web_analytics`
  WHERE totals.newVisits = 1
  AND date BETWEEN '20160801' AND '20170430'
), features_label AS (
  SELECT
  fullvisitorid,
  IF(COUNTIF(totals.transactions > 0 AND totals.newVisits IS NULL) > 0, 1, 0) AS will_buy_on_return_visit
  FROM `data-to-insights.ecommerce.web_analytics`
  GROUP BY fullvisitorid
)
SELECT * EXCEPT(fullVisitorID)
FROM features
JOIN features_label
USING (fullVisitorId)


Ajuda com view laravel

Question: Preciso mostrar duas categorias em uma view. Tentei da forma abaixo, porém sem sucesso:
public function index()
{
    return View::make('Titles.IndexFutebol')->withType('time1')->withType('time2');

}

somente mostra type time2.
Comment: Qual a versão do Laravel?
Comment: versão do laravel é 4.2
Comment: Já tentou com `View::make('Titles.IndexFutebol')->with('time1', $time1)->with('time2', $time2);` ?
Comment: public function index()
 {

$time1= \Title::where('type', 'atletico');
$time2= \Title::where('type', 'cruzeiro');

  return View::make('Titles.IndexFutebol')->with('type', $time1)->with('type', $time2);

 }
Comment: e assim app.viewModels.titles.index.start('cruzeiro','atletico');
Comment: Você não pode repetir o nome `type`
Comment: return View::make('Titles.IndexFutebol')->with('type', $time1,$time2); só mostra $time2
Answer: Pelo o que eu li nos comentários você está usando a versão 4.2 do laravel (não considera dá um upgrade?).
Tenta assim:
public function index()
{
    return View::make('Titles.IndexFutebol')->with('type', $time1, $time2);

}

Ajuda com view laravel


Won't let me install VSIX extension

Question: I am using Visual Studio Professional 2013 and I have downloaded an .vsix file called "DiscordRPCVS" and when i run it, it gives me the following error(s). I also tried installing it through Tools>Visual Studio Command Prompt.
Click here for error image
And this is the console log error:
01-Oct-18 7:35:58 PM - Microsoft VSIX Installer
01-Oct-18 7:35:58 PM - -------------------------------------------
01-Oct-18 7:35:58 PM - Initializing Install...
01-Oct-18 7:35:58 PM - Extension Details...
01-Oct-18 7:35:58 PM -  Identifier      : discord_rpc_vs.Company.b011d8bc-b0bf-4cf1-9948-4bf45efb4d54
01-Oct-18 7:35:58 PM -  Name            : DiscordRPCVS
01-Oct-18 7:35:58 PM -  Author          : Swan
01-Oct-18 7:35:58 PM -  Version         : 1.7.0
01-Oct-18 7:35:58 PM -  Description     : Enables Discord Rich Presence for Visual Studio 2017
01-Oct-18 7:35:58 PM -  Locale          : en-US
01-Oct-18 7:35:58 PM -  MoreInfoURL     :
01-Oct-18 7:35:58 PM -  InstalledByMSI  : False
01-Oct-18 7:35:58 PM -  SupportedFrameworkVersionRange : [4.5,)
01-Oct-18 7:35:58 PM -
01-Oct-18 7:35:58 PM -  Supported Products :
01-Oct-18 7:35:58 PM -      Microsoft.VisualStudio.Community
01-Oct-18 7:35:58 PM -          Version : [15.0]
01-Oct-18 7:35:58 PM -
01-Oct-18 7:35:58 PM -  References      :
01-Oct-18 7:35:58 PM -      -------------------------------------------------------
01-Oct-18 7:35:58 PM -      Identifier   : Microsoft.VisualStudio.MPF.15.0
01-Oct-18 7:35:58 PM -      Name         : Visual Studio MPF 15.0
01-Oct-18 7:35:58 PM -      Version      : [15.0]
01-Oct-18 7:35:58 PM -      MoreInfoURL  :
01-Oct-18 7:35:58 PM -      Nested       : No
01-Oct-18 7:35:58 PM -
01-Oct-18 7:35:58 PM -
01-Oct-18 7:35:58 PM - Searching for applicable products...
01-Oct-18 7:35:58 PM - Found installed product - Microsoft Visual Basic Express 2010
01-Oct-18 7:35:58 PM - Found installed product - Microsoft Visual Studio Professional 2013
01-Oct-18 7:35:58 PM - Found installed product - Microsoft Visual Studio 2013 Shell (Integrated)
01-Oct-18 7:35:58 PM - Found installed product - Global Location
01-Oct-18 7:35:58 PM - VSIXInstaller.NoApplicableSKUsException: This extension is not installable on any currently installed products.
   at VSIXInstaller.App.InitializeInstall()
   at System.Threading.Tasks.Task.InnerInvoke()
   at System.Threading.Tasks.Task.Execute()
Answer: You need VS 2017 to use this extension

Won't let me install VSIX extension


DataBase Error: Column count doesn't match value count at row 1

Question: echo $column;//Here $column="Date ,1007001 ,1007002 ,1007003 ,1007004 ,1007005 ,1007006";
echo $columnvalue; // Here $columnvalue="'12/27/2012' ,'1' ,'0' ,'1' ,'1' ,'0' ,'1'" ;
$sql_cmd ="INSERT INTO `databasename`.`$table` (`$column`) VALUES ($columnvalue)";
if(!mysql_query($sql_cmd)) {
       die('inside AddUserToDataBase Error: ' . mysql_error());
       }

Here I got the error:Column count doesn't match value count at row 1
How to fixed it?
Please help.
Comment: you're giving `$column`, which is putting one back tick around all of the values in $column. you should have the back ticks inside of each column name in $column, instead of surrounding a backtick in the query.
Comment: Learn about [database normalization](http://en.wikipedia.org/wiki/Database_normalization)
Answer: ('$column') should be ($column)
('$column') means the column name
('Date ,1007001 ,1007002 ,1007003 ,1007004 ,1007005 ,1007006')

And that is basically 1 column with a strange name (the name is 'Date ,1007001 ,1007002 ,1007003 ,1007004 ,1007005 ,1007006' ) and it should either be
(Date ,1007001 ,1007002 ,1007003 ,1007004 ,1007005 ,1007006)

or
('Date' ,'1007001' ,'1007002' ,'1007003' ,'1007004' ,'1007005' ,'1007006')

Comment: Also I do not think it is good practice to call a column Date. That is a MySQL keyword and should be avoided.
Answer: "Column count doesn't match value count at row 1"
usually occurs when your columns defined in the values clause don't match your actual table columns.
say your table has 4 coulmns, col1 col2 col3 col4
and you want to only insert data into col2, col3, col4
Your insert statement should be:
Insert into table (col2, col3, col4) values (col2val, col3val, col4val)


find and number of days range

Question: I tried to code in bash an archiving script but I can't seem to get find() working with an interval in number of days.
The ranges I need to code are

files last modified between today and 31 days old. This works:

find . -name "*.VER" -mtime -31 -exec mv '{}' /opt/html/31';' -print

files last modified between 31 days and 62 days old. This does not work:

find . -name "*.VER" -mtime -31 -mtime -62 -exec mv '{}' /opt/html/62 ';' -print

files last modified between 62 days and 93 days old
files last modified between 93 days and 124 days old
...you get the idea (up to year)....

Is there a way to code my find() command to use a number of days range??
Comment: Possible duplicate of [How to find the difference in days between two dates?](https://stackoverflow.com/questions/4946785/how-to-find-the-difference-in-days-between-two-dates)
Answer: I think you have to change the logic of + and - in the times:
find . -name "*.VER" -mtime +31 -mtime -62 -exec mv '{}' /opt/html/62 ';' -print

This tells: files with a mtime greater than 31 days but less than 61 days.

find and number of days range


How to start background service when user start using android device?

Question: I have implemented an Android service (START_STICKY) which starts on device boot and runs in background. Functionality of this service is to interact with SD card. As it is running continuously, started with sticky it consumes battery. To solve heavy battery consumption I wanted to start this service when user is using device.
Ideally start/stop service based on the ACTION_SCREEN_ON & ACTION_SCREEN_OFF intents.
When I have tested this found that I can't register for ACTION_SCREEN_OFF & ACTION_SCREEN_ON in the Manifest, so I have created a Broadcast Receiver in my service to capture the ACTION_SCREEN_OFF & ACTION_SCREEN_ON.
But, since I cannot register for the intents in the manifest, when I stop my service on ACTION_SCREEN_OFF. How can I possibly start it when the screen comes back on?
Note :
As I have already mentioned SCREEN_ON + SCREEN_OFF cannot be registered in manifest file. It is registered like
// REGISTER RECEIVER THAT HANDLES SCREEN ON AND SCREEN OFF LOGIC

IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_ON);
filter.addAction(Intent.ACTION_SCREEN_OFF);
broadcastReceiver = new TestReceiver();
registerReceiver(broadcastReceiver, filter);

So when service is not running then this intent will not fire.
Comment: Well, in your BroadcastReceiver for SCREEN_ON + SCREEN_OFF, simply forward these to the service via startService with the same action. In the service, you can check in onStartCommand which action the intent has, if it's screen_on -> start the service, if it's screen_off, the service should already be running, so you shut it down.
Comment: As I have already mentioned SCREEN_ON + SCREEN_OFF cannot be registered in manifest file. SO when service not running it will not get called.
Comment: Similar question: http://stackoverflow.com/questions/9477922/android-broadcast-receiver-for-screen-on-and-screen-off and the answer was that you have to use long run service (sticky).
Answer: you can use BroadCastReciever to call your service based on the type of broadcast
public class MyReceiver extends BroadcastReceiver {

     public static boolean wasScreenOn = true;

    @Override
    public void onReceive(Context context, Intent intent) {

        if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {

            // do whatever you need to do here

        } else if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) {
              // and do whatever you need to do here

        }
       else if(intent.getAction().equals(Intent.ACTION_BOOT_COMPLETED))
        {
          // and do whatever you need to do here
       }

    }

Comment: As I have already mentioned SCREEN_ON + SCREEN_OFF cannot be registered in manifest file. It is registered like // REGISTER RECEIVER THAT HANDLES SCREEN ON AND SCREEN OFF LOGIC IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_ON); filter.addAction(Intent.ACTION_SCREEN_OFF); broadcastReceiver = new TestReceiver(); registerReceiver(broadcastReceiver, filter); So when service is not running then it will start.
Comment: see i am developing a custom lock screen and i too have to detect screen state, its working for me .. and i have register the receiver in manifest with :
Comment: Yes, you are right. BOOT_COMPLETED can be registered in manifest and this works. But when we register SCREEN_ON & SCREEN_OFF in manifest then you wont get fired on screen on/off. you can try. So then I cant start service if it is killed by android system.        I have seen that even though it is sticky, when device is in sleep mode it get killed and doesnt start again.
Answer: Have a Broadcast Receiver for ACTION_SCREEN_ON, ACTION_SCREEN_OFF and ACTION_USER_PRESENT.
onResume of the activity will be called when ACTION_SCREEN_ON is fired. Create a handler and wait for ACTION_USER_PRESENT. When it is fired, implement what you want for your activity.
Register receiver as below:
private void registBroadcastReceiver() {
    final IntentFilter theFilter = new IntentFilter();
    /** System Defined Broadcast */
    theFilter.addAction(Intent.ACTION_SCREEN_ON);
    theFilter.addAction(Intent.ACTION_SCREEN_OFF);

    mPowerKeyReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String strAction = intent.getAction();

            if (strAction.equals(Intent.ACTION_SCREEN_OFF) || strAction.equals(Intent.ACTION_SCREEN_ON)) {
                // > Your playground~!
            }
        }
    };

    getApplicationContext().registerReceiver(mPowerKeyReceiver, theFilter);
}

Comment: As I have mentioned it is background service, not activity. SO no onResume function.


Trouble testing some twice with JavaScript

Question: I have an object with 2 items, each item contains an array of numbers.
selected: {
  item1: [1, 2, 3],
  item2: [4, 5, 6]
}

In a function I need to do something if the number passed to it isn't in either item. So for instance if 6 is passed do nothing, but if 7 is passed then do something.
The following returns true and false if one of the items contains the number
Object.entries(selected).forEach((itemParent)=>{
  console.log(
    itemParent[1].some((itemChild)=>{
      return itemChild === no;
    })
  )
});

But when I add the code below I get an error: Uncaught TypeError: Cannot read property 'some' of undefined
Object.entries(selected)
  .forEach((itemParent)=>{
    itemParent[1].some((itemChild)=>{
      return itemChild === no;
    })
  }
).some((item)=>{
  return item === true;
});

Im using bable so I can use the latest ES6 syntax.
Comment: Your code inside the `forEach` callback doesn't actually do anything. You check `itemParent[1].some((itemChild)=>{return itemChild === no;})`, but you don't do anything with the result, so it's immediately discarded. Then, of course, `forEach` returns `undefined`, so you can't chain another `some` after it. Why are you using `forEach` anyway?
Comment: cause `itemParent[1]` is `2` or `5`... `itemParent` is array and `itemParent[i]` is element of that array
Comment: @Evans, what about our answers ?
Comment: @Alexandru-IonutMihai Ive accepted one...
Comment: @Evans, yes, but you can upvote other solutions which includes our effort in order to gives you a solution.
Answer: Assuming the object is different than the given data, then you could nest some and check. Then return the result of checking.
return Object
    .entries(selected)
    .some(itemParent => itemParent[1].some(itemChild => itemChild === no))

Answer: You are overcomplicating things. And btw, you are even using ES2017 features, so check whether Babel is configured accordingly.
Here is a short solution to your problem:

const no = 7;

const selected = {
  item1: [1, 2, 3],
  item2: [4, 5, 6]
};

const containsNumber = Object.values(selected).some(array => array.includes(no));

console.log(containsNumber);

The reason you got an error message was that forEach does not actually return anything.
Answer: You're getting this error in your second example because forEach doesn't return the array but undefined, and undefined doesn't have any method named some.
Answer: You can use Object.values in combination with concat function in order to obtain a more simple approach.

let selected= {
  item1: [1, 2, 3],
  item2: [4, 5, 6]
};
let contains= [].concat(...Object.values(selected)).includes(7);
console.log(contains);
Answer: A simpler approach I think:

var selected = {
  item1: [1, 2, 3],
  item2: [4, 5, 6]
}
function exists(inputNumber) {
    return Object.keys(selected).some(key => selected[key].some(number => number === inputNumber));
}
console.log(exists(6));
console.log(exists(7));

And even simpler with Object.values:

var selected = {
  item1: [1, 2, 3],
  item2: [4, 5, 6]
}
function exists(inputNumber) {
    return Object.values(selected).some(arr => arr.some(number => number === inputNumber));
}
console.log(exists(6));
console.log(exists(7));
Comment: Wouldn't `Object.values` or `Object.entries` be better than `Object.keys`?
Comment: @Faly, or using `concat` and `spread syntax`: `let contains= [].concat(...Object.values(selected)).includes(7);`
Comment: Yes, with Object.values, it will be simpler
Comment: @Alexandru-IonutMihai Smart idea, great