How can I visualize fitting survival data to a proportional hazards model with a continuous variable?

Question: I have (censored) survival data that I am fitting with a proportional hazards model with a continuous covariate, X (for my purposes, X ranges from 0 to 1). After fitting the model, I get a statistically significant relationship between X and survival. The problem is, how do I actually illustrate this relationship?
An important point here is that I want to illustrate not merely that survival time is associated with x (if it were just that, I could divide the data into two groups - one with x > some cutoff and another <= the cutoff); I want to illustrate that the relationship is a continuous one: that the larger x gets, the worse survival gets (or the opposite), across the whole range of x. So just arbitrarily dividing the data up into several groups isn't ideal.
Here's some example data (and the Cox model) in R:
set.seed(1234)
x <- runif(1000,0,1)
NumericStatus <- sample(c(0,1),length(x),replace=TRUE)
medianSurvMin <- 5
medianSurvMax <- 50
median.surv <- medMin + x*(medMax-medMin)
rates <- 1/median.surv
surv.time <- rexp(length(x), rate=rates)
library(survival)
cph <- coxph(Surv(surv.time,NumericStatus)~x)
summary(cph)$coefficients

Here, I get a coefficient on x of about .17 and a p-value of basically 0. Now, without censoring (if we set all values in 'NumericStatus' to 1), just plotting survival times against x well illustrates the association is continuous (or, alternatively, discrete). But with censoring I can't really do this. A major issue here is that, with the Cox proportional hazards model, we assume that we don't know what the baseline hazard is, but it still contributes to the data, which makes inherently problematic to try to illustrate the data along with the imputed proportional hazards model. It's hard to plot data along with the model you're fitting it to when you start from the assumption that you can't know the full model.
Is there any plot or table I could make to illustrate the continuous relationship between x and survival time? References to academic literature are welcome; I did a cursory search and didn't find what I was looking for.
Comment: Do you specifically need survival time? Are you restricted to the Cox model?
Answer: It is actually a very frequent problem in survival analysis. I have recently published a preprint on this topic, which can be found here: https://arxiv.org/abs/2208.04644. All plots that I am proposing in this preprint are included in the associated R-package contsurvplot, available on github: https://github.com/RobinDenz1/contsurvplot
Let's return to your example. First we create the data and fit the model:
library(survival)

# create the data
set.seed(1234)
x <- runif(1000,0,1)
NumericStatus <- sample(c(0,1),length(x),replace=TRUE)
medMin <- 5
medMax <- 50
median.surv <- medMin + x*(medMax-medMin)
rates <- 1/median.surv
surv.time <- rexp(length(x), rate=rates)
data <- data.frame(time=surv.time, status=NumericStatus, x=x)

# fit the cox model
cph <- coxph(Surv(time, status) ~ x, data=data, x=TRUE)

Now we install the contsurvplot package:
devtools::install_github("RobinDenz1/contsurvplot")

Now we can use the following code to get a survival area plot:
library(contsurvplot)
library(riskRegression)
library(ggplot2)
library(pammtools)

plot_surv_area(time="time",
               status="status",
               variable="x",
               data=data,
               model=cph)

Alternatively, we could create survival contour plot:
plot_surv_contour(time="time",
                  status="status",
                  variable="x",
                  data=data,
                  model=cph)

I personally think that both of these plots are better than artifical categorization of the continuous covariate and using simple Kaplan-Meier plots.
Answer: I'm dealing with exactly the same issue. I tried the SmoothHR package in R, but this is more a prediction approach. It yield a hazard ratio for every value of a continuous variable but does not provide an optimal cut off point.


Opposite of String.Split with separators (.net)

Question: Is there a way to do the opposite of String.Split in .Net? That is, to combine all the elements of an array with a given separator.
Taking ["a", "b", "c"] and giving "a b c" (with a separator of " ").
UPDATE: I found the answer myself. It is the String.Join method.
Comment: I have forgotten, searched for, and found this question / answer 3 times now in the last year.
Comment: This can get confusing, since LINQ gives `string[]` a Join method that does something completely different.
Answer: Found the answer. It's called String.Join.
Answer: You can use String.Join:
string[] array = new string[] { "a", "b", "c" };
string separator = " ";
string joined = String.Join(separator, array); // "a b c"

Though more verbose, you can also use a StringBuilder approach:
StringBuilder builder = new StringBuilder();

if (array.Length > 0)
{
    builder.Append(array[0]);
}
for (var i = 1; i < array.Length; ++i)
{
    builder.Append(separator);
    builder.Append(array[i]);
}

string joined = builder.ToString(); // "a b c"

Answer:
using string.join():

string[] array = new string[] { "a", "b", "c" };
string separator = ",";
string joined = String.Join(separator, array); // "a,b,c"

using StringBuilder

StringBuilder namesSB = new StringBuilder();
namesSB.AppendJoin(separator, array);
string joined =namesSB.ToString();


add a column with different label

Question: I want to add a column that contains two different labels. Let's say I have this text
aa bb cc
dd ee ff
gg hh ii
ll mm nn
oo pp qq

and I want to add 1 at hte first column of the first two lines and 2 at the first column of the remaining lines, so that eventually I will get that text:
1 aa bb cc
1 dd ee ff
2 gg hh ii
3 ll mm nn
4 oo pp qq

Do you know how to do it?
thanks
Answer: I'm assuming that you want to do this using the shell, if your data is in a file called input.txt, you can either use cat -n or nl.
% tail -n+2 input.txt | cat -n
     1  dd ee ff
     2  gg hh ii
     3  ll mm nn
     4  oo pp qq
% tail -n+2 input.txt | nl
     1  dd ee ff
     2  gg hh ii
     3  ll mm nn
     4  oo pp qq

The first line can be added back manually.
The two commands will behave differently if you have empty lines in your input file.
Answer: Could you please try following and let me know if this helps you.
Solution 1st: By using a variable named count whose initial value is 1 and then checking if line number is either 1 or 2 then simply append 1 in $1 else increase variable count's value by 1 and append it in $1's value.
awk -v count=1 '{$1=NR==1||NR==2?1 FS $1:++count FS $1} 1'   Input_file

Solution 2nd: Checking if line number is 1 or 2 then simply adding 1 to $1 else checking if a line is NOT NULL then add NR-1(which means subtract 1 from it's line number) and add to $1's value.
awk '{$1=NR==1||NR==2?1 FS $1:(NF?FNR-1 FS $1:"")} 1' Input_file

Answer: Assuming you are processing a text file in Linux shell, you could use awk for this. Your problem description says you want two labels 1 and 2, this would be
cat input.txt | awk '{print (NR<=2 ? "1 ":"2 ") $0}'

Your expected output says you want label 1 for the first two lines, and start counting from 2 beginning with the third line, this would be
cat input.txt | awk '{print (NR<=2 ? "1 ":NR-1" ") $0}'

Comment: IMHO you need not to use cat with awk, as awk could read Input_file by itself.

add a column with different label


How should I perform a redirect in hook_form_alter()?

Question: When users log in, I want to redirect them to another page, when they have a certain role. In Drupal 7, I'd use drupal_goto() in hook_user_login() to do the redirect, and hook_module_implements_alter() to make sure that my module is last in the list, so that everything else gets a chance to run.
In Drupal 8, it seems that performing a redirect outside of a controller is not a supported use case.
On that page, gngn has the same problem, and manually generates a RedirectResponse and sends it.
The problem is that, as I see it, send() doesn't terminate the request and the page will have two HTML documents: a 'redirecting to...' page, followed by whatever page would have been there in the first place. Which could be a security issue.
johnvb notes this, and inserts a call to exit() after send().
Presumably something useful is being done in the $kernel->terminate() call in index.php, which is being bypassed by calling exit().
In Drupal 7, drupal_goto() called drupal_exit() to handle this problem.
drupal_goto() was removed says that modules needing to interrupt the request flow should throw an HTTP exception, but there are no 'redirect' exceptions.
As the user login also does a redirect, another approach would be to alter the redirection URL, as suggested on the drupal_goto() change record link above. However, that approach will result in my method being called on every single request, which for what I'm doing seems insanely wasteful.
So, how should I perform a redirect from hook_form_alter() in Drupal 8?
Answer: use Drupal\Core\Form\FormStateInterface;

/**
 * Implements hook_form_FORM_ID_alter().
 */
function [MODULENAME]_form_user_login_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  // Alter login form and add own custom submit handler.
  $form['#submit'][] = '_[MODULENAME]_user_login_form_submit';

  // Not all forms pay attention to $form['#submit'][]. For these
  // try adding your submit hook to the #submit for the specific
  // button.  e.g.,
  $form['actions']['submit']['#submit'][] = '_[MODULENAME]_user_login_form_submit';
}

/**
 * Custom submit handler for login form.
 */
function _[MODULENAME]_user_login_form_submit($form, FormStateInterface $form_state) {
  // Set redirect to login form.
  $form_state->setRedirect('custom.redirect_callback');
}

Answer: You have several ways to redirect user after login. As in the previous answers you can do it by implementing  hook_form_FORM_ID_alter() and adding additional submit function, but you can still use hook_user_login function too:
To redirect to some route with parameters generating some url (using Symfony\Component\Validator\Constraints\Url class reference):
$form_state->setRedirectUrl(new Url('route_name', ['route' => 'parameters']));

To redirect to some route:
$form_state->setRedirect('route_name', ['route' => 'parameters']);

Also you can use Symfony\Component\HttpFoundation\RedirectResponse, for example if you want to redirect a user to some custom user page:
function your_module_user_login($account) {
    global $base_url;
    $redirect = new RedirectResponse($base_url .'/your-url/'.$account->uid->value);
    $redirect->send();

}

Comment: Where would I get $form_state from if I'm using hook_user_login? Using RedirectResponse like this results in two responses being sent (the redirect masks it, but it's not good security practice)
Comment: Yes, i agree, RedirectResponse is not a good example in this context. It can be used in other redirect purposes not in form API.
Comment: `hook_user_login()` has never been though to be used to redirect users with `drupal_goto()` or `RedirectResponse`.
Answer: The correct way to set a redirection after a form is submitted, in Drupal 8, is following these steps.

Implement hook_form_alter() or hook_form_FORM_ID_alter() to add a form submission handler to the form
On the form submission handler, use FormState::setRedirect(), which require a route name, or FormState::setRedirectUrl(), which requires a \Drupal\Core\Url object as argument.

The alternative would be using the redirect.destination service. In this case, also with Drupal 8 it would be possible to use hook_user_login().
function mymodule_user_login(UserInterface $account) {
  \Drupal::destination()->set($url_destination_as_string);
}

The documentation for RedirectDestination::set() says, though:

This method should be used really rarely, for example views uses it, in order to override all destination calls in all of its rendering.

As side note, the correct method to redirect users after they log in, in Drupal 7, is using code similar to the following one.
function mymodule_user_login(&$edit, $account) {
  $edit['redirect'] = $path_to_redirect_users_to;
}

It works because the &$edit parameter the hook receives is the $form_state parameter passed to the login form submission handler.
function user_login_submit($form, &$form_state) {
  global $user;
  $user = user_load($form_state['uid']);
  $form_state['redirect'] = 'user/' . $user->uid;
  user_login_finalize($form_state);
}

function user_login_finalize(&$edit = array()) {
  global $user;
  watchdog('user', 'Session opened for %name.', array(
    '%name' => $user->name,
  ));

  // Update the user table timestamp noting user has logged in.
  // This is also used to invalidate one-time login links.
  $user->login = REQUEST_TIME;
  db_update('users')
    ->fields(array(
    'login' => $user->login,
  ))
    ->condition('uid', $user->uid)
    ->execute();

  // Regenerate the session ID to prevent against session fixation attacks.
  // This is called before hook_user in case one of those functions fails
  // or incorrectly does a redirect which would leave the old session in place.
  drupal_session_regenerate();
  user_module_invoke('login', $edit, $user);
}


