What is the LCM of $x,2x, 3x$?

Question: My understanding says the lcm should be $6x$.
Comment: And your understanding is correct.
Comment: $$\textbf{Yes!}$$
Comment: You are right. I have supplemented an easy procedure to find the LCM between any number
Answer: The technique I use for finding the LCM of 3 numbers is best shown with an example. Let's assum we want the LCM of $ 8, 20, 50$, the first thing we do is a prime factorisation of each number:
$$8 = 2 \times 2 \times 2$$
$$20 = 2 \times 2 \times 5$$
$$50 = 2 \times 5 \times 5.$$
Now we first look at what number all three of them have in common. All three of them contain a $2$ and so the first number we have is :
$$2.$$
We are now left with
$$8 \rightarrow 2 \times 2$$
$$20 \rightarrow 2 \times 5$$
$$50 \rightarrow 5 \times 5.$$
As we now don't have the same number in all three of them, we look for a number we have in two of them. Both $8$ and $20$ have a $2$ and both $20$ and $50$ have a $5$. So now multiplying all the numbers we have taken out together gives us
$$2 \times 2 \times 5.$$
We are now left with
$$8 \rightarrow 2$$
$$20 \rightarrow 0$$
$$50 \rightarrow 5.$$
Now, as we don't have the same number in any two of them, we just take the remainig number and multiply that with the numbers we have already multiplied, giving us
$$\mathrm{LCM} = 2 \times 2 \times 5 \times 2 \times 5 = 200,$$
which is the answer.
We can use this technique for your question. As we don't know if $x$ is a prime number, let's assume it is. Breaking up all three numbers gives us
$$x = x$$
$$2x = 2 \times x$$
$$3x = 3 \times x.$$
Now, the first number we take out is $x$ as they all have that in common. We are then left with
$$x \rightarrow 0$$
$$2x \rightarrow 2$$
$$3x \rightarrow 3.$$
As we don't have the same number in any two of them now, we just take out the remaining numbers and so to find our LCM we have to multiply
$$x \times 2 \times 3 = 6x.$$
So you are correct.
Answer: Another easy way is to "factor" a term out if $2+$ terms have the same factor. Then multiply the factors with what's left.
Let me explain with an example:

Find the LCM of $2,5,14,60$.

We notice $2,14,60$ can factor out a $2$. Thus, we have $$2| 1,5,7,30\tag1$$
Again, we notice that $5,30$ have common factor $5$. Thus, we have$$2|1,5,7,30\\ 5|1,1,7,\hspace{2mm}6$$
Multiplying what's remaining, we get the LCM as $2\cdot 5\cdot 1\cdot 1\cdot 7\cdot 6=\boxed{420}$

The same thing can be used to find the LCM of $x,2x,3x$. We notice that we can factor out $x$. Doing so, we obtain$$x|1,2,3$$
Since we can't factor anything out, we multiply everything to obtain $x\cdot 1\cdot 2\cdot 3=\boxed{6x}$

What is the LCM of $x,2x, 3x$?


Print multiple columns individually

Question: Using the following query:
SELECT title, nid, created FROM node WHERE uid = $account->uid ORDER BY changed DESC

How do I go about printing the title, nid, created separately (in PHP)?
Thanks! (I'm sure this is VERY simple, I'm just not used to PHP yet)
Answer: This is a very basic question, try google for tutorials.  Here's a c/p from the very first google result about PHP and mysql which shows the technique you're after.
// Retrieve all the data from the "example" table
$result = mysql_query("SELECT * FROM example")
or die(mysql_error());

// store the record of the "example" table into $row
$row = mysql_fetch_array( $result );
// Print out the contents of the entry

echo "Name: ".$row['name'];
echo " Age: ".$row['age'];

http://www.tizag.com/mysqlTutorial/mysqlquery.php
Answer: If you expect only one result:
$query = "SELECT title, nid, created FROM node WHERE uid = '".$account->uid."' ORDER BY changed DESC";
$resource = mysql_query($query) or die (mysql_error());

if(mysql_num_rows($resource)>0)
{

   $row = mysql_fetch_array($resource);
   echo 'Title: '.$row['title'].'
';
   echo 'ID: '.$row['nid'].'
';
}
else
{
  echo 'no record found';
}

Otherwise (i reread the title of the question now, sorry)
while ($row = mysql_fetch_array($resource))
{
      echo 'Title: '.$row['title'].'
';
      echo 'ID: '.$row['nid'].'
';
}

Print multiple columns individually


How to integrate content type to webform Drupal 7?

Question: I have a content type called "student".
now I want to set that content type as select option component in webform.
Are there any way to do so? thanks,
Comment: in my opinion your question is vague, I suggest that you can add more information to your question about, for example, what do you want to display in the list, the list of content of that content type to select one or several nodes? and after that, what do you want that happens?
Comment: Do you want that content to show up in the Webform content type when an admin is creating a new webform? Or on the actual webform for a user?
Answer: Tvphong, I think that the best way to go about doing this is by using a custom module so that you can then integrate that content type within the select list of preloaded options.
Perhaps this link can serve you well in this.
What I ended up doing is a slight tweak of this. So my custom module looks something like this (which is for location content types):
<code><?php

/**
 * Reference:  http://eureka.ykyuen.info/2012/04/11/drupal-7-dynamic-select-options-for-webform/
 * The following piece of code is based on the blog post above
 */
function webform_options_webform_select_options_info() {
 $items = array();

 if (function_exists('get_location_titles')) {
  $items['location_titles'] = array(
    'title' => t('Location titles'),
    'options callback' => '_get_location_titles',
    );
 }

 return $items;
}

function _get_location_titles() {
 $options = array();
 $type = "location";

 $result = db_query('SELECT nid, title FROM {node} n WHERE n.type = :tname', array(':tname' => $type));
 foreach ($result as $row) {
  $options[$row->nid] = $row->title;
 }
 return $options;
}
</code>


Javascript tem um operador xor?

Question: Existe um operador xor em javascript e qual seria a forma 'simbólica' dele (por exemplo or tem || e and tem &&)?
Comment: `!!(true ^ false)`?
Answer: O JavaScript não possui um operador XOR lógico.
Tem um operador XOR bit a bit ^ que pode realizar uma comparação bit a bit de dois números, mas isso não ajuda quando você deseja obter o resultado de uma XOR de duas expressões, que não retornam um número.
O que você pode fazer é criar uma função para fazer este tipo de operação lógica:
function myXOR(x, y) {
  return (x || y) && !(x && y);
}

if (myXOR(hasValue(value1), hasValue(value2))) {
  //FAZ ALGUMA COISA
}

Seguem algumas referências para você entender melhor como funciona as operações lógicas no JS.
https://developer.mozilla.org/pt-BR/docs/Web/JavaScript/Guide/Expressions_and_Operators#operadores_bit_a_bit
http://www.howtocreate.co.uk/xor.html
https://docs.microsoft.com/en-us/scripting/javascript/reference/bitwise-xor-operator-decrement-hat-javascript
Answer: Você pode utilizar o operador ^ como descrito nessa resposta
Ex.:
var nb = 5^9 // = 12

Para valores booleanos você pode converter com !!, que irá inverter o resultado transformando-o em boolean, depois invertendo-o novamente
Ex.:
!!(false ^ true)

Answer: Se você analisar a tabela verdade do XOR, também conhecido como "Ou exclusivo", verá que a saída é verdade apenas quando as entradas são diferentes.
┌───────────┬───────────┬───────┐
│ entrada_a │ entrada_b │ saida │
├───────────┼───────────┼───────┤
│ false     │ false     │ false │
│ false     │ true      │ true  │
│ true      │ false     │ true  │
│ true      │ true      │ false │
└───────────┴───────────┴───────┘

Dito isso, é bem simples implementar um xor correspondente à tabela acima, pois o resultado é verdadeiro apenas se as entradas são diferentes. Basta retorna entrada_a != entrada_b.
function xor(a, b) {
    return a !== b;
}

Estou usando comparação estrita, mas você deve usar dependendo da sua necessidade, entenda a diferença em "Qual a diferença entre os operadores == e === em JavaScript?".

Lembrando que o operador XOR possui comutatividade, ou seja:
(a ^ b) ^ c == a ^ (b ^ c)

Usando operador != como um xor mantém a comutatividade, veja exemplos:
(0 ^ 1) ^ 1; // 1
0 ^ (1 ^ 1); // 1

(0 !== 1) !== 1; // true
0 !== (1 !== 1); // true

Comment: Mas aí entra validação de inputs que não é o escopo da resposta (a tabela verdade mostra que os inputs válidos são apenas `true` e `false`). Você está usando como exemplo que `null` e `undefined` seriam valores válidos para a função. Essas peculiaridades específicas do seu caso devem ser ajustadas de acordo com a necessidade. Para demonstração de conceito, acredito que adicionar esta informação seria desnecessária na resposta.
Comment: Bom, não exatamente... se passar `xor(null, undefined)` ou `(4, 2)` ele retorna `true`, o que está errado. Uma implementação melhor seria `function xor(a, b) { return !!a !== !!b }`. O valor booleano tem que ser diferente, não o valor real.
Answer: Olha, pra não ter que converter para booleano, você pode "improvisar" um XOR usando AND e if/else. Segue aí um trecho de código, usando duas variáveis p e q.

var p = false
var q = true

p = window.confirm("Selecione 'OK' para p==true, e 'Cancelar' para p==false.")
q = window.confirm("Selecione 'OK' para q==true, e 'Cancelar' para q==false.")

if (!p && q){
  window.alert ("A expressão é verdadeira.")
}else{
  if (!q && p){
    window.alert ("A expressão é verdadeira.")
  }else{
    window.alert ("A expressão é falsa.")
  }
}

Javascript tem um operador xor?


Componente joomsocial causa erro "class 'CAccess' does not have a method 'authorise'"

Question: Eu instalei o joomsocial em meu joomla, porem quando eu conclui a instalação o seguinte erro aparece:

