Standardizing single coefficient in multivariate analysis

Question: I have panel data and for the I have a following equation
$$
logY = \beta_1 +  \beta_2 logX +  \beta_3 m logW
$$
Problem is with $\beta_3$ coefficient. Since m is outside the log and it is a very small value, the overall $mlogW$ is very small and the resulting coefficient is very large (in thousands). One alternative would be to use standardization but my results change drastically if I standardize the variables. A solution I thought of was to multiply the variable with a constant such as 10000. So the new equation will become:
$$
logY = \beta_1 +  \beta_2 logX +  \beta_3 m logW*10000
$$
My question is, is this a right thing to do? It should only change the magnitude of the coefficients just for the sake of reporting the coefficients but actually it is changing how all the other coefficients behave when I multiply it say by 1000 or 10000.
Or is there a way to standardize the coefficients after estimation? since I have panel data, the division and multiplication with standard deviations seem complex.
Any idea how to make it work?
Thank you
Comment: Your results will not change at all by standardizing the variables. The fact that they do implies you are not actually standardizing them. I suspect--assuming that "$logX$" means $\log(X)$ and "$mlogW$" means $m\times\log(W)$--that you might have standardized $X$ and $W$. (It is unclear whether $m$ is a variable or a constant.) That drastically changes the entire model. The variables you might wish to standardize (although it will make no difference) are $\log(X)$ and $\log(W)$. What's the problem with large coefficients, anyway? Just use appropriate units of measurement to report them.
Comment: You need to understand "results" in terms of the estimated relationship between the independent and dependent variables.  *Standardizing will not change this.* (In fact, almost all regression software will automatically standardize the variables in order to do its calculations.) Because you changed *how you express the variables' values,* of course the estimated coefficients will change! Multiplying a variable by a constant merely changes the units by which you measure it. There's absolutely nothing wrong with that.
Comment: thank you for the quick response. $m$ is a share of imports to GDP so it is not a constant. Unfortunately, standardization IS changing my results alot. if I standardize $log(W)$ the very small number is $m$ will again make the variable very small and problem will persist. Problem with large coefficients is that the table looks very ugly. two coefficients around the value "1" and this one ranging from 4000 to 20000 in different models. Is multiplying a variable with a constant a serious crime?
Comment: "Multiplying a variable by a constant merely changes the units by which you measure it. There's absolutely nothing wrong with that"

exactly as I thought but significance levels are changing when I do that. which is very weird.
Comment: It sounds like you might need to share more details about what you are doing, then. But please note that if $m$ is one of your independent variables then the standardization also changes the interpretation of the coefficients: there's [a lot of discussion about that on this site.](http://stats.stackexchange.com/questions/86769/about-transforming-interaction)  Perhaps that answers your question?
Answer: Your question is, is this (multiplying  by a scalar) a right thing to do?
My answer is: Yes.
Multiplying by 1000 should not be changing the other coefficients, its a totally normal processes to multiply your predictors by any coefficient. Actually if you multiply a coefficient by 1000 you should see your coefficient decrease by a factor of .001 exactly.
An example is if I measured weight in kg and wanted to convert it to pounds I would multiply it by 2.2 and include that in the model. This would not change the R-squared or the fits of the other parameters at all. By multiplying by 2.2 we are not actually changing the correlations or relationship to the other variables in the model, they would still have the exact same correlation. If the other coefficients are changing you may have accidentally changed something else?
I am not aware of a way to scale parameters after fitting.
You could always try exploring the scale() function in R:
http://stat.ethz.ch/R-manual/R-patched/library/base/html/scale.html
Comment: thank you for your comment. The effect on other variables after this rescaling is not too big but the significance and sign of the coefficient itself changes dramatically if I multiply it by 10000 instead of 100000. Just to add one more thing (if that might help) I am using fully modified OLS for estimation of long run estimates of cointegrated equations.


Drush command to uninstall from enabled...?

Question: Is there a command for Drush so I can uninstall a module from the enabled state?  I hate having to drush dis mymod -y (and) drush pm-uninstall mymod -y
Comment: Drush pm-uninstall exists now. Just do drush pm-unistall module-name
Answer: Another solution here if you don't want to take the alias route that Tony brought up is to use the && operator to do a one-liner:
drush dis -y my_module && drush pm-uninstall -y my_module

Comment: This drush && works for me.
Comment: For Drupal 8 just uninstall: drush pm-uninstall -y my_module cause Drupal 8 does not support disabling modules.
Answer: No, drush was design so you would not uninstall an enabled module.  The same way Drupal was. You will have to create your own shell script to run these commands.
If you want to create your own drush command you should read this tutorial and this sample reference
Comment: @Ingacio can you include version # of Drush that now does this.
Comment: I don't think this is the case. I'm using 7.0-dev and it still prompts me to disabled before uninstalling the module.
Comment: This answer is not valid anymore. Just use drush pm-uninstall, just like pal4life said.
Comment: The tutorial link is broken, please update your answer.
Answer: I'm using Drush 6.2, and pm-uninstall does not appear to disable AND uninstall a module.  I thought I'd share another solution/alternative to creating a custom drush command.  I was searching for the exact same thing and discovered a method using aliases and a custom bash script.
Example:
drush uninstall module_name

In drushrc.php file, add:

$options['shell-aliases']['uninstall'] = '!drushu';

And create a script (add to your $PATH), called drushu with the following:
#!/bin/bash
drush dis $1 -y
drush pm-uninstall $1 -y

If in a multi-site environment, site aliases would likely be required.  Tested and works using the following...
Example:
drush @site-alias uninstall module_name

In drushrc.php file, add:

$options['shell-aliases']['uninstall'] = '!drushu {{@target}}';

And in the drushu script, add:
#!/bin/bash
drush $1 dis $2 -y
drush $1 pm-uninstall $2 -y


Add failure handling in AWS Firehose

Question: I am using Lambda to send batch messages to Redshift via Firehose. As per Firehose API docs, if there is some delivery issue (poisoned message,endpoints down etc), Firehose will keep trying for 24 hrs and delete the message. I would like to move failed message to another queue after X failed attempts  (essentially like SQS Redrive Policy). What's the best way to do this , preferably without cross-checking the target Redshift database ?
Answer: From your link, I am assuming you are interested in tracking failures to PutRecord to the Firehose Kinesis stream, and not the Kinesis -> S3 -> Redshift flow.
When you initialize your Firehose client, you can actually specify the number of retries you want to occur. When there's an exception received (failure to PutRecord to the stream), Firehose will automatically try up to the max retries you set; this is done under the hood, in the SDK, so you won't know that your retries have been exceeded until you get the exception bubbling up to your function. When you get this exception, you can assume that the retries have been exceeded. This exception handling can include sending the message to a SQS queue.
You can learn more about your Firehose client configuration here, it's not well known, but is very useful. Firehose ClientConfiguration.
Comment: I am looking for failures in Kinesis -> S3 -> Redshift flow. +1 for the client config link though..hope there's something similar in the python sdk .
Answer: This can be done quiet differently in the below way, not in a straight forward way from firehose.

You can have your lambda function call firehose which would write to S3.
Create kinesis analytics that reads from firehose.
Configure different streams upon kinesis analytics

Successful Records (In-stream) will move to a firehose which will be loaded into redshift.
Error Records (error-stream) will be loaded into a different firehose which will be loaded into S3.

You have successful records loaded into redshift and unsuccessful records filtered to S3.
This is an approach which we follow , let me know if you need any clarifications on this.

Add failure handling in AWS Firehose


initialization of 'char' from 'char *' makes integer from pointer without a cast

Question: I'm trying to anonymously create a struct using a couple variables and gcc, given the flag -Werror, won't compile the following:
char file_name[A1FS_NAME_MAX];
strcpy(file_name, strrchr(path, '/') + 1);
a1fs_dentry *new_dentry_ptr = (a1fs_dentry *) fs->data_table + last_extent->start * A1FS_BLOCK_SIZE + remaining_directory_entries * sizeof(a1fs_dentry);
*new_dentry_ptr = (a1fs_dentry) {
    .ino = (a1fs_ino_t) fs->first_free_inode_i,
    .name = file_name
};

where a1fs_dentry is defined as follows:
typedef struct a1fs_dentry {
    /** Inode number. */
    a1fs_ino_t ino;

    /** File name. A null-terminated string. */
    char name[A1FS_NAME_MAX];

} a1fs_dentry;

The warning causing it to fail is at .name = file_name. It also says error: missing braces around initializer. I tried casting file_name to a char array but it doesn't like that. My goal is to get it to where it doesn't give those warnings anymore.
Comment: You'd probably need to initialize with an empty/zero name, then strcpy into it instead of trying to assign the stack-allocated file_name into it...
Answer: This initialization of the compound literal in the statement below is invalid
*new_dentry_ptr = (a1fs_dentry) {
    .ino = (a1fs_ino_t) fs->first_free_inode_i,
    .name = file_name
};

You may not initialize the character array name with the expression file_name that is implicitly converted to a pointer when used as an initializer,
So instead of using the compound literal you should explicitly assign values to data members of the object pointed to by the pointer new_dentry_ptr and for the data member name use the standard string function strcpy as for example
strcpy( new_dentry_ptr->name, file_name );

initialization of ‘char’ from ‘char *’ makes integer from pointer without a cast


Como fazer esta requisição SQL com esta particularidade?

Question: Nesta busca quando o array retorna o 4 conforme a SQL demonstrada mais abaixo, eu preciso que o sistema retorna todos os resultado cujo a quantidade de dormitórios e >= 4. Podem me ajudar a chegar neste resultado.
Converti a coluna para INT. Tá feia a coisa na DB, não fui eu quem fiz, estava pronta.
# Selecionando conforme quantidade de dormitorios
$dormi = $_POST['dorm'];
if (isset($_POST['dorm']) && is_array($_POST['dorm']) && count($_POST['dorm']) > 0){

    $where .= " DORMITORIO IN (". implode(', ', $dormi).") AND ";
    if (in_array(4, $_POST['dorm'])){

        $where .= trim($where,' AND ').' OR DORMITORIO >= 4 AND ';

    }

}

Este é o SQL resutaldo desta busca:

SELECT * FROM imovel WHERE 1=1 AND DORMITORIO IN (1, 2, 3, 4)
Answer: Você precisa fazer uma rotina que gere:
SELECT * FROM imovel WHERE dormitorio >= 4

em vez de IN. Não faz o mínimo sentido usar IN neste caso.
Você pode definir os options do form como sendo 1,2,3 e 4, e usar uma array neste formato para gerar a query :
$opcoes = Array( '>= 0', '= 1', '= 2', '= 3', '>= 4' );

assim, basta fazer:
$dormi = 0 + @$_POST['dorm']; // A supressão é aceitável neste contexto
$dormi = $dormi>4 ? 4 : $dormi;
$opcoes = Array( '>= 0', '= 1', '= 2', '= 3', '>= 4' );

$where .= ' DORMITORIO '.$opcoes[$dormi];

e os resultados para 0, 1, 2, 3 e 4 serão respectivamente estes:
WHERE DORMITORIO >= 0
WHERE DORMITORIO = 1
WHERE DORMITORIO = 2
WHERE DORMITORIO = 3
WHERE DORMITORIO >= 4

Não deixa de ser um reparo técnico 1, então sugiro otimizar para o seu caso pratico.