How to check that a random variable is in $L^p(\Omega,F,\mathbb{P})$

Question: How to check that a random variable is in $L^p(\Omega,F,\mathbb{P})$?
Maybe I should provide an example to get my point across.
Let $X_\alpha$ be a random variable with CFD $F_\alpha(x) = (1 - \frac{1}{x^\alpha})\mathbb{1}_{[1,\infty]}(x)$
I want to find for which values $\alpha$ $X_\alpha$ belongs to $L^p$.
Should I look at integrating the density function to the power p in absolute value or rather the CFD? I am a bit confused.
Answer: $X_\alpha$ is nonnegative, so it suffices to check $E X_\alpha^p < \infty$.
Since you have the CDF, it is easiest to use the tail sum probability for this expectation.
$$E X_\alpha^p = \int_0^\infty P(X_\alpha^p > t) \, dt = \int_0^\infty (1 - F_\alpha(t^{1/p})) \, dt.$$
Hopefully this helps you finish the question.
Comment: What happened to $p$ in the last expression?
Comment: @RobertIsrael Thanks for catching my mistake.
Comment: What if the sign $X_\alpha$ is not known?
Comment: @qcc101 The CDF you gave implies $X_\alpha \ge 0$ almost surely.
Comment: Yes, I mean: what if in another case I do not know the sign of my random variable?
Comment: @qcc101 I'm not sure what you are asking, but you would have to show $E|X_\alpha|^p < \infty$ some other way, using whatever information about $X_\alpha$ that you have...


SSRS date range parameter

Question: I have a report in SSRS 2016 that contains one SP which has a date field called startdate.  I'd like to create a parameter where the user can select between two ranges: startdate >='2017'or startdate < '2017'.  This seems like it should be simple, but I can't see to find an easy way to do this.
I've tried to create a parameter in SSRS where I chose "Specify Values" and manually added these values but I get an error that the "expression references the parameter "startdate" which does not exist in the Parameters collection.
I'm sure I can create this by creating a stored procedure with these dates, but that seems like more work than is needed.
Does anyone know of a better way to do this?
Comment: I'm not quite sure what you mean by *the user can select between two ranges: startdate >='2017-01-01' or startdate < '2017-01-01'.* Are you wanting the user to choose two dates for the report, and filter the results where the start date is between the two? A query containing `WHERE startdate >= '20170101' AND startdate < '20170101'` would return no results, as something cannot be greater or equal to a value while being less than the same value.
Comment: I want the user to have two options to choose from: startdate>='2017' would be the first option.  The second option would be startdate < '2017'.
Comment: What if you allow the user to select these ranges and pass a varchar instead of a date/datetime field? i.e. The drop down would offer two options 'Before' or 'After' and you could filter within the sproc based off of these values? That seems pretty straight forward.
Comment: Add 2 parameters to your SSRS report, for example called `DtStart` and `DtEnd`. Then, in your where clause, use `AND StartDate >= @DtStart AND StartDate < @dtEnd`.
Comment: @Steliok--can you be more specific on how to filter within the sproc based on the values?  Right now my SPROC looks like: and Datefrom >='2015-01-01'.
Comment: @Larnu--if I try this the parameters populate with every date.  I just want the selection to be "Before 2017" and "Since 2017"
Answer: If you are looking to have a parameter that has two options, 0 - Before 2017, and 1 - After 2017 then you should just create a Date parameter which has two options, Before 1/1/2017 in the label field with a 0 in the value field and After 1/1/17 in the label field with a 1 in the value field. Then in your report you just have to filter your data based upon the 1 or 0 value.
For example:
<code>DECLARE @DateFilter INT = 1

    IF ( @DateFilter = 0 )
        BEGIN
            SELECT * FROM dbo.MyTable t
            WHERE t.DateFilter < '1/1/17'
        END

    IF ( @DateFilter = 1 )
        BEGIN
            SELECT * FROM dbo.MyTable t
            WHERE t.DateFilter >='1/1/17'
        END
</code>
I don't know why you would filter your data this way. I recommend to use Larnu's suggestion that you have two parameters, a Start Date and an End Date. Otherwise this could return a lot of rows for the second option as time goes on.
Comment: @Jesalyn--this is what I'm looking for, but I'm confused as to how to implement this. I created a new dataset in SSRS called DateFilter and used that code.  I then created a parameter called DateFilter and used Before as a Label with a value = 0, and After as a label with a value = 1.  I get the same results for both selections.
Comment: Make sure your query or stored procedure uses this filter. I used separate if statements so it would filter differently on these values. Can you post your code that you are using the parameters for?
Comment: I ended up creating one dataset with dates before 2017 and another with dates after 2017.  The dropdown box runs one report if the before is selected and the other if the after is selected.  It's probably not the most efficient way, but it works.
Answer: Add a couple of parameters in SSRS say, FromDate and ToDate and make its data type as Date/Time.
You can specify the default values for these parameters using DateAdd functions and samples give below:
Today:
<code>=Today()
</code>
last week from today:
<code>=DateAdd(DateInterval.Day, -7,Today())
</code>
You can add/reduce year, quarter month etc. in a similar way as shown below. Just change the number to the required length
<code>=DateAdd(DateInterval.Year,-1,Today())

=DateAdd(DateInterval.Quarter,-1,Today())

=DateAdd(DateInterval.Month,-1,Today())

=DateAdd(DateInterval.DayOfYear,-1,Today())

=DateAdd(DateInterval.WeekOfYear,-1,Today())

=DateAdd(DateInterval.WeekDay,-1,Today())

=DateAdd(DateInterval.Hour,-1,Today())

=DateAdd(DateInterval.Minute,-1,Today())

=DateAdd(DateInterval.Second,-1,Today())
</code>

SSRS date range parameter


Image based on node taxonomy terms

Question: Here is what I am trying to do.
If there is an empty image field on a node I want it replaced based on what taxonomy terms are on the page, but the key is I want to apply it site wide so it will affect not only the tpl files but Views as well. I'm guessing this needs to be done via mytheme_preprocess_field in template.php but I'm not quite sure how to do it.
I can easily do this in node.tpl.php but I need it done site wide, not just in the node-type template.

VID 1

TID 1
TID 2
TID 3
TID 4

VID 2

TID 5
TID 6
TID 7

VID 3

TID 8
TID 9
TID 10