Warning: call_user_func_array() expects parameter 1 to be a valid callback, class 'CAccess' does not have a method 'authorise' in /home/swingudi/public_html/social/components/com_community/helpers/access.php on line 74
Comment: Boa noite, qual versão do joomlasocial e do joomla esta usando (NÃO COMENTE) e como fez a tal instalação do componente, edite a pergunta e coloque informações importantes como esta pra que seja possivel conseguirmos lhe ajudar. Provavelmente você instalou uma versão que não é compativel com o Joomla que esta usando.
Comment: Outra dica, todo veem aqui procurando ajuda, escrever no titulo coisas como "Ajuda", "por favor", "Help" é totalmente irrelevante. Crie titulos relevantes ao topico da pergunta. Tenho certeza que vai levar o meu comentário como uma critica construtiva.
Comment: Acho que não leu o comentário eu disse NÃO COMENTE, edite a pergunta, de detalhes, informe as versões exatas que esta usando do Joomla e do componente, **por favor leia com mais atenção**, as dicas aqui são pra tentar lhe ajudar a melhorar a pergunta pra que consigamos um parâmetro por onde começar a detectar o problema o seu problema, comente coisas relevantes apenas, por exemplo respostas a outros comentários. Tenho certeza que vai levar o meu comentário como uma critica construtiva. :)
Comment: Wellington, observe os comentários deixados por outros usuários em suas perguntas pois eles geralmente dão boas dicas de como evitar o fechamento e deixar sua pergunta com uma qualidade maior. Justamente por você ter várias perguntas fechadas recentemente o sistema acabou te bloqueando de perguntar. Se você conseguir fazer com que sua pergunta seja reaberta esse bloqueio do sistema deve ser suspenso logo em seguida.
Comment: Ola realmente esta relacionada a versão do joomla, o erro ocorreu apos a atualização do mesmo, eu tenho a versão 3 do joomsocial,
O problema é que eu estou tentando instalar a verção mais antiga do joomla mas não esta dando certo, não completa a instalação
Comment: Eu não entendi a edição do titulo e nem a tag Helper, vou fazer o rollback. Titulos devem ser intuitivos.
Answer: Simples, sua classe não tem um método chamado "authorise". Você precisa definir este método na classe ou ele pode ser privado, neste último só poderá ser chamado de dentro da própria classe. Procure especificar melhor sua pergunta, isso vai nos ajudar a responder.
Comment: Pois é, @Wellington, este é um site para programadores, um mínimo de conhecimento da sua parte é necessário.
Comment: Ola amigo é que eu sou designer e não entendo muito sobre php, pra falar a verdade eu ainda nao entedi o que voce quis dizer com o metodo de chamado
Comment: onde eu devo ir para mudar
Comment: mas é desta forma que vou aprendendo


Universal hashing family

Question: I'm not really sure this question is proper for MathExchange but I have found it more suitable than StackOverFlow.
So, I'm taking the course of Data Structures and Algorithms and we got some example for a hashing function family described by a matrix.
I also found it be taught by MIT through this lesson: https://www.youtube.com/watch?v=z0lJ2k0sl1g&t=3424s
And I have some questions regarding this example as shown during 32:00 to 36:30:

I begun losing him in 33:24 when he suggests to represent every key by the base of $m$ and this key is somehow translated to a vector of $m$ coordinates, and the process of transforming it to a vector is not really understandable.
Then he takes some key, representing it by a column vector, defining a dot product which generates hashes to other keys (?).

So, these two points are pretty not clear for me, and I also tried to think of a suitable matrix for this kind of hash function couldn't find one.
Can someone clarify these issues?
Comment: Could you please make the post more self-contained by adding the main content of the relevant part of the video?
Comment: @Berci It will probably just complicate the issue than it is really.
Answer: Let's start with a simplified "universe" (his term, not mine), the integers from $0$ to $63$. There are $64$ total elements in this universe, and we see that $64 = 2^6$. In other words, for every key in our universe, I can represent it as a vector in base-$2$ with six coordinates. For example, $42$ can be represented as $(1, 0, 1, 0, 1, 0)$, and $13$ can be represented as $(0,0,1,0,1,1)$. Here I'm taking the leftmost entry to be the most significant digit. These representations look awfully familiar: concatenate the entries, and you have the binary representation of a number: $42_d = 101010_b$, $13_d = 001101_b$, etc.
Take a moment to remember our ultimate goal in creating a hashing function: we want to map any key to an integer between $0$ and the number of "buckets," $m$. He defines the hash function as follows: take the dot product of some randomly pre-chosen key $a$ and the key $k$ which you wish to hash, then take the result modulo $m$ (this is to ensure that the hash function returns a number between $0$ and $m-1$, inclusive). So if I'm trying to hash $13$ and my pre-chosen key $a$ was $42$, then I would first compute the dot product of their vector representations: $(1,0,1,0,1,0) \cdot (0,0,1,0,1,1) = 2$, then take the remainder when divided by $m$ ($m$ = 2 in this example, so our hash function returns $0 \equiv 2 \text{ mod } 2 $).
I'm not quite sure what you mean by this statement: "I also used to figure a suitable matrix out of this family and couldn't fine one," but I hope the above explanations helped!
Comment: Yes, I think for the purpose of his lecture, it was random. For example, I could just choose arbitrarily, as in the example, that $a=42$. I don't think there's really a difference so long as you don't choose $a = 0$, but for simplicity, he just chose it to be random.
Comment: As for the question about matrices, I guess you could define the matrix $B = a^T$ over the finite field $\mathbb{F}_m$, and premultiply any key $k$ that you wish to hash by $B$, i.e. hash($k$)=$Bk$.
Comment: In this example, $m=2.$
Comment: Correct, I should make that clear.
Comment: Okay. So it becomes clear. But I'm not sure about that chosen $a$. Do we actually generate our hash function out of some random key? Why is it? And can we generate a matrix which represent this hash function? Will this matrix be linear at all? Generally, now the creating of the hash function is pretty vague for me. Thank you for this good answer!

Universal hashing family


Combined variance following multiple imputation with survival model

Question: I have created 5 imputations of a dataset and have fit a survival model to them all in R. I want to combine the estimates of the coefficients and the standard errors of the coefficients. To do this I have taken the mean of the coefficients and combined the standard errors using Rubins formula, i.e.
$$(1+1/m) \times \text{between imputation variance} + \text{within imputation variance}$$
I was thinking about it and I'm having some doubts as to whether this makes sense? Wouldn't the variance be over estimated in this case? I performed a t-test on the coefficients and it results in a relatively high p-value when I know the data should show a good correlation. I use Rubins df formula for the t-test. Is there an alternative method of producing the combine variance, one that doesn't result in over estimation?
Answer: I'm not sure why you think Rubin's variance estimator is biased upwards? In certain situations (e.g. the imputer assumes less than the analyst, see http://www.stat.harvard.edu/Faculty_Content/meng/StatSci94.pdf) it can be biased upwards, but in these cases multiple imputation is often still the most practical approach to handling missingness. The preceding paper gives a careful analysis of the conditions under which Rubin's variance estimator is unbiased, and when it overestimates the variance.


Calender System module and webform

Question: Does "Calender System" only works with "content types " ? The date popup options does not show while adding a "date" type field in to a webform node .

https://drupal.org/project/calendar_systems
https://drupal.org/project/webform

Date Field properties in a content type .

Date field properties in a webform node .

Any clue ?
thanks :)
Comment: Please try to provide links to modules when asking questions. It saves the people who want to help you time.
Comment: for which language type you want use it ?
Comment: i need to use arabic date popup in a webform field .
Answer: The module info page at https://drupal.org/project/calendar_systems claims it has webforms support. 4th last item. So I suppose it does not only work for content types.
Comment: Thank you @Neograph734 for your response. Any idea why the date type field is different ? i added the screenshots above
Comment: Sorry, I don't know that.

Calender System module and webform


Populate spinner from database content (SQLite)

Question: How can I populate a spinner content from database (SQLite)
I have POJO: categories, contain id and name,
I have the table already, with a function to get the ArrayList like this:
public List<SetcardCategory> getAllSetcardCategory()
{
    List<SetcardCategory> setcardCategories = new ArrayList<SetcardCategory>();
    String selectQuery = "SELECT  * FROM " + TABLE_SETCARD_CATEGORIES;

    SQLiteDatabase db = this.getReadableDatabase();
    Cursor c = db.rawQuery(selectQuery, null);

    // looping through all rows and adding to list
    if (c.moveToFirst()) {
        do {
            SetcardCategory setcardCategory = new SetcardCategory();
            setcardCategory.setId(c.getInt((c.getColumnIndex("id"))));
            setcardCategory.setName(c.getString(c.getColumnIndex("name")));

            // adding to tags list
            setcardCategories.add(setcardCategory);
        } while (c.moveToNext());
    }
    return setcardCategories;
}

Then on Activity I call it like this:
List<SetcardCategory> setcardCategories = db.getAllSetcardCategory();
    ArrayAdapter<SetcardCategory> arrayAdapter = new ArrayAdapter<SetcardCategory>(
            this, android.R.layout.simple_spinner_item, setcardCategories);
    arrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    Spinner sItems = (Spinner) findViewById(R.id.setcardCategory);
    sItems.setAdapter(arrayAdapter);

when I run it, it loads string like this: "schema.SetcardCategory@22293c98"  and many others values similar to that.
How can I populate the spinner to show the name field as a label, and id field as the value that we fetch to save into DB?
Comment: in the pojo class overide tostring method and return the value you want to display in the spinner
Comment: you can do that just in 5 lines of code by using `SimpleCursorAdapter`
Answer: class Pojo{
 private String name;
  @Override
    public String toString() {
        return name;
    }
}

do it like this in the pojo class, so this will return a value for the object when it uses the to string method in the adapter, to load the data
Answer: Solution 1
Overide the toString method in your SetcardCategory class
class SetcardCategory {
...
...
@Override
    public String toString() {
        return this.name;
    }
}

Solution 2
If you just want to show the name, Just pick name only from DB
public List<String> getAllSetcardCategory()
    {
        List<String> setcardCategories = new ArrayList<String>();
        String selectQuery = "SELECT  * FROM " + TABLE_SETCARD_CATEGORIES;

        SQLiteDatabase db = this.getReadableDatabase();
        Cursor c = db.rawQuery(selectQuery, null);

        // looping through all rows and adding to list
        if (c.moveToFirst()) {
            do {
                // adding to tags list
                setcardCategories.add(c.getString(c.getColumnIndex("name")));
            } while (c.moveToNext());
        }
        return setcardCategories;
    }

And create Array Adapter as
List<String> setcardCategories = db.getAllSetcardCategory();
    ArrayAdapter<SetcardCategory> arrayAdapter = new ArrayAdapter<SetcardCategory>(
            this, android.R.layout.simple_spinner_item, setcardCategories);
    arrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

Comment: by using this one, i cannot fetch the id, right? Manoj kumar answer fit the situation better
Comment: I given both solutions. I have given the second solution because of looks like you only need the name.
Comment: oh ya, im so sorry, i saw Manoj answer first, but actually your answer posted first.
Comment: @Gabriel no, it does not provide valid row IDs in the adapter, for that you should use `CursorAdapter` - for example `SimpleCursorAdapter`


Como usar UpdatePanel no gridview?

Question: Tenho um grid e quero fazer ele não dar postback quando clicado em algum boundfield (aqueles botões de ações).
Fiz dessa maneira abaixo, mas sempre atualiza a pagina.
    <asp:ScriptManager ID="ScriptManager" runat="server"></asp:ScriptManager>
        <asp:UpdatePanel runat="server" UpdateMode="Conditional" ChildrenAsTriggers="true" >
            <ContentTemplate>
                <asp:GridView ID="GridView" runat="server" .. ETC />
                <Columns>
                <asp:ButtonField ButtonType="Image" CommandName="Excluir" />
                </Columns>
               </asp:GridView>
    </ContentTemplate>
</asp:UpdatePanel>

Comment: Por que você usa `UpdateMode="Conditional"`?
Answer: Mude o atributo ChildrenAsTriggers para false.
Esse atributo faz com que todos os controles filhos causem o PostBack.
Se precisar que algum controle específico seja usado como gatilho, configure-o da seguinte forma:
<Triggers>
     <asp:AsyncPostBackTrigger ControlID="Button1" EventName="Click" />
</Triggers>