1. Gambiarra
Comment: Talvez, mas é um tanto estranho alguém querer uma casa com 1 ou 4 dormitórios apenas... E olhe que eu já atendi uma série de imobiliárias. Mas vai saber né? :)
Comment: @Bacco , acho que ele envia essas dados com `checkbox`, onde pode ter várias opções selecionadas.
Comment: @MarcosVinicius claro, você deve fazer o que for conveniente. É que nestes casos geralmente o pessoal adota o mínimo (de 1 pra cima, de 2 pra cima, de 3 pra cima) pois quem procura 2, provavelmente vai aceitar uma casa com 3 quartos, mas não o inverso. No seu caso em específico, é claro que você deve fazer da melhor forma que agrade seu cliente.
Comment: Ai a query fica mais simples ainda, nao precisa do array. `WHERE DORMITORIO > '.(0+@$_POST['dorm']);` (Usei o melhor do estilo **[XGH](http://goo.gl/lZ37UE)** pra bolar esse código do comment :D )
Comment: Pois é, rs... Aqui tem outra pergunta dele, acho que é do mesmo sistema. http://pt.stackoverflow.com/questions/31319/como-enviar-dados-de-checkbox-para-uma-consulta-com-mysql
Comment: @Bacco pode ser estranho quem está procurando 1 quarto procurar por 4 ao mesmo tempo mas não é tão estranho procurar por 3 e 4. E se eu colocar `>=4` elimino 75% dos imóveis da busca pois estes são de 3 quartos pelo menos neste sistema.
Comment: Tem extrema lógica o que falou !!!
Answer: Você pode fazer assim:
if (isset($_POST['dorm']) && is_array($_POST['dorm']) && count($_POST['dorm']) > 0){

   if (in_array('4', $_POST['dorm'])) {

      $where .= " ( DORMITORIO IN ('".implode("', '", $_POST['dorm'])."') OR DORMITORIO > 4 ) AND ";

   } else $where .= " DORMITORIO IN ('".implode("', '", $_POST['dorm'])."') AND ";

}

Assim, mesmo que o usuário selecione as opções 2, 4, o retorno será consistente:

SELECT * FROM imovel WHERE 1=1 AND DORMITORIO IN ('2','4') OR DORMITORIO > 4

Mas caso você queria que ao selecionar a opção 4, mostre apenas os registros com dormitórios maior ou igual a 4, faça assim:
if (isset($_POST['dorm']) && is_array($_POST['dorm']) && count($_POST['dorm']) > 0){

   if (in_array('4', $_POST['dorm'])) {
      $where .= ' DORMITORIO >= 4 AND ';
   } else {
      $where .= " DORMITORIO IN ('".implode("', '", $_POST['dorm'])."') AND ";
   }

}

Assim, se o usuário selecionar as opções 2, 4, o retorno será:

SELECT * FROM imovel WHERE 1=1 AND DORMITORIO >= 4

Obs.: Recomendo usar uma classe que fornece opções para criação de filtros dinâmicos, como essa.
Comment: Fatal Error: Syntax error or access violation: 1064 Você tem um erro de sintaxe no seu SQL próximo a 'WHERE 1=1 AND DORMITORIO IN ('4') OR DORMITORIO > 4' na linha 1 ...
Comment: Não identifiquei nenhum erro ai, fiz um teste aqui e deu normal... Coloca o SQL gerado completo ai pra ver o que está dando errado.
Comment: Isso no banco funciona: `SELECT * FROM imovel WHERE 1 =1 AND DORMITORIO IN ('1',  '2',  '3',  '4') OR DORMITORIO > 4` ... na requisição, não ! Deve ser erro na SQL dinâmica.
Comment: Kadu, consegue ver aonde está dando erro? Seleciono o `4` e dá erro >>>> http://puu.sh/c3kAx/d13eb5844e.png
Comment: Fiz uma atualização ali no código, veja se resolve. A principio não vejo nenhum erro de syntax... :/


Is 22.214.171.124/24 a valid private subnet?

Question: I've been administrating an office network that was set up by someone else and I always found this weird about it:
Their internal subnet is in this range: 126.96.36.199/24.
It's been working fine, but it does not conform with RFC 1918.
I've been trying to find out who has IPs in the range 126.96.36.199/8, but a simple WHOIS only shows that they "belong" to ARIN. Could it be that they're simply unassigned? I tried ICMP pinging a wide range of them and got no response...
I guess I'll eventually change the subnet to something more standard, but it's a curious thing, don't you think?
Comment: You might want to add a Nagios check for "whois 22.214.171.124". :)
Comment: Ignoring the ip address range that is currently in use: private networks don't have to conform to RFC 1918. It's slightly unorthodox but it's not wrong to not use RFC 1918 ip addresses internally.
Comment: Follow-up: the range has been assigned to GOOGLE!
Answer: No, it's not a valid private subnet, as you can seen in the RFC.  You've most likely not had issues because of the use of NAT when hitting the Internet.  In which case, you would only run into issues if you were trying to access something using that range.
You should take the time to correct the subnet to avoid any future problems.
Answer: Someday ARIN may allocate 172.253.x.y to somebody.
There are two sides to it, it will take effort to migrate away from your current configuration, and how likely is it that you will want to connect to that somebody.
But on the other hand, it will be a pain to troubleshoot, and resolve on short notice if you do want to connect.
Answer: The subnet does not appear to be assigned (yet), but is not reserved for private use, as you already pointed out. You may want to switch it sometime soon before the address' are allocated.

Is 172.253.16.0/24 a valid private subnet?


How is a javelin throw measured if the javelin does not stick into the ground?

Question: If a javelin "slips" on landing and does not stick cleanly into the field, how is the throw measured?
Answer: This is covered by the IAAF Competition Rules. Quoting from the 2014–2015 edition, Rule 187.20:

The measurement of each throw shall be made [...] from where the head of the javelin first struck the ground to the inside edge of the arc, along a line to the centre of the circle of which the arc is part.


Como logar somente usuários ativos?

Question: Na autenticação além dos dados necessários para logar o usuário, quero que somente os que estão com status ativo = 1 faça login, mas não sei como fazer esta verificação.
table user:
id
username
email
password
ativo

UserController
public function store()
{
      $userdata = array(
          'email'    => Input::get('email'),
          'password' => Input::get('password')
      );
      $rules = array(
          'email'    => 'required',
          'password' => 'required'
      );
      $message = array(
         'email.required'    => 'O :attribute é obrigatório.',
         'password.required' => 'A senha é obrigatória.'
        );
      $validator = Validator::make($userdata, $rules, $message);

     if ($validator->passes())
      {
       if (Auth::attempt($userdata))
          {
           return Redirect::to('')->with('success', 'You have logged in successfully');
          }
          else
          {
           return Redirect::route('admin.create')->withErrors(array('password' => 'Senha inválida'))->withInput(Input::except('password'));
          }
      }

  // Something went wrong.
  return Redirect::route('admin.create')->withErrors($validator)->withInput(Input::except('password'));

}
Answer: Passa o terceiro parametro que é correspondente a sua coluna de status (ativo ou inativo, exemplifiquei como activated):
 $userdata = array(
      'email'     => Input::get('email'),
      'password'  => Input::get('password'),
      'activated' => 'A'
  );

O Laravel adicionará o activated ao where no momento de localizar o usuário, caso o mesmo esteja inativo não trará.
Comment: Muito obrigado Flávio H. Ferreira.
Answer: Outra maneira seria assim:
        if (Auth::attempt(array('username' => Input::get('username'), 'password' => Input::get('password')), Input::has('lembar') ? true : false)) {
            if(Auth::user()->status == TRUE) {
                return Redirect::intended('dashboard');
            } else {
                Auth::logout();
                return Redirect::route('entrar')->withErrors('Desculpe, mas o Usuário está desativado.');
            }

        } else {
            return Redirect::route('entrar')->withErrors('Usuário ou Senha Inválido.');
        }

Comment: Oi, Marcus, bem vindo ao [pt.so]. É legal dar uma explicação, ainda que breve, de porquê seu código resolve o problema. O guia [answer] tem mais detalhes.

Como logar somente usuários ativos?


How to find a lower bound for $T(n)=T(n-1)+n^2+n^2\log n$?

Question:
How to find a lower bound for $T(n)=T(n-1)+n^2+n^2\log n$?

This question is in continuation to the following one :
Find an upper bound for $T(n)=T(n-1)+n^2+n^2\log n$
For upper bound the logic is to "round" the indices towards $n$, but I really don't have a clue how to go about the lower bounds.
Comment: Ah ok if you want asymptotics, sure we don't really care about the first term $T(1), T(2), ...$. So you already have an upperbound of $O(n^3 \log n)$. However using the inequality I suggested ( $1 \leq \log(n)  $), you get $\Omega(n^3)$ so you cannot conclude any $\Theta(f(n))$.
Comment: How tight should the bound be ? Otherwise you could simply use $1 \leq \log(n)$ (for $n \geq e)$ and solve the reccurence and handle the first case for small $n$ "manually".
Comment: @Zubzub it should be $\Theta$ in big-O notation. Can you please show an example of how handle small $n$ "manually"?
Comment: $$T(n)=T(0)+\sum_{k=1}^nk^2\log (ek)\geqslant\sum_{k=n/2}^n(n/2)^2\log(en/2)\geqslant(n/2)(n/2)^2\log(n)=\Theta(n^3\log n)$$
Answer: Obviously, $$T(n)=T(0)+\sum^n_{k=1}(k^2+k^2\log k).$$ Now we know that $$\sum^n_{k=1}k^2=\frac{n(n+1)(2n+1)}{6}=f(n).$$ Then, by partial summation,
$$\sum^n_{k=1}k^2\log k=\sum^n_{k=1}[f(k)-f(k-1)]\log k=f(n)\log(n+1)-\sum^n_{k=1}f(k)\log\left(1+\frac1{k}\right),$$ and since $\log\left(1+\frac1{k}\right)<\frac1{k},$
$$\sum^n_{k=1}k^2\log k\ge f(n)\log(n+1)-\sum^n_{k=1}\frac{f(k)}{k}=f(n)\log(n+1)-\frac1{6}\left(2f(n)+3\frac{n(n+1)}{2}+n\right)$$
I think the rest should be clear.
Answer: From the previous question I restate the summation and I assume that you are looking for an asymptotic lowerbound $T(n) = \Omega(f(n))$ and since in the previous question you already obtained $T(n) = O(n^3 \log n)$ we will aim for the same lowerbound.
$$
T(n) = \overbrace{\sum_{i=1}^n i^2}^{\Omega(n^3)} + \sum_{i=1}^n i^2 \log(i) \overset{(*)}{\geq} \Omega(n^3) + \frac{n}{2}\left((\frac{n}{2})^2\log(n/2) \right) = \Omega(n^3\log(n))
$$
$(*)$ The trick is to retain only half of the term in the sum and lowerbound them by the central term. For example, assuming $f(n)$ is positive and increasing, then $f(1) + f(2) + f(3) + f(4) \geq f(3) + f(3)$ (we throw away $f(1)$ and $f(2)$ which creates a lowerbound on the sum and we then lowerbound the remaining term ($f(3)$ and $f(4)$) by the smallest remaining term which is $f(3)$. More generally $\sum_i^n f(i) \geq \frac{n}{2} f(n/2)$.
Comment: All terms are positive in the sum. So if I remove half of them, I will lowerbound the sum !
Comment: How do we know that we can retain $\frac{n}{2}$?


How to show administrative shares in Windows Server 2012's Server Manager?

Question: How do I make default administrative shares visible in File and Storage Services, in the Windows Server 2012 Server Manager?
With the Computer Management MMC add-in all shares hosted by a server are visible, hidden or otherwise. This is true when connecting remotley, you can right-click on C$ and choose Open to connect to \\SERVER\C$. However the Server Manager interface shows only non-default shares, and I can't find how to make C$ etc visible.
This is a minor irritation; it's an insconsistent design but not otherwise a problem.
Comment: Why do you call it inconsistent design? Just because **you** want to see it in Server Manager doesn't mean that Microsoft wants you to see it there. Server Manager presents what it was designed to present. Server Manager isn't a tool that was intended to be used to manage the default hidden shares, probably because those hidden shares aren't "user facing" and don't directly provide services to end users. As it stands, you can't make them visible in Server Manager because Server Manager isn't a tool for managing those hidden shares and the UI has no mechanism by which to present them to you.
Comment: If the Computer Management console and the Server Manager console had the same design goals and the same intended use then I'd call that inconsistent design, but they don't so it's not.
Comment: It's inconsistent because the feature was present in the previous MMC incarnation. The current Server Manager would seem to be geared towards remote management of your server farm, and this information is missing. But whatever.
Answer: The following command will show all shares on the machine including administrative shares.
net share

Comment: Yes, but doesn't answer the question at all. Can you update your answer or consider removing it?


Is std::unique_ptr an application of RAII?

Question: Is that an accurate description of it? Does it make sense?
Are you guaranteed that the object it points to won't be deleted until the unique_ptr goes out of scope [even if you're not using the unique_ptr]?
Comment: @wrhall no, it doesn't. The compiler knows nothing about the semantics of objects, it merely generates calls to constructors and destructors as necessary.
Comment: Wanna just make that the answer so I can give you a check?
Comment: yes, it's an RAII class. I don't see how "the object it points to won't be deleted until the unique_ptr goes out of scope" is relevant – a sufficiently stupid programmer can `delete ptr.get()` and corrupt memory at will, but this doesn't make `unique_ptr` "less RAII".
Comment: @TheParamagneticCroissant I was just curious if it is possible for the compiler to ever clean up the garbage before it actually goes out of scope if it's not being used. Does that make sense?
Answer: Yes, std::unique_ptr follows the RAII design principle.
No, std::unique_ptr does not prevent other code from doing something stupid, like calling delete on a pointer that belongs to the unique_ptr.  The unique_ptr itself will call a deleter1 on the object it owns when either:

it goes out of scope

or

the unique_ptr is reassigned (via operator= or reset) to point to a different object

One can also revoke unique_ptr's ownership of an object by moving to a different smart pointer, or using the release member function.  This breaks the association between the object and the unique_ptr and unique_ptr will no longer clean up the object.

1 The default deleter will use either delete or delete [], depending on whether the target has array type.  But unique_ptr is a template and its deleter can be customized, for example the cleanup operation for a FILE* can be chosen to be a call to fclose.
This capability can be used to schedule an arbitrary cleanup action to take place when the unique_ptr goes out of scope.  RAII is used for keeping locks, closing files, and so forth -- clearly there would be major problems if the cleanup action were performed early just because the compiler didn't see any future usage of the smart pointer.  Luckily the C++ object lifetime rules are completely deterministic (even the order of destruction for multiple automatic variables in the same scope is well defined), and you can count on the smart pointer cleaning up its owned object exactly when the smart pointer is itself destroyed.
Answer: std::unique_ptr is RAII, as the creation of the object also initializes it.

Are you guaranteed that the object it points to won't be deleted until the unique_ptr goes out of scope [even if you're not using the unique_ptr]?