Here is what I am trying to do.
<code>// Set Variables
$term1 = $content['field_term1'][0]['#markup'];
// Must use if statement or else there will be an error
if ( isset( $content['field_term2'][0]['#markup'] ) ) {
  $term2 = $content['field_term2'][0]['#markup'];
}
// Must use if statement or else there will be an error
if ( isset( $content['field_term3'][0]['#markup'] ) ) {
  $travel_type = $content['field_term3'][0]['#markup'];
}
if (isset($content['field_node_image'][0]['#item']['uri'])) {
  $image_path = file_create_url($content['field_node_image'][0]['#item']['uri']);
} else {
  switch ($term1) {
    case 'TID 1':
      switch ($term2) {
        case 'TID 5':
          $term_type = '5';
          break;
        case 'TID 6':
          $term_type = '6';
          break;
        case 'TID 7':
          $term_type = '7';
          break;
      }
      break;
    case 'TID 2':
      $term_type = '2';
      break;
    case 'TID 3':
      switch ($term3) {
        case 'TID 8':
          $term_type = '8';
          break;
        case 'TID 9':
          $term_type = '9';
          break;
        case 'TID 10':
          $term_type = '10';
          break;
      }
      break;
    case 'TID 4':
      $term_type = '4';
      break;
  }
  $image_path = '/sites/all/themes/themename/term-images/' . $term_type . '.jpg';
}
</code>
Comment: all you need to do is described here: [Achieve Taxonomy Image function in Drupal 7 with Imagefield](https://drupal.org/node/1224916).
Comment: I've updated my question to make a bit more sense of what exactly I am trying to do.
Comment: If user will choose any term from your vocabulary, then his post will contain some image related with this term, right?
Answer: I used to use the Taxonomy Image module. It has full views integration as well.
<code>Features:

    Image configuration happens within existing admin/taxonomy menu structure.
    Admins can add custom tags to <img> markup when displaying images.
    Allows one-to-one term-to-image relationships.
    Allows many-to-one term-to-image relationships.
    Admin-permitted users can disable the images.
    Administrators can force images to be a standard size.
    May use the ImageCache module if it is available.
    Works with Views.
    Utilizes core file.inc and taxonomy.module APIs.
    Small module with specific, focused functionality.
    Add-on modules that virtually eliminate the need for theme changes.
</code>
Answer: If you want to do some custom coding based on what's in the node from the field template you can get to the node from $variables in preprocess_field like so:
<code>// Parent entity could be a node or custom fieldable entity, usually going to be a node.
if(!empty($variables['element']['#object'])){
  $parent_entity = &$variables['element']['#object'];
}
</code>
At this point you can do whatever you were doing in the node preprocess in the field preprocessor. This can potentially get a bit heavy, so beware

Image based on node taxonomy terms


measure of the boundary of the support

Question: Let $\mu$ be a Borel probability measure on $\mathbb R^d$. Does the boundary of the support of $\mu$ have measure zero, i.e. do we have
$$\mu(\partial(\text{supp}\mu))=0,$$ where we define the support of $\mu$ as the smallest closed set such that its complement has $\mu$-measure zero?
Answer: No; for instance, consider the case that $\mu$ is a point mass.
Comment: ok so the boundary of a point is the point itself

measure of the boundary of the support


Erro ao fazer um Post

Question: Estou tentando salvar as informações que vem do meu formulário de cadastro com essa função:
public function postCreate()
{

    $this->beforeFilter('csf', array('on' => 'post'));
    $validator = Validator::make($data = Input::all(), Despesa::$rules);
    if ($validator->fails())
    {
        return Redirect::back()->withErrors($validator)->withInput();
    }
    unset($data['_token']);
    //dd($data);
    Despesa::create($data);
    return Redirect::route('admin.despesas');
}

Mas quando quando envio me dá um erro:
Illuminate \ Database \ Eloquent \ MassAssignmentException

id

C:\xampp\htdocs\teste\Projetos\l4\bootstrap\compiled.php
{
    $totallyGuarded = $this->totallyGuarded();
    foreach ($this->fillableFromArray($attributes) as $key => $value) {
        $key = $this->removeTableFromKey($key);
        if ($this->isFillable($key)) {
            $this->setAttribute($key, $value);
        } elseif ($totallyGuarded) {
            throw new MassAssignmentException($key);
        }
}

Answer: Quando se passa dados diretamente para o Eloquent::create você está fazendo um Mass Assignment, o mesmo é considerado inseguro pelo fato de que o usuário poderá inserir dados como quiser em sua tabela.
Para evitar que o Laravel detecte isso como uma falha de segurança você deve especificar quais campos podem ou não serem modificados diretamente, para isso adicione uma propriedade $fillable ou $guarded.
A $fillable representa os campos que podem ser modificados diretamente e o $guarded tem efeito contrário, exemplo:
<?php
class Model extends Eloquent {
    $fillable = array('nome','senha');
    $guarded  = array('id','codigo');
}

Quando eu usar Eloquent::create na minha model acima ela vai bloquear qualquer valor nos campos id e codigo e vai permitir modificação direta apenas dos campos nome e senha.
Comment: só não tinha adicionado nada em $fillable
Answer: Em referência no próprio site Laravel, o link mass-assignment explica porque tal erro acontece

When creating a new model, you pass an array of attributes to the model constructor. These attributes are then assigned to the model via mass-assignment. This is convenient; however, can be a serious security concern when blindly passing user input into a model. If user input is blindly passed into a model, the user is free to modify any and all of the model's attributes. For this reason, all Eloquent models protect against mass-assignment by default.

Tradução Site Google

Ao criar um novo modelo, você passar uma matriz de atributos para o construtor do modelo. Esses atributos são então atribuído ao modelo via mass-atribuição. Isto é conveniente; no entanto, pode ser um problema sério de segurança quando cegamente passando a entrada do usuário em um modelo. Se a entrada do usuário é passada cegamente em um modelo, o usuário é livre para modificar qualquer e todos os atributos do modelo. Por esta razão, todos os modelos eloqüentes proteger contra mass-assignment por padrão.

Para definir esse tipo de configuração segue exemplo básico:
class Carro extends Eloquent {
    protected $fillable = array('cor', 'modelo');
}

Referência:

http://laravel.com/docs/eloquent#mass-assignment
http://laravel.com/docs/eloquent
http://laravel.com

Erro ao fazer um Post


If $H$ is a subgroup of a finite abelian group $G$, then $G$ has a subgroup that is isomorphic to $G/H$.

Question: I know Is every quotient of a finite abelian group $G$ isomorphic to some subgroup of $G$? has two answers. I don't understand how the first answer works and I have doubt about that answer. The second answer uses character theory which I don't intend to use since I am practicing for my qualifying exam. This problem showed up in our last exam. None of my classmates can solve this problem and the professors in our department just provided us with some hints saying look the homomorphism and do induction which helped a little but didn't lead me to an answer.
Now I list the two approaches I have tried and the reasons why they don't work.
The first approach I tried is the following:
Suppose $G$ is finite abelian. Let $|G|=p_1^{\alpha_1}p_2^{\alpha_2}\cdots p_k^{\alpha_k}$ and $|H|=p_1^{\beta_1}p_2^{\beta_2}\cdots p_k^{\beta_k}$. By the elementary divisor decomposition, we have $G\cong G_1\times G_2\times\cdots\times G_k$ and $H\cong H_1\times H_2\times\cdots\times H_k$ where $G_i$ is a Sylow subgroup of $G$ and $H_i$ is a Sylow subgroup of $H$ for all $i=1,2,...,k$. Hence $G/H\cong(G_1/H_1)\times(G_2/H_2)\times\cdots\times(G_k/H_k)$. So it suffices to show the result when $G$ is a $p$-group. Suppose $|G|=p^n$.
Now by the invariant factor decomposition, $G\cong\mathbb{Z}_{p^{a_1}}\times\mathbb{Z}_{p^{a_2}}\times\cdots\times\mathbb{Z}_{p^{a_t}}$ with $a_1\geq a_2\geq\cdots\geq a_t$ and $a_1+a_2+\cdots+a_t=n$. For $i=1,...,t$, let $e_i=(...,0,1,0,...)$. Then $G/H=\left<e_1H,...,e_tH\right>$. WLOG, let $\{e_1H,e_2H,...,e_sH\}$, $s\leq t$, be a smallest set of generators for $G/H$.
Claim: $G/H\cong\left<e_1H\right>\times\cdots\times\left<e_sH\right>$.
So $G/H\cong\mathbb{Z}_{p^{b_1}}\times\cdots\times\mathbb{Z}_{p^{b_s}}$ with $b_i\leq a_i$ for all $i=1,...,s$. (This is due to the canonical projection $G\mapsto G/H$ and thus $|e_iH|\mid |e_i|$ for all $i=1,...,s$.) Therefore, $G/H$ is isomorphic to a subgroup of $G$.
This looks promising, but the claim is false. A counterexample is this: Let $G=\mathbb{Z}_4\times\mathbb{Z}_4$. Then $G/\left<(2,2)\right>\cong\mathbb{Z}_4\times\mathbb{Z}_2$, but $(0,1)+\left<(2,2)\right>$ and $(1,0)+\left<(2,2)\right>$ both have order 4.
The second aprroach I tried is the following: Suppose $G$ is finite abelian and $H\leq G$. Let $|G|=p_1^{\alpha_1}p_2^{\alpha_2}\cdots p_k^{\alpha_k}$ and $|H|=p_1^{\beta_1}p_2^{\beta_2}\cdots p_k^{\beta_k}$ where $p_1,...,p_k$ are distinct primes. By the elementary divisor decomposition, we have $G\cong G_1\times G_2\times\cdots\times G_k$ and $H\cong H_1\times H_2\times\cdots\times H_k$ where $G_i$ is a Sylow $p_i$-subgroup of $G$ and $H_i$ is a Sylow $p_i$-subgroup of $H$ for all $i=1,2,...,k$. Since $H_i\unlhd G_i$ for all $i=1,...,k$, $G/H\cong(G_1/H_1)\times(G_2/H_2)\times\cdots\times(G_k/H_k)$. So it suffices to show the result when $G$ is an abelian $p$-group. We proceed by induction.
If $|G|=p$, then $H=1$ or $G$, so $G/H\cong1$ or $G$.
Suppose the result holds for all abelian $p$-groups of order less than $|G|$. Now by the fundamental theorem of finite abelian groups, $G=\mathbb{Z}_{p^{\alpha_1}}\times\cdots\times\mathbb{Z}_{p^{\alpha_n}}=\left<x_1\right>\times\cdots\times\left<x_n\right>$. Consider $\varphi:G\to G$ such that $x\mapsto x^p$. Since $G$ is abelian, $\varphi$ is a group homomorphism with $\ker\varphi=\left<x_1^{p^{\alpha_1-1}}\right>\times\cdots\left<x_n^{p^{\alpha_n-1}}\right>$. By Cauchy's theorem, $H':=\ker\varphi\cap H\neq1$ and it is elementary abelian. So WLOG, $H'\cong\left<x_1^{p^{\alpha_1-1}}\right>\times\cdots\left<x_m^{p^{\alpha_m-1}}\right>$ where $m\leq n$. It follows that $G/H'$ is isomorphic to a subgroup of $G$. By the third isomorphism theorem, we have $G/H\cong(G/H')/(H/H')$. Since $|G/H'|<|G|$, by the induction hypothesis, $(G/H')/(H/H')$ is isomorphic to a subgroup of $G/H'$ and thus it is isomorphic to a subgroup of $G$. Therefore, $G/H$ is isomorphic to a subgroup of $G$.
Now in this proof I assume that if $B$ and $C$ are isomorphic subgroups of a finite abelian group $A$, then $A/B\cong A/C$ which is not true. A counterexample is $A=\mathbb{Z}_4\times\mathbb{Z}_2$, $B=\left<(2,0)\right>$ and $C=\left<(0,1)\right>$. Here $A/B\cong\mathbb{Z}_2\times\mathbb{Z}_2\not\cong\mathbb{Z}_4\cong A/C$.
Now my question is does anyone know how to fix either of the problems in my two attempts above to make it work? Or have a better explanation for the first answer in the post Is every quotient of a finite abelian group $G$ isomorphic to some subgroup of $G$?? This problem have haunted me for months. I would really appreciate the help.
Answer: Since no one answered my question, I did some reading and found out that this is a very well known result. By using the concept of a "basis" of an abelian group, I did the following proof.
Suppose $G$ is a finite abelian group and $H\leq G$. Let $|G|=p_1^{\alpha_1}p_2^{\alpha_2}\cdots p_k^{\alpha_k}$ and $|H|=p_1^{\beta_1}p_2^{\beta_2}\cdots p_k^{\beta_k}$ where $p_1,...,p_k$ are distinct primes. By the elementary divisor decomposition, we have $G\cong G_1\oplus G_2\oplus\cdots\oplus G_k$ and $H\cong H_1\oplus H_2\oplus\cdots\oplus H_k$ where $G_i$ is a Sylow $p_i$-subgroup of $G$ and $H_i$ is a Sylow $p_i$-subgroup of $H$ for all $i=1,2,...,k$. Since $H_i\unlhd G_i$ for all $i=1,...,k$, $G/H\cong(G_1/H_1)\oplus(G_2/H_2)\oplus\cdots\oplus(G_k/H_k)$. So it suffices to show the result when $G$ is an abelian $p$-group. We proceed by induction.
Notice it is easier to think of $G$ as an additive group in stead of a direct product.
If $|G|=p$, then $H=1$ or $G$, so $G/H\cong1$ or $G$.
Suppose the result holds for all abelian $p$-groups of order less than $|G|$. Since $G$ is an abelian $p$ group, by the fundamental theorem of finite abelian groups, $G=\left<x_1\right>\oplus\left<x_2\right>\oplus\cdots\oplus\left<x_t\right>$ with $|x_i|=p^{\alpha_i}$ for all $i\in\{1,...,t\}$ and $\alpha_1\geq\alpha_2\geq\cdots\geq\alpha_t\geq1$. Notice that $x_1,x_2,...,x_t$ are linearly independent in the sense that $x_i$ cannot be write as a linear combination of $x_1,...,x_{i-1},x_{i+1},...,x_t$.
Case 1: $H=\left<g\right>$ with $|g|=p$. Since $|g|=p$, $g=m_1p^{\alpha_1-1}x_1+m_2p^{\alpha_2-1}x_2+\cdots+m_tp^{\alpha_t-1}x_t$ with $m_i\in\{0,1,...,p-1\}$ for all $i\in\{1,...,t\}$ (hence, $m_i=0$ or $(m_i,p)=1$). WLOG, assume $m_t\neq0$. Let $x_t'=m_1p^{\alpha_1-\alpha_t}x_1+m_2p^{\alpha_2-\alpha_t}x_2+\cdots+m_{t-1}p^{\alpha_{t-1}-\alpha_t}x_{t-1}+m_tx_t$. Notice that $|x_t'|=p^{\alpha_t}$. Since $\left<x_t\right>\cap(\left<x_1\right>\oplus\cdots\oplus\left<x_{t-1}\right>)=0$, $\left<x_t'\right>\cap\left<x_i\right>=0$ for all $i\in\{0,1,...,t-1\}$ otherwise $x_t'$ would be a linear combination of $x_1,...,x_{t-1}$. Hence, $G=\left<x_1\right>\oplus\left<x_2\right>\oplus\cdots\oplus\left<x_t'\right>$ (This is basically changing the basis of $G$). Since $\left<g\right>\leq\left<x_t'\right>$, $G/H\cong\left<x_1\right>\oplus\left<x_2\right>\oplus\cdots\oplus(\left<x_t'\right>/\left<g\right>)$. Since $\left<x_t'\right>$ is cyclic, $\left<x_t'\right>/\left<g\right>$ is isomorphic to a subgroup of $\left<x_t'\right>$. So $G/H$ is isomorphic to a subgroup of $G$.
Case 2: $|H|>p$. By Cauchy's theorem, there exists $g\in H$ such that $|g|=p$. By Case 1, $G/\left<g\right>$ is isomorphic to a subgroup of $G$. Now by the third isomorphism theorem, $G/H\cong(G/\left<g\right>)/(H/\left<g\right>)$. Since $|G/\left<g\right>|<|G|$, by the induction hypothesis, $(G/\left<g\right>)/(H/\left<g\right>)$ is isomorphic to a subgroup of $G/\left<g\right>$ which is isomorphic to a subgroup of $G$. Hence $G/H$ is isomorphic to a subgroup of $G$.
Comment: Thanks. I found out this paper https://link.springer.com/content/pdf/10.1007/BF01228254.pdf and in László Fuchs's book, he discussed in detail about abelian groups. It is very hard as a prelim problem.
Comment: What did you read to find that it's a well-known result? Also, on a first reading your answer, this is good stuff.  Well done! (+1)


UpdateModel() causing row(s) to not be updated

Question: I'm having a problem using UpdateModel(theModelToUpdate) causing concurrency issues.
Basically whats happening is, there is a row in the database that contains most but not all the information needed for that row. The rest of the needed information is NULL. The user (using a listbox) would then add information to this row, as well as creating new rows (An ajax command is sent for every item in the listbox. So the controller is being called very fast because of the loop used to get the items).
In my controller I first check to see if the columns the user will be updating are NULL. If they are, I use UpdateModel to update the row. If they are not null (meaning the row is complete ) then I create new rows with the remaining listbox items.
When debugging, I notice that since the controller is called so quickly, the UpdateModel isn't called right away like I had planned. Several items from the listbox get skipped because of this and I get an error saying the row cannot be updated.
How can I solve this?
Answer: Not sure I got this right: When is the controller invoked using AJAX? You say this happens very fast, so I assume you invoke the controller multiple times on submit, rather than every time the user actually adds a row. Under "very fast" I understand multiple operations per second.
Well, for once I think you shouldn't use UpdateModel if you merely add an entry to a row - you could do this manually.
Second, invoking the controller on the same item in fast succession might indeed lead to concurrency issues on the database because it has to acquire a lock somewhere. However, I think this will depend on your database abstraction, the database type and the locking mechanism you use.
I'd suggest you write a small controller action that only adds a single entry interactively, i.e every time the user actually does something. This should keep you from concurrency issues.
Answer: I resolved the issue by not using UpdateModel to update the row. Instead I Insert the rows, then go back and delete the row with the missing information. Probably not the best solution, but it fixed my problem.


Which is greater, $\left(\frac{e}{2}\right)^\sqrt{3}$ or $(\sqrt{2})^{\pi/2}$? (no calculators)

Question: From a math contest in 1985:
Determine which of the following is greater: (no calculators)
$$\left(\frac{e}{2}\right)^\sqrt{3} \, \hspace{3mm} \text{or} \hspace{3mm} \,  (\sqrt{2})^{\pi/2}$$
Hints are welcome, but I'm totally lost and would really appreciate a solution.
Comment: Did you look at their ratio and take the logarithm?
Comment: Yep. Doesn't quite solve it
Comment: Not the answer, but one is less than $e-1$ and the other greater than $e-1$
Answer: This comparison is potentially pretty tricky inasmuch as the numerical values are pretty close, within $2\%$:
$$\left(\frac{e}{2}\right)^{\sqrt{3}} = 1.701\ldots, \qquad (\sqrt 2)^{\pi / 2} = 1.723\ldots$$
The following method is pretty quick-and-dirty, and I doubt that it's the most elegant way. But it doesn't use anything more advanced than knowledge of a few well-known Taylor series, and it doesn't involve integers with more than two digits.
Hint Since $\log$ is an increasing function, we may as well take the logarithms of both sides and compare quantities with the awkward exponents in more tractable places, so we're comparing $\sqrt{3}(1 - \log 2)$ and $\frac{\pi}{4} \log 2$. Subtracting these and collecting terms in $\log 2$ gives
$$\left(\frac{\pi}{4} + \sqrt{3}\right) \log 2 - \sqrt{3},$$
and the claim that $(\sqrt 2)^{\pi / 2} > \left(\frac{e}{2}\right)^{\sqrt{3}}$ is equivalent to showing that this quantity is positive. At this point we can see that this amounts to establishing sufficiently tight lower bounds for $\pi, \log 2$.
One efficient way to produce such bounds is to use the first terms of the Maclaurin series
$$\operatorname{arctanh} x \sim x + \frac{1}{3} x^3 + \cdots \qquad \textrm{and} \qquad \arcsin x \sim x + \frac{1}{6} x^3 + \cdots,$$ the identities
$$\log 2 = \log\left(\frac{1 + \frac{1}{3}}{1 - \frac{1}{3}}\right) = 2 \operatorname{arctanh} \frac{1}{3} \qquad \textrm{and} \qquad \pi = 6 \arcsin \frac{1}{2},$$ and the facts that all of the coefficients of both of these series are nonnegative. These are good choices in part because both series converge relatively quickly at the indicated values.

Solution Using the first two terms of each series gives \begin{align*}\log 2 &= 2 \operatorname{arctanh} \frac{1}{3} > 2 \left[\left(\frac{1}{3}\right) + \frac{1}{3}\left(\frac{1}{3}\right)^3\right] = \frac{56}{81}, \\ \pi &= 6 \arcsin \frac{1}{2} > 6 \left[\left(\frac{1}{2}\right) + \frac{1}{6}\left(\frac{1}{2}\right)^3\right] = \frac{25}{8} ,\end{align*} giving the bound $$\left(\frac{\pi}{4} + \sqrt{3}\right) \log 2 - \sqrt{3} > \left[\frac{1}{4}\left(\frac{25}{8}\right) + \sqrt{3}\right] \frac{56}{81} - \sqrt{3} = \frac{25}{4 \cdot 81}(7 - 4 \sqrt{3}).$$ So, it suffices to show that $7 > 4 \sqrt{3}$, but squaring both sides shows that this is equivalent to $49 > 48$.
Answer: Both $\frac{\pi}{4}$ and $\log(2)$ can be simply approximated in terms of Beuker integrals:
$$ \int_{0}^{1}\frac{x^4(1-x)^4}{1+x^2}=\frac{22}{7}-\pi,\qquad \int_{0}^{1}\frac{x^3(1-x)^3}{1+x}\,dx = 16\log(2)-\frac{621}{56} $$
hence in order to prove that
$$ \frac{\pi}{4}\log(2) > \sqrt{3}(1-\log 2), $$
i.e. that $\left(\sqrt{2}\right)^{\pi/2}>\left(\frac{e}{2}\right)^{\sqrt{3}}$, it is enough to show that
$$ \left(\frac{22}{7\cdot 4}\cdot\frac{621}{896}\right)^2-3\cdot\left(1-\frac{621}{896}\right)^2>\frac{1}{100} $$
since the relative error of both the approximations $\pi\approx\frac{22}{7},\log(2)\approx \frac{621}{896}$ is less than five parts in ten thousands. The last inequality is tedious to check but utterly straightforward.
A tighter inequality can be derived through Cauchy-Schwarz:
$$ \int_{0}^{1}\frac{\log(1+x)}{(1+x^2)^2}\,dx \int_{0}^{1}\log(1+x)\,dx \geq \left(\int_{0}^{1}\frac{\log(1+x)}{1+x^2}\,dx\right)^2 $$
leads to
$$ 4\pi-24\log(2)-12\pi\log(2)+48\log^2(2)+8\pi\log^2(2)-\pi^2\log^2(2)\geq 0.$$
Answer: Edit: used same strategy correctly but had to take a $\log_2$ at the end to get the answer.
Assume $(\frac{e}{2})^{\sqrt3} = (\sqrt2)^{\frac{\pi}{2}}$
Square both sides
$$(\frac{e}{2})^{2\sqrt3} = (2)^{\frac{\pi}{2}}$$
Raise both sides $\sqrt3$
$$(\frac{e}{2})^6 = (2)^{\frac{\pi\cdot \sqrt3}{2}}$$
Multiply both sides by $2^6$
$$e^6 = (2)^{\frac{\pi\cdot \sqrt3+12}{2}}$$
Take the $6th$ root of both sides
$$e = 2^{\frac{\pi\cdot \sqrt3+12}{12}}$$
Taking $\log_2$ both sides
$$\frac{\log(e)}{\log(2)} = {\frac{\pi\cdot \sqrt3+12}{12}} = \frac{3.14\cdot 1.73+12}{12}= 1.45$$
Then $1.44 < 1.45$
So $(\frac{e}{2})^{\sqrt3} < (\sqrt2)^{\frac{\pi}{2}}$
Comment: ((e/2)^(sqrt3))^4 is just (e/2)^(4sqrt3) though right?
Comment: Yes, I delete and try again


Haskell HDBC-Sqlite3 always returns SqlByteString values

Question: I am using HDBC sqlite3 haskell driver to access local sqlite3 database which
PRAGMA encoding

is
UTF-8

And as result, for example for
SELECT id, title FROM some_table

I'm always getting the result like this:
[[SqlByteString "1", SqlByteString "\210\129\123\211"], ... ]

That's weird!
Yes, title contains 'national' symbols and yes, I'm sure that id has type of INTEGER.
So the questions are:

Why 1 unicode symbol are threated as 2 ascii-like symbols?
Why integer columns results bytestring values?
Answer: SQLite is an untyped database, so the fields in your database don't really have a type at all. You should be converting them to a more Haskellish value by using fromSql or safeFromSql from Database.HDBC.SqlValue.
Comment: Their examples return `SqlString` and `SqlNull` but not `SqlInt` --- look more closely at what is returned (`SqlString "0"` etc). I presume the implementation has changed at some point to use `SqlByteString` instead of `SqlString`, I don't know why.
Comment: But in the "Real World Haskell" book (http://book.realworldhaskell.org/read/using-databases.html) they using sqlite3 engine in chapter 21 and their examples do return correct (like SqlInt or SqlString) values. Why?


Group Theory: let $G$ be a group and let $G=H\times K$, is it true that $G/H\cong K$?

Question: I have been asked to prove or disprove the following statement:
Let $G$ be a group that equals to the inner direct product of $H$ and $K$, in symbols, $G=H\times K$, is it true that the factor group of $G$ by $H$ is isomorphic to $K$, or $G/H\cong K$?
I guess the statement is true, but I have missing pieces in my proof. Define the mapping $\phi: G/H\rightarrow K$ as $\phi(aH)=a$, $a\in K$. If the mapping is a well defined function, then I can readily show that it is a bijection and preserves operation, and hence the isomorphism. So the crux here is proving its well-definedness, that is, proving the codomain of $\phi$ is indeed $K$. I separated this into two cases:

If $aH=H$, then $a\in H$. If we also require $a\in K$, then $a\in H\cap K=\left\{e\right\}$, meaning that $a=e$.
If $aH\neq H$, then $a\not\in H$. Since $G=H\times K$ implies $H\trianglelefteq G$, $aH=Ha\leqslant G=HK$. Simplifying, we get $Ha=HK$. Here is the problem, can I just say $\exists k\in K$ with $a=k$?

I am not sure if this is illogical, and even if it is not, there must be steps missing in between. Please help.
Comment: I'm not sure what you mean by "$\exists k\in K$ with $a = k$". Are you just claiming that $a\in K$? In any case, it's easier here to apply the first isomorphism theorem to the projection $G = H\times K \to K$.
Comment: Just a typesetting comment, `\cong`, which prints $\cong$, is probably want you want, rather than $\approx$.
Comment: Thanks @pjs36, I have modified the symbol.
Answer: Hint:
Let $\phi: G \to K$, $\phi(hk) = k$ (each $x \in G$ can be written as $hk$ for $h \in H$ and $k \in K$).
This map is well-defined and surjective of course, and its kernel is..
Comment: I have not studied kernel in Group Theory yet, sorry... but your mapping does not look injective, as elements in $G$ might be product of different $hk$'s.
Comment: @Letian of course it's not required to be injective. I'm hinting at the 1st isomorphism theorem. Have you heard of it?
Comment: @Letian kernel = the preimage of the identity element.


$n$ positive integer, then $n=\sum_{d|n} \phi(d)$ (proof Rotman's textbook)

Question: I've just read in Rotman's group theory textbook the proof of the following statement:
Statement
If $n$ is a positive integer, then $$n=\sum_{d|n} \phi(d),$$
where the sum is over all divisors $d$ of $n$ with $1 \leq d \leq n$.
Proof. If $C$ is a cyclic subgroup of a group $G$, let $gen(C)$ denote the set of all
its generators. It is clear that $G$ is the disjoint union
$G = \coprod gen(C)$, where $C$ ranges over all the cyclic subgroups of $G$. We have just seen, when $G$ is cyclic of order $n$, that there is a unique cyclic subgroup $C_d$ of order $d$ for every divisor $d$ of $n$. Therefore, $n = |G| = \sum_{d|n}|gen(C_d)|$. In Exercise 2.20, however, we saw that $|gen(C_d)| = \phi(d)$; the result follows.
This is a very nice result and the proof is pretty short and simple, however I have a basic doubt, I don't see why $$G= \coprod gen(C)$$
it is evident that any generator is an element of $G$,so I can see one of the inclusions, but I don't see why $G \subset \coprod gen(C)$, maybe I am not understanding what $gen(C)$ is, I interpret it as $gen(C)=\{g \in G : <g>=C\}$, if $c \in C$, then $c=g^k$ for some $k$, but this doesn't imply that $c \in \{g \in G : <g>=C\}$, so what $gen(C)$ is as a set?
I hope it is clear what my doubt is, I would appreciate if someone could clear this up to me.
Comment: $\operatorname{gen} (C)$ is the set of generators of the subgroup $C$ of $G$. Since every element of $G$ generates some (cyclic) subgroup of $C$, you have $G \subset \coprod_{C \leqslant G} \operatorname{gen} (C)$.
Answer: Probably gives that proof because the book is on group theory.
A function $f$ from the positive integers to the positive integers (or to any semigroup, really) is called multiplicative if $\gcd(a,b)=1$ implies
$f(ab) = f(a) f(b).$
Given any such $f,$ one may prove without trouble that
$$g(n) = \sum_{d|n} f(d)$$ is multiplicative in the same sense. As a result, it suffices to check any relation on primes and prime powers.
$$ 1 + (p-1) = p,  $$
$$ 1 + (p-1) + (p^2 - p) = p^2,  $$
$$ 1 + (p-1) + (p^2 - p)  + (p^3 - p^2)= p^3,  $$
and so on.
Answer: It might be the case Rotman means to consider the set of generators of subgroups of $G$. Let me give an example. Take the group $C_{21}=\{1,\ldots,g^{20}\}$. The generators of the trivial groups are $1$, of the cyclic subgroup of size $7$, $g^k$ such that $k<21$ and $21/(k,21)=7$, i.e. such that $(k,21)=3$, i.e. such that $(k,7)=1$ and $3\mid k$. These are $g^3,g^6,g^9,g^{12},g^{15},g^{18}$. The generators of the cyclic subgroup of size $3$ are similarily those $k<21$ such that $(k,3)=1$ and $7\mid k$, so $g^7,g^{14}$, and finally the generators of $G$ itself which are $g,g^2,g^4,g^5,g^8,g^{10},g^{11},g^{13},g^{16},g^{17},g^{19},g^{20}$.
The tally is thus that $$21=1+2+6+12=\varphi(21/21)+\varphi(21/7)+\varphi(21/3)+\varphi(21/1)$$
The point here is that for $C_n$; the cyclic subgroup of order $d\mid n$ has exactly $\varphi(n/d)$ generators.


Inferential statistics on census data when response rate low

Question: I have read the comments about inferential statistics  on census data. I am doing PhD and also facing the same problem with a little difference.
I have collected census data from the population of deans, directors,chairpersons and head of departments because of lack of availability on their part and can get about 64 % response rate.
can i take this 64% response as my sample and by  applying inferential statistics eg t test and One way ANOVA draw conclusion regarding  mean difference on the basis of gender, age, experience, administrative posts and generalize the results on the whole population. iif it is so then please send me the reference of its justification so that i can defend this conceptual point in my phD thesis. i have been trying a lot but can not find the reference. please is there any one who can help me i shall appreciate and acknowledge it in my dissertation.
Answer: You are "allowed" to do this. The problem is trying to justify that the 64% who responded are a random sample of the population. (This is the same problem as with all sampling).
While 64% is a pretty good response rate, compared with a lot of studies, the results could nevertheless be very misleading if there is bias.
If you have any information on the 36% who did not respond, you can use that to compare with the 64% who did. That doesn't eliminate the possibility of bias, but it does go some way towards limiting it.
Comment: Sir I have to use it in my phD thesis. I cant do any thing without reference. would you please give me a hint where i can find its reference so that i can quote and defend it before my thesis cometti
Comment: I don't have a specific reference in mind. Sorry.
Comment: @sadaf: A common technique is to approach *some* of the 36% of non-responders & cajole/bribe/menace them into responding - resource constraints won't allow you do this for *all*, but you then have a sample from the non-responder group - it's a way of getting the information on them that Peter mentioned


Choice of hyper-parameters for Recursive Feature Elimination (SVM)

Question: Suppose that I am interested in applying Recursive Feature Elimination (such as RFE() in sklearn), and my data set is of medium size, with $n>p$, where $p$ is the number of features. Let's say I have reason to believe that the data is relatively noisy, and I believe that feature selection may improve classification accuracy.
If I wanted to implement RFE with a support vector classifier (say SVC() with a linear kernal), the model must be trained, then passed to RFE(), which then can find a subset of the features to use in the final model.  Then, do we retrain the SVC on the dataset using the subset of the features? So my question:
Is this the correct interpretation? If so, then how do we address the tuning of hyperparameters within the model? (Linear) SVC's use the parameter $C$ to control the amount of regularization which can drastically affect the bias/variance tradeoff. Thus, do we optimize $C$ first, then pass the model to RFE(), derive best subset feature selection, then fit the same model on the subsetted features? Or do we choose an arbitrary $C$ (say 1), pass to RFE(), then train and tune a final model on the remaining features? Of course, all tuning is being done with cross-validation in this scenario.
The former option seems more correct to me, but I also think that we are missing out on some possible improvements in accuracy by not tuning the model again on the subset of the features. (Perhaps two tunings? Before RFE and after RFE?)
Can we generalize this procedure to other classifiers? What about if an $l_1$ penalty is available?
Answer: I will answer my own question for posterity.
In the excellent book Applied Predictive Modeling by Kjell Johnson and Max Kuhn, the RFE algorithm is stated very clearly. It is not stated so clearly (in my opinion) in Guyon et al's  original paper. Here it is:

Apparently, the correct procedure is to fully tune and train your model on the original data set, then (using the model) calculate the importances of the variables. Remove $k$ of them, then retrain and tune the model on the feature subset and repeat the process.
I am a python user, so I will speak to that: if you are using sklearn's RFE or RFECV function, this form of the algorithm is not done. Instead, you pass a model (presumably already tuned), and the entire RFE algorithm is performed with that model. While I can offer no formal proof, I suspect that if you use the same model for RFE selection, you will likely overfit your data, and so care should probably be taken when using sklearn's RFE or RFECV functions out of the box. Though, since RFECV does indeed perform cross-validation, it is likely the better choice.
As to whether RFE should be done with an $l_1$ penalty in the model -- I don't know. My anecdotal evidence was that, upon trying this, my model (a linear support vector classifier) did not generalize well. However, this was for a particular data set with some problems. Take that statement with a large spoon of salt.
I will update this post if I learn more.


Beginner - How can I illustrate that an operation should yield null if negative.

Question: The problem I'm having that may or may not have a solution is trying to find a way of ensuring that if $x < 0$ then $x := 0$.
Just like you could ensure that if $x < 0$ then $x := -x$ with $\sqrt[2]{x^2}$ or $|x|$
Thanks for the help guys, really appreciate it.
Comment: If you explain what the formula is about, your chance for getting an answer is higher.
Comment: Thanks for the suggestion, but I'm not sure it's relevant here (actually worried if would be more confusing than anything). I've changed the question around to make things clearer.
Comment: Same question but I did completely rewrite it to keep things as simple and clear as possible.
Comment: Multiply by the indicator function $1[x > 0]$?
Comment: Thanks I'll look into that. I've been playing around and wondering.. Would $\frac{x+|x|}{2}$ work?
Comment: Yeah, that'll do. It's hard to recognise, though - a mathematician would more readily understand multiplying by the indicator function.
Comment: Ok great thanks. And what are the differences in notation? I'm kind of unclear. Is $1_{[x > 0]}$  equivalent to defining cases for $1_A(x)$ and then writing $1_{[0,+\infty)}(x)$ ?
Comment: The notation $x^+:=\max\{x,0\}$ and $x^-:=\max\{-x,0\}$ is quite common. One then has $x=x^+ -x^-$ and $|x|=x^+ + x^-$.
Comment: great thanks I'll add that to the answer.
Answer: Thanks to @patrick-stevens for his help.
If you want to convey that $x := 0$ if $x < 0$ then you can either use the indicator function :
$$ x \mathbb{1}_{x \geq 0}$$

An indicator function or a characteristic function is a function defined
  on a set X that indicates membership of an element in a subset A of X,
  having the value 1 for all elements of A and the value 0 for all
  elements of X not in A. - Wiki

Or as per @christian-blatter's comment the following notation:
$$x^+$$

The notation $x^+:= max \{x,0\}$ and $x^−:=max \{−x,0\}$ is quite common.
  One then has $x=x^+−x^−$ and $|x|=x^++x^−$.

Or if you need to programmatically calculate $x$ you can use:
$$x :=\frac{x+|x|}{2}$$


Functions continuous in each variable

Question: Suppose we have a map $f:X \times Y \rightarrow Z$, where $X,Y$, and $Z$ are topological spaces. Are there any conditions on $X$,$Y$, and $Z$ that would allow one to determine that $F$ is continuous if it was known that it was continuous in each variable? It seems like there should be a theorem related to this.
By definition, a  path homotopy $F: X \times I \rightarrow Y$ is continuous. What results in algebraic topology would not hold if we only required the map to be continuous in each variable? Would path homotopies not necessarily generate the fundamental group?
Comment: Even in the nice case $X=Y = \mathbb R$ the continuity in each variable is not sufficient for the continuity as a function of two variables - the same will hold if you take $X=Y=[0,1]$.
Comment: f(x,y)=$ \frac{2xy}{x^2+y^2}; f(0,0)=0 $is a standard counterexample; continuous for each of x,y separately , but not continuous (check the limit at $(0,0)$ , e.g., along the direction y=x ). You may have to use sequential continuity ( if you have first-countability), or just the "old-fashioned" way, by showing that the inverse image under f of an open set in Z is open in the product topology of $X \times Y \$
Answer: Letting $S^1=\{z\in\mathbb{C}\colon\vert z\vert=1\}$ be the unit circle, consider the map $F\colon S^1\times I\to S^1$ given by
$$
F(e^{2\pi\theta i},s) = e^{2\pi\theta^si}
$$
for $0 < \theta\le 1$ and $s\in I$. Then $F$ is continuous in each variable, $F(z,1)=z$ and $F(z,0)=1$. So, if you only required continuity in the individual variables, the circle would be contractible. More generally, every topological space would have trivial fundamental group. Suppose that $X$ is a topological space and $\gamma\colon I\to X$ is a closed curve. Define $F\colon I\times I\to X$ by $F(x,s)=\gamma(x^s)$ for $x,s\in I$ and $s > 0$, and $F(x,0)=\gamma(0)=\gamma(1)$. Then $\gamma$ is null-homotopic (relative to ${0,1}$). So, the fundamental group collapses to the trivial group, as do all the higher homotopy groups.
Comment: There's a nice paper in the Math Monthly about this idea: Deloup, Florian "The fundamental group of the circle is trivial." Amer. Math. Monthly 112 (2005), no. 5, 417–425
Answer: As is the case with two others who have responded (at the time I wrote this), I don't have an answer to your specific questions (conditions on $X$, $Y$, and $Z$; homotopy analogs for separately continuous maps). However, Piotrowski's 1996 survey paper or my 2005 sci.math post (which contains some references not given in Piotrowski's paper -- [2], [4], and [6]) might have something of interest to you or lead you to a relevant reference.
Zbigniew Piotrowski, "The genesis of separate versus joint continuity", Tatra Mountains Mathematical Publications 8 (1996), 113-126. [MR 98j:01026; Zbl 914.01007]
http://people.ysu.edu/~zpiotrowski/papers/genesisseperatevsjoint.pdf
sci.math -- "Continuity in each variable vs. joint continuity" (4 June 2005)
http://groups.google.com/group/sci.math/msg/a1b3752adec7650e

Functions continuous in each variable


Find unique polynomial of deg $d$ s.t $(P(0), P(\frac{1}{d}), P(\frac{2}{d}), \ldots,P(1)) = a\forall a \in \mathbb{R}^{d+1}$

Question: Let $T:\mathcal{P}_d(\mathbb{R})$ be the set of polynomials of degree max $d$ and with coefficients in $\mathbb{R}$.
We define the linear map$$ T:\mathcal{P}_d(\mathbb{R})\to \mathbb{R}^{d+1} $$
$$P \mapsto (P(0), P(\frac{1}{d}), P(\frac{2}{d}), \ldots,P(1)) $$
I want to show that there exists a unique polynomial $P$ such that $T(P) = (a_0,\ldots , a_i)$ for any $(a_0,\ldots , a_i) \in \mathbb{R}^{d+1}$
I.e $P(\frac{i}{d}) = a_i$
I tried to take general polynomials of degree $2$ and $3$ and solve for the coefficients of the general polynomial
$$ \sum_{i=0}^{d} \lambda_ix^i, \lambda_i \in \mathbb{R} \text{ for } i = 0,\ldots, d$$
But I can't seem to figure out the pattern.
It it clear (?) that $a_0= \lambda_1 \text{ and } a_d =  \sum_{i=0}^{d} \lambda_i$ but what about $a_1,\ldots, a_{d-1} $ ?
Sorry for the minimal effort shown here but I find this problem quite challenging.
Comment: The set of polynomials with degree less than or equal to $d$ with coefficients in $\mathbb{R}$ is usually denoted by $\mathbb{R}[x]_{\leq d}$
Comment: @vrugtehagel Yeah, sorry about that. My lecturer seems to prefer $\mathcal{P}_d(K)$, where $K$ is a field, for some unknown reason and I just copied the problem.
Comment: Ah, right. As you noticed, this problem is closely related to linear algebra. You have a set of $d+1$ equations with $d+1$ unknowns - is your question to prove that such system has one unique solution?
Answer: You want to show, that the map is bijective. It is a linear map of finite-dimensional vector-spaces of the same dimension. Hence it suffices to show that kernel is trivial. However the kernel consists of polynomials of degree $d$ with at least $d+1$ zeros...
Comment: That did it! I was looking at the problem at a weird angle. got it Thank you so much!


Firebase messaging error: Topic is malformed

Question: I have been facing for some time the Malformed error on the firebase topic, inside a firebase Message.
When I try to create a firebase push notification, and I add the topic condition, it fails.
I can not find other questions solving my case.
I have been following this documentation
This is my topic string example:
"'165' in topics || '16' in topics || '166' in topics || '15' in topics || '7' in topics"
I am not sure what could be wrong there.
This is my message construction code:
 new Message()
    {
        Data = new Dictionary<string, string>
        {

            ["Sound"] = SoundName,
            ["UseSound"] = string.IsNullOrWhiteSpace(SoundName) ? "false" : "true",

        },
        Notification = new Notification
        {
            Title = $"{Interest.ToTitleCase()}Update",
            Body = Title
        },
        // Next line I think, its where the error is.
        Topic = string.Join(" || ", Tags.Select(t => $"'{t}' in topics"))
    };

Answer: After one day I suddenly paid more attention and discovered that, in order to get a condition worker, I should have use the Condition property instead of Topic .
new Message()
    {
        Data = new Dictionary<string, string>
    {

        ["Sound"] = SoundName,
        ["UseSound"] = string.IsNullOrWhiteSpace(SoundName) ? "false" : "true",

    },
    Notification = new Notification
    {
        Title = $"{Interest.ToTitleCase()}Update",
        Body = Title
    },
    // Condition instead of Topic.
    Condition = string.Join(" || ", Tags.Select(t => $"'{t}' in topics"))
};


Como evitar o NoClassDefFoundError?

Question: Estou desenvolvendo um projeto que tem muitas classes, e muitos arquivos .java, e de um tempo para cá, de vez em quando, esse problema acontece, aleatoriamente. Digamos: Uma classe que eu já usava, está funcionando perfeitamente, do nada se "rebela" e resolve dar esse erro.
Há uma maneira de "prever" e "evitar" esse erro, vendo que isso está aparecendo aleatoriamente no meu projeto?
Eu sei como resolver o problema via código (tanto que existem diversos tutoriais sobre isso), mas esse projeto vai ser usado em uma empresa, e eu não vou ter tempo de vir e corrigir isso toda vez que o sistema resolver se "rebelar".
Comment: NoClassDefFoundError acontece geralmente quando o ClassLoader não consegue ler uma classe informada. Basta dar uma certa atenção aos imports feitos, e bibliotecas de dependencia da aplicação estão corretamente declaradas no classPath, se as classes estiverem todas corretamente na aplicação, este erro dificilmente ocorrerá.
Comment: Como é que você resolve esse problema via código? Só para ver se eu entendi o que acontece.
Comment: Math, eu resolvo de uma maneira bem "tosca", não é bem em código, eu copio todo o conteúdo do arquivo que eu desejo "corrigir" (ctrl+a e ctrl+c), apago o arquivo, crio um novo com o mesmo nome e colo tudo de volta lá, ele volta a funcionar normalmente. diegofm, pelo que eu pesquisei, é exatamente o que você falou, mas acontece o seguinte, eu executo o código 1 vez para fazer testes, fecho o programa, quando abre de novo, ele já não funciona mais, é meio raro acontecer, mas ainda assim é chato quando acontece.
Comment: Como você está executando o programa? É a partir de uma IDE, console? A classe que apresenta problema fica dentro de um JAR?
Comment: estou utilizando a IDE netBeans, mas programando os componentes e afins na unha, as janelas são JDialogs e chamadas por botões, todos estão em .java, no momento estou utilizando apenas o "executar" do netbeans para testes, mas vou transferir para JAR quando o programa estiver concluído
Answer: Segundo a documentação oficial da Oracle sobre este erro :

Lançada se a Java Virtual Machine ou uma instância ClassLoader tenta carregar na definição de uma classe (como parte de uma chamada de método normal ou como parte da criação de uma nova instância usando a nova expressão) e nenhuma definição da classe pôde ser encontrado.
  A definição de classe procurada existia quando a classe atualmente em execução foi compilada,mas a definição não pode mais ser encontrado.

E caso querer dar uma olhada completa na documentação você pode ver aqui.
Ou seja,isso é causado quando há um arquivo de classe que seu código depende e está presente em tempo de compilação, mas não foi encontrado durante a execução. Olhe por diferenças de seu tempo de construção e o tempo de execução das classpaths.
Por que não usar try-catch e colocar o seu código  para sempre que for ocorrer este erro,arrumar ou pelo menos mostrar uma mensagem de erro ?
try
{
// Código que irá aparacer caso não ocorra nenhum erro.
}
catch (NoClassDefFoundError e)
{
// Procure olhar no seu código se está instanciando de forma correta.
}

Te aconselho a olhar os seguintes links para saber como resolver,por que eles ocorrem e como prevenir este erro :
http://javaeesupportpatterns.blogspot.com.br/2012/06/javalangnoclassdeffounderror-how-to.html
http://javaeesupportpatterns.blogspot.com.br/2012/06/javalangnoclassdeffounderror-how-to_15.html
http://javaeesupportpatterns.blogspot.com.br/2012/07/javalangnoclassdeffounderror-how-to.html
http://javaeesupportpatterns.blogspot.com.br/2012/08/javalangnoclassdeffounderror-parent.html
Comment: Valeu a ajuda, vou utilizar sua dica e do utluiz, qualquer coisa posto aqui! valeu!
Answer: O erro NoClassDefFoundError ocorre quando uma classe existe, mas o ClassLoader do Java não consegue carregá-la ou inicializá-la corretamente.
Isso pode ocorrer em várias situações, por exemplo:

Se você tem um bloco de inicialização estático ou atributo estático que lança alguma exceção, portanto a classe não é carregada.
Se a classe falha ao carregar uma classe importada por qualquer razão.

Dado que você está executando o código na sua IDE e resolve recriando a classe, o problema pode ser simplesmente que as classes existentes não estão sendo recompiladas na medida em que você faz alterações.
Primeiro, verifique se o NetBeans está configurado para compilar as classes ao salvar o arquivo.
Se não resolver, use a opção Clean and Build Project em todos os projetos envolvidos para forçar a recompilação do projeto.
Se ainda não resolver, verifique suas dependências. Se houver versões diferentes de bibliotecas no classpath, isso significa que você pode estar ora carregando uma versão ora outra versão e tendo erros aleatórios.
Comment: Obrigado a ajuda, vou arrumar aqui e ver se continua dando o erro, qualquer coisa posto aqui!

Como evitar o NoClassDefFoundError?


Likelihood ratio test for one sided test for two variances

Question: Let $X_{1}, \ldots, X_{n}$ be a random sample from $N\left(\mu_X, \sigma^{2}_X\right)$ and $Y_{1}, \ldots, Y_{m}$ be a random sample from $N\left(\mu_Y, \sigma^{2}_Y\right)$. Assume $\mu_X$ and $\mu_Y$ are known for simplicity. We would like to test $H_{0}: \sigma^2_X = \sigma_Y^2$ vs $H_{1}: \sigma^2_X > \sigma_Y^2$. How to derive a likelihood ratio test (LRT). Are there any references?
Comment: Google variations of 'Likelihood derivation of F test' to see online references. I don't know the exact level of your course, but one promising possibility is [this](http://users.stat.umn.edu/~sandy/courses/8311/handouts/ch06.pdf) around p111. Be sure to put 'Likelihood ratio' in the search and look for class notes from major universities. // Suggest for this level, you should flee at the first sign of ads or a video.
Comment: Does this answer your question? [Likelihood Ratio Test for Common Variance from Two Normal Distribution Samples](https://stats.stackexchange.com/questions/541681/likelihood-ratio-test-for-common-variance-from-two-normal-distribution-samples)
Answer: Comment. I won't do the theoretical part. However, sometimes it helps to see a likelihood test in action
when trying to interpret the results of the ratio to get the
test statistic and the critical value.
So here is R output with some remarks:
Fictitious two-sample data with sample variances and their F-ratio:
set.seed(2021)
x1 = rnorm(20, 50, 7);  x2 = rnorm(40, 100, 15)

var(x1); var(x2)
[1] 58.0856
[1] 252.5335
var(x1)/var(x2)
[1] 0.2300114

Output from test of $H_0: \sigma_1^2/\sigma_2^2= 1$ against one-sided alternative
$H_a: \sigma_1^2/\sigma_2^2 < 1.$ Note: your test is right-tailed, mine is left-tailed.
var.test(x1, x2, alt="less")

        F test to compare two variances

data:  x1 and x2
F = 0.23001, num df = 19, denom df = 39, p-value = 0.0005719
alternative hypothesis:
 true ratio of variances is less than 1
95 percent confidence interval:
 0.0000000 0.4669059
sample estimates:
ratio of variances
         0.2300114

Critical value. Reject $H_0$  at the 5% level if the F-ratio is smaller than critical value $c = 0.4926,$
shown as a dotted red line in the figure below.
qf(.05, 19, 39)
[1] 0.4926291

Note: Usually, the likelihood
ratio makes it clear what test statistic to use, and whether to reject for
large or small values of the test statistic. However, you need to identify the
distribution of the test statistic and use printed tables or software to
find the numerical value of the critical value.
The observed value of the F-statistic is 0.2300, shown as a solid black line in the figure.
The P-value of the test
is the area under the density curve to the left of the solid black line.
Ordinarily, you cannot find exact P-values by looking at printed tables.
(P-values are 'creatures' of the computer age.)
pf(0.230, 19, 39)
[1] 0.0005717457  # agrees with printout up to rounding error

R code to make the figure above:
hdr = "Density of F(10,30)"
curve(df(x, 19, 39), 0, 3, lwd=2, col="blue",
         ylab="Density", xlab="F", main=hdr)
 abline(h=0, col="green2")
 abline(v=0, col="green2")
 abline(v = 0.4926, col="red", lwd=2, lty="dotted")
 ab;ine(v = 0.230, lwd = 2)

Using printed tables. For a right sided test at the 5% level, the critical value will be in the right tail
of the distribution $\mathsf{F}(19, 39)$ at $2.0960.$ You should be
able to find this value is a printed table of F-distributions. [Maybe you'll have to approximate, using degrees of freedom 20 and 40, if 19 and 39 are left out
to save space.]
qf(.95, 19, 39)
[1] 2.095977

By contrast, the left-sided critical value is not shown in many printed F-tables. But it is easy to get in R.
qf(.05, 19, 39)
[1] 0.4926291

Note: To get a left-sided critical value from tables you may have to take the reciprocal of a value
from a printed table, with the degrees of freedom reversed.
qf(.05, 19, 39)
[1] 0.4926291      # not available in some printed tables
1/qf(.95, 39, 19)  # DF reverse: available in table
[1] 0.4926291      # ... reciprocal of available value

One reason I'm showing a left-sided test is to have motivation to show you this identity.
Comment: Maybe the answer should also show, the derivation of the likelihood-rato-test, and show why the F-test is equivalent to a likelihood ratio test.
Comment: I guess that would  require showing the LR test in detail, which I chose to leave for OP. But it is done in the reference in my comment.


Evaluating $ \int \frac1{5S_{8} - 9S_{10} + 7S_{12} - 2S_{14}} {\rm d}x$, where $S_n = \sin^n(x) + \cos^n(x)$

Question:
Prove that
$$ \int \frac1{5S_{8} - 9S_{10} + 7S_{12} - 2S_{14}} {\rm d}x = 2x - \arctan \left( \frac{\tan2x}{2 + \tan^22x} \right) + C$$
where $S_n = \sin^n(x) + \cos^n(x)$.

Even differentiating the right doesn't end up with anything close to that monster integrand.
$$ \frac{{\rm d}}{{\rm d}x} \left( 2x - \arctan \left( \frac{\tan2x}{2 + \tan^22x} \right) + C \right)
\\ = 2 + \frac{(\tan^22x+1)(2\tan^22x-4)}{\tan^42x+5\tan^22x+4}
\\ = \frac{ 4 } {\sin^42x+ 5\sin^22x\cos^22x + 4\cos^42x}
\\ = \frac1{\sin^8x + \sin^2x\cos^6x +\cos^2x\sin^6x + \cos^8x} $$
Comment: $S_0=2,S_2=1$

$$S_{m+2}=\sin^mx(1-\cos^2x)+\cos^mx(1-\sin^2x)=S_m-\sin^2x\cos^2xS_{m-2}$$
Comment: The denominator in your final expression is $S_6$
Answer: Let $c=\cos2x$. Then applying the double angle identities,
$$\sin^2x=\frac{1-\cos2x}2,\quad\cos^2x=\frac{1+\cos2x}2,$$
to each occurrence of $\sin^nx$ and $\cos^nx$, we get
$$\begin{cases}
S_8=2^{-3}(1+6c^2+c^4)\\
S_{10}=2^{-4}(1+10c^2+5c^4)\\
S_{12}=2^{-5}(1+15c^2+15c^4+c^6)\\
S_{14}=2^{-6}(1+21c^2+35c^4+7c^6)
\end{cases}$$
Combining these expressions to match the denominator of the integrand, we find that it reduces to
$$5S_8-9S_{10}+7S_{12}-2S_{14}=2^{-2}(1+3c^2)$$
so that
$$\int\frac{\mathrm dx}{5S_8-9S_{10}+7S_{12}-2S_{14}}=\int\frac4{1+3\cos^22x}\,\mathrm dx=\int\frac8{5+3\cos4x}\,\mathrm dx$$
The antiderivative is $-\arctan(2\cot2x)+C$, which I don't think should be too hard to reconcile with the given solution.
Comment: The pure elegance and beauty of this answer is incredible. I commend you with a meaningless upvote.


How many sounds do we have In beatbox?

Question: I'm curious to learn more about beatboxing. Can you please enlighten me by sharing how many distinct sounds are typically incorporated in beatboxing?
Comment: I'm voting to close this question as a combo of various close-reasons: somewhat opinion-based, too broad to answer definitively, and list-based.
Comment: Hi! Please check out [this help page about 'subjective' answers](https://music.stackexchange.com/help/dont-ask). This question suffers a bit from open-endedness ("share whatever thoughts you might have") and from attempting to make a definitive list of something that isn't definitive (one clue is that your own answer says "there is no definitive answer"). If you search the [meta section for 'list'](https://music.meta.stackexchange.com/search?q=list) you'll find we also have a policy against questions for which the answer is simply a list of items....
Comment: ... because they can be, like this one, impossible to draw hard boundaries around; or (like "list all of Beethoven's piano sonatas") lack any extra useful info.
Comment: @AndyBonner I did a research about all beatbox sounds I collected them in a list I can estimate the amount of sounds.If it's ok I can Improve my answer.
Comment: @AndyBonner every sound in beatbox has many variations.If I don't consider it I can tell you the estimated number.
Comment: It is interesting that lying is not a reason to close. "I'm curious to learn more about beatboxing" sounds quite dishonest when it's immediately answered by the same person spamming their own website.
Comment: @ojs I wouldn't go so far to call it lying- asking a question to answer it yourself is allowed and even encouraged, and it's hard to ask the question without pretending you don't already know the answer.  It's still a poorly formed question with the goal of sharing the creator's website either way.
Answer: There is no definitive answer to the exact number of beatbox sounds, as beatboxing is a creative and evolving art form that allows for endless possibilities. However, there are several common beatbox sounds and techniques that are widely recognized and used by beatboxers. Here are some of the popular beatbox sounds:

Kick drum: Mimicking the sound of a bass drum.
Snare drum: Simulating the sound of a snare drum hit.
Hi-hat: Replicating the sound of an open or closed hi-hat cymbal.

These are just a few examples, and beatboxers continue to explore and innovate to create new sounds and techniques. With experimentation and practice, beatboxers can develop their unique style and incorporate a wide variety of sounds into their performances.
Human Beatbox Sounds

I couldn't find a website with audio samples that mentioned all the sounds, so I created it myself.
All Beatbox Sounds

Update
I apologize for any confusion caused by my previous response. I want to clarify that I did not intend to promote my own website. However, I did come across a PDF file that provides information on beatboxing sounds, specifically mentioning that there are 544 documented sounds. Beatboxing is an ever-evolving art form with a wide range of techniques and possibilities.
Beatbox Sound.pdf
Comment: It bothers me that in answer to a really far too broad question, the answer is basically just a plug for your own web site.

How many sounds do we have In beatbox?


Possível problema de permissão

Question: Ao tentando rodar um código de php na minha máquina Ubuntu
if ( ! is_dir($system_path))
{
    header('HTTP/1.1 503 Service Unavailable.', TRUE, 503);
    echo 'Your system folder path does not appear to be set correctly. Please open the following file and correct this: '.pathinfo(__FILE__, PATHINFO_BASENAME);
    exit(3); // EXIT_CONFIG
}

Ele está apresentando erro:
Percebo que pode ser erro de permissão ma minha maquina, já tentei seguir este tutorial:
http://fideloper.com/user-group-permissions-chmod-apache
Mas ao executar segundo comando: $ chmod go+x /var/www meu Ubuntu apresenta a seguinte mensagem de erro:
chmod: alterando permissões de "/var/www": Operação não permitida

Alguma dica do que pode ser?
Comment: Já deu permissão de leitura para todos os diretórios do grupo `www-data`: `sudo chown www-data:www-data -R *`. E depois incluiu seu usuário ao grupo root.www-data  algo como `sudo chown seu_user.www-data ` ?
Comment: para modificar permissões de diretórios do sistema você deve executar o comando como *root*, utilize `sudo chmod ...`
Comment: @IvanFerrer Meu usuário já estava no grupo de www-data, mas não tinha rodado ainda o comando de dar permissão de leitura para todos os diretórios do grupo www-data. Mesmo executando agora, não resolveu.
Comment: @Sanção, sim eu já executo os comandos com o sudo... valeu
Comment: Com `print_r($system_path); die();` o que aparece na página?
Comment: tentou: 'sudo chmod 775 -R /var/www' ? para alterar permissões é preciso entrar com sudo
Comment: Faça `sudo chmod 0755 /var/www`, deve ser o suficiente.
Answer: Se fores admin da maquina faz
sudo chmod go+x /var/www

Vai-te pedir a pw e executa depois.
Comment: Executei este comando, nada, ele continua não conseguindo ter a permissão necessária.

Possível problema de permissão


In the Key of C major what would an F# major chord be?

Question: Roman Numeral Analysis
G   F#    F   all major chords
Comment: Is the F# just a short, passing chord between the G and the F?
Comment: G=V; F#=#IV, F=IV, assuming key C. That works for me, and is clear. Suppose it could be V/VII but why bother?
Comment: Basically, and honestly I'd just call it a V-#IV-IV. Wikepedia calls it a Chromatic Passing chord. I see lead sheets but know figured bass for that chord.
Comment: I know right. Or you could say your borrowing the C lydian mode the IV which would be F#major. I know in lydian mode The VII is minor, beautiful mode.
Answer: V, #IV, IV.   Or maybe neater as V, bV, IV.   Chromatic runs often use flats coming down, sharps going up.    I don't think you need to look for functional significance in this bit of 'planing'.
Answer: Roman numerals have a functional meaning. As such, #IV and bV, while literally accurate, "don't exist" in Roman numeral (functional) analysis. They would be given other numerals based on their functional role.
In C major, given no other context, G F# F would be interpreted as G Gb F, because while F# has no functional role in C major (or F major or G major), Gb does have a roll in F major, the target of the progression: it's the bII or "Neapolitan" chord, whose job it is to resolve down by half step.
Interpretation #1

Thinking in terms of F, the IV chord in C major, the Roman numeral analysis would be V bII/IV IV.

Interpretation #2

However, in functional analysis (Roman numeral analysis), moving from V to IV is unusual at best. Instead, an interpretation in G major (the V chord in C major) could be considered: V bII/bVII/V bVII/V.


SMS com link do GoogleMaps não é enviado

Question: Trabalho com envio de SMS com o link do GoogleMaps, mas em alguns casos, o telefone não envia, não consigo saber o motivo, outros links são enviados normalmente.
Segue a imagem da mensagem:

Gostaria de uma ajuda para resolver esta questão. E, importante, a idéia de utilizar o SMS é para não ser obrigatório a internet.
Segue o código que utilizo para a geração:
<code>String uri = "http://maps.google.com/maps?q=" + latitude + "," + longitude;
    if (!preferences.getNumber(activity).equals("")) {
        smsBody.append(Uri.parse(uri));
        String telefone1 = preferences.getNumber(activity);
        try {
            smsManager.sendTextMessage(telefone1, null, msgASerEnviada, null, null);
            smsManager.sendTextMessage(telefone1, null, smsBody.toString(), null, null);//mensagem com o link
            Toast.makeText(activity, "Mensagem enviada para " + telefone1, Toast.LENGTH_SHORT).show();
        } catch (Exception e) {
            e.printStackTrace();
            Toast.makeText(activity, "Há algo errado, por favor verifique o número enviado", Toast.LENGTH_SHORT);
        }
    }//Na edição foi adicionada mais uma barra.
</code>
Answer: Solved by removing the http: //


NativeScript Sidekick: "No matching version found for email@example.com"

Question: After installing AndroidStudio, I could start the Android Emulator Nexus 5X, but when trying to run my NativeScript project in Sidekick, I get "Error detected during LiveSync on emulator-5554: No matching version found for email@example.com". Has anyone an idea where this could come from? Thank you!
Answer: I had to set a current version (5.3.1) in package.json, then it worked.
<code>"nativescript": {
    "id": "otp.kis.mobile",
    "tns-android": {
      "version": "5.3.1"
    },
    "tns-ios": {
      "version": "0.0.1"
    }
  },
</code>

NativeScript Sidekick: "No matching version found for tns-android@0.0.1"


Flutter - using same provider for updating dropdown and sending to data to another widget

Question: I want to pass selected value from DropDown to its parent and then to child through constructor, after that update list by setState functions.
So, I want selected value from Dropdown be accessible in child of Restrictions (UserOffers).
Sending data from parent to child its actually working, but only when im passing data definied in parent class to child by constructor = im not sure if its a good way.
Now i am using provider to update data on Dropdown only, but i dont know how to pass it.
CountryProvider class:
class CountryProvider with ChangeNotifier {
  List<String> _items = [
    "Argentina",
    "Brazil",
    ...
   "Spain",
    "Switzerland",
  ];

  String _selectedItem;

  List<String> get items => _items;

  String get selected => _selectedItem;

  void setSelectedItem(String s) {
    _selectedItem = s;
    notifyListeners();
  }
}

CountryDropDown class:
class CountryDropDown extends StatefulWidget {
  @override
  _CountryDropDownState createState() => _CountryDropDownState();
}
class _CountryDropDownState extends State<CountryDropDown> {
  @override
  void initState() {
    super.initState();
  }
...
          ChangeNotifierProvider<CountryProvider>(
            create: (context) => CountryProvider(),
            child: Container(
              width: 215,
              child: Consumer<CountryProvider>(
                builder: (_, provider, __) {
                  return DropdownButton<String>(
                    hint: Text("Not selected"),
                    icon: Icon(Icons.flight),
                    value: dropdownValue,
                    onChanged: (String newValue) {
                      provider.setSelectedItem(newValue);
                      dropdownValue = provider.selected;
                      print(newValue);
                    },
                    items: provider.items
                        .map<DropdownMenuItem<String>>((String value) {
                      return DropdownMenuItem<String>(
                        value: value,
                        child: Text(value),
                      );
                    }).toList(),
                  );
...

And parent:
Restrictions class:
class Restrictions extends StatefulWidget {
  @override
  _RestrictionsState createState() => _RestrictionsState();
}

class _RestrictionsState extends State<Restrictions> {
  @override
  void initState() {
    super.initState();
  }
...
Column(
                  children: <Widget>[
                    Container(
                      margin: EdgeInsets.only(left: 20),
                      child: FieldDropDown(),
                    ),
                    Container(
                      padding: EdgeInsets.only(top: 10),
                      margin: EdgeInsets.only(left: 20),
                      child: CountryDropDown(),
                    ),
                  ],
                ),
                Container(
                  child: DateSelector(),
                ),
              ],
            ),
            Container(
              child: UserOffers(
                country: selectedCountry,
                field: selectedField,
              ),
...

Answer: @Boras ! You made a lot of work for me with all the ....
I think you need to lift state higher up the widget tree so that UserOffers can change when the user selects a country from the drop down menu.
Complete example app below.
Note that I changed the model class name to SingleSelectCountry. An instance of that model class is not a provider. An instance of that model class is what is being provided by a provider. There's an important distinction there.
Note also that all the widgets extend StatelessWidget. Often with package provider you can avoid using StatefulWidget.
import 'dart:collection';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';

// Model ---------------------------------------------------

class SingleSelectCountry with ChangeNotifier {
  final List<String> _items = <String>[
    "Argentina",
    "Belgium",
    "Brazil",
    "Denmark",
    "England",
    "France",
    "Finland",
    "Germany",
    "Holland",
    "Ireland",
    "Norway",
    "Poland",
    "Scotland",
    "Spain",
    "Sweden",
    "Switzerland",
    "Wales",
  ];

  String _selectedItem;

  UnmodifiableListView<String> get items {
    return UnmodifiableListView(this._items);
  }

  String get selected {
    return this._selectedItem;
  }

  set selected(final String item) {
    this._selectedItem = item;
    this.notifyListeners();
  }
}

// User Interface ------------------------------------------

void main() {
  return runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(primarySwatch: Colors.blue),
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatelessWidget {
  @override
  Widget build(final BuildContext context) {
    // The provider has to be in the widget tree higher than
    // both `CountryDropDown` and `UserOffers`.
    return MultiProvider(
      providers: [
        ChangeNotifierProvider<SingleSelectCountry>(
          create: (final BuildContext context) {
            return SingleSelectCountry();
          },
        ),
      ],
      child: Scaffold(
        appBar: AppBar(
          title: Text('My Home Page'),
        ),
        body: Restrictions(),
      ),
    );
  }
}

class Restrictions extends StatelessWidget {
  @override
  Widget build(final BuildContext context) {
    return Column(
      children: <Widget>[
        CountryDropDown(),
        UserOffers(),
      ],
    );
  }
}

class CountryDropDown extends StatelessWidget {
  @override
  Widget build(final BuildContext context) {
    return Consumer<SingleSelectCountry>(
      builder: (
        final BuildContext context,
        final SingleSelectCountry singleSelectCountry,
        final Widget child,
      ) {
        return DropdownButton<String>(
          hint: const Text("Not selected"),
          icon: const Icon(Icons.flight),
          value: singleSelectCountry.selected,
          onChanged: (final String newValue) {
            singleSelectCountry.selected = newValue;
          },
          items: singleSelectCountry.items.map<DropdownMenuItem<String>>(
            (final String value) {
              return DropdownMenuItem<String>(
                value: value,
                child: Text(value),
              );
            },
          ).toList(),
        );
      },
    );
  }
}

class UserOffers extends StatelessWidget {
  @override
  Widget build(final BuildContext context) {
    return Consumer<SingleSelectCountry>(
      builder: (
        final BuildContext context,
        final SingleSelectCountry singleSelectCountry,
        final Widget child,
      ) {
        return Text(singleSelectCountry.selected ?? '');
      },
    );
  }
}

Comment: Wow thank you very much!! But is it possible to use more consumers? I need actualy four - one more dropdown and two from datepicker.
Comment: It is possible to use more consumers. You can have four model classes `with ChangeNotifier` and then nest four `Consumer` or you can use `Consumer4`. Another option is to use a single model class `with ChangeNotifier` with four members and then `Consume` it in each place that needs to be updated.
Comment: Thanks, it works, but now im struggling with implement it to DatePicker.
Answer:
Thanks, it works, but now im struggling with implement it to
DatePicker.

no need to use consumer for widget with ShowDatePicker
just make callback with smth like Provider.of(context, listen: false).setDate1(DateTime.now())


É possível criar uma coluna que receba o resultado de uma equação de outras colunas no postgresql?

Question: Eu tenho uma tabela que possui duas colunas VALOR e QDT. Quero criar uma coluna TOTAL que recebe VALOR * QDT. É possível fazer somente com SQL?
Comment: sim é possível usando colunas computadas, pode ler mais sobre isso aqui https://pt.stackoverflow.com/questions/514534/para-que-serve-a-estrutura-de-dados-virtual-no-dbeaver-ou-no-mysql/516720#516720  e na documentação: https://www.postgresql.org/docs/current/ddl-generated-columns.html
Answer: Conforme dito nos comentários, para criar a tabela com uma coluna computada:
CREATE TABLE tabela (
    valor numeric,
    qtd numeric,
    total numeric GENERATED ALWAYS AS (valor * qtd) STORED
);

Se a tabela já existir, basta alterar uma  para isso:
ALTER TABLE tabela
ADD COLUMN IF NOT EXISTS total numeric
GENERATED ALWAYS AS (tabela.valor * tabela.qtd) STORED;

Vale notar que há diversas restrições que se aplicam à definição de colunas geradas e tabelas envolvendo colunas geradas. As principais, mas vale a pena consultar a documentação oficial, estão listadas abaixo:

A expressão de geração só pode usar funções imutáveis e não pode usar subconsultas ou se referir a qualquer coisa além da linha atual de nenhuma maneira.

A expressão de geração não pode se referir a outra coluna gerada.

A expressão de geração não pode se referir a uma coluna de sistema, exceto tableoid.

A coluna gerada não pode ter uma definição padrão de coluna ou uma definição de identidade.

A coluna gerada não pode ser parte de uma chave de particionamento.
Comment: Olá Mansueli, tomei a liberdade de editar para que a resposta sirva para além do autor da pergunta (AP), assim servirá um pouco melhor para qualquer um que vier a buscar sobre como criar ou alterar. Eu estava a adicionar mais alguns detalhes, mas creio que isso você pode ter ideia melhor de como fazer, pois é importante citar que *colunas geradas* tem **diversas restrições**, e como a sua resposta pode atrair mais pessoas, por falta desses detalhes pode ser que seja melhor deixar claro isso na resposta, assim indo além do suporte pessoal. *Agradeço a compreensão*.
Comment: @GuilhermeNascimento `GENERATED ALWAYS AS (valor / total) STORED` não era pra ser `(valor * total)`? Só pra alinhar com a pergunta.
Comment: @CmteCardeal corrigido!


Extract certificate information using openssl

Question: I would like to verify the sender and 'addressee' certificate information of an encrypted/signed file. So far, I came up with the following set of arguments to openssl:
openssl cms -inform DER -cmsout -print -recip my.crt -in cms_file

This returns the following information:
CMS_ContentInfo:
  contentType: pkcs7-envelopedData (1.2.840.113522.214.171.124)
  d.envelopedData:
    version: 2
    originatorInfo:
...
            issuer: O=TheirCompany, CN=TheirCA
...
            subject: O=TheirCompany, CN=TheirEndpoint
...
    recipientInfos:
...
          issuer: O=TheirCompany, CN=TheirCA
...

So I've got most of the information I'm looking for, except the subject of the recipient. How do I extract this information?
Answer: I'm not sure you can do this, since the recipientInfos structure is not defined, e.g. per RFC 5652, to contain a certificate.  Keys, yes...but not certificates.
RFC 5652, Section 6.1 "EnvelopedData Type" specifies the structure of OriginatorInfo, which may contain a set of certificates.  Section 6.2 "ReicipientInfo Type" and subsections describe the structure of the possible RecipientInfo types; none of those types' structures contain certificates.  Thus it may not be possible, given the current structures, to achieve what you are looking for.