Ou, se quiser ter um controle mais refinado de quando o UpdatePanel deve ser atualizado, no codebehind chame:
 meuUpdatePanel.Update();

Como usar UpdatePanel no gridview?


Problema de sintaxe sql ao rodar migrate no ruby on rails(schema_migrations)

Question: tudo blz?
Estou com um problema ao tentar subir um aplicação em rails, quando rodo o comando bundle exec rake db:migrate
ele me da um erro de sintaxe ao criar a tabela schema_migrations.
Segue o erro:
ActiveRecord::StatementInvalid: Mysql2::Error: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'string NOT NULL PRIMARY KEY)' at line 1: CREATE TABLE schema_migrations (version string NOT NULL PRIMARY KEY)
Estou fazendo um update do ruby e do rails.
A versão atual são as seguintes:
Rails 5.2.6 e Ruby 2.5.8p224
Na pasta initializer eu já possuo o arquivo abstract_mysql2_adapter que eu solicito o carregamento no enviroment.rb
Conteúdo do abstract_mysql2_adapter :
require 'active_record/connection_adapters/mysql2_adapter'

class ActiveRecord::ConnectionAdapters::Mysql2Adapter
  NATIVE_DATABASE_TYPES[:primary_key] = "int(11) auto_increment PRIMARY KEY"
end

E não possuo nenhuma migrate para essa tabela.
Versão das gems:
mysql2 (0.5.3)
Docker mysql image: mysql:5.6
Answer: Tente adicionar na sua migration a nova versão do Active Record que é a mesma do Rails provavelmente: no exemplo abaixo adcionei a versão [5.2]
class AddEtniaPatients < ActiveRecord::Migration[5.2]
  def change
    add_column :patients, :etnia, "char(1)", after: :raca_cor
  end
end

Comment: Infelizmente não surtiu efeito, continuo com o mesmo erro e sem conseguir utilizar migrate ou seed pra popular o banco...
Comment: Eu adicionei 5.2 porem é a versão que eu atualizei. Você deve verificar para qual versão está sendo atualizado e fazer algo similar.
Comment: Entendi, mas essa table **schema_migrations**, está sendo criada automaticamente, não consigo controlar, o unico modo de "pular" essa tabela é criando manualmente ela no banco da forma correta(varchar)


Can code running in the browser change that browser's configuration via about:flags

Question: Since Chrome and other browser's configuration flags are accessible via a URL, and the configuration is done typically within a web page, I was wondering if it presented a security vulnerability.
I was thinking it might be exploitable by a specifically-formed URL, such as
<code>chrome://flags/javascript:handleEnableExperimentalFeature(Displaylist2Dcanvas, enable)
</code>
or by a bookmarklet-style javascript that loads and manipulates the flags page? I've tried to do this but it didn't work; I'm not sure if that's because I did it wrong, or because it just isn't vulnerable to that type of attack.
Comment: `I've tried to do this but it didn't work;` seeing your javascript code might be helpful.
Answer: No you cannot do that. Just imagine if people could edit chrome flags via URL, it would be a disaster. Unless you write a chrome extension or some other client side application to change said chrome flag, you can't do that.


PHP ZipArchive non-English filenames return funky filenames within archive

Question: This code works properly to make the ZIP file with the wanted files, except the filenames in the archive, which are not in English (in this case they are Hebrew), have weird characters instead of the proper hebrew letters.
<?php
$filesfordown = $_POST['GEMin'];
    if(empty($filesfordown))
    {
        echo "No files were seleceted for download.";
    }
    else
    {
$zip_name = "RMW." . time() . ".zip";
$zip = new ZipArchive;
$zip->open($zip_name, ZipArchive::CREATE);
foreach ($filesfordown as $filefordown) {
  $zip->addFile($filefordown);
}
$zip->close(); }

header('Content-Type: application/zip');
header("Content-disposition: attachment; filename='$zip_name'");
header('Content-Length: ' . filesize($zip_name));
readfile($zip_name);

ob_flush;
?>

I did some searching around, it seems that iconv, setlocalte, or mb_convert_encoding might help, but whatever I tried didn't work.
Any ideas?
P.S. As a side question, is there a way to not keep directory structure in the zip?
ETA:
An example of the $_post may be www.domain.com/path/שלום_01.mp3
Comment: Seems like this may be an old bug:
https://bugs.php.net/bug.php?id=53948
Answer: Yay!  Fixed!
First the code, then an explanation:
<?php
setlocale(LC_ALL, 'he_IL.UTF-8');
$filesfordown = $_POST['GEMin'];
    if(empty($filesfordown))
    {
        echo "לא נבחרו.. נסה שוב";
    }
    else
    {
$zip_name = "RMW" . time() . ".zip";
$zip = new ZipArchive;
$zip->open($zip_name, ZipArchive::CREATE);
echo "מכין את ההורדה...";
foreach ($filesfordown as $filefordown) {
  $zip->addFile($filefordown, iconv("UTF-8","CP862",basename($filefordown)));
}
$zip->close();

3 things needed to be changed.

Verify that the actual php file is UTF-8.
setlocale() needs to include the .UTF-8 at the end.
ZipArchive does not handle UTF-8 correctly.  Must use CP.  Hebrew was CP862.  Therefore, use extra option $localname for addFile, and its basically iconv("UTF-8","CODE_PAGE_REF",$localname)
Comment: Two notes: 1) Choose the appropriate Code Page, could be Hebrew CP862, Western Europe CP850 or any other. 2) If your filenames differ in Code Page or uses characters from different Code Pages in a single filename, this method won't do it.
Answer: It also works with: iconv("UTF-8", "CP852", $nameFile);


Retorno [object HTMLInputElement], o que signfica e como resolver?

Question: Olá,
Eu quero armazenar no localStorage alguns dados, porém, quando recarrego a página os dados se recuperam de forma bagunçada, mostrando também a informação [object HTMLInputElement]. Você entende onde estou errando?
Aqui um fiddle: https://jsfiddle.net/9rjLo73z/
Aqui o código, caso preferir:

<!doctype html>

  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">

Dados

    <form>
        <input id="item" type="text" placeholder="dado">

        <input id="item2" type="text" placeholder="dado1">
      <input type="button" value="create" onclick="create()">
    </form>

Items

    <button>Limpar</button>

Answer: Oi, Thiago, tudo bem?
Seu problema era basicamente esse:
data.forEach(item => {
  divMaker(item);
  divMaker2(item2); // este elemento referencia o input de texto, que é renderizado como objeto no HTML
});

Basicamente, só de mudar para isso, seu código já deveria funcionar, já que cada funçao basicamente adiciona uma classe, mas o texto ainda precisa ser o elemento item:
data.forEach(item => {
  divMaker(item);
  divMaker2(item);
});

No entanto, fiz uma versão simplificada do seu código, caso queira dar uma olhada e ver como poderia deixá-lo mais enxuto: https://jsfiddle.net/diogocosta/8j9w1qye/15/
Conforme você for ganhando mais experiência, um bom exercício é tentar remover a duplicidade do seu código.
Um abraço!
Comment: Meu caro, muito obrigado! Vou analisar ao máximo teu exemplo pra entender bem a lógica. Abraço!!


Passing aws credentials to Docker

Question: I have a docker container golang code which interacts with aws resources. In the testing environment, we use iam role. But How do I test locally. How to use aws credentials to run my docker locally.I am using docker file to build the docker image.
Answer: Just mount your credential directory as read-only using:
docker run -v ${HOME}/.aws/credentials:/root/.aws/credentials:ro  ...

given you have root as the user in the container and also have setup the host using this guide for credentials file.
or pass them directly using environment variables as:
docker run -e AWS_ACCESS_KEY_ID=<ACCESS_KEY> -e AWS_SECRET_ACCESS_KEY=<SECRET_KEY> ...

Comment: `${USERPROFILE}` or `$env:USERPROFILE` for those using windows as a host. Is there any way to do this using a dockerfile (not docker-compose file)

Passing aws credentials to Docker


Any Crud example for Meteor and react with SimpleSchema

Question: I make a simple page where data is inserted into database by a form using Refs of react.Can any body help me out how i can insert the data using aldeed:Simple schema or any curd example using that package.
please check my simple code for insertion.
import React,{Component} from 'react';

import {DoctorsList} from '../../../api/lists/DoctorsList.js';

export class DoctorCreate extends  Component
{
    addDoctor(event){
        event.preventDefault();
       var text= this.refs.DoctorName.value.trim();
        console.log(text);

            DoctorsList.insert({
                name:text,
                createdAt: new Date(),
                owner: Meteor.userId(),           // _id of logged in user
                username: Meteor.user().username,  // username of logged in user
            });
        this.refs.DoctorName.value="";

    }
    render()
    {
        return (

                <form className="form" onSubmit={this.addDoctor.bind(this)}>

                         Name
                    <input ref="DoctorName" type="text" className="form-control" placeholder="name..."/>

                    <input type="submit" value="save" className="btn btn-primary"/>

                </form>

                Back to list

        )
    }
}

Thanks in advance.
Answer: Meteor official TODOs app is using simple schema. Link to github source https://github.com/meteor/todos/blob/1.3-module-exports/imports/api/lists/methods.js


Panels "Page not found" when using required wildcard argument

Question: I have a Panel Page, which displays several View Panes.  I have specified a term name as an argument in the path settings. This is used to filter the View Panes.
When I use an optional argument everything works fine - clinical-role/!role_name.  But when I change to a required argument clinical-role/%role_name then I get page not found when visiting /clinical-role and when visiting /clinical-role/early-skills-for-non-training-grade-doctors
I need the argument to be required because I don't want the panel to display when people visit /clinical-role.
Here is an export of the Panel Page: http://pastebin.com/ASmFnVU5
Here are my argument settings:

And also my context settings:
Comment: You could try having an optional argument and then in the selection rules add something like "taxonomy term is not empty"
Comment: Are you absolutely _sure_ that things work correctly if the argument is optional? It's not just that the panes happen to be working anyway? I can't think of a reason it would stop working because an argument changed from optional to required, as long as the argument was there in the first place.

Try creating a blank text pane and output the argument token in it for debugging, I would expect this to fail even when the argument is conditional, which points to something being wrong in the argument setup.

@PontusNilsson's suggestion sounds like a nice workaround though. :)
Comment: You're right, I added the term name to a text pane and nothing appears!  I've added my argument and context settings to the question, do they seem correct?  I'm quite new to panels ...
Comment: I think the problem is that my term has a hyphen in it - "Early skills for non-training grade doctors".  When I use a term that has no hyphen then the term name appears in my text pane. Must be related to the "transform dashes" option in views.
Comment: Yep - https://www.drupal.org/node/672606
Answer: The problem was that my taxonomy terms had dashes, e.g. "Early skills for non-training grade doctors".  When used in conjunction with views contextual filters and the option to "Transform spaces to dashes in URL", it doesn't match properly, so no value for the context is provided.  This is related to the following views bug - https://www.drupal.org/node/672606 (no solution as yet for panels but there is a solution if you're just using a view page in comment #16).  My solution was to remove all dashes from my term names.  Not ideal but fixes the problem.
Here is how I set things up to pull a taxonomy term name contextual filter into a View Pane, in case it helps someone.  If anyone knows a better way to go about this then please let me know and I will update this answer:
View Setup - Contextual Filter