If you make a few assumptions:

You don't move the unique_ptr (that would cause the newly moved to location to be the one that will delete
You don't delete the pointer yourself or add it to another control structure.

Or put more succinctly, yes it will live that long.
Answer: It is an application of RAII, indeed.
But you are not granted that the object it points to is not deleted by someone else before the unique_ptr goes out of scope.
E.g.
int* p = new int;
int* cp = p;
std::unique_ptr<int> up(p);
delete cp;

will give undefined behavior.
Comment: The `undefined behaviour' in this instance would be throwing a software developer into a crevasse.
Answer: std::unique_ptr can be used for RAII, but doesn't prevent you from doing something like this:
#include <memory>

class Foo{};

int main()
{
    Foo* pFoo = new Foo;

    std::unique_ptr<Foo> upFoo(pFoo);
    delete pFoo; // WRONG, double deletion when upFoo's destructor is called
}

Usually, the best way to use smart pointers is to pass the raw pointer as their constructor or make-like function, such as
#include <memory>

class Foo{};

int main()
{
    std::unique_ptr<Foo> upFoo(new Foo); // or make_unique in C++14
}


How to pass params to SP and retrieve select filed to repeater

Question: I use vs2010 and ms sql with (linq to sql) SP to pass p1 p2 p3 and retrieve selected  data to repeater
The problem is the repeater ignore p1,p2,p3 and just display all data in the movie table
I have 3 tables :  (Movie , Director, Movie-director)
SP:
ALTER PROCEDURE [dbo].[SelectMovie]
    @P1 nvarchar(50),
    @P2 nvarchar(255)= null,
    @P3 nvarchar(255)= null   AS SET NOCOUNT ON
    SET TRANSACTION ISOLATION LEVEL READ COMMITTED
    SELECT
        Movie.Movie_ID
        , Movie.title
        , Movie.image
        , Movie.actors
        , Movie.description
        ,Director.name
    FROM
        Movie
            INNER JOIN Movie-director ON Movie.Movie_ID = Movie-director.Movie_ID
            INNER JOIN Director ON Movie-director.Director_ID = Director.Director_ID
    WHERE
        (title LIKE '%' + (@p1) +'%')
        OR
        (actors LIKE '%' + (@p2) +'%')
        OR
        (cat_ID LIKE '%' + (@p3) +'%')

ASPX:
<asp:Repeater ID="Repeater1" runat="server" >
<HeaderTemplate> </HeaderTemplate>
<ItemTemplate>

            <a href="movie_details.aspx?id=<%# DataBinder.Eval(Container.DataItem, "Movie_ID")%>" class="thumb" title="An image">
                <img src="<%# DataBinder.Eval(Container.DataItem, "image")%>" alt="Post" style="opacity: 1; float:left; width:80px ; height:100px; border:3px solid #fff ; margin:5px;">

            <a href="movie_details.aspx?id=<%# DataBinder.Eval(Container.DataItem, "Movie_ID")%>" class="header">

                    <%# DataBinder.Eval(Container.DataItem, "title")%>
                    ( <%# DataBinder.Eval(Container.DataItem, "actors")%>)

                <%# DataBinder.Eval(Container.DataItem, "description")%>

                <%# DataBinder.Eval(Container.DataItem, "name")%>

</ItemTemplate>

C#:
CDTDataContext dc = new CDTDataContext();
protected void Page_Load(object sender, EventArgs e)
{
        if (!IsPostBack){ }
}
protected void Button1_Click(object sender, EventArgs e)
{
    string Cat_ID = DropDownList1.SelectedValue;
    string keyword1 = TextBox2.Text;
    string keyword2 = TextBox3.Text;
    int? cid = int.Parse(cat_id);
    Repeater1.DataSource = dc.SelectMovie(keyword1, keyword2, cid);
    Repeater1.DataBind();
}

Answer: I think your SQL query is wrong, because of OR's if you pass empty string you will match all records in Table:
ALTER PROCEDURE [dbo].[SelectMovie] @P1 NVARCHAR(50)
    ,@P2 NVARCHAR(255) = NULL
    ,@P3 NVARCHAR(255) = NULL
AS
SET NOCOUNT ON
SET TRANSACTION ISOLATION LEVEL READ COMMITTED

SELECT Movie.Movie_ID
    ,Movie.title
    ,Movie.IMAGE
    ,Movie.actors
    ,Movie.description
    ,Director.NAME
FROM Movie
INNER JOIN Movie - director ON Movie.Movie_ID = Movie - director.Movie_ID
INNER JOIN Director ON Movie - director.Director_ID = Director.Director_ID
WHERE (title LIKE '%' + (@p1) + '%') --title has to be matched
    AND (
           (
                    actors LIKE '%' + (@p2) + '%' AND @p2 IS NOT NULL) --match only then when @p2 is not null
        OR (
                    cat_ID = @p3 OR @p3 IS NULL --if @p3 IS NULL then do not filter by @p3
           )
        )


Select list ajax callback fire only once to update textfield

Question: I face an issue when fire ajax callback function in my coding. I have a select list and a text box. If there is any change in select list field, the text box will be updated by selected value. I added my code in form_alter function. But, it fired only one time. Below is my code.
 function field_collection_form_alter(&$form, &$form_state, $form_id) {
if($form_id == 'employee_performance_node_form') {

$form['field_my_weight_select'][LANGUAGE_NONE]['#ajax']= array(
      'callback' => 'custom_test_entity_callback',
      'wrapper' =>'custom_test_entity_wrapper',
      'method' => 'replace',
      'effect' => 'fade',
      'event' => 'change',
    );

$form['field_text_for_test']['#prefix']='
';
$form['field_text_for_test']['#suffix']='
';

if(isset($form_state['values']['field_my_weight_select'])){
      $content_type = $form_state['values']['field_my_weight_select'][LANGUAGE_NONE][0]['value'];
      $form["field_text_for_test"][LANGUAGE_NONE][0]['value']['#value']=$content_type;
    }
    else{ $form["field_text_for_test"][LANGUAGE_NONE][0]['value']['#value']=1;}
}
}

function custom_test_entity_callback($form, $form_state){
  return $form['field_text_for_test'];
}

Could you tell me what is wrong in my code??
Thank you
Answer: Quickly tested your code and it works.
The only thing that looks a bit odd in your hook implementation, is the name of the function. It seems you are writing your custom code as if your module was named 'field_collection'. There is already a contrib module called that, and you may have already installed it. It would be better to place your function into your custom module's "namespace". Event better would be to also use the hook_form_FORM_ID_alter hook, since it's more efficient.
In any case, with those two small rewrites, the code ran as expected and I was able to get multiple ajax updates of the text_for_test field.
/**
 * Implements hook_form_FORM_ID_alter().
 */
function YOUR_CUSTOM_MODULE_form_employee_performance_node_form_alter (&$form, &$form_state) {
  $form['field_my_weight_select'][LANGUAGE_NONE]['#ajax'] = array(
    'callback' => 'custom_test_entity_callback',
    'wrapper' => 'custom_test_entity_wrapper',
    'method' => 'replace',
    'effect' => 'fade',
    'event' => 'change',
  );

  $form['field_text_for_test']['#prefix'] = '
';
  $form['field_text_for_test']['#suffix'] = '
';

  if (isset($form_state['values']['field_my_weight_select'])) {
    $content_type = $form_state['values']['field_my_weight_select'][LANGUAGE_NONE][0]['value'];
    $form["field_text_for_test"][LANGUAGE_NONE][0]['value']['#value'] = $content_type;
  }
  else {
    $form["field_text_for_test"][LANGUAGE_NONE][0]['value']['#value'] = 1;
  }
}

/**
 * Ajax callback for updating field_text_for_test.
 */
function custom_test_entity_callback($form, $form_state) {
  $form['field_text_for_test']['#prefix'] = '
';
  $form['field_text_for_test']['#suffix'] = '
';
  return $form['field_text_for_test'];
}

Update: If you want to make sure, your form alter hook is called last (in relation to other modules):
/**
 * Implements hook_module_implements_alter().
 */
function CUSTOM_MODULE_module_implements_alter(&$implementations, $hook) {
  if ($hook != 'form_employee_performance_node_form_alter') {
    return;
  }
  $module = 'CUSTOM_MODULE';
  $group = array($module => $implementations[$module]);
  unset($implementations[$module]);

  $implementations = $group + $implementations; //You want your implementation to run last.
}

Good luck!
Comment: But actually I am trying to alter the filed_collection module and this why I use  field_collection_form_alter.
Comment: The convention is that such a MYMODULE_hook implementation belongs to MYMODULE code/files. This is where it is also expected to be found (by developers at least). This is not really blocking you from altering the field_collection module's form elements. A form alter hook is in any case not a field_collection specific thing, but a Form API one.
Comment: I do not know if I understand your idea or not. But could I add the above code in field_collection_form_alter or not?
Comment: You should not have a function field_collection_form_alter at all, it means you are messing with a contrib module's code. Unless you are creating a patch for the module (which does not seem to be the case), this is a bad practice and idea. You should instead create you own module, e.g. performance_customizations, and inside that module's performance_customizations.module file, you should place the form alter hook which would then be named performance_customizations_form_employee_performance_node_form_alter
Comment: Ok, I understand now.. But I could not do custom module now because I already did a lot of customization and alter in field_collection_form_alter. So, do you have a way to let this code work in field_collection_form_alter?? Thank you
Comment: Unfortunately, I don't see any problem with the code you posted. If there are other parts of code that may be causing the error, you should post them as well in the original question. And you can always try to run that part of the code in a separate module and see if that fixes your problem.
Comment: The other parts of the code is just hide and dispaly the fields in field collection.. I do not think it causes this error.. I will try to run this code in separate module and I will check.. Thank you.
Comment: I tried to disable all the other parts of the code but the isuue is still. I notice that the id of textfield is change after the first selection
Comment: before
Text for test
Comment: after
Text for test
Comment: Okay, you found the reason why it doesn't works the second time. I updated my code update (custom_test_entity_callback), in order to force the #id to be returned via AJAX. Could you try it like this and check if the updated HTML contains the  wrapper?
Comment: Unfortunately, it didn't work. In the second time it contains  but the id of the input change    (--2) was added to the id. I don't know why..
Comment: Could anyone help me to find a solution to this issue?
Comment: You need to update your post with more information. Your current drupal version as well as the contrib modules you are using. And any additional custom code that you think may be related. From your side, you should try to disable contrib modules and/code gradually, in order to find out which is actually causing the problem. The code you posted afaict is correct and it worked on my standard D7.53 without any problems.
Comment: I create a custom module and it my code works. What I discover today that my code is working in an admin user account but it does not work in a normal user. Before, I just test it in a normal user account. I tried to check the permissions but I did not find any permission that related to ajax. So, do you have an idea why it does not work in a normal user account?  Thank you
Comment: This piece of code, does not have any roles-specific logic. That means, that it should work the same for all kind of roles. Unless there is some other module changing things. Which one cannot tell from the code you provide, unfortunately.
Comment: You can try (a) changing the module hook order (see code update in my answer. If that doesn't work, you should (b) debug this using a proper debugger and backtracing to locate the code that changes the form array. Or, start disabling contrib modules till you figure out which one introduces the conflict. Tedious, I know, go for the proper debugging if you have the option.
Comment: Thank you Stefanos Petrakis for your help and for you support. I found who causes this issue. I gave the normal user a full permissions and I tried to disable permissions one by one. Then, I found that the permissions of Pathauto module causes this issue. So, I enable the permissions and my code is working now.
Comment: Excellent. Best thing to do now would be to give a separate answer to this question for other people to find, describing your findings.
Answer: My issue has been solved. I gave the normal user full permissions and I disable the permissions one by one until I found that the permissions that related to Pathauto module cause this issue. So, I enable them and then my code works.


Understanding the logical context

Question: When I display my logical context after having checked it, I get, among many other things:
inconsistent():1
m_asserted_formulas.inconsistent():1
#1 := true
#2 := false
... (follows around 40 of theses assertions)
#144 := (not #143)
asserted formulas:
#23 #125 .... #2

I understand that in the list of asserted formulas, there are some inconsistencies. The first one I see is assertion number 2:
#2 := false

Am I right, or could it be that "false" is a true assertion ?
Thanks in advance,
AG.
Answer: Yes, false was asserted to be true in your context. Note that, the context is tagged as inconsistent: inconsistent():1. The 1 here means true as usual in C. Note that, this low level representation of the logical context should only be used for debugging purposes. It is not really meant for "external" consumption. Finally, false may have not been explicitly asserted by the user, but is instead implied by the assertions performed by the user.
Comment: I see. Something like 2=1 could have been asserted, which is equivalent to asserting false. I am glad I asked the question. Thanks for the answer. I am indeed debugging.
Comment: Yes, you are correct. `assert 2=1` is equivalent to `assert false`.

Understanding the logical context


SQL Server : splitting the results of GROUP BY into a separate columns

Question: I've got a SQL Server 2008 R2 database with around 500 million rows of data in it, it currently looks like this
ID          Eventtype
201         1
201         3
201         4
201         1
201         1
664         1
664         0
664         1
664         3

I can't seem to find a query that will provide the data back in this format:
ID         Event0   Event1  Event2  Event3  Event4
201        0        3       0       1       1
664        1        2       0       1       0

This is as far as I've gotten at this point:
select distinct ID as ID, count(EventType)
from database.dbo.events
group by questID, EventType

which spits data back to me like:
ID       EventType
201      0
201      3
201      0
201      1
201      1
664      1
664      2
664      0
etc.

This does display all the data I need, but the formatting and guesswork involved in trying to figure out which EventType is which is quite frustrating.
Can anyone suggest a better query that will return the data in a good format?
Comment: Which version of Sql Server is this?
Answer: How about something like...
select ID, sum(Event0), sum(Event1), sum(Event2), sum(Event3), sum(Event4)
from (
    select ID,
        case EventType when 0 then 1 else 0 end as Event0,
        case EventType when 1 then 1 else 0 end as Event1,
        case EventType when 2 then 1 else 0 end as Event2,
        case EventType when 3 then 1 else 0 end as Event3,
        case EventType when 4 then 1 else 0 end as Event4
    from dbo.events
) E
group by ID

Assuming there are exactly 5 event types numbered 0 through 4.
Depending how the table is indexed it may take a significant amount of sort space, and can fail if sufficient space is not available.
Comment: Awesome, thanks! This worked perfectly. Nikola's reply was also correct, but the pivot table took 14min to run where joshp's case version took 6min.
Answer: There is pivot functionality in Sql Server. If you have for instance 6 distinct events, you can use this:
select ID, [0], [1], [2], [3], [4], [5]
from events
pivot
(
  -- aggregate function to apply on values
  count(EventType)
  -- list of keys. If values of keys are not fixed,
  -- you will have to use dynamic sql generation
  for EventType in ([0], [1], [2], [3], [4], [5])
) pvt

For dynamic pivot generation, see this SO post.
Btw, I believe that your original query should read:
select ID, EventType, count(EventType)
from events
group by ID, EventType
order by ID, EventType

You can see it in action @ Sql Fiddle (scroll down to see pivoting results).
Comment: Thanks! This did work just fine, it took a bit longer to run than joshp's case version.


Clustered standard errors in 2-period Dif-in-Dif?

Question: in order to rectify invalid t-stats because of autocorrelation in Difference-in-Differences (DnD) models, Duflo et al (2004) propose (among other solutions) to collapse data so as to have a before-after DnD. My question: What if we already HAVE a before-after setting (e.g. pre-reform vs post-reform)? Would it be still ok to use clustered SE (provided the number of clusters would be high enough)? Or is it automatically wrong to use them EVEN IF we already have data that has 2 time periods only.
Would appreciate any comments. Thanks.
Answer: Bertrand et al. propose collapsing so that you don't have to cluster your standard errors. Just use a common t-statistic comparing two groups with unequal variances for your test:
$$\begin{equation*} \frac{\bar{y}_1 - \bar{y}_0}{\sqrt{\frac{\hat \sigma^2_0}{N_0} + \frac{\hat \sigma^2_1}{N_1}}} \end{equation*}$$
See that this assumes no correlation between observations within the pre- and post-periods and no correlation between pre- and post-periods. The first is a common cross-section assumption and Bertrand et al. show that the latter is reasonable in the panel context.
The above works when you have a balanced panel with all individuals experiencing the intervention at the same time. If this is not the case, perform the following regression. For each individual, get a pre-period average of the outcome $y$, $\bar{y}_{i0}$ and similarly a post-period average $\bar{y}_{i1}$. Now, for each individual, there are two observations: before and after. Turn this into a panel with $2N$ rows, where $N$ is the number of individuals. Run a regression on these data, including individual fixed effects and a treatment indicator.
Bertrand, Marianne, Esther Duflo, and Sendhil Mullainathan. 2004. "How Much Should We Trust Differences-In-Differences Estimates?" The Quarterly Journal of Economics 119 (1): 249–275.
Comment: Hi Charlie. Thanks a lot for your remarks. So do I understand that I really don't have to cluster with 2 periods? Bertrand et al say that collapsing improves the rejection rate, but I am not sure whether this implies that clustered SE are no better than standard robust SE in this situation. So: what IF I do cluster even though I have only two periods? Will the estimator of my SE be biased then? Thanks!
Comment: No, you don't need to cluster. You'd only have one parameter that clustering would be estimating anyway (see the info about the regression above). I guess that you could if you wanted to, but it's not necessary. Bertrand et al. don't speak to what the results are if you do cluster.


1500$ Digital or acoustic piano?

Question: I have a budget of 1500$. I've never played piano before. Should I buy a digital or acoustic (maybe used) piano with the budget I have? Does a 1500$ acoustic piano sound better than a digital one?
Comment: Try some. Buy the one you like the most.
Comment: https://music.stackexchange.com/questions/10175/is-a-digital-or-acoustic-piano-a-better-option-for-a-beginner-sound-and-feel and https://music.stackexchange.com/questions/45325/acoustic-piano-vs-digital-piano-is-there-any-solid-evidence-for-one-being-bette Might be useful
Comment: I've had a piano that my brother payed the rent 60 years ago, some years later we could buy it. So I might have a sentimental relationship to this instrument. About six years ago I've sent it in a revision. The owner of this piano-firm told me he has a lot to to at the moment with piano tuning and revisions of music school.
Maybe he will have time in February. (It was October when my piano went into the revision.) About 2 years later I called and told him that I am missing my piano and send my kindest greetings. He sent me another piano - he would look at the other. I still don't have it back
Answer: If you just want it for joy and hobby you could buy a digital piano. (There are many advantages: Price, costs for tuning, weight, transport, loudness, mobility, other sounds, connection to computer and others. If you have the goal to become a pianist (level of piano teacher) you need an acoustic piano.
Comment: I guess it's subjective, but IMO an acoustic piano makes a bigger emotional impact than a digital piano, and so it might be better for learning and motivation. It's the same with almost any acoustic instrument, when an actual thing vibrates in same physical room where you are. It just feels better when it's actually present. Like a cake vs. a picture of a cake. Or a real person vs. a video conference.
Comment: The resonance of the room can even be a drawback when you have e.g. a grand piano in a floor without carpet.
Answer: So many factors involved here.
Where you live, where the piano is situated will have a bearing on how an acoustic piano will cope with changing temperature/humidity. No such problems with an electronic (digital) piano.
Unless you pay a lot of money, you won't buy a good acoustic piano - which will need transport and re-tuning soon after - an extra expense. And every year or so after! And, will take up much more of your room - and probably not be as quiet for practice, as an electronic one, with headphones.
So, as a beginner, a fairly priced electronic will not be detrimental to your touch, will be better value for money, take up less room, be easier on your neighbours, will provide extra facilities (should you need them), cost nothing in maintenance, probably be easier to sell on, consequently, would be a better bet initially.
After a year or two, an acoustic may well be a better replacement. However - buying an acoustic, whether new and especially pre-loved, is a more involved job than buying an electronic. Take an expert along at that time.
With an acoustic, there'll be a better action but essentially one sound. Bear in mind that actions vary from piano to piano, so merely buying an acoustic won't necessarily mean it has a good action, or even one that suits you (which you won't really be aware of for a while after playing anything!). Electronics are getting better with action - but for many 1000s. Their advantage is a plethora of sounds, a lot of which sound very good. And there's little maintenance. And you can record on them. And they often have built in drum patterns.
I use both, and am lucky enough to have both. But if one had to go: difficult decision. It also depends on what style of music you wish to play.
Comment: @AlbrechtHügli - bear in mind that post is 5 1/2 yrs old. Digitals have moved along a lot since then. So even better!
Comment: Mostly I play on the acoustic piano - but I agree with the one who has written in one of topo mortos links above: *Better a digital piano than a bad acoustic piano.* I have also both - that means 2-3 different keyboards and this replacement piano. But I am really thinking about forgetting the acoustic piano as I have opportunity to play on other instruments.

1500$ Digital or acoustic piano?


Display Network Encryption Type in Tshark?

Question: I've been using tshark to gather some basic information on networks near where I live. I've got tshark to display the bssid, ssid, and rssi but I was wondering if there was also a way to display the networks encryption type as well. I'm using the following command:
tshark -i wlan1mon -l -T fields -e wlan.bssid -e wlan.ssid -e radiotap.dbm_antsignal -Y 'wlan.ssid' | grep -v "ff:ff:ff"

and this is and example of the output I get:
00:11:22:33:44:55   Bell Wireless    -74,-74
66:77:88:99:00:22   Dlink            -83,-83
33:44:55:66:77:88   NetflixNChill    -68,-83

Ideally I'd want the output to look more like this:
00:11:22:33:44:55   Bell Wireless   WPA  -74,-74
66:77:88:99:00:22   Dlink           WPA2 -83,-83
33:44:55:66:77:88   NetflixNChill   Open -68,-83

Any help would be greatly appreciated!
Answer: Maybe -e wlan.rsn.pcs.type and -e wlan.rsn.gcs.type are what you're looking for?  Those are for the Pairwise Cipher Suite type" and "Group Cipher Suite type", respectively.
In case those aren't the fields you're interested in, or in case you want to include additional fields, you can find a complete list of display filters, including wlan filters, online at the Wireshark Display Filter Reference page.
You can also get this information from:

Wireshark itself via "View -> Internals -> Supported Protocols -> ...", but unfortunately the sorting leaves much to be desired there.
tshark using the tshark -G fields command, but this output isn't very user-friendly either.


can not run js file with nodemon

Question: I install nodemon from npm in project but cant run js file with 'nodemon run start' and facing this error:
nodemon : The term 'nodemon' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
Answer: You need to install nodemon globally using the -g option.
npm install -g nodemon

This will add nodemon to your PATH environment variable so that your terminal knows where the executable file for nodemon is.
Otherwise your terminal doesn't know which executable you're trying to run.
Your second option is to run it through npx.
Use the following:
npx nodemon {filename}

npm will handle locating and running the executable for you. The npx command is installed on your computer by default when you install npm.
Answer: You will need to install  nodemon if you haven't already
for dev environment run
$ npm install --save-dev
to install nodemon globally run
npm install -g nodemon

to run your app/server use
nodemon app

If the name of your entry file is not app use its name in the command
nodemon {filename}

can not run js file with nodemon


Why do some people use "None" as enumeration member?

Question: I noticed that some enumerations have "None" as a enumeration member.
For example what I mean
enum Mode
{
    Mode1 = 1,
    Mode2 = 2,
    Mode3 = 3,
    None = 4
}

Why do they use it ? In what cases solution with a none member is more preferable (less preferable) ?
Answer: None is important for [Flags] enums, and should have the value 0. Otherwise... questionable. A Nullable<Mode> would also suffice. But None may be demanded for their serialization or ORM layers (it might map to an expected string / int-value etc). Or it might just make the API simpler.
Answer: It is required by a Code Analysis rule, see http://msdn.microsoft.com/en-us/library/ms182149(VS.100).aspx for the official reason.
Comment: (re non-flags enums) pah... if "0" isn't already a valid case for my enum, I'm not having one. I'll check for the valid values myself, ta. I need to check for **every other** value that isn't defined: why should 0 be any different just because it is the default? 1124521 is *just* as invalid (presumably).
Answer: Logically None could be a valid choice (depends on the meaning of your enumeration) -> could have a separate branch in a switch case (arguably - not always a None option makes sence)
Regarding having a None option an a Nullable<Mode> variable: I would go for None for consistency: if you have 3 valid options and None is one of them, why treat it differently?
And if you choose or not to have a None option you should always have a enum value mapped as 0 (the default option). The link provided by Hans Kesting makes a good point about having a value mapped as 0:
The default value of an un-initialized enumeration, like other value types, is zero. A non-flags attributed enumeration should define a member with the value of zero so that the default value is a valid value of the enumeration. If appropriate, name the member 'None'. Otherwise, assign zero to the most commonly used member. Note that if the value of the first enumeration member is not set in the declaration, its value is zero by default.


Installing and accessing classes within a NuGet package from a Java application

Question: I have created a NuGet package (.Net standard 2.0 and .Net Framework 4.8 - compatibility) that I would like to know if it is possible to access from a Java application.
Answer: Nuget is a package format that is used in .NET. Not in Java. Java has Maven for that.
So there is no simple way (or any way I could recommend) to use the code easily in Java.
But if you really need to use the methods you have in the package, you can try to do the following:

Compile the code that the package contains, so that you have .dll file
Try to make use of the compiled dll in Java. I don't know much Java but it seems this is already answered in Stack Overflow: How to call a method in DLL in a Java program

Basically you should be able to call the methods defined in your DLL. Similar thing you can do in .NET. It is possible to take a dll, and call it's methods from .NET knowing the method signature. It is called Interoperability
Also please note that the nuget package is a zip repository in fact. You can open it using any zip tool, you can extract it and compile the code with dotnet command.


waagent not deprovisioning on preparing debian VHD Azure

Question: When running the final command which is sudo waagent –force -deprovision after preparing a Debian VHD for Kali but it keeps finishing with the below messages:
Traceback (most recent call last):
File "/usr/sbin/waagent", line 33, in <module>
sys.exit(load_entry_point('WALinuxAgent==2.2.47', 'console_scripts', 'waagent')())
File "/usr/sbin/waagent", line 25, in importlib_load_entry_point
return next(matches).load()
File "/usr/lib/python3.9/importlib/metadata.py", line 77, in load
module = import_module(match.group('module'))
File "/usr/lib/python3.9/importlib/init.py", line 127, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 1030, in _gcd_import
File "<frozen importlib._bootstrap>", line 1007, in _find_and_load
File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 680, in load_unlocked
File "<frozen importlib.bootstrap_external>", line 790, in exec_module
File "<frozen importlib.bootstrap>", line 228, in call_with_frames_removed
File "/usr/lib/python3/dist-packages/azurelinuxagent/agent.py", line 34, in <module>
import azurelinuxagent.common.event as event
File "/usr/lib/python3/dist-packages/azurelinuxagent/common/event.py", line 632, in <module>
event_logger = EventLogger()
File "/usr/lib/python3/dist-packages/azurelinuxagent/common/event.py", line 304, in init
osutil = get_osutil()
File "/usr/lib/python3/dist-packages/azurelinuxagent/common/osutil/factory.py", line 50, in get_osutil
return _get_osutil(distro_name, distro_code_name, distro_version, distro_full_name)
File "/usr/lib/python3/dist-packages/azurelinuxagent/common/osutil/factory.py", line 79, in _get_osutil
return DebianOSBaseUtil()
NameError: name 'DebianOSBaseUtil' is not defined`