View Setup - Argument Input
This part is counter intuitive, you have to choose "No argument input".  Providing a context from panels will prevent the default filter value from being used.  Thanks to the following comment for helping me figure this out: Views contextual filters taxonomy name

Panel Setup
N.b you have to use a panel page here (structure > pages), so that you can make use of the wildcard feature.  I tried this by panelizing a node initially but couldn't get it to work.
Basic settings:

Argument settings:


Can I use cross elasticity of demand for time series data?

Question: I would like to determine, whether two products are complementary. I have one year of data (day by day), where I have prices and demands for both products.
Can I use cross elasticity of demand? I guess it's too simple "model". For example I've noticed big variation of demand during a month, which I guess might be related to the payday. There might huge amounts of variables determining demand for product Y. I was event trying to compare similar days from different months, to avoid that "payday seasonality".
Is there any model, which helps to determine, whether two goods are complementary based on time series data?
I know, I'm might be quite naive, that I could use a cross elasticity for that.
Answer: Most models that assess the cross-price elasticity with non-experimental data do so using time series data. With any regression model, the cross-price elasticity will be biased if you omit relevant variables. So, you need to include variables that capture seasonality, pay day effects, lagged effects, and anything else.
Many, many, models have been developed for this type of problem. The simplest is to have a regression with the dependent variable being the log of demand, and the log of the prices of both products as independent variables, along with all the other variables you need. More complex approaches include using time series models with transfer functions, converting the demand into share data and then use some type of model that can model shares (e.g., variants of logit),simultaneously model multiple dependent variables, etc. There would be many hundreds, and perhaps many thousands, of papers and books in the marketing and econometrics literatures on this.


Custom Validation while adding a term under taxonomy

Question: I want to use custom validation while adding a term. I used form alter and #validate function it's not working.Default validation function under taxonomy module is working but my custom validate function is not.
Here is my code
  function lms2_validate_form_alter($form , &$form_state, $form_id){

    if ($form_id == 'taxonomy_form_term'){
      $form['#validate'][] = 'lms2_validate_term_validate';
    }
  }

  function lms2_validate_term_validate($form ,&$form_state){
      drupal_set_message('hello');
  }

Answer: In Drupal 7, if you go through hook_form_alter.
It uses $form as a reference. You need to use & before $form.

/**
 * Implements hook_form_alter
 */
function hook_form_alter(&$form, &$form_state, $form_id) {
  switch ($form_id) {
    case 'taxonomy_form_term':
      $form['#validate'][] = 'mymodule_taxonomy_form_custom_validate';
      break;
  }
}
/**
 * Implements hook_form_validate
 */
function hook_taxonomy_form_custom_validate($form, &$form_state) {
  //validation goes here
}

Let say if your module name is lms2_validate then use:

function lms2_validate_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'taxonomy_form_term') {
    $form['#validate'][] = 'lms2_validate_term_validate';
  }
}

function lms2_validate_term_validate($form, &$form_state) {
  drupal_set_message('hello');
}

Answer: This would solve your problem for sure.
However I would recommend you to have a look at hook_form_FORM_ID_alter
It is recommended to use hook_form_FORM_ID_alter if your module is implementing the hook only for a couple of forms or so. It gives better performance as it is being invoked only for the particular form and not for all and then checking it in if/else or switch/case loop.
Example:
Considering your module name is: lms2_validate
function lms2_validate_taxonomy_form_term_alter(&$form, &$form_state, $form_id) {
 $form['#validate'][] = 'lms2_validate_term_validate';
}

function lms2_validate_term_validate($form, &$form_state) {
 drupal_set_message('hello');
}

NOTE: There is no if/else loop needed.
Comment: You probably mean 'lms2_validate_form_taxonomy_form_term_alter.


Finding the correct step-size in Richardson Iteration

Question: I am reading the lecture notes of Daniel Spielman on the Conjugate Gradient Descent method (Link to the lecture notes) and he proves therein that the optimal step size for $\alpha$ is given by $$ \frac{2}{\lambda_1 + \lambda_n}.$$
I do not understand how this is derived. In detail: Let $0 < \lambda_1 \leq \ldots \leq \lambda_n$ be the eigenvalues of the psd matrix $A$. Then the stepsize $\alpha$ is given by the minimum w.r.t. $\alpha$ of
$$\max_i | 1- \alpha \lambda_i| = |\max(1-\alpha \lambda_1, 1- \alpha \lambda_n) |.$$
I was wondering how I can calculate this solution?
Answer: Note that to minimize $\max\limits_{i}\left|1-\alpha\lambda_i\right|$ with respect to $\alpha$, we want the extreme values bounding it, namely $\left|1-\alpha\lambda_1\right|$ and $\left|1-\alpha\lambda_n\right|$, to be equal.
Hence, set $\left|1-\alpha\lambda_1\right| = \left|1-\alpha\lambda_n\right|$. Recall that $\alpha > 0$ and $\lambda_1 < \lambda_n$. Given these constraints, the only way we can obtain equality is when $1 - \alpha\lambda_n < 0$ and $1-\alpha\lambda_1 > 0$ and vice versa. Thus, we have
$$
1-\alpha\lambda_1 = -(1-\alpha\lambda_n) \implies \alpha = \frac{2}{\lambda_1 + \lambda_n}
$$


Shell bad interpreter problem

Question: I moved my system from ubuntu 9 to debian 5 and the cron each time that try to execute a script throws...
-bash: ./somescript.sh: /bin/sh^M: bad interpreter: No such file or directory

all my scripts begin with
#!/bin/sh

any clue ? should I change the shell cron is running ? it is using another shell ?
Answer: That ^M bit makes me think that your script uses CR-LF line endings. This usually happens when you edit a file using a Windows text editor.
To fix it, install the tofrodos package and convert the file:
sudo aptitude install tofrodos
fromdos -b /path/to/script.sh

Comment: great, I'm using this, it worked perfectly. I used a windows machine as backup before the migration, that is why. Thanks
Answer: You have carriage returns in your document (Probably edited with a Windows program).  You need to run:
cat somecript.sh | tr -d '\r' > somescript2.sh

Make sure that you use a new file name like I did in my example (somescript2.sh). You can read this blog post for the full story.
Comment: Here, have a UUOC award. :-p
Comment: Well since tr doesn't take filename arguments I figure that is a little clearer than `tr -d '\r' < input > output`

Shell bad interpreter problem


Do ideals partition a ring?

Question: Say we have two principal ideals- $(a)$ and $(b)$. Is $r_{1}*a=r_{2}*b$ possible for $r_{1},r_{2}\in R$, with $(a) \neq (b)$?
I don't see a problem with this as long as the multiplicative inverses of $r_{1}$ and $r_{2}$ are not present in $R$.
Edit: Clarification- in other words, if $(a) \neq (b)$, is $(a)\bigcap (b)$ always $=\phi$?
Comment: How is the title connected to the question?
Comment: If ideals did always partition a ring, then the concept of intersection of ideals would be moot...
Comment: The intersection of two ideals is always an ideal. Ideals are never empty. (In fact, every ideal contains the element $0$, which gives a trivial solution to your equation: $0a=0b=0$.)
Comment: @Dennis: If $r_1*a\neq r_2*b$ for all $r_1,r_2,a,b\in R$, then $(a)\cap(b)=\varnothing$ if $a\neq b$, so the principal (left) ideals would indeed give a partition of $R$. Problem is, every ring has a $0$, so such a partition is possible only for $R=(0)$...
Answer: The way posted, the you actually ask whether it is possible that $(a)\cap(b)\neq(0)$. The answer is yes: take any commutative ring $R$, and $r_1=b$ and $r_2=a$.
Comment: Thank you. I suppose I got my answer.

Do ideals partition a ring?


How many edges does a complete graph with n nodes have?

Question: I know the answer but i need a mathematical prove for it.
Thanks for help.
Comment: how many pairs you can chose out of $n$ points. that's an equivalent question. the answer is ${n \choose 2} $ .
Answer: Each of the $n$ nodes has $n-1$ edges emanating from it. However, $n(n-1)$ counts each edge twice.  So the final answer is $n(n-1)/2$.


Send e-mail after entityform submission using field from referncing node

Question: I have a content type called contact page and several entity forms. The content type contact page has two fields on it one entityreference field that is used to reference an entityform and the other a text field used to store an e-mail address.
If the user selects an entity form then when the contact page is rendered so is the referenced entityform. When a user submits and entityform I would like to send an email to the email address supplied on the contact page.
I've been looking at rules but I am struggling to find out where I can load fields from the referencing entity so that I can use the email address on the contact page once an entityform is submitted.
Answer: First you have to add a condition "this entity has the field". Then you will be able to access this field in the selector in other condition.


How can I prepopulate a field's value when creating a new entity

Question: I have a custom entity (foo) which contains an entity reference field to another custom entity (bar). I would like to create a URL on the bar's unique page to create a new foo entity, where the entity reference is pre-populated with the correct target_id.
For example, a link to /admin/structure/my_module/foo/add?target_id=2501
Is this feature already available? Can I add something to the entity buildForm method to prepopulate my value?
class FooForm extends ContentEntityForm {
  public function buildForm(array $form, FormStateInterface $form_state) {
    //SOMETHING LIKE THIS?
    //if (isset(REQUEST::get('target_id'))) {
    //  $form_state['edit-bar-id-0-target-id'] = REQUEST::get('target_id');
    //}
    /* @var $entity \Drupal\my_module\Entity\Foo */
    $form = parent::buildForm($form, $form_state);
    $entity = $this->entity;
    return $form;
  }
}

I'm not familiar enough with the structure of the $form_state or best practices on get() to be comfortable testing this.
Comment: https://www.drupal.org/project/prepopulate ?
Comment: Thanks for the find. However, it's alpha phase and has several outstanding bugs, including the possibility of having a major refactor in the future. Not good for production. Ignoring DI, the solution I came up with is just two lines of code. Although, I'm waiting on accepting my answer since it's possible there's a better way.
Answer: After adding dependency injection of a requestStack, this works.
/**
 * @var Symfony\Component\HttpFoundation\RequestStack
 */
protected $requestStack;

/**
 * Constructor.
 *
 * @param Symfony\Component\HttpFoundation\RequestStack $request_stack
 */
public function __construct(RequestStack $request_stack) {
  $this->requestStack = $request_stack;
}

/**
 * {@inheritdoc}
 */
public static function create(ContainerInterface $container) {
  return new static(
    $container->get('request_stack')
  );
}

public function buildForm(array $form, FormStateInterface $form_state)
  /* @var $entity \Drupal\my_module\Entity\Foo */
  $target_id = $this->requestStack->getCurrentRequest()->query->get('target_id');
  $this->entity->set('bar_id', $target_id);
  $form = parent::buildForm($form, $form_state);
  $entity = $this->entity;

  return $form;
}


Querying custom database(Mongodb)

Question: I am trying to create a search bar to query an api endpoint that searches my database for specific titles. I have tested my route on Postman and it works correctly however when I try to hit my api on my frontend it returns nothing. I have tried logging the response I get from my axios call however when I do so the page fails to compile and my response is declared as not defined(no-undef). Here are my files:
Frontend file
import React, { useState, useEffect } from "react";
import axios from "axios";
import NavigationBar from "../Components/HomeNav";
import { Button } from "react-bootstrap";