The deployment fails in Azure and I think this may be apart of that issue. I have reviewed their documentation and seen users having the same issue. Anyone ever faced this issue?
The original document in question that was used is this: https://learn.microsoft.com/en-us/azure/virtual-machines/linux/debian-create-upload-vhd
Answer: It looks like there is an error in the factory.py file.
try changing line 25 to add ", DebianOSBaseUtil" to the end of the import statement.


How do I (or is it advisable) downgrade Redhat Enterprise from 5.9 to 5.8 and find out when the original upgrade happened?

Question: Two fold question.

How do I find out when the upgrade from 5.8 to 5.9 happened?  Where is this logged?
What is the process of rolling back or downgrading from 5.9 to 5.8?

Background:  Supporting a client who is adding a NetApp storage device in the upcoming weeks and the configuration is certified up to 5.8, but not with 5.9.  It is then certified with 6.x versions.  Since the rest of the servers that will be using the device are all running 5.8 the desired outcome is to roll this one back and find out when it was upgraded (I am semi-new to the project, and the previous admin is long gone).
Kernel versions are the same across the servers, /etc/redhat-release is showing 5.8 for all but one, which is showing
$ more /etc/redhat-release
Red Hat Enterprise Linux Server release 5.9 (Tikanga)
Possibly worth noting, they are running Oracle Enterprise Linux, but for all (most) intents and purposes, they can be treated the same as RHEL.
Answer: You really shouldn't downgrade at this point. If you're not seeing a system stability or performance issue, keep the system at the 5.9 revision level. There's more risk in attempting to rollback than just dealing with issues as they come on the currently-supported version. Remember, Red Hat strives to keep minor OS revisions consistent and compatible throughout the support lifetime. E.g. a RHEL 5.5 box should run similarly to a 5.9 system.
In terms of logging, check to see if the system had the yum-updatesd daemon is running (with chkconfig or ntsysv). That would run automatic updates on the system and could be the reason why the server was pushed from 5.8 to 5.9.
The other location to examine for update and package installation activity is the /var/log/yum.log - You'll see the timestamps and package actions listed...
Jan 06 19:35:49 Installed: iplike-2.0.2-1.el6.x86_64
Jan 08 12:46:26 Installed: jwhois-4.0-19.el6.x86_64
Jan 13 20:30:55 Updated: selinux-policy-3.7.19-155.el6_3.14.noarch
Jan 13 20:31:20 Updated: selinux-policy-targeted-3.7.19-155.el6_3.14.noarch
Jan 13 20:31:21 Updated: iperf-2.0.5-3.el6.x86_64