const Search = () => {
  const [queryTitle, setQueryTitle] = useState({});
  const [queriedPosts, setQueriedPosts] = useState(null);

  const handleSearch = (event) => {
    event.preventDefault();
    setQueryTitle({ title: event.target.value });
    axios
      .get("/api/posts/search", queryTitle)
      .then((response) => setQueriedPosts(response.data), console.log(response))
      .catch((error) => console.log(error));
  };

  return (
    <>
      <NavigationBar />
      {queriedPosts
        ? queriedPosts.map((post) => {
            return (
              <>

{post.title}

              </>
            );
          })
        : ""}
      <Button onClick={() => console.log("title", queryTitle)}>rest</Button>
      <Button onClick={() => console.log("posts", queriedPosts)}>rest</Button>

Search

      <input
        id="title"
        name="title"
        type="text"
        name="recipes"
        onChange={handleSearch}
      />
    </>
  );
};

export default Search;

Route file
const router = require("express").Router(),
jwt = require('jsonwebtoken');
let User = require("../db/models/User"),
Post = require('../db/models/Post');

router.post("/api/users", async (req, res) => {
  const { name, email, password } = req.body;
  let user = await User.findOne({ email });
  if (user) {
    throw new Error("Use a different email!");
  }
  try {
    const newUser = new User({
      name,
      email,
      password,
    });

    const token = await newUser.generateAuthToken();
    res.cookie("jwt", token, {
      httpOnly: true,
      sameSite: "Strict",
      secure: process.env.NODE_ENV !== "production" ? false : true,
    });

    res.status(201).json("User added");
  } catch (error) {
    res.status(400).json({ error: error.toString() });
  }
});

router.post("/api/users/login", async (req, res) => {
  const { email, password } = req.body;
  try {

    const user = await User.findByCredentials(email, password);
    const token = await user.generateAuthToken();

    res.cookie("jwt", token, {
      httpOnly: true,
      sameSite: "strict",
      secure: process.env.NODE_ENV !== "production" ? false : true,
    });
    res.json(user);
  } catch (error) {
    res.status(400).json({ error: error.toString() });
  }
});

router.get("/api/posts/search", async (req, res) => {
  const { title } = req.body;
  try {
    const recipeTitle = await Post.find();
    const recipeQuery = recipeTitle.filter(post => {
      let recipeName = post.title;
      return recipeName.includes(title) || recipeName.toLowerCase().includes(title);
    })
    res.json(recipeQuery);
  } catch (error) {
    res.status(404).json({error: error.toString()})
  }
})

module.exports = router;

I am not exactly sure what is going on as I am expecting for my response to at the very least return an empty array or am I wrong to assume that? Also after entering a query string queriedPosts returns as an empty array and queryTitle returns as an Object {title: 'string'}.
After fiddling with my backend route file I have discovered that when I comment out my filter method and return recipeTitle my web page will display all the titles of the all the posts in my database however this does not explain why Postman returns a correctly filtered response.
Comment: Does your axios get request have a baseURL set? If you're server is running locally the URL should be something like ```http://localhost:3000/api/users```. Also can you check the dev tools to see more request info.
Comment: When I log documents.baseURI I get localhost:3000/search which is the local url I am on. Also I have tried playing with the route and discovered that my filter method could be a possible culprit. When I comment it out and return Post.find() I get all the posts in my database
Answer: One of the problems is with this line: .then((response) => setQueriedPosts(response.data), console.log(response)). I think you want to log the response on success, however, you somehow ended up trying to log it when the promise is rejected.
The .then() method takes up to two arguments: callback functions for the success and failure cases of the promise.
.then(
  // first callback, function is called if the promise is fulfilled
  (response) => setQueriedPosts(response.data),
  // second callback, "function" is called if the promise is rejected
  // response is undefined
  console.log(response)
)

If you try to log the response in the first callback, you won't receive an undefined variable error:
.then((response) => {
  setQueriedPosts(response.data);
  console.log(response);
})

Another issue is that when you try to fetch the search results you pass the previous title state and not the current one. Don't forget that useState is asynchronous. You can't update the state on one line and assume it's already changed on the next one. So save the input value and use that in your request instead.
const handleSearch = (event) => {
  let title = event.target.value;
  setQueryTitle({ title });
  axios
    .get('/api/posts/search', title)
    .then((response) => {
      setQueriedPosts(response.data);
      console.log(response);
    })
    .catch(console.log);
};

And as Kyle mentioned in a comment, make sure that the API URL is correct.
On the backend your current filter wouldn't find 'Pumpkin Muffin' if the user types 'muFfin' in the search field. You should update it, just convert both the title and the search term to lowercase:
const recipeQuery = recipeTitle.filter((post) => {
  return post.title.toLowerCase().includes(title.toLowerCase());
});

Comment: `setQueryTitle({ title });` is just the shorthand form of `setQueryTitle({ title: title });`, so it is a key-value pair. Not sure which string is undefined though. On the front end or the back end? Could you clarify that?
Comment: This helped in the .then, but for the latter my page errors out because I need to send an object with a key value pair of title and a string to the backend. I changed your fix but now for some reason my string is undefined and it does't work on postman either
Answer: After much help I found a way to correctly populate my webpage with the queried string a user would pass through.
Frontend file
  useEffect(() => {
    axios
      .post("/search/api/posts/", queryTitle)
      .then((res) => {
        setQueriedPosts(res.data);
      })
      .catch((error) => console.log(error));
  }, [queryTitle]);

  const handleSearch = async (event) => {
    event.preventDefault();
    let recipeTitle = event.target.value;
    setQueryTitle({ title: recipeTitle });
  };

These are the only changes I made to the frontend file. My input element runs handleSearch which updates my queryTitle state. Instead of a get request, I send a post request to my backend. The useEffect is used to properly update and display the state change of the posts we wish to query. In the dependency array of the useEffect, I put queryTitle to make my component re-render.
Backend file
router.post("/search/api/posts/", async (req, res) => {
  const  title  = req.body.title;
  const regex = /title/g
  try {
    const recipeTitle = await Post.find({title: {$regex: title, $options: '<gi>'}});
    res.json(recipeTitle);
  } catch (error) {
    res.status(401).json({error: error.toString()})
  }
})