Comment: He could also check the modification date of `/etc/redhat-release`.
Comment: @dwaynehoov That's because going from 5.8 to 5.9 is _not_ a version upgrade, it's just a bunch of updates rolled up and given a number (similar to a Windows service pack).
Comment: @EEAA Yah, but where's the fun in that?!?
Comment: Hehe, true. It's just a quick way to check. `yum.log` is a better solution, as it not only delivers the information the OP asked about, but also other useful information.
Comment: the first thing that I did was check the timestamp on redhat-release, I wanted to be 100% sure that the date was reliable. Also checked yum.log, nothing there indicating a version upgrade, just some package updates.  Also, it looks like yum-updatesd is running on the 5.9 server as well as the 5.8 boxes.  I don't think I can reliably say that it was automatically updated.
Comment: I think i found the issue.  automatic updates are running and there is a discrepancy in the repos listed in the yum.repos.d directory.  namely, the server that is at 5.9 had this enabled:  [ol5_UEK_latest]
name=Latest Unbreakable Enterprise Kernel for Oracle Linux $releasever ($basearch)
baseurl=http://public-yum.oracle.com/repo/OracleLinux/OL5/UEK/latest/$basearch/
gpgkey=http://public-yum.oracle.com/RPM-GPG-KEY-oracle-el5
gpgcheck=1
enabled=1
Answer: RHEL 5.9 was released on 2013-01-07, so it should be more recently than that.
Take a look at /var/log/yum.log (I'm going off CentOS).  There should be some package like redhat-release-notes-5.9 with a timestamp on the installation.
Comment: checked that out, nothing substantial, just some perl, python and nagios package updates.


PKIX Sun Certification issues with Eclipse

Question: My Eclipse (2020-03 - Running on Windows 10) was working perfectly. Then suddenly my company updated policies and absolutelly nothing more worked.
I keep getting:
Unable to read repository at https://download.eclipse.org/technology/epp/packages/2023-03/202303091200/content.xml.
javax.net.ssl.SSLHandshakeException: PKIX path building failed:
sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
at java.base/sun.security.ssl.Alert.createSSLException(Unknown Source)

NOTHING works anymore. Build, Compile, even the MarketPlace returns this error.
I tried a LOT of solutions in SO like this one, but none worked.
Added the certificate manually, updated policy, disabled company firewall (with the own company support).
When compiling, I even manually download each maven dependency and pom to the right place, so I could "bypass" the dep download, but didn´t work.
I manage to resolve it with the bellow answer. I am leaving it here to help someone in need like me in the future. (I spent 3 days trying to solve this issue).
Answer: The thing that did the trick for me, is describet in this thread.
Basically:
use the windows trust store by providing by adding the following option in eclipse.ini:
-Djavax.net.ssl.trustStoreType=Windows-ROOT
It ensures that eclipse uses all Windows Trusted SSL Certificates, and in my case, the issue is gone.
Hope it helps someone.
Thanks.


Buscar no banco de dados e comparar

Question: Tenho um código simples cujo objetivo é obter o valor de um campo e efetuar uma comparação, caso o valor seja zero, faz uma coisa, caso contrário, faz outra.
Entretanto eu devo estar errando em alguma coisa, pois não está funcionando como esperado.
Essa foi minha tentativa:
<?

$teste=$produto['fold'];

if($teste==0) {

?>

---

<?

} else {

?>

<a href="<?= $produto['fold']; ?>">Link

<?

}

?>

Com este código ele entra tanto no if quanto no else. Onde está meu erro?
Comment: Para começar, você tem certeza que o PHP está interpretando seu código? Como você está testando?
Comment: Tem certeza disso @RodolfoOliveira, o problema, com certeza, não é o código estar passando no `if` e no `else` de um mesmo `statement`, por que assim que ele entra no `if`, não tem motivo para ir pro `else` e se entra no `else` foi porque não satisfez a condição imposta... Existe um looping por fora desse `if`?
Comment: Como assim faz sentido, @BrunoAugusto? O que ele diz que está ocorrendo é impossível! Acho que o Bacco está intuindo o problema real, o código não está sendo interpretado e por isso tanto o `---` quanto o link estão sendo impressos. Talvez seja simplesmente o caso de não usar shorttags. Ou de fato acessar o servidor se o acesso estiver sendo feito por file:///. Só que o autor precisa esclarecer o que está fazendo antes de podermos reabrir. Porque para mim continua não estando claro.
Comment: Algum erro em particular, ou algo que posso ajudar a descobrir o problema? $produto['fold'] possui qual valor?
Comment: Ele possui ou um link ou 0,entretanto o codigo funciona,so que ele entra tanto no if quanto no else,e não entendo o porque
Comment: Acabei de copiar e rodar aqui este trecho de código e não está com o problema que tu relatou, até porque é impossível entrar no `if` e no `else` ao mesmo tempo. Nos mostre o que tu tem ao redor deste código.
Comment: Editado. Agora o tópico faz sentido e pode ser reaberto.
Comment: @RodolfoOliveira tente entender qual é o problema realmente. Acrescente mais informações do seu código na pergunta.
Comment: Não removi a última frase apenas para não violar a intenção do OP, mas é um teste lógico. Sim, sim, não, não, logo se entra no `If`, não pode estar entrando no `else` também.
Comment: Bom, eu compreendi a questão, isolei o problema e elaborei uma resposta explicativa. Estou apenas aguardando a reabertura do tópico apenas.
Comment: @BrunoAugusto Ok, estou reabrindo, poste sua resposta.
Comment: @RodolfoOliveira esse problema surge mesmo quando usas tags de PHP _completas_? ou seja `` para fechar?
Comment: Puxa... Quase que eu perco a chance por não ter visto o tópico sendo reaberto. Obrigado pelo voto de confiança.
Answer: O problema é com o cast burro e intrometido do PHP.
Segundo o manual (tradução livre):

Se você comparar um número com uma string ou a comparação consistir de strings numéricas, então cada string será convertida para um número e a comparação ocorrerá numericamente. […] Essa conversão não se aplica quando a comparação é feita com os operadores === ou !== uma vez que isso caracteriza comparação por valor e por tipo.

Dito isso, no seu teste:
if( $teste == 0 )

O lado esquerdo primeiramente está sendo interpretado como a variável que ele representa.
O lado direito, por ser um número "sugere" ao interpretador que a comparação deve ser numérica e com isso a string que a variável representa, passa, internamente, a ser um número também.
É como se estivesse sendo feito isso:
if( (int) $teste == 0 )

E como uma string não pode ser um número (óbvio) o resultado da conversão passa a ser zero e o resto é lógica.
Para resolver esse tipo de problema sutil e de difícil depuração use comparação tipada como diz o manual:
if( $teste === 0 )

E o link passará a ser criado.
À parte disso, deixo como sugestão que quando você estiver gerando HTML com PHP prefira utilizar a sintaxe alternativa das estruturas de controle pois fica MUITO mais fácil de compreender o abre-e-fecha de tags:
<?php if( $produto['fold'] === 0 ) : ?>

---

<?php else : ?>

<a href="<?= $produto['fold']; ?>">Link

<?php endif; ?>

Buscar no banco de dados e comparar


Normal distribution comparing 3 or more variables

Question: Let's say we had 3 students about to run race and their previous run times each follow a normal distribution,

$X \sim N(10, 2)$
$Y \sim N(14, 3)$
$Z \sim N(5, 1)$

Where $X$, $Y$ and $Z$ are independent.
I want to know if it is possible to work out the probability that $X$ will run the fastest time?
I feel like the question boils down to $P((X>Y) \cap (X>Z))$. I can work out $P(X>Y)$ and $P(X>Z)$  by creating a new distribution for each and just calculating mean and variance. But I am struggling to go this extra step to determine the probability that both scenarios are true.
Comment: What is $A$? $~~$
Comment: Sorry that was a typo it was meant to be X
Answer: If $\phi_1,\phi_2,\phi_3$ are the density function sof $X,Y$ and $Z$ then $$P((X>Y)\cap (X>Z))$$ $$=\int_{-\infty}^{\infty} \int_z^{\infty}\int_y^{\infty} \phi_1(x)\phi_2(y)\phi_3(z) dx dydz$$ $$+ \int_{-\infty}^{\infty}  \int_{-\infty}^{z}\int_z^{\infty} \phi_1(x)\phi_2(y)\phi_3(z) dx dydz$$
Comment: Sorry can you elaborate as to why those are the bounds for each integration?
Comment: @Sam You want to integrate over the region $\{(x,y,z): x>y, x >z\}$. If $y >z$ this reduces to the single condition $x>y$ and if $y z$. So split the integration w.r.t $y$ into the parts $y>z$ and $y <z$. Rest should now be clear.
Comment: Yes, that is crystal clear really appreciate the explanation


Tossing a coin with time evolving bias

Question: Consider the following random process starting at time $t = 1$ with a coin such that $\Pr(\text{Heads}) = p_1$. The bias of the coin, $p_t$, evolves with time as follows for $t \geq 1$:
At time $t$, the coin is tossed (it has $\Pr(\text{Heads}) = p_t$). Let $X_t$ denote the outcome of the toss.
\begin{align}
p_{t+1} = \begin{cases} \max\{p_t - \Delta_1, 0\} & \text{ if } X_t = \text{Heads}, \\
\min\{p_t + \Delta_2, 1\} & \text{ if } X_t = \text{Tails},\end{cases}
\end{align}
where $0 < \Delta_1 < \Delta_2$ are some small known constants. Thus, the bias of the coin evolves with time such that it always attempts to make the coin a fair one based on the observed outcome of a toss.
I am interested in bounding the following expression: $\displaystyle \Pr\left( \bigcup_{t = 1}^T \{p_t < \epsilon\} \right)$ for some $\epsilon > 0$. The value of $T$ is known and $\Delta_1$ and $\Delta_2$ are small constants, roughly $O(1/T)$, so that the $p_t$ does not tend to saturate to extreme values often.
Intuitively, this probability should be small because of the "corrective" nature of the underlying random process. However, I am unable to obtain an elegant upper bound on the same. The union bound is resulting in a very weak bound. I have also tried some Martingale based approaches but haven't been to find a concrete answer.
Any hints or references will be highly appreciated. Thank you.
Comment: I've been working for a few years on first-return times in a very similar model (with$\Delta_1=\Delta_2$) for a few years, on and off, in my nonexistent spare time. Mine is framed as a biased random walk but it's the same thing. You need some constraints on $\Delta$ and the initial condition to ensure that $p$ stays between zero and one. Then you can get some expressions involving hypergeometric functions for the z-transform of $\Pr(p_t=x)$. But you are interested in a special case ("near the endpoints" in my random walk) where you might find a simple approximation.
Comment: @sasquires Thanks for your reply. So this is a simplified version of the problem I am working on. In the original one, the constraints ensure that $p_t$ stays in $[0,1]$. Yeah I also tried using the MGF of $p_t$ but in that case I have to end up using the union bound which is too weak. I didn't really explore the biased random walk angle but I can give it shot. Do you have some specific references/insights that you might have come across and could share here? It might help give me a good starting point. Thanks for your help!
Comment: One clarification: when I mentioned Fourier transforms and z-transforms above, then this is what you would do if the problem was not bounded in space.  For this particular problem it's easier to think of these as generating functions, as I did in my answer below.  (But of course these are basically different representations of the same thing.)
Answer: This is too long to be a comment, and it will necessarily be incomplete, but I'll start writing up some of what I know whenever I get a chance.  (I apologize in advance that I'll edit this post a few times, but I won't have a chance to write it all in one sitting.)
In terms of references, I had a hard time finding anyone else who had studied this problem, because the literature uses different terminology than I would have.  I searched for random walks, biased coin tosses, avalanche processes, and branching processes.  But the main results in this field are from Karlin and McGregor studying "birth-death processes" in the 1950s.
They study a case where the probability of births/deaths is linearly biased, which is similar to our problem, but I don't think it's exactly the same, because the population is not bounded from above.  It's been a long time since I read these papers, so I could have misremembered something.  The best short summary that I remember reading is in the following book, under the topic "random walk polynomials":  Recurrence Relations, Continued Fractions and Orthogonal Polynomials by Richard Askey and Mourad Ismail.
As you've already seen and I will make explicit below, the problem is equivalent to a random walk where the probability of moving left/right is linearly biased with respect to the current position.  (I have jokingly called this "a drunkard in a valley," since the drunkard is more likely to move downhill toward the center of the valley.)
There are a number of famous results that apply to random walks with arbitrary move coefficients.  For example, there is a series representation due to Touchard.  There is also an extremely easy way to represent the time generating function of the first-return time as a continued fraction, and there is a method for handling such continued fractions due to Flajolet from around 1990.  But I wasn't able to use any of these to get something useful out of the problem.  I was successful using the poor physicist's standard trick of applying transforms.  I suspect that I don't have enough to solve your problem but definitely enough to get started.
Most of my existing results are in my office, where I can't access them right now because of the pandemic.  But I have enough at home that I should be able to give the really basic results.
My formulation of the problem is that there is a random walk with position $X(t)$ where the probability of moving left/right when at position $x$ is
$$ \begin{align} \ell_x &= 1 - \frac{x}{N} \\ r_x &= \frac{x}{N} \end{align} $$
where $N$ is a positive integer.
Let $p_{x,t}^s$ be the probability that $X(t)=x$ given that $X(0)=s$ (the "start" position).  Then $p_{x,t}^s$ satisfies
$$ p_{x,t}^s = (1 - \delta_{x,0}) r_{x-1} p_{x-1,t-1}^s + (1 - \delta_{x,N}) \ell_{x+1} p_{x+1,t-1}^s + \delta_{x,s} \delta_{t,0} $$
where $\delta$ is the Kronecker delta.  The first term represents a walk moving right from $x-1$ to $x$.  The second is a walk moving left from $x+1$ to $x$.  The third is the initial condition.
Let $P_x^s(z)$ be the generating function of $P_{x,t}^s$ with respect to $t$, i.e.,
$$ P_x^s(z) = \sum_{t=0}^\infty p_{x,t}^s z^t $$
Then one can show from the time-evolution equation of $p$ that
$$ P_x^s(z) = (1 - \delta_{x,0}) z r_{x-1} P_{x-1}^s(z) + (1 - \delta_{x,N}) z \ell_{x+1} P_{x+1}^s(z) $$
Now let $P^s(u, z)$ be the generating function of $P^s(z)$ with respect to $x$, i.e.
$$ P^s(u, z) = \sum_{x=0}^N P_x^s(z) u^x $$
The time-evolution equation becomes a differential equation in $P^s(u,z)$ in $u$:
$$ \frac{z}{N} (u^2 - 1) \frac{dP^s}{du} + (1 - uz) P^s = u^s $$
This is a linear first-order inhomogeneous differential equation, so the solution is straightforward.  The homogeneous part has solution
$$ \begin{align}
H(u, z) &= \exp\left( \frac{N}{z} \int \frac{1 - uz}{1 - u^2} du \right) \\
        &= C_s(z) (1 - u)^{-\alpha(z)} (1 + u)^{\beta(z)}
\end{align} $$
where $\alpha(z) = \frac{N}{2z}(1-z)$ and $\beta(z) = \frac{N}{2z}(1+z)$.  $C_s(z)$ is an integration constant that can depend on $z$ since the integration is with respect to $u$.  The integral is easy (just decompose into partial fractions).
The inhomogeneous part can be written as an integral in the usual way.  The closed form solution is an Appell $F_1$ function.  (The full expression is in my office notes.)  But in many applications, including mine but possibly not yours, there is one really important thing to observe.  The inhomogeneous solution must be $O(u^{s+1})$.  You can see this by writing the solution $P^s(u, z) = u^{s+1} f(u, z)$ and then show that $f(0, z)$ is a constant.
This has a hugely important corollary: For $x \le s$, the homogeneous part is the entire solution.  I'll use this below.  (Everything below is based on the assumption that $x \le s$.)  Moreover, if you need to consider $x > s$, then you can note that the original problem has a symmetry where the substitutions $x \to N - x$ and $s \to N - s$ do not affect the probabilities.  So you can essentially figure out quite a lot about the probabilities without ever calculating the inhomogeneous solution.
On the other hand, there is still $C_s(z)$.  There isn't an obvious boundary condition to determine $C_s(z)$ without the full inhomogeneous solution.  (For example, we know that $P^s(1,1)=\frac{1}{1-z}$, but this involves terms where $x>s$.)  It turns out that $C_s(z)$ is closely related to the inhomogeneous solution.  I believe that the relationship is something like $C_s(z)=-I_s(1,z)$, where $I_s(u,z)$ is the inhomogeneous solution.  This is based off of my memory, but I think that there is a simple argument to show this based on requiring $I_s(u,z)$ to be well-behaved near $u=1$.  This means that you can derive a lot of information about the ratios of probabilities at different values of $x$, but you can't get the absolute probabilities unless you solve the inhomogeneous problem.
With all this in mind, we can start inverting the generating functions.
The series for $H(u,z)$ in $u$ is
$$ \begin{align}
H(u,z) &= C_s(z) \sum(1 - u)^{-\alpha(z)} (1 + u)^{\beta(z)} \\
       &= C_s(z) \sum_{j,k} (-1)^j \binom{-\alpha}{j} \binom{\beta}{k} u^{j+k} \\
       &= C_s(z) \sum_x u^x \sum_j (-1)^j \binom{-\alpha}{j} \binom{\beta}{x-j} \\
       &= C_s(z) \sum_x u^x \binom{\beta}{x} {_2}F_1\left(\begin{matrix} \alpha, -x \\ \beta - x + 1 \end{matrix}; -1 \right)
\end{align} $$
where ${_2}F_1$ is the Gauss hypergeometric function.  So for $x \le s$ then we have
$$ P^s_x(z) = C_s(z) \binom{\beta}{x} {_2}F_1\left(\begin{matrix} \alpha, -x \\ \beta - x + 1 \end{matrix}; -1 \right) $$
This may be the end of the results that I have that are useful to you.  I'm not really sure.  I'm happy to keep discussing here when you have thought about it.  I am mainly interested in deriving simple numerical approximations for the first-passage time to $x=s-1$, which is related to the ratio $P^s_s(z)/P^s_{s-1}(z)$.  If this is useful I can probably provide some more information.  But you may need absolute probabilities near $x=0$ or $x=N$, which is something I haven't devoted a lot of time to thinking about this.
One more piece of advice.  The hypergeometric representation above is hard to invert, but it is very versatile and you can extract a lot of information from it.  (There are a bunch of equivalent hypergeometric representations using Euler and Pfaff transforms, and of course there are also integral representations.)  And there are other approaches to the same problem, like the orthogonal polynomial representation of Karlin and McGregor mentioned above, that are closely related.
Disclaimer: All of the above is based on very messy notes where I had re-derived some of the main expressions at home, and there may be typos, so some of it may need fixing.  Please let me know if you find errors.
Comment: (If this wasn't clear, I am going to dig up my notes and post more. But I have a three year old that keeps me busy nonstop, and our work schedule is crazy due to the pandemic, so it will come in bits and pieces when I get time over the next few days.)
Comment: Thanks a lot for the references. I will go through them and see if I get some ideas from there and also look into the z-transform method again. I should hopefully get some leads from there. Also whenever it is comfortable for you (there is no rush at all, these suggestions should keep me occupied for a while) can you please share the basic results you have? Would be helpful to have something to check against especially if I get stuck again. Once again, thank you so much for your time. I understand these few months have been challenging and I really appreciate you taking out time for this. :)
Comment: That is an amazingly detailed answer! Thank you so much for taking out the time for writing that up. It would definitely be very helpful. It will take me a while to absorb all this and adapt this to my situation (especially I have limited experience with generating functions and hypergeometric functions). I will get back to you once I have made some progress or if I have some more questions. Thank you so much once again for sharing this with me! :)
Comment: You're welcome. For my problem, this is just the very beginning. I'm using this to understand finite-size effects in certain avalanche processes, and I've been planning on writing a paper about this for years now, basically since I finished grad school, but I haven't found the time. I am mostly just glad that someone is interested in the same model, though presumably for different reasons.
Comment: Oh that's interesting! And I definitely understand that part of not being able to get time to work on a pet problem. In my case, I am working on a totally different problem and one of the lemmas involves bounding that probability for slightly complicated variant of the problem I posted. Now after reading your answer, it seems I've opened a Pandora's box. It seems like a very interesting problem in its own right. I'm glad I posted this on MSE and got your insights. There is no way I'd worked this out. I hope you get around to finally publish that paper! Definitely looking forward to it!