In my backend file I changed my get request to a post request and removed my filter method and used find(). When passed an object with the property and value you wish to query in your database find() will filter out any occurrences that do not match via the regex expression. More about this concept on the MongoDB docs. (https://docs.mongodb.com/manual/reference/operator/query/regex/)

Querying custom database(Mongodb)


How can I run a python code with input on Linux terminal?

Question: I have a file named myadd.py that contains only the following function:
def myadd(a,b):
    return a+b

How can I run it on Linux terminal?
I am looking for something easy like this:
python myadd 2,3

My final goal is to send multiple jobs to the server by making a .sh file containing:
bsub -J job1 python myadd 2,3
bsub -J job1 python myadd 4,5
bsub -J job1 python myadd 6,3
.
.
.
.

Let me know if I need to make any changes to be able to do something like the line above.
Answer: You can use argparse
code:
import argparse

ap = argparse.ArgumentParser()
ap.add_argument("-n", "--numbers", required=True, default=None, type=str,
    help="Input your numbers to add separated by comma")

args = vars(ap.parse_args())

numbers = args["numbers"].split(",") # Parse the arguments
numbers = [int(i) for i in numbers] # convert from str to int list

def addition(a: int, b: int):
    """Add function"""
    return a+b

print("Result: {}".format(addition(numbers[0], numbers[1])))

Usage:
(pyenv)  ✘ rjosyula  ~  python x.py --help
usage: x.py [-h] -n NUMBERS

optional arguments:
  -h, --help            show this help message and exit
  -n NUMBERS, --numbers NUMBERS
                        Input your numbers to add separated by comma

Results in
python x.py --numbers 2,3
Result: 5

Answer: You need to use sys.argv to accept command line arguments. I suggesting using a space between the two numbers instead of a comma. For more details, see sys.argv[1] meaning in script and the official documentation. If you need more complex command line arguments, I suggest you check out the argparse library.
Answer: Also the fire module.
This only needs:
import fire

def myadd(a, b):
    return a+b

if __name__ == '__main__':
    fire.Fire(myadd)

The import guard was edited in. It isn't needed here as the script is unlikely to be used as a module. I intentional left it out due to that.
To result in a command
python script.py 1 2

That prints 3
Answer: You need to use command line arguments.
For example, in the following code:
import sys

print ('# Args:', len(sys.argv))
print ('Argument List:', str(sys.argv))

If you call it from the terminal...
python3 test_args.py ar1 ar2 ar3 ar4 ar5

Gives as a result:
# Args:: 6
Argument List: ['test_args.py', 'ar1', 'ar2', 'ar3', 'ar4', 'ar5']


AngularJS select with hard coded options

Question: Q. Why my drop down is not showing the selcted value ?
Here is the javascript code that i have

     <select ng-model="myModel.Active" convert-to-number>
       <option value="-1">Select</option>
       <option value="1">Yes</option>
       <option value="2">No</option>
       <option value="3">Maybe</option>
     </select>
     {{myModel.Active}}

The javascript
var myApp = angular.module("myApp",[]);
myApp.controller("MyCtrl", function($scope){
      $scope.myModel = {};
      $scope.myModel.Active=2; //

});

The js-fiddle link -- https://jsfiddle.net/shatherali/4mxwzL5y/19/
Edit: Please note i dont want to use string value. Active has to be a number value.
Comment: The `convert-to-number` from http://stackoverflow.com/a/34114258/652669 doesn't work?
Comment: Not for me atleast, may be i am doing wrong something that i cannot figure out. I updated fiddle with convert-to-number
Comment: See my answer, I linked a demo with `convert-to-number` which works fine. Hope it would help you
Answer: This solves your issue:
var myApp = angular.module('myApp', []);

myApp.controller('MyCtrl', function ($scope) {
      $scope.myModel = {};
      $scope.myModel.Active = '2'; // it's a string
});

DEMO

The convert-to-number directive works fine.
var myApp = angular.module('myApp', []);

myApp.directive('convertToNumber', function () {
    return {
        require: 'ngModel',
        link: function(scope, element, attrs, ngModel) {
            ngModel.$parsers.push(function(val) {
                return parseInt(val, 10);
            });
            ngModel.$formatters.push(function(val) {
                return '' + val;
            });
        }
    };
});

DEMO
Comment: That's not a built-in directive! :) Actually they make their `select` directive to be used with the `ng-options` attribute. They should have done an `option` directive to override the default one but they didn't, so you have to use string values or to "hack" it. :/
Comment: Thanks, i just update my question, i cannot change the value to string, it has to stay number
Comment: So basically the solution is either use the string value or create your own directive to take use that value ( just like you did ), any idea why built in convert-to-number directive not working ?
Comment: Ahhh my bad, actually i did look at the code example at the botton of the angular select documentation page, but never paid attention to the plunker code and thought that its a built in directive. Thanks again.  https://docs.angularjs.org/api/ng/directive/select


Finding The Number Of Solutions To $e^x -2 = \cos x$

Question: Hello everyone how many solution the equation $e^x -2 = \cos x$ have?
I tried to convert it to a function $y = e^x - \cos x -2$ and Find extreme points by:
$y' = e^x + \sin x$ but I don't know how to solve this equation.
Comment: You can find one solution through a simple application of the Intermediate Value Theorem. To argue there is exactly one solution, suppose there are two and apply Rolle's theorem to obtain a contradiction
Answer: Solutions can only be found where
$$-1\le e^x-2\le1,$$  i.e. $x\in[0,\log 3].$ In this range, $e^x-2$ is increasing and $\cos x$ decreasing, and there can only be one solution, which does exist, as
$$e^0-2<\cos0\land e^1-2>\cos1^*.$$

$^*$By Taylor,
$$e-2>\frac12+\frac1{3!}=0.6666666\cdots$$ and
$$\cos1<1-\frac12+\frac1{4!}=0.5416666\cdots$$
Answer: Just a visive approach with Desmos plotting two elementary functions $f(x)=\cos x$ and $g(x)=e^x-2$ (it is the $e^x$ shifted down of $-2$) and you can seen one only solution.


Generalised linear model with Binomial errors

Question: I have data on germination of acacia seeds.
I want to know which germination treatment is better, I am using 6 treatments, one of them being a control. But I got confused about the difference between response and explanatory variable. I have 3 columns Temperature, Germinated seeds and smoke.
Comment: Search this site for logistic regression
Comment: What are the treatments, different temperatures, or the presence / absence of smoke?
Comment: My treatments are: Temperature at 60 and 100 degrees C, smoke, 60 degrees& smoke, 100 degrees & smoke, and a control. Thanks
Comment: It is usually better to edit your clarification into the original question.
Answer: Sometimes it can be a little confusing when there are multiple names for the same variable. In an analysis, the response variable is the phenomenon we wish to explain/model. It is also known as the dependent variable, the explained variable, the predicted variable, or the regressand.
Your explanatory variables represent the set of determinants of your response variable, and are otherwise called the independent variable, the control variable, the predictor variable, or the regressor.
In your case, if your sample population consists of the acacia seeds, and you are interested in modelling the probability that a seed will germinate (as the criterion on which you judge treatment quality) using your explanatory variables, you could fit a logistic regression model:
$$\mathrm{logit}(\pi)=\log\left(\frac{\pi}{1-\pi}\right)=\beta_0+\beta X_{1i}+...\beta X_{ki}+\epsilon_i$$
In the above, each explanatory variable is represented by $X$ with a given subscript, modelling the log odds of probability of "success" (germination) as a function of explanatory variables.
The set of estimated coefficients from fitting the logistic regression model can then guide your inference as to which treatment is better.
For more information, here are a good few sources:
https://onlinecourses.science.psu.edu/stat504/node/216
How to interpret logistic regression coefficient
What is the significance of logistic regression coefficients?
Wooldridge, J. M. 2006. Introductory econometrics: a modern approach. Mason, OH, Thomson/South-Western.


Read a XML file with XStream

Question: I have this xml:
<testsuite name = "testsuite1" time = "19.0" tests = "2" skipped = "0" errors = "1"  failures = "1">
<testcase name = "test1" time = "10.0">
    <failure type = "testcase" message = "error"></failure>
</testcase>
<testcase name = "test2" time = "9.0">
    <failure type = "testcase" message = "error"></failure>
</testcase>

I define 3 clases:
TestSuiteBean.class
public class TestSuiteBean {

private List<TestCaseBean> testcases;

@XStreamAsAttribute
private String name;

@XStreamAsAttribute
private long time;

@XStreamAsAttribute
private int failures;

@XStreamAsAttribute
private int tests;

@XStreamAsAttribute
private int skipped;

@XStreamAsAttribute
private int errors;

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

public long getTime() {
    return time;
}

public void setTime(long time) {
    this.time = time;
}

public int getFailures() {
    return failures;
}

public void setFailures(int failures) {
    this.failures = failures;
}

public int getTests() {
    return tests;
}

public void setTests(int tests) {
    this.tests = tests;
}

public int getSkipped() {
    return skipped;
}

public void setSkipped(int skipped) {
    this.skipped = skipped;
}

public int getErrors() {
    return errors;
}

public void setErrors(int errors) {
    this.errors = errors;
}

public List<TestCaseBean> getTestcases() {
    if (testcases == null) {
        testcases = new ArrayList<TestCaseBean>();
    }
    return testcases;
}

public void setTestcases(List<TestCaseBean> testcases) {
    this.testcases = testcases;
}

}
TestCaseBean.class
public class TestCaseBean {

private FailureBean failure;

@XStreamAsAttribute
private String name;

@XStreamAsAttribute
private long time;

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

public long getTime() {
    return time;
}

public void setTime(long time) {
    this.time = time;
}

public FailureBean getFailure() {
    return failure;
}

public void setFailure(FailureBean failure) {
    this.failure = failure;
}

}
FailureBean.class
public class FailureBean {

private String type;
private String message;

public String getType() {
    return type;
}

public void setType(String type) {
    this.type = type;
}

public String getMessage() {
    return message;
}

public void setMessage(String message) {
    this.message = message;
}

}
and the main.class
final XStream xStream = new XStream(new StaxDriver());
    xStream.setMode(XStream.ID_REFERENCES);
    xStream.alias("testsuite", TestSuiteBean.class);
    xStream.alias("testcase", TestCaseBean.class);
    xStream.alias("failure", FailureBean.class);

    FileInputStream file;
    try {
        file = new FileInputStream("config1.xml");
        TestSuiteBean xml = (TestSuiteBean) xStream.fromXML(file);

and i get next error:
Exception in thread "main" com.thoughtworks.xstream.converters.ConversionException: Element testcase of type el2.test.zephyr.read.TestCaseBean is not defined as field in type el2.test.zephyr.read.TestSuiteBean
---- Debugging information ----
class               : el2.test.zephyr.read.TestSuiteBean
required-type       : el2.test.zephyr.read.TestSuiteBean
converter-type      : com.thoughtworks.xstream.converters.reflection.ReflectionConverter
line number         : 4
version             : null
Answer: testcase actually appears multiple times, so I guess you need to replace:
xStream.alias("testsuite", TestSuiteBean.class)
with
xStream.addImplicitCollection(TestSuiteBean.class, "testcases",
    "testcase", TestCaseBean.class)

Read a XML file with XStream


CMAccelerometerHandler thread1 error

Question: Im trying to experiment with the accelerometer of the iPhone but I'm getting the error "Thread 1:EXC_BREAKPOINT (code=1,subcode=0x1000a3734). I've read that it may be because of a breakpoint, but I deleted all the breakpoints and still the error occurs, also I read it might be because of a nil variable but even if the handler is empty the error still happens. Im at a loss and i'm teaching myself the language. Im using swift 3.0 for this.
import UIKit
import CoreMotion

class ViewController: UIViewController {

//Variables

    var Accelx: Double = 0.0
    var Accely: Double = 0.0
    var Accelz: Double = 0.0
    var Gyrox:  Double = 0.0
    var Gyroy:  Double = 0.0
    var Gyroz:  Double = 0.0

    var motionManager = CMMotionManager()

//IBOutlets
    @IBOutlet var lblX: UILabel?
    @IBOutlet var lblY: UILabel?
    @IBOutlet var lblZ: UILabel?

    override func viewDidLoad() {
        super.viewDidLoad()
        self.resetValues()

        motionManager.accelerometerUpdateInterval = 0.2
        motionManager.startAccelerometerUpdates(to:
            OperationQueue.current!,
            withHandler:
                {(accelData: CMAccelerometerData, Error: NSError)
                    in
                    self.outputAccelData(acceleration:accelData.acceleration)
                    if(Error != nil){
                        //print("\(Error)")
                    }
                } as! CMAccelerometerHandler  )

        super.viewDidLoad()
    }

    func outputAccelData(acceleration: CMAcceleration){
        lblX?.text = "X: \(acceleration.x)"
        lblY?.text = "Y: \(acceleration.y)"
        lblZ?.text = "Y: \(acceleration.z)"
    }
}

Answer:     //Motion Sensor
    if (motionManager.isAccelerometerAvailable){
        motionManager.startAccelerometerUpdates(
            to: OperationQueue.current!,
            withHandler: {(accelData: CMAccelerometerData?, errorOC: Error?) in
                self.outputAccelData(acceleration: accelData!.acceleration)
                    })
    }

    if (motionManager.isGyroAvailable){
        motionManager.startGyroUpdates(
            to: OperationQueue.current!,
            withHandler: { (gyroData: CMGyroData?, errorOC: Error?) in
                self.outputGyroData(gyro: gyroData!)
        })
    }

For anyone who happens to come across this issue, this was the solution. I believe it was that CMAccelerometerData and NSError were not being unwrapped and that the handler CMAccelerometerHandler needs those two to be unwrapped. Also I was trying to cast the anonymous function as a handler.
P.S. Yay! I got a tumbleweed badge!
Answer: The handler's second parameter's type should be Error, not NSError.

CMAccelerometerHandler thread1 error


The dot product of two vectors as the integral of two functions. Clarification please.

Question: I read that the dot product of two vectors $v_1$ and $v_2$ is equivalent to the integral of the product of two like functions.
For example, the vectors $[1,0]$ and $[0,1]$ are orthogonal and so their dot product is equal to $0$.
Now, on the unit circle I treated these two vectors as special cases of the following functions which are always $90$ degrees out of phase to each other on the unit circle.
\begin{align}
    f(x) &= e^{i\pi x}\\
    g(x) &= e^{i \pi (x+\pi/2)}
\end{align}
However, I am unable to get the product of these two functions and integrate them in such a ways as to get zero.
Where am I going wrong with my Math/intuition?
Answer: First, note that you actually want $e^{ix}$ and $e^{i(x + \pi/2)}$ (without the constant of $\pi$ already there). Then,
\begin{align}
  \int_0^{2\pi} (fg)(x) dx &= \int_0^{2\pi} e^{ix} e^{i(x + \pi/2)}\ dx\\
  &= \int_0^{2\pi} e^{i(2x + \pi/2)}\ dx\\
 &= \left[ \frac{1}{2i} e^{i(2x + \pi/2)} \right|_0^{2\pi}\\
 &= \frac{1}{2i} \cdot \left(e^{i(9\pi /2)} -  e^{i(\pi/2)} \right)\\
 &= \frac{1}{2i} \cdot ((\cos(9\pi/2) + i\sin(9\pi/2)) - (\cos(\pi/2) + i\sin(\pi/2)))\\
  &= 0
\end{align}
In general, we call $\int_I f(x)g(x)\ dx$ the inner product of the functions $f$ and $g$, which is usually defined on some interval $I$. Here's a link to another answer that gives even more insight on the inner product of two functions.
Comment: It is easier to see if you take $e^{\frac{i\pi}{2}}$ outside the integral sign.  The integral is then the result of going around a circle twice.
Comment: @herbsteinberg yes that's certainly a much more intelligent way of going about it!


What is the M-step for Expectation Maximization for a multivariate Gaussian hidden Markov model with missing observations?

Question: Is there a closed-form solution for the M-step of the expectation maximization (EM) algorithm for a multivariate Gaussian hidden Markov model (HMM) where observations are missing at random?
$\newcommand\given[1][]{\:#1\vert\:}$

My HMM notation, largely borrowed from https://www.princeton.edu/~rvan/orf557/hmm080728.pdf, is:

$X_t \in \mathrm{E}$ is a discrete hidden state with transition
matrix $P$ and initial distribution $\mu$
The state space $\mathrm{E} \equiv \left\{1, 2, \ldots, d\right\}$ is finite
The observations are $\left(\,Y_t \given X_t = i\,\right)\sim \mathcal{N}\left(\mathbf{m}_i, \mathbf{v}_i\right)$
If the observations are scalars, $\mathbf{m}$ and $\mathbf{v}$ are simply vectors of means and variances (one for each hidden state)
If the observations are multivariate normal, say $Y_t \in \mathbb{R}^k$, each $\mathbf{m}_i$ is a $k$-vector of means and each $\mathbf{v}_i$ is a $k$-by-$k$ covariance matrix

I'm interested in estimating $P$, $\mu$, $\mathbf{m}$ and $\mathbf{v}$ using the EM algorithm.  Let $\mathbf{y}$ denote an $n$-by-$k$ matrix of observed data.  Let $\pi_{it}$ denote the posterior probability over hidden state $i$ for observation $t$, computed under the previous iteration's parameters, i.e. $\pi_{it} = \Pr[X_t = i \given \mathbf{y}]$.
The notes I linked to earlier give the M step when $k$ = 1, i.e. scalar Gaussian observations (section 6.2, page 87):
$$\begin{equation*}
\mathbf{m}_i = \frac{\sum^n_{t=1} \mathbf{y}_t \, \pi_{it}}{\sum^n_{t=1} \pi_{it}}
\end{equation*}$$
$$\begin{equation*}
\mathbf{v}_i = \frac{\sum^n_{t=1} \left(\mathbf{y}_t - \mathbf{m}_i\right)^2 \, \pi_{it}}{\sum^n_{t=1} \pi_{it}}
\end{equation*}$$
I'm interested mainly in the updates to $\mathbf{m}$ and $\mathbf{v}$ so I'll omit the updates to $P$ and $\mu$ for clarity.
The M-step updates for multivariate Gaussian observations are quite similar.  The update to $\mathbf{m}_i$ is identical (the only difference being that $y_t$ is now a $k$-vector), and the update for the covariance matrices is:
$$\begin{equation*}
\mathbf{v}_i = \frac{\sum^n_{t=1} \left(\mathbf{y}_t - \mathbf{m}_i\right) \, \left(\mathbf{y}_t - \mathbf{m}_i\right)^{\intercal} \, \pi_{it}}{\sum^n_{t=1} \pi_{it}}
\end{equation*}$$
This equation appears on slide 9 of http://personal.ee.surrey.ac.uk/Personal/P.Jackson/tutorial/hmm_tut4.pdf, for example, with slightly different notation.

What is the M-step if elements of $\mathbf{y}$ (the $n$-by-$k$ matrix of observations) are missing at random?  My guess is to first define a matrix $\tilde{\mathbf{y}}$ containing 1s where $\mathbf{y}$ is observed and 0s where it is missing (i.e. a matrix of indicators for non-missing data).  I then recode the missing observations in $\mathbf{y}$ as 0.
My updates (after the recoding described above) are:
$$\begin{equation*}
\mathbf{m}_i = \frac{\sum^n_{t=1} \mathbf{y}_t \, \pi_{it}}{\sum^n_{t=1} \tilde{\mathbf{y}}_t \, \pi_{it}}
\end{equation*}$$
$$\begin{equation*}
\mathbf{v}_i = \frac{\sum^n_{t=1} \left(\mathbf{y}_t - \mathbf{m}_i\right) \, \left(\mathbf{y}_t - \mathbf{m}_i\right)^{\intercal} \, \pi_{it}}{\sum^n_{t=1} \tilde{\mathbf{y}}_t \, \tilde{\mathbf{y}}_t^{\intercal} \pi_{it}}
\end{equation*}$$
In the equation above, both the numerator and denominator are $k$-by-$k$ matrices.  The fraction should be read as an element-wise division.
Is this correct -- is it even guaranteed to produce a positive definite covariance matrix?  Does a correct analytical update exist?  Any pointers to papers or lecture notes that discuss multivariate Gaussian HMMs with observations missing at random would be much appreciated.

A relevant paragraph from https://en.wikipedia.org/wiki/Estimation_of_covariance_matrices:

In the general case, the unbiased estimate of the covariance matrix
  provides an acceptable estimate when the data vectors in the observed
  data set are all complete: that is they contain no missing elements.
  One approach to estimating the covariance matrix is to treat the
  estimation of each variance or pairwise covariance separately, and to
  use all the observations for which both variables have valid values.
  Assuming the missing data are missing at random this results in an
  estimate for the covariance matrix which is unbiased. However, for
  many applications this estimate may not be acceptable because the
  estimated covariance matrix is not guaranteed to be positive
  semi-definite. This could lead to estimated correlations having
  absolute values which are greater than one, and/or a non-invertible
  covariance matrix.

Do any references discuss how to deal with this problem in the context of multivariate Gaussian HMMs?

Here's a little R example showing covariance matrix estimates with negative eigenvalues:
<code>library(mixtools)  # For rmvnorm

get_sigma_hat <- function(n_obs, sigma, pr_missing) {
    ## Generate random multivariate data y with observations missing at random
    ## Return estimated variance-covariance matrix
    stopifnot(0 <= pr_missing && pr_missing < 1)
    stopifnot(all(eigen(sigma)$values > 0.0))
    stopifnot(identical(sigma, t(sigma)))
    y <- rmvnorm(n_obs, sigma=sigma)
    stopifnot(all(dim(y) == c(n_obs, nrow(sigma))))
    y_non_missing <- matrix(1*(runif(n_obs * nrow(sigma)) > pr_missing), n_obs, nrow(sigma))
    mean(y_non_missing)  # Should be close to (1 - pr_missing)
    observed_y <- ifelse(y_non_missing, y, 0)  # Careful, NAs recoded to zero
    sigma_hat <- t(observed_y) %*% observed_y / (t(y_non_missing) %*% y_non_missing)
    return(list(sigma_hat=sigma_hat,
                sigma_hat_positive_definite=all(eigen(sigma_hat)$values > 0.0)))
}

set.seed(543987)

sigma <- matrix(c(1.0, 0.5, 0.6,
                  0.5, 2.0, 0.7,
                  0.6, 0.7, 3.0), 3, 3)  # True variance-covariance matrix for observations in R^3
n_reps <- 1000
reps <- replicate(n_reps, get_sigma_hat(n_obs=500, sigma=sigma, pr_missing=0.10), simplify=FALSE)

mean(sapply(reps, function(x) x$sigma_hat_positive_definite))  # 1.0 i.e. all positive definite
mean(sapply(reps, function(x) x$sigma_hat[1, 1]))  # Close to sigma[1, 1]
mean(sapply(reps, function(x) x$sigma_hat[3, 2]))  # Close to sigma[3, 2]

reps <- replicate(n_reps, get_sigma_hat(n_obs=400, sigma=sigma, pr_missing=0.80), simplify=FALSE)
mean(sapply(reps, function(x) x$sigma_hat_positive_definite))  #  Some negative eigenvalues!
sigma_hat <- Filter(function(x) !x$sigma_hat_positive_definite, reps)[[1]]$sigma_hat
eigen(sigma_hat)$values  # Third eigenvalue is negative
cov2cor(sigma_hat)  # ...but all correlations are in [-1, 1]

another_sigma_hat <- Filter(function(x) !x$sigma_hat_positive_definite, reps)[[2]]$sigma_hat
eigen(another_sigma_hat)$values  # Again, third eigenvalue is negative
cov2cor(another_sigma_hat)  # This one has some correlations above 1
</code>
The code simulates a simplified version of the problem I describe above, where the $Y$s have mean zero and there are no weights $\pi$.
Answer: Typically, when using the EM algorithm you would consider missing observations as hidden variables that would be estimated. Instead of setting missing observations to 0, you would have to estimate them in the M-step.
However, for the case of HMM, given the current state, each observation is independent. Because of this,  it turns out that we do not need to estimate missing observations, as long as we estimate all the hidden states.
The update equations for the M-step turn out to be what you've guessed!
This is explained in detail in the below paper:
Roberta Paroli and Luigi Spezia, "Parameter estimation of Gaussian hidden Markov models when missing observations occur", Metron-International Journal of Statistics, 2002 (https://www.researchgate.net/publication/5182349_Parameter_estimation_of_Gaussian_hidden_Markov_models_when_missing_observations_occur)
Comment: Thank you for your answer.  The paper you posted is almost what I'm looking for, but I'd like something that explicitly discusses multivariate observations.  If I am reading them correctly, Paroli and Spezia only consider scalar observations, right?


Why does my onClick() button call the HttpPost method within my controller?

Question: I have a button which onClick() execute a JS script, but for some reason it keeps executing my SubmitForm() Action method within my controller and i don't understand why
  @using (Html.BeginForm("SubmitForm", "Home", FormMethod.Post,

                new
                {
                    traName = Request.Form["nameOfTra"],
                    amount = Request.Form["amountRequested"],
                    memberName = Request.Form["commiteeMember"],
                    date = Request.Form["agmDate"],
                    signed = Request.Form["signed"],
                    dated = Request.Form["dated"],
                    numberOfRows =  Request.Form["numberOfRows"]

}))
{

 TRA grant application

This is the TRA Grant form for the association named below who agree to use these funds to cover the cost of administration of the TRA

    Name of TRA:
    <input type="text" name="nameOfTra" value="" />

 List of items the money will be spent on

        Description of Items
        Quantity
        Cost

        <input type='text' size="30" />
        <input type='text' size="30" />
        <input type='text' size="30" />

<button onclick="addRow()">Add Item</button>
<input type="hidden" id="rows" value="1" name="numberOfRows" />

 public ActionResult SubmitForm(string traName,  float? amount,
            string memberName, string date, string signed, string dated, int? numberOfRows, HttpPostedFileBase file, HttpPostedFileBase file2, HttpPostedFileBase file3){}

I have some extra logic in my Submitform() action which I dont want to execute, I dont understand why it keeps calling this action which it should simply just call the script.
Answer: You not declared your submit button to your SubmitForm(). Add inside FormBegin your submit button:

<input type="submit" value="Submit Button" />

@Edit:
Change:
<button onclick="addRow()">Add Item</button>

To:
<input type="button" onclick="addRow()" value="Add Item"/>

Comment: Tried this, it still calls the action method
Comment: You already tried to change your  for ?


Dell SCCM 2012 Integration and deployment packs - Do they support Windows Server 2012 yet?

Question: I am looking to migrate my dev SCCM 2012 SP 1 install from Windows Server 2008 R2 to Windows Server 2012.  I have been looking at the documentation for the Dell integration packs and want to incorporate this into my environment.
http://en.community.dell.com/dell-blogs/software/b/software/archive/2012/04/02/dellopenmanageintegrationsuiteformicrosoftsystemcenter.aspx
http://www.dell.com/support/drivers/us/en/555/DriverDetails?driverId=85VWM
http://support.dell.com/support/edocs/software/smddp/2_0/en/itg/itg.pdf
http://en.community.dell.com/techcenter/b/techcenter/archive/2012/07/31/dell-client-integration-pack-for-ms-configuration-manager-2012-is-now-available.aspx
However it doesn't look like, according to this documentation, the Dell integration packs will run on/support Windows Server 2012 yet.  Has anyone tried to install any of this stuff into SCCM 2012 SP1 running on Server 2012?  Is the documentation lagging behind real world or is this not supported yet?
EDIT:  Updated to reflect I actually have SP1 up and running.  More so asking about the Dell products.
Answer: You will want to get your hands on System Center 2012 SP1 which fully supports Windows Server 2012.
Comment: Sorry.  I updated to reflect that I had SP1 already.  Really asking about the functionality of the Dell products on Server 2012, not SCCM.
Comment: Gotcha.  Misunderstood the question and thought it was related directly to System Center 2012 only.  I will ask around as well.
Answer: SCCM 2012 is not yet supported for installation on Server 2012.  It will [reportedly] be supported with the release of SP1 for SCCM 2012.  (The beta SP1 for SCCM 2012 is available for download, if you wish to try that out, but I wouldn't roll it to production until the RTM version of the Service Pack is made available.)
Comment: Sorry. I updated to reflect that I had SP1 already. Really asking about the functionality of the Dell products on Server 2012, not SCCM.


Logistic regression with few observations

Question: I suppose regression analysis with few observations has some peculiarities.
Here are results for my logistic regression.
$R^2_{\rm LR}$ = 0.7,
Number of 1 = 6 (4 predicted),
Number of 0 = 78 (all predicted)
Is it good-fitting? If the number of observation is 10 times higher I would have on doubt but here I'd like to ask for an expert's opinion.
Answer: Whether it is a "good" fitting is context dependent.
Is the fact that 2 of 6 '1's were missed OK or not?  That depends on what a '1' is. If this is about, say, airplanes crashing on takeoff, then that's pretty bad. In other circumstances it could be pretty good.
What is your context?
Comment: Actually, my objective is not a prediction but testing the impact of independent variables. The dependent variable is election win/lose.
Comment: For looking at impact of independent variables, you should look at odds ratios or other effect size measures. Unfortunately, with a 0 in one cell, OR doesn't work. But you can look at difference in proportions, for example.
Comment: Thanks. I use z-test for each independent variable. I'm now interested in overall fitting of my model.
Comment: If you are interested in the impact of independent variables, use effect size (that's what you said in one comment). If you are interested in overall fit, then think of the context.
Comment: I need to know overall fit in order to justify my results concerning the impact of independent variables. I'm not going to predict anything with the aid of my model so why does the context matter?
Comment: Because what is a good fit in one context is a bad fit in another context, regardless of whether you are trying to explain or predict. You may be thinking of justifying the assumptions of the model - that is different.
Comment: You mean I should ask my question to an expert in political science?


Probability bound for complex random variable

Question: Let $Z=X+iY$ be complex random variable. Consider the following probability
$$\mathrm{Pr}\left( | Z|\geq \epsilon \right)$$
 I want to bound this in terms of the real and imaginary parts of $Z$, i.e. suppose that I have bounds for $\mathrm{Pr}\left( |X|\geq \epsilon \right)\leq C(\epsilon)$ and $\mathrm{Pr}\left( | Y|\geq \epsilon \right)\leq C'(\epsilon)$. For starters,
\begin{align}
\mathrm{Pr}\left( | Z|\geq \epsilon \right)
&=\mathrm{Pr}\left( |X+iY|\geq \epsilon \right) \\
&= \mathrm{Pr}\left( \sqrt{X^2+Y^2}\geq \epsilon \right)\\
&= \mathrm{Pr}\left( X^2+Y^2\geq \epsilon^2 \right)
\end{align}
How to proceed?
Context: I am trying to understand how to lift the standard Chernoff bound to complex random variables. (see also in this MO question
)
Answer: $P(|Z| \geq \epsilon) \leq P(|X|\geq \epsilon /2)+P(|Y|\geq \epsilon /2)$ because $|Z| \leq |X|+|Y|$.
[ The event $(|Z| \geq \epsilon) $ is contained in the union of the events $(|X| \geq \epsilon) $ and $(|Y| \geq \epsilon) $].
Comment: weird, but then in the link, the real-valued Chernoff bound is $2e^{-K\epsilon^2/2b^2}$ but replacing $\epsilon$ with $\epsilon / 2$, I have $2\times 2e^{-K(\epsilon/2)^2/2b^2}=4e^{-K \epsilon^2 / 8b^2}$  but they get $4e^{-K \epsilon^2 / 4b^2}$ what is going on there?


Create mutable List from array?

Question: I have an array I'd like to turn into a List, in order to modify the contents of the array.
Stack Overflow has plenty of questions/answers that address Arrays.asList() and how it only provides a List view of the underlying array, and how attempting to manipulate the resulting List will generally throw an UnsupportedOperationException as methods used to manipulate the list (e.g. add(), remove(), etc.) are not implemented by the List implementation provided by Arrays.asList().
But I can't find an example of how to turn an array into a mutable List.  I suppose I can loop through the array and put() each value into a new List, but I'm wondering if there's an interface that exists to do this for me.
Answer: One simple way:
Foo[] array = ...;
List<Foo> list = new ArrayList<Foo>(Arrays.asList(array));

That will create a mutable list - but it will be a copy of the original array. Changing the list will not change the array. You can copy it back later, of course, using toArray.
If you want to create a mutable view onto an array, I believe you'll have to implement that yourself.
Comment: Java needs to make mutability/immutability clear in all these static factory methods. It's a bummer to find out you made an immutable thing at runtime.
Comment: Arrays.asList returns a view onto an array, with those mutating methods supported that don't affect the size of the list
Comment: @dustinevan: The documentation is pretty clear IMO: "Returns a fixed-size list backed by the specified array. (Changes to the returned list "write through" to the array.)"
Comment: @jon-skeet I know, I was just stating that Arrays.asList gives you an array backed list with limited mutability, if you need add/remove/insert then the ArrayList wrapping is a better approach.
Comment: @JonSkeet don't want to waste your time--thanks for all you do. I'd just like to put a vote in for more clarity in the names themselves--I'm sure the docs are clear. Some of us are dancing between languages, and this is reasonably clear in other languages.
Comment: This is completely acceptable for my needs.  I'm fine with discarding the original array.
Comment: @TimoWestkämper: Yes, but I'm then creating a new `ArrayList` from that view.
Answer: And if you are using google collection API's (Guava):
Lists.newArrayList(myArray);

Comment: Even Guava itself recommends using either `new ArrayList<>(Arrays.asList(...))` - the javadoc for the method implies it will become deprecated because it is not useful enough.
Comment: 2020 and still not deprecated.  Jump on in!
Comment: This is the most concise answer. Thanks.
Answer: This simple code using the Stream API included in Java 8 creates a mutable list (or view) containing the elements of your array:
Foo[] array = ...;
List<Foo> list = Stream.of(array).collect(Collectors.toCollection(ArrayList::new));

Or, equally valid:
List<Foo> list = Arrays.stream(array).collect(Collectors.toCollection(ArrayList::new));

Answer: If you're using Eclipse Collections (formerly GS Collections), you can use FastList.newListWith(...) or FastList.wrapCopy(...).
Both methods take varargs, so you can create the array inline or pass in an existing array.
MutableList<Integer> list1 = FastList.newListWith(1, 2, 3, 4);

Integer[] array2 = {1, 2, 3, 4};
MutableList<Integer> list2 = FastList.newListWith(array2);

The difference between the two methods is whether or not the array gets copied. newListWith() doesn't copy the array and thus takes constant time. You should avoid using it if you know the array could be mutated elsewhere.
Integer[] array2 = {1, 2, 3, 4};
MutableList<Integer> list2 = FastList.newListWith(array2);
array2[1] = 5;
Assert.assertEquals(FastList.newListWith(1, 5, 3, 4), list2);

Integer[] array3 = {1, 2, 3, 4};
MutableList<Integer> list3 = FastList.wrapCopy(array3);
array3[1] = 5;
Assert.assertEquals(FastList.newListWith(1, 2, 3, 4), list3);

Note: I am a committer for Eclipse Collections.
Comment: That's a nice collections API you've got there.  The first one I've seen that might tempt me away from my own implementations... only thing it seems to be missing that I find generally useful is a sorted set implementation backed by an array (which I find is much more efficient than a tree-based implementation for either data which is rarely modified or for sets that may be modified frequently but typically hold less than 10 or so elements).
Answer: myNewArrayList = new ArrayList<>(Arrays.asList(myArray));

Comment: @JonSkeet i know that your comment is from 2012, and i'm livin in the future now, but i'm assuming this comment hasn't held well considering my IDE specifically underlines and says "hey, don't declare this with a declared type. you don't need it there"?
Comment: @BrentThoenen: I don't understand your comment. Did you notice that my comment referred to revision 1, which used `myNewArrayList = new ArrayList(...)`, i.e. the raw type? There's a difference between "using the diamond operator to let the compiler work out a type argument" and "using a raw type".
Comment: I posted this answer and lived in oblivion all this time that @JonSkeet Himself commented on my answer.   Thanks Brent for commenting.
Comment: @JonSkeet ahh, my bad. i didn't check the revision you were commenting on. I made a wrong assumption in that 2012 java assumed empty diamond operator as a raw type as well. That is my b. thanks for the answer!

Create mutable List from array?


Jasper Report Generation Date

Question: I'm creating jasper report and want to print the report generation date(current) on the report? How do I do that with ireport? I hope you can help me.
Comment: Your question is not clear, anyway to show the date you can use simple static text, and if you want to print through parameter you can create a parameter and give a default date in this format -- new Date(114,02,31) for date 31-March-2014.
Answer: Open Palette (Window->Palette) and drag "Current date" from "Tools" section to your report.
Answer: You can take a static field and then create instance of the Date class as new Date() to print current date in desired pattern.
Answer: Use the following in your jrxml...Cheers! Screenshot
<textField pattern="MMM d, yyyy h:mm:ss a z">
            <reportElement x="0" y="1" width="280" height="21" isRemoveLineWhenBlank="true" uuid="3f452153-41b0-4296-84b9-5a78825a18dc"/>
            <textElement verticalAlignment="Middle">

            </textElement>
            <textFieldExpression><![CDATA["Report Generated on: "+new java.util.Date()]]></textFieldExpression>
        </textField>

Answer: <textField pattern="**dd-MMM-yyyy hh:mm**">
            <reportElement x="0" y="1" width="280" height="21" isRemoveLineWhenBlank="true" uuid="3f452153-41b0-4296-84b9-5a78825a18dc"/>
            <textElement verticalAlignment="Middle"/>
            <textFieldExpression><![CDATA["Report Generated on: "+new java.util.Date()]]></textFieldExpression>
</textField>
The new java.util.Date() allows your to format date in a more clean way and precise.The pattern i have specified above will print 26-Oct-2017 17:50for the 24 hour format.

Jasper Report Generation Date