Tossing a coin with time evolving bias


Prove that f is differentiable in $\mathbb{R}$

Question: Let $f: \mathbb{R} \rightarrow \mathbb{R}$ some function that all $x$ and $y$ in $\mathbb{R}$ satisfies: $$\left|f(x)-f(y)\right| \le (x-y)^2$$

Prove that f is differentiable in any point in $\mathbb{R}$.
Prove that f is constant.
Comment: FYI, it's "differentiable" :)
Comment: A function with the property that $|f(x)-f(y)| \le C |x-y|$ for some $C \gt 0$ and all $x,y$ is said [Lipschitz continuous](http://en.wikipedia.org/wiki/Lipschitz_continuity).  There's a story that makes the rounds in math grad schools that a PhD student was defending a thesis on marvelous properties of functions with Lipschitz exponent greater than 1, meaning something of the sort illustrated here by a square power.  Possibly apocryphal, as the story goes an implication was pointed out by a defense committe member other than the thesis adviser, that all such functions are (as here) constant.
Comment: @Jim thank's :)
Comment: For another approach, see Davide Giraudo's answer in [this](http://math.stackexchange.com/questions/144621/a-question-about-holder-spaces/144622) post.
Answer: You have $|f(x)-f(y)|\le |x-y||x-y|$ then $\displaystyle\frac{|f(x)-f(y)|}{|x-y|}\le|x-y|$ Just take the limit as $x\to y$ , you get $|f'(y)|\le 0$(then $f'(y)=0)$ for all $y$ then $f$ is constant
Comment: Please edit to use the absolute value in the denoninator
Comment: @Barbara Thank you for pointing it out
Answer: I would like to point out that it is possible to prove the assertion without proving differentiability in the first place.
For each x we have
$$|f(x)-f(0)| = \left|\sum_{k=1}^n f\left(\frac{k}{n} \cdot x\right)-f\left(\frac{k-1}{n}\cdot x\right)\right|$$
Thus by the triangle inequality
$$|f(x)-f(0)| \le \sum_{k=1}^n \left|f\left(\frac{k}{n}\cdot x\right)-f\left(\frac{k-1}{n}\cdot x\right)\right|$$
Since for each $k$
$$\left|f\left(\frac{k}{n}\cdot x\right)-f\left(\frac{k-1}{n}\cdot x\right)\right| \le \left|\frac{k}{n}\cdot x-\frac{k-1}{n}\cdot x\right|^2 = \left|\frac{x}{n}\right|^2$$
It follows that
$$|f(x)-f(0)| \le \sum_{k=1}^n \frac{x^2}{n^2} = \frac{x^2}{n}$$
And thus
$$|f(x)-f(0)|\le \limsup_{n\rightarrow\infty} \frac{x^2}{n} = 0$$
Hence for all $x$
$$f(x)=f(0)$$
Thus f is constant. It follows that f is differentiable everywhere ;)
Answer: For each $x\in\mathbb R$, for each $y\in\mathbb R$ with $y\neq x$, we have $0\leq |\frac{f(x)-f(y)}{x-y}|\leq |x-y|$. Let $y\to x$. Then by squeezing we obtain $f'(x)=0$ for all $x\in\mathbb R$ so that $f$ is constant.
Comment: I think you mean $y \to x$.
Comment: Shouldn't there be absolute values as in $\le \vert x-y \vert$?
Answer: Let $a\in\Bbb R$ be fixed and $x\neq a$ then
$$\left| \frac{f(x)-f(a)}{x-a}\right|\le|x-a|$$
Since $\lim_{x\to a}|x-a|=0$, we get $\lim_{x\to a} \left| \frac{f(x)-f(a)}{x-a}\right|=0$. So $f$ is differentiable at $a$.
And $f'(a)=0$ for all $a$, By mean value theorem we get
$$f(x)-f(y)=f'(c)(x-y)$$
for some $c$. Since $f'(c)=0$, we get $f(x)=f(y)$, So $f$ is constant.
Answer: By definition of what it means to be differentiable, you want to prove that the limit
$$
\lim_{x\to y} \frac{f(x)- f(y)}{x-y}
$$
exists for all $y\in \mathbb{R}$. That will follow (in this case) from showing that
$$
\lim_{x\to y} \left\lvert\frac{f(x)- f(y)}{x-y}\right\rvert
$$
exists. Now you have that
$$
0\leq \left\lvert\frac{f(x)- f(y)}{x-y}\right\rvert = \frac{\lvert f(x)- f(y)\rvert}{\lvert x-y\lvert} \leq \frac{\lvert x - y\rvert^2}{\lvert x - y\rvert} = \lvert x - y\rvert.
$$
Now you have $\lvert x - y\rvert \to 0$ as $x \to y$. So by the Squeeze Theorem you must also have
$$
\lim_{x\to y} \left\lvert\frac{f(x)- f(y)}{x-y}\right\rvert = 0
$$
And so
$$
\lim_{x\to y} \frac{f(x)- f(y)}{x-y} = 0
$$
That means that $f$ is differentiable and that the derivative at any number $y$ is zero: $f'(y) = 0$.
As others have already mentioned this means that $f$ must be a constant: If you had $f(x) \neq f(y)$ for some $x$ and $y$. Then by the Mean Value Theorem you would have a $c$ between $x$ and $y$ such that $0\neq f(x) - f(y) = f'(c)(x-y) = 0$. This is a contradiction, so indeed $f(x) = f(y)$ for all $x$ and $y$.
Comment: It's not the *same* to show the absolute value of the difference quotient has a limit, but to show the difference quotient tends to zero it *suffices* to show the absolute value of the difference quotient tends to zero.
Comment: @MatthewLeingang: I edited. Thanks.


ASP.NET MVC + Entity - Como mapear novas tabelas

Question: Bom dia,
Tenho um projeto utilizando ASP.MVC + EF e mapiei cerca de 20 tabelas usando o assistente do VS (criando o ADO.NET Entity Data Model, selecionando a base de dados e as tabelas que quero), mas agora tenho mais 16 tabelas para inserir no sistema e não encontro uma opção para inclui-las utilizando o mapeamento automático (como nas primeiras 20).
Pelo que vi, algumas pessoas indicam excluir a minha classe que possui os DbContext (criada a partir do assistente do ADO.NET Entity Data Model) e recria-la, mas não tenho certeza se esse é o caminho ideal, visto que os models do inicio já estão formatados com Data Annotations e são usados em diversos controllers.
Existe alguma forma de mapear novas tabelas usando o Wizard do Entity Data Model sem a necessidade de excluir o DBContext criado no primeiro mapeamento?
Estou usando o Visual Studio Community 2017 e o modo Code First from DataBase.
Answer: Você pode abrir o designer clicando com o botão direito do mouse no seu arquivo .EDMX e selecionando Open With -> ADO.NET Entity Data Model Designer

Clique com o botão direito na superfície de designer do designer .EDMX e clique em Update Model From Database.

Todas as entidades são atualizadas por padrão, as novas entidades só são adicionadas se você as selecionar.
Comment: Olá, Marconcilio Souza! Muito obrigado pela ajuda.

No caso que citei acima, não tenho .EDMX pois usei o EF Code First from Database - pelo que pesquisei, o EDMX é gerado quando utiliza-se o Designer Centric (Model First e DataBase First).

De qualquer forma, para resolver o meu problema criei os models na mão. Talvez não tenha sido a forma mais agil, mas consegui aprender alguns concetos importantes que não tinha notado até então.

Muito obrigado pela sua disponibilidade em ajudar! Abraço!


File listing shows attributes in some folders but not in others

Question: I'm having trouble trying to get attributes from files in my list. The code is:
if ($this->dir = opendir($caminho))
{
    $this->itens = array();
    $this->itensTotal = 0;
    $tipos = array("dir" => 0, "file" => 1);

    while ($item = readdir($this->dir))
    {
        if (!in_array($item, $this->skip))
        {
            $t = filetype($item);
            $this->itens[$tipos[$t] . $item] = array("nome" => $item,
                                                     "size" => filesize($item),
                                                     "tipo" => $t,
                                                     "perm" => fileperms($item));

            $this->itensTotal++;
        }
    }
}

Seeing that my script is 'file.php' and is in the folder 'www'. When it reads it's own folder (www) it works ok and lists all files and directoryies with their attributes. But when it tryies to read eg.: /www/folder/ the function filetype(), filesize() an fileperms() doesn't works! I get these warnings for all itens in the directory:

Warning: filetype() [function.filetype]: Lstat failed for bkp in
  D:\UniformServer\UniServer\www\files.php on line 174
Warning: filesize() [function.filesize]: stat failed for bkp in
  D:\UniformServer\UniServer\www\files.php on line 176
Warning: fileperms() [function.fileperms]: stat failed for bkp in
  D:\UniformServer\UniServer\www\files.php on line 178

It's opens the folder, read it's contents but these functions doesn't woks =s
Notes:

As you can see I'm running it on Windows
$caminho has valids paths

Please, any help will be welcome cause google doesn't helped.
Comment: You say `/www/folder`, but you're on Windows, which uses `\ ` for paths, not `/`. Which are you using?
Comment: Well, I'm using `/` cause `$_SERVER['DOCUMENT_ROOT']` returns me `D:/UniformServer/UniServer/www/`. I didn't realize that on the warning it's uses `\\`
Comment: php can translate the slashes, that's not a worry.
Answer: I think $item only contain the basename of the file. You should probably prepend the directory path to it, like this: filetype(this->dir . $item).
Comment: You both right, but `$this->dir` handles the resource, `$caminho` has the path.
Answer: The file operations use the real directory names on the system, not the relative path of the website,  and "/www/folder" probably doesn't exist then.  From your comment, you would need either: "D:/UniformServer/UniServer/www/folder" or use a relative path from the php script.


How do I display a block on an edit form for particular content types?

Question: It's fairly simple to display a block on the node add form for a particular content type. Simply restrict visibility to a URL path like node/add/article and you're good to go.
I would like to know how to display a block on the edit form for a particular content type. For instance, when editing an article, the URL path is node/NID/edit.
Is there an easy way to display a block for edits of a given content type?
Comment: You need to use `php code` to implement this.
Comment: Do you have an example of a snippet I could put into the PHP code textarea to accomplish this?
Answer: You need to add php code in the block Visibility settings in admin section of block. You can follow below code.
$node = menu_get_object();

   if (isset($node) && $node->type == 'article' && arg(2) == 'edit') {

     return TRUE;
   }

   return FALSE

Another example:
$nid = arg(1);

   $node = node_load($nid);

   if (isset($node) && $node->type == 'article' && arg(2) == 'edit') {

     return TRUE;
   }

   return FALSE

Answer: Here's how to display a block on an add and edit form for a particular content type via PHP code in the block configuration.
<?php
    $show_block = false;
    $content_type = 'article';
    $types = array($content_type);

    if (arg(0) == 'node' && is_numeric(arg(1))) {
        $nid = arg(1);
        $node = node_load($nid);
        $type = $node->type;
        $show_block |= in_array($type, $types);
    } else if (arg(0) == 'node' && arg(2) == $content_type) {
        $show_block = true;
    }
    return $show_block;
?>


Gray overlay and no dialog when clicking Image button in CKEditor

Question: Attempting to get CKEditor and Media to work together on a Drupal7 site. Things are mostly working great, but when I click the regular Image button (or double-click an image, or use the context menu to access image properties), I get only a gray overlay and no dialog window.
I'm using CKEditor 7.x-1.18 with the 4.10.0 FULL library locally installed (in libraries), as well as CKFinder 3.4.4 (also in libraries), all with Media 7.x-2.19 and the Media CKEditor 7.x-2.5 bridge module.
When I click the Image button, I get this error in console:
<code>TypeError: Drupal.settings.picture is undefined[Learn More] plugin.js:152:15
init/<
http://example.com/sites/all/modules/picture/ckeditor/plugins/plugin.js:152:15
n
http://example.com/sites/all/libraries/ckeditor/ckeditor.js:10:222
CKEDITOR.event.prototype</<.fire</<
http://example.com/sites/all/libraries/ckeditor/ckeditor.js:12:42
CKEDITOR.dialog
http://example.com/sites/all/libraries/ckeditor/ckeditor.js:594:500
openDialog
http://example.com/sites/all/libraries/ckeditor/ckeditor.js:642:134
openDialog/<
http://example.com/sites/all/libraries/ckeditor/ckeditor.js:642:492
e
http://example.com/sites/all/libraries/ckeditor/ckeditor.js:258:175
y
http://example.com/sites/all/libraries/ckeditor/ckeditor.js:258:332
v
http://example.com/sites/all/libraries/ckeditor/ckeditor.js:258:412
A/e.$.onload/<
http://example.com/sites/all/libraries/ckeditor/ckeditor.js:259:327
</code>
I'm not Drupal-technical enough to understand this error entirely. But my intuition is that I don't have something configured correctly. (Installation instructions I have found are so ancient, I'm not even sure the module supports this version of CKEditor.)
Answer: After discovering that the Image button works fine in the default "Advanced" text format, which I did not modify, and which doesn't have the Media button added, I started investigating differences.
Turns out that if I disable the Picture module in Editor Appearance > Plugins, things work.
I just don't know what I'm giving up by disabling this. I would like images to be responsive. :-(


Aren't SQL Server Views portable?

Question: During an application architecture review meeting, one of my colleagues said that, if we are going to make our schema portable (i.e. From SQL Server to Oracle/MySQL/Any other relational DB), we only have to stick to "Tables" and not create "Views"; as they are not portable.
I'm not convinced by the answer, as I see no reason why Views are not portable.
Can someone throw some light? I'm unable to get the right direction with search engines.
Comment: @Downvoter: Can you please comment why? Your reason could help improve myself.
Answer: The basic CREATE VIEW syntax containing a SELECT query is standard SQL1 and has been for a very long time. However, certain options and features, such as schema-binding and indexed views are product specific.
Having Views and Tables, and having them be largely interchangable is based on the original relational model. Codd's rules include

Rule 6:- The view updating rule:
All views that are theoretically updatable are also updatable by the system.

Also, of course, having a portable schema is one of those things that sounds sensible but almost never works out in practice. There are too many actual deviations from the standards in real products. If you limit yourself to only the portable subset, you'll almost certainly have a broken database with half of the constraints that should be enforced not.

1The various SQL standards, as finally published, are not freely distributable. However, this draft of the ANSI-92 standard (named after the year of its standardization) largely reflects what was in the standard and contains:

     11.19  <view definition>

     Function

     Define a viewed table.

     Format

     <view definition> ::=
          CREATE VIEW
 [ <left paren> <view column list>
          <right paren> ]
            AS <query expression>
            [ WITH [ <levels clause> ] CHECK OPTION ]

     <levels clause> ::=
          CASCADED | LOCAL

     <view column list> ::= <column name list>

Comment: Thank you @Damien_The_Unbeliever for the answer.
Comment: @DanGuzman, Thanks for that, and understood.  I usually wait for a day at least.
Comment: @CodeMad - and that's why I don't personally do these sort of chase up comments. If people engage with the site, sooner or later they'll accept answers on most of their questions. I can wait :-)

Aren't SQL Server Views portable?