Can I write estimate $\pm$ its standard error?

Question: Suppose I have an MLE estimate $\hat{\theta}$ for a parameter $\theta$, and $\hat{\sigma}$ is the sqrt of the inverse of the negative of the Hessian of the log likelihood at $\hat{\theta}$. Can I write $\hat{\theta} \pm \hat{\sigma}$?
In general, if I have an estimate $\hat{\theta}$ for a parameter $\theta$, and an estimate $\hat{\sigma}$ of the standard deviation of $\hat{\theta}$, can I write $\hat{\theta} \pm \hat{\sigma}$? Will others understand what I mean? Is it also what others write?
Comment: under certain regularity conditions MLEs are asymptotically normal.
Answer: It's fairly common, but not standard enough that it needs no explanation. $\hat\theta\pm 1.96 \hat\sigma$ is also common—an (approximate perhaps) 95% confidence interval.
Answer: I think it depends what you want to convey.
To report the standard error or your estimate you could just write $\hat{\theta} (\hat{\sigma})$. This notation is quite common in the statistical literature, but for the sake of clarity you might mention that the standard error is in parenthesis/brackets the first time you use this notation.
To provide a confidence interval with your estimate you might want to write $\hat{\theta} \pm z_{\alpha/2}\hat{\sigma}$, where $z_{\alpha/2}$ is the quantile of the standard normal distribution and $1-\alpha$ the confidence level of your choice. A common choice is $\alpha = 0.05$ leading to $\hat{\theta} \pm 1.96\hat{\sigma}$.
The second option is a much stronger statement. In addition of providing the standard error of the estimate, it gives a confidence interval relying on the normality of the MLE, which might be too coarse in finite samples: it might include invalid parameter values (e.g., probabilities larger than one), and/or wrongly imply that the confidence interval is symmetric.
Comment: That's a really good point: the nomenclature (symbol-clature?) should be appropriate for the audience. I have never seen the subscript-sigma notation in psychology or biology paper, even it is apparently used frequently in other fields.
Comment: @Matt Krause Indeed, the notation might be field-specific. Please note that in the notation I mentioned the standard error is not a subscript, but rather in parenthesis (e.g., $4.2(0.2)$).
Comment: I've seen that in tables, but I think I would be baffled if I just stumbled across "The average temperature was 4.2(0.2)C" or whatever in a paragraph. All the more reason to explain your notation!
Answer: There are lots of parameters that are written as $x \pm y$. Off the top of my head, I have seen people use this format to report:

mean and standard error:
mean and standard deviation
mean and confidence interval
mean and range/tolerance (particularly on blueprints or design documents)
median and mean absolute deviation.

All of these are fine, as long the values are clearly described Some version of the APA style require explicit labels like "The line's slope was close to unity ($M\pm SE: 1.01 \pm 0.05$). That can be handy, but it can clutter up the text. If you're reporting a lot of values, a simple note ("All data is shown as mean $\pm$ standard errors") can work too.
Obviously, also consider the point you want to make. Standard deviation/MAD/ranges hints at the shape of a distribution, but not about the precision of an estimate. Standard error tells you how precise the estimate is, but does not describe the shape of the distribution.


Deixar menu selecionado

Question: Tenho um menu lateral e toda vez que eu clicar em algum item para abrir uma página, gostaria que ficasse selecionado com uma cor.
Menu.xhtml
<ui:composition xmlns="http://www.w3.org/1999/xhtml"
xmlns:ui="http://xmlns.jcp.org/jsf/facelets"
xmlns:h="http://xmlns.jcp.org/jsf/html">

            <h:link outcome="/page/main.xhtml">Início</h:link>

            <h:link outcome="/page/cargo/cons_cargo.xhtml">Cargos</h:link>

            <h:link outcome="/page/setor/cons_setor.xhtml">Setores</h:link>

            <h:link outcome="/page/aud/cons_auditoria.xhtml">Auditoria</h:link>

            <h:link outcome="/page/seg/cons_usuario.xhtml">Usuários</h:link>

            <h:link outcome="/page/seg/form_usuario_alt_senha.xhtml">Alterar Senha</h:link>

O css do menu
    /* MENU */
.aw-menu {
    font-size: 1.1em;
}

.aw-menu > ul {
    margin: 0;
    padding: 0;
    list-style: none;
}

.aw-menu > ul a {
    display: block;
    padding: 10px 15px;

    text-decoration: none;
    font-weight: 500;
    color: #373737;
}

.aw-menu > ul i {
    margin-right: 6px;
}

.aw-menu > ul a:hover, .aw-menu > ul a:focus {
    background-color: #dfdfdf;
}

.aw-menu > ul .is-selected {
    border-left: 3px solid #0978EA;
    background-color: #f3f3f3;
}

.aw-menu > ul .is-selected a {
    margin-left: -3px;
    color: #0978EA;
}

Comment: Eu faria em php... if($pagina==x) echo "active"; dentro do class..
Comment: O projeto é em Java
Comment: :( Entendi. Daí não sei te ajudar
Answer: Eu gosto de usar javascript pra fazer o serviço:
$(document).ready(function(){
    var get = document.URL;
    if(get.match(/main/i)){
        $('.aw-menu li:eq(0)').addClass('is-selected');
    }
    if(get.match(/cargo/i)){
        $('.aw-menu li:eq(1)').addClass('is-selected');
    }
    if(get.match(/setor/i)){
        $('.aw-menu li:eq(2)').addClass('is-selected');
    }
});

Por ser extremamente flexível fica muito simples fazer qualquer personalização que a página exija.
Comment: Deu certo a sua solução. Obrigado
Answer: O seu css deve ser implementado para tag "li" e não para "ui".
.aw-menu > li a:hover, .aw-menu > li a:focus {
    background-color: #dfdfdf;
}
.aw-menu > li a {
    background-color:transparent
}

Espero ajudar.
Comment: Colocando no li não funcionou o css
Answer: Pode acrescentar uma class manualmente à página onde está, ou seja:
Se estiver na página cons_cargo.xhtml:

      <h:link outcome="/page/cargo/cons_cargo.xhtml">Cargos</h:link>

E finalmente nos seus CSS:
...
.active-menu {
    color: red !important; /* aqui é para reforçar esta propriedade, caso tenha definido alguma outra cor neste elemento mais abaixo */
}
...

Comment: Desse modo a opção que eu cliquei não fica selecionado em vermelho  enquanto navego na página.

Deixar menu selecionado


is there hierarchical user level structure in drupal

Question: Is there any hierachical structure of user in Drupal?
I just see user role in drupal, but can we define some level of user?
As example:
<code>user1
--user2
---user3
--user4
---user5
---user6
</code>
Comment: what do you need to user level for? I am curious because the permission-role system can give you many "hierarchies" in terms of permissions. I imagin adding the user levels as you describe could add complexity to the system. Say user6 has Role Admin, how do you handle this?
Answer: Check out Subuser module to see if it fits your needs.
If you want "just" the roles to be hierarchical, Role delegation might be useful
Related: https://stackoverflow.com/questions/1281964/drupal-for-users-creating-sub-users
Answer: For handling hierarchies, I prefer to use organic groups and sometimes og_subgroups.  This gives you hierarchies of groups rather than hierarchies of users, but I have used this, for example, to make a hierarchy of "officers", and other group members are the officer's assistants.  The other advantage of hierarchy of groups over a hierarchy of users is that it is possible for one user to appear at multiple places in the hierarchy, if necessary.


Sending data from a database to list view in android

Question: I have been trying to print data I have retreived from a database in android to a list view but whilst I get the data back I am not getting anything printed out. I believe I might be missing some code but I am not sure.
Here is the code I have to retrieve and print from the database:
public class DrinksDiaryActivity extends Activity {

    private ListView listView;
    public static ArrayList<String> ArrayOfDrink = new ArrayList<String>();

    @Override
    public void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_drinks_diary);
        populateLayoutFromDrinkDiaryTitles();
    }

    public void onNewDrinkButtonClicked(View v){
        Intent drinkEntry = new Intent(this, DrinkEntryActivity.class);
        startActivity(drinkEntry);

    }

    private void populateLayoutFromDrinkDiaryTitles(){
        DatabaseHandler db = new DatabaseHandler(this);
        List<Drink> drinkEntry = db.getAllDrinkEntrys();
        for (Drink cn : drinkEntry) {
            String log = "Id: "+cn.getID()+", Drink: " + cn.getDrinkType() + ", Drink Volume: " + cn.getDrinkVolume() + ", Alcohol Percentage: " + cn.getAlcoholPercentage() + ", Time: " + cn.getTimeStamp() +
                ", Units: " + cn.getUnits();
            System.out.println(log);

        }
        //db.getAllDrinkEntrys();

        listView = (ListView) findViewById(R.id.drinkDiaryList);

        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
                android.R.layout.simple_list_item_1, ArrayOfDrink);

        listView.setAdapter(adapter);

        listView.setOnItemClickListener(new OnItemClickListener() {
            public void onItemClick(AdapterView<?> parent, View v,
                int position, long id) {
               Toast.makeText(getApplicationContext(),
                ((TextView) v).getText(), Toast.LENGTH_SHORT).show();
            }
        });
    }
}

My database handler:
public class DatabaseHandler extends SQLiteOpenHelper  {
    // Database Version
    private static final int DATABASE_VERSION = 1;
    // Database Name
    private static final String DRINKS_DIARY_DATABASE = "drinksDiaryDatabase";
    // Contacts table name
    private final String DRINKS_DIARY_TABLE = "drinksDiaryDatabase";
    // Contacts Table Columns names
    private static final String KEY_ID = "id";
    private static final String KEY_DRINK_TYPE = "drinkType";
    private static final String KEY_DRINK_VOLUME = "drinkVolume";
    private static final String KEY_ALCOHOL_PERCENTAGE = "alcoholPercentage";
    private static final String KEY_TIMESTAMP = "timeStamp";
    private static final String KEY_UNITS = "units";

    public DatabaseHandler(Context context) {
        super(context, DRINKS_DIARY_DATABASE, null, DATABASE_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        String CREATE_DRINK_DIARY_TABLE = "CREATE TABLE " + DRINKS_DIARY_TABLE + "(" + KEY_ID + " INTEGER PRIMARY KEY, " + KEY_DRINK_TYPE
            + " TEXT, " + KEY_DRINK_VOLUME + " TEXT, " + KEY_ALCOHOL_PERCENTAGE + " TEXT, " + KEY_TIMESTAMP + " TEXT, " + KEY_UNITS + " TEXT" +  ")";
         db.execSQL(CREATE_DRINK_DIARY_TABLE);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

         db.execSQL("DROP TABLE IF EXISTS " + DRINKS_DIARY_TABLE);

        onCreate(db);
    }

    public void addDrinkEntry(Drink drinkEntry) {
    SQLiteDatabase db = this.getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put(KEY_DRINK_TYPE, drinkEntry.getDrinkType());
        values.put(KEY_DRINK_VOLUME, drinkEntry.getDrinkVolume());
        values.put(KEY_ALCOHOL_PERCENTAGE, drinkEntry.getAlcoholPercentage());
        values.put(KEY_TIMESTAMP, drinkEntry.getTimeStamp());
        values.put(KEY_UNITS, drinkEntry.getUnits());
        db.insert(DRINKS_DIARY_TABLE, null, values);
        db.close();
    }

    public Drink getDrinkEntry(int id) {
        SQLiteDatabase db = this.getReadableDatabase();
        Cursor cursor = db.query(DRINKS_DIARY_TABLE, new String[] {
        KEY_ID, KEY_DRINK_TYPE, KEY_DRINK_VOLUME, KEY_ALCOHOL_PERCENTAGE, KEY_TIMESTAMP, KEY_UNITS,
        }, KEY_ID + "=?", new String[] {
            String.valueOf(id) }, null, null, null, null);
        if (cursor != null){
            cursor.moveToFirst();
        }
        Drink drinkEntry = new Drink(Integer.parseInt(cursor.getString(0)), cursor.getString(1), cursor.getString(2), cursor.getString(3), cursor.getString(4), cursor.getString(5));
        return drinkEntry;
    }

     public List<Drink> getAllDrinkEntrys() {
         List<Drink> drinkEntryList = new ArrayList<Drink>();
         String selectQuery = "SELECT  * FROM " + DRINKS_DIARY_TABLE;
         SQLiteDatabase db = this.getWritableDatabase();
         Cursor cursor = db.rawQuery(selectQuery, null);
         if (cursor.moveToFirst()) {
             do {
                 Drink drinkEntry = new Drink();
                 drinkEntry.setID(Integer.parseInt(cursor.getString(0)));
                 drinkEntry.setDrinkType(cursor.getString(1));
                 drinkEntry.setDrinkVolume(cursor.getString(2));
                 drinkEntry.setAlcoholPercentage(cursor.getString(3));
                 drinkEntry.setTimeStamp(cursor.getString(4));
                 drinkEntry.setUnits(cursor.getString(5));
                 drinkEntryList.add(drinkEntry);
             }
             while (cursor.moveToNext());
             }
          return drinkEntryList;
     }

     public int getDrinkEntryCount() {
         String countQuery = "SELECT  * FROM " + DRINKS_DIARY_TABLE;
         SQLiteDatabase db = this.getReadableDatabase();
         Cursor cursor = db.rawQuery(countQuery, null);
         cursor.close();
         return cursor.getCount();
     }

     public int updateDrinkEntry(Drink drinkEntry) {
         SQLiteDatabase db = this.getWritableDatabase();
         ContentValues values = new ContentValues();
         values.put(KEY_DRINK_TYPE, drinkEntry.getDrinkType());
         values.put(KEY_DRINK_VOLUME, drinkEntry.getDrinkVolume());
         values.put(KEY_ALCOHOL_PERCENTAGE, drinkEntry.getDrinkVolume());
         values.put(KEY_TIMESTAMP, drinkEntry.getTimeStamp());
         values.put(KEY_UNITS, drinkEntry.getUnits());

         return db.update(DRINKS_DIARY_TABLE, values, KEY_ID + " = ?", new String[] { String.valueOf(drinkEntry.getID()) });
     }

      public void deleteDrinkEntry(Drink drinkEntry) {
         SQLiteDatabase db = this.getWritableDatabase();
         db.delete(DRINKS_DIARY_TABLE, KEY_ID + " = ?",
             new String[] { String.valueOf(drinkEntry.getID()) });
         db.close();
    }

}

And my database:
public class Drink {

    int _ID;
    String _drinkType;
    String _drinkVolume;
    String _timeStamp;
    String _alcoholPercentage;
    String _units;

    public Drink(){

    }

    public Drink(int id, String drinkType, String drinkVolume, String timeStamp, String alcoholPercentage, String units){
        this._ID = id;
        this._drinkType = drinkType;
        this._drinkVolume = drinkVolume;
        this._timeStamp = timeStamp;
        this._alcoholPercentage = alcoholPercentage;
        this._units = units;
    }

    public Drink(String drinkType, String drinkVolume, String timeStamp, String alcoholPercentage, String units){
        this._drinkType = drinkType;
        this._drinkVolume = drinkVolume;
        this._timeStamp = timeStamp;
        this._alcoholPercentage = alcoholPercentage;
        this._units = units;
    }

    public int getID(){
        return this._ID;
    }

    public void setID(int id){
        this._ID = id;
    }

    public String getDrinkType(){
        return this._drinkType;
    }

    public void setDrinkType(String drinkType){
        this._drinkType = drinkType;
    }

    public String getDrinkVolume(){
        return this._drinkVolume;
    }

    public void setDrinkVolume(String drinkVolume){
        this._drinkVolume = drinkVolume;
    }

    public String getAlcoholPercentage(){
        return this._alcoholPercentage;
    }

    public void setAlcoholPercentage(String alcoholPercentage){
        this._alcoholPercentage = alcoholPercentage;
    }

    public String getTimeStamp(){
        return this._timeStamp;
    }

    public void setTimeStamp(String timeStamp){
        this._timeStamp = timeStamp;
    }

    public String getUnits(){
        return this._units;
    }

    public void setUnits(String units){
        this._units = units;
    }
}

Can any one show me what I have been doing wrong and how to fix it?
Thanks
Comment: Make sure you have added the data in your `ArrayOfDrink` array.
Comment: What is your `ArrayOfDrink` ? Please show some more code.
Comment: I have added the full Activity, it seems like I am not adding any data to it. How would I add the data I have retrieved to that array, Have I got confused and created more arrays then I need?
Comment: Which data do you want to show in your list?
Comment: The Data retireved here to be placed into an array to be placed into the list.

`String log = "Id: "+cn.getID()+", Drink: " + cn.getDrinkType() + ", Drink Volume: " + cn.getDrinkVolume() + ", Alcohol Percentage: " + cn.getAlcoholPercentage() + ", Time: " + cn.getTimeStamp() +
                ", Units: " + cn.getUnits();`
Comment: Thankyou I have got it working now. cheers for your help
Comment: Welcome :) Vote the answer as correct if it helped.
Answer: Your ArrayList<String> ArrayOfDrink is null as you have not added any data into your arraylist and you are directly setting that ArrayList in your ListView.
I have simply added the drink types to show the demo. You can add any detail whichever you want.Add the data in your ArrayList as below:
private void populateLayoutFromDrinkDiaryTitles(){
        DatabaseHandler db = new DatabaseHandler(this);
        List<Drink> drinkEntry = db.getAllDrinkEntrys();
        for (Drink cn : drinkEntry) {
            String log = "Id: "+cn.getID()+", Drink: " + cn.getDrinkType() + ", Drink Volume: " + cn.getDrinkVolume() + ", Alcohol Percentage: " + cn.getAlcoholPercentage() + ", Time: " + cn.getTimeStamp() +
                ", Units: " + cn.getUnits();
            System.out.println(log);
           ArrayOfDrink.add(cn.getDrinkType().toString);

        }


Should my drum sticks be the same size?

Question: I bought a snare (which came with drum sticks) on craigslist. It turns out one of the sticks is fatter than the other one, and heavier.
Is this a "thing" or did they just give me mismatched sticks?
Comment: The seller probably has a pair exactly the same - ask if you can swap one of them - after reading Tetsujin's and other answers. Not met a drummer yet who uses unmatched sticks, but there's still time. It's actually food for thought, as our hands/wrists/arms are different, why shouldn't our sticks be? No jokes - yet...
Comment: /me waits for the whole slew of 'How to confuse a drummer…' jokes. Go.
Answer: I'm sure someone, somewhere, will come up with a valid reason to have different sticks - but general convention is that they should be a matched pair.
See How to Choose the Best Drumsticks for Your Hands and Playing Style
They recommend 5As for beginners, which sounds like a fair compromise. I've always used 7As, even though I play rock. I can get a better wrist-snap with them than I can with anything heavier which, for me, equates to greater volume when needed & greater control when not.
I'd take a trip to a local music shop & try some out for feel.
Comment: @ToddWilcox - I actually bought the components of my kit with volume/EQ balance in mind. I guess that's what you get when a grown sound engineer goes back many years later to the drumming he left behind at age 13. ;))
Comment: @pixelearth Also: I'm not a drummer, but I get the impression that people go through sticks fairly regularly (faster of course if you're in certain genres or doing something wrong) and the basic ones don't cost too terrible much. Maybe get a few pairs just to have your next ones ready!
Comment: I experimented with different size sticks to try to influence the balance between the hats and snare. It sort of works, but if you do any rolls or work on the same piece with both sticks you can hear it. I concluded it's better to just learn control.
Comment: Oh yeah totally - I hate seeing high hats marketed as being able to "cut through the mix". As an engineer, I almost always wish for thinner, smaller hats that don't cut through anything
Comment: As far as weight goes, wood choice matters as much as drumstick size- I'm currently using a pair of "Natural" (?) Hickory 5B's that are much lighter than my usual, smaller Hickory 5A's, which are much lighter than even smaller 5A designs made out of maple.
Comment: For me practicing on a pad with a bit of a heavier stick (5B) has helped my stamina and speed.  Recently also got some 7A's for a switch-up - highly recommended if you are finding you're practice sessions are becoming a bit stale and you're feeling like a change.

Should my drum sticks be the same size?


Django main query ordered by subquery

Question: I want to make main queryset ordered by subquery list.
The relationship between models can be briefly expressed as follows.
class Firm(models.Model):
    cik = models.IntegerField(primary_key=True)

class Stock(models.Model):
    ticker = models.CharField(max_length=5,primary_key=True)
    firm = models.ForeignKey(Firm, on_delete=models.CASCADE,null=True)

class File(models.Model):
    accNumber = models.IntegerField(primary_key=True)
    firm = models.ForeignKey(Firm, on_delete=models.SET_NULL, null=True)

What I want to query :
SELECT ticker
FROM Stock
WHERE firm_id =
            ( SELECT firm_id, count(*) as total
              FROM File
              WHERE created_at >yesterday AND created at < today
              GROUP BY firm_id
              ORDER BY total )

I use django.db.models.Subquery to make the nested SQL above.
Django code :
firm_list = File.objects\
    .filter(Q(created_at__gte=yesterday)|Q(created_at__lte=today))\
    .values('firm_id')\
    .annotate(total=Count('firm_id'))\
    .order_by('-total')

ticker_list = Stock.objects
    .filter(firm_id__in=Subquery(firm_list.values('firm_id')))
    .only('ticker')

I want to make ticker list ordered by firm list order. firm list order is like
>>>firm_list.values('firm_id')
<QuerySet [{'firm_id': 1750}, {'firm_id': 1800}, {'firm_id': 4977}, {'firm_id': 3453}]>

but the ticker list is not ordered by subquery.
>>> ticker_list.values('firm_id')
<QuerySet [{'firm_id': 1750}, {'firm_id': 1800}, {'firm_id': 3453}, {'firm_id': 4977}]>

How can I make the main query ordered by subquery list order?? I'm using sqlite for db. Thank you.
Answer: I solved it by Case, When in django.db.models.
firm_list = File.objects\
        .filter(Q(created_at__gte=yesterday)|Q(created_at__lte=today))\
        .values('firm_id')\
        .annotate(total=Count('firm_id'))\
        .order_by('-total')\
        .values_list('firm_id',flat=True)

preserved = Case(*[When(firm_id=firm_id,then=pos) for pos, firm_id in enumerate(firm_list)])

ticker_list = Stock.objects\
       .filter(firm_id__in=Subquery(firm_list.values('firm_id')))\
       .order_by(preserved)

Django main query ordered by subquery


I upload modifications to testflight and the testers do not see the changes

Question: I have created an app and I have uploaded it to testflight the first versions all in order but they asked me for more changes and I have uploaded them and the internal tester of my app do not see the changes made, ie if you send them the message that there is a new version to download and they see the version number and they can download it but when testing it you do not see the changes it looks just as it was before. Any idea what it could be? I have searched for info and I can not find almost nothing. Thanks
Comment: most likely you submitted an old version to TF.  Be sure that you are doing a complete rebuild of the app before submitting
Comment: I solved it, I did two things, I did clean and rebuild the project and changed the provisioning profile and it worked.
Answer: I've run into this issue before as well. The only way I was able to solve it was to delete the bin/obj folders, close solution, clean, rebuild.
Then the next time the changes were shown.
I'm using Xamarin Forms and Visual Studio


Laço "for" não percorre todos os itens da lista

Question: Estou com um problema na seguinte função:
function limpaLista() {
    var lista = document.getElementById('resposta');
    var itens = document.getElementsByClassName('Repos');
    for (item of itens) {
        lista.removeChild(item);
    }
}

Ela deveria excluir totalmente uma lista de nomes, mas por algum motivo ela exclui metade da lista apenas a cada execução.
Comment: Coloca um console.log e verifica se a quantidade de itens e a lista realmente são os corretos, além disso, verifica se realmente todos os itens contém essa classe Repos.
Comment: segue o resultado:
```
function limpaLista() {
    var lista = document.getElementById('resposta');
    var itens = document.getElementsByClassName('Repos');
    console.log(itens.length);
    console.log(itens);
    for (item of itens) {
        lista.removeChild(item);
    }
    console.log(itens.length);
    console.log(itens);
}
```
Comment: Resolvido com a resposta abaixo, vlw
Answer: A lógica não está errada, mas tem uma armadilha nesse código.
O retorno do método getElementsByClassName é um HTMLCollection, uma lista "viva" que é atualizada conforme você adiciona ou remove elementos no DOM. Ao remover esses elementos do DOM, você está removendo da sua lista também, e é preciso ter cuidado ao se iterar sobre uma lista que está sendo reduzida.
Minha sugestão é transformar esse HTMLCollection num array comum antes de remover os itens, assim, apesar dos elementos serem removidos do DOM, ao menos a estrutura da sua lista se mantém integra durante a iteração:
function limpaLista() {
    var lista = document.getElementById('resposta');
    var itens = Array.from(document.getElementsByClassName('Repos'));
    for (item of itens) {
        lista.removeChild(item);
    }
}

Ou alternativamente faça um while para remover todos os itens enquanto eles existirem:
function limpaLista() {
    var lista = document.getElementById('resposta');
    var itens = document.getElementsByClassName('Repos');
    while (itens.length) {
        lista.removeChild(itens[0]);
    }
}


uniformly distributed random variable

Question: Suppose that a uniformly distributed random variable X can have each of the seven values

$-1, 0, 1, 2, 3, 4, 5$

and $Y = X^2-2X$
I want to get the probability mass function of Y
I used the Transformation of Random Variables and got PMF of y which is
$\frac{1}{7\sqrt{1+y}}$
is there another way to get PMF of y without using Transformation of Random Variables?
thanks
Answer: Your answer makes no sense.
Make a table with two columns. The first column is labeled $X$ and has the seven given values listed in the column. The second column is labeled $Y=X^2-2X$ and had the values of $Y$ listed in it; each $Y$ value being the square of the number in the left hand column minus twice the number in the left column.
Now, look at the right hand column. If you have seven different numbers listed there, $Y$ takes on those seven values with probability $\frac{1}{7}$ each. If a number occurs more than once, $Y$ takes on that value with probability $\frac{k}{7}$ where $k$ is how many times that number occurs in the right column.

uniformly distributed random variable


Hypergeometric function $\,_1 F_1(0;0;x)$?

Question: What is $\,_1F_1(0;0;x)$? Since its first argument is $0$, either we say it is 0 or since its first and second arguments are equal we say it is $e^x$? I cannot understand.
Answer: The function is constant:
$$
\,_1F_{1}(0;0;x) = 1
$$
The exponential form comes from
$$
\,_1F_{1}(1;1;x) = e^{x}
$$
From functions.wolfram.com

Note the special case you ask about:

You have focused on a special case of $b=0$. From WolframMathworl:
Comment: Thanks but how can we prove it?
Comment: @LİLA: Prove the 0 result or the exponential result?
Comment: Proof of the 0 result?


Convergence errors in parametric bootstraps (PBmodcomp) of lmer models

Question: I am using PBmodcomp from the pbkrtest to perform a parametric bootstrap model comparison. However, for some of the comparisons a warning message stating that the models failed to converge appear. A example of the R script for my lemr models can be found here: https://stackoverflow.com/questions/25111939/error-runnning-parametric-bootstrap-pbmodcomp-on-lmer-objects
<code>modelfit.04b[[1]] <- PBmodcomp(output.04b[[1]], output.04a[[1]])
Warning messages:
1: In checkConv(attr(opt, "derivs"), opt$par, ctrl = control$checkConv,  :
  Model failed to converge: degenerate  Hessian with 1 negative eigenvalues
2: In checkConv(attr(opt, "derivs"), opt$par, ctrl = control$checkConv,  :
  Model failed to converge: degenerate  Hessian with 1 negative eigenvalues

modelfit.04b[[1]]
Parametric bootstrap test; time: 611.59 sec; samples: 1000 extremes: 156;
large : y ~ age_c + gender_R2 + ibphdtdep + iyeareducc + apoegeno + age_c *
    apoegeno + ABCA7_carrier + age_c * ABCA7_carrier + ABCA7_carrier *
    apoegeno + age_c * ABCA7_carrier * apoegeno + (age_c | pathid)
small : y ~ age_c + gender_R2 + ibphdtdep + iyeareducc + apoegeno + age_c *
    apoegeno + ABCA7_carrier + age_c * ABCA7_carrier + (age_c |
    pathid)
         stat df p.value
LRT    6.5422  4  0.1621
PBtest 6.5422     0.1568
</code>
My models have no issues with convergence outside of the bootstrap.
So my question is does this affect the p.value I get from the PBmodcomp function? Is it still valid?
Thanks
Answer: Your p-values are meaningless. The methods in the package you are stating must be using a Newton method of sorts to solve an optimization problem. The Newton method involves finding the inverse of the matrix of second derivatives (Hessian). The error is saying that this matrix became singular at some point (degenerate eigenvalues) and hence could not complete. In any case, it is throwing up the values it got till the point of termination
Comment: Thanks for the explanation. So the solution would be to just rerun the bootstrap untill I get one with no convergence errors?
Answer: My answer was getting too long so I put up a new post.
I do not think too much will change on re-running, you may need to reformulate the setup. I haven't looked into the details of the package as to what exactly is being optimized but here is an explanation of why things might not change too much. Hope this helps you make an informed decision/hope other people chip in.
This error suggests that at some point your second derivative is becoming +/- $\infty$. If I tell you I want to minimize f(x) with this property using a solver which iteratively does it, will my starting point matter? Not if my problem is convex! (as is the case in most problems). Eventually you will probably to get stuck in the pit which pulls the solution towards -$\infty$. As a simple example, suppose I ask you to minimize x where x is real the answer is -$\infty$
9/10 cases I will say restructure the problem to rid yourself of this singularity. I am not sure if your problem falls in the 1/10 case but the odds are pretty low it does


Robolectric "Failed to create a android.widget.Button" error

Question: When I try to run my robolectric tests I receive exception:
java.lang.RuntimeException: Failed to create a android.widget.Button
However if activity doesn't contains any buttons everything runs ok, but I need buttons :)
I use robolectric 2.0-alpha-3-SNAPSHOT, what is more few days ago all tests was run successfully.
Any ideas what can be wrong?
Answer: Finally I've solved this problem! My buttons used text color defined like:
<color name="TEXT">@android:color/white</color> it seems that robolectric doesn't have support for @android:color values, so replacing it by <color name="TEXT">#FFF</color> solved my problem
Comment: Any idea why would this work, because its not in my case. I am setting a color `#000000` to my activity background. e.g. container.setBackgroundColor(R.color.foo);


Different behavior of direct and copy initialization on MS VC++ (using user-defined conversion operators)

Question: The following code compiles fine with both g++ 9.1 and clang 8.0.0 (compilation flags are -std=c++17 -Wall -Wextra -Werror -pedantic-errors), but not with MSVC 19.22 (compilation flags are /std:c++17 /permissive-):
struct X{};

struct Bar
{
    Bar() = default;

    Bar(X){}
};

struct Foo
{
    operator X() const
    {
        return X{};
    }

    operator Bar() const
    {
        return Bar{};
    }
};

int main()
{
    Foo foo;
    [[maybe_unused]]Bar b1 = foo; // OK
    [[maybe_unused]]Bar b2(foo);  // failed
}

MSVC compilation errors:
<source>(27): error C2668: 'Bar::Bar': ambiguous call to overloaded function
<source>(8): note: could be 'Bar::Bar(Bar &&)'
<source>(7): note: or       'Bar::Bar(X)'
<source>(27): note: while trying to match the argument list '(Foo)'

Is it a bug in MSVC?
Comment: Over at [RexTester](https://rextester.com/NZZMM41358), I also got `note: or 'Bar::Bar(const Bar &)'`, which makes a bit more sense.
Comment: @PaulSanders Rextester uses an old version of *MSVC* (provided together with *Microsoft Visual Studio 2015*), in godbolt that I have used *MSVC 19.22* (provided together with the latest *MSVS 2019 version 16.2*) is available.
Answer: I think this is basically a manifestation of CWG 2327, which dealt with this example:
struct Cat {};
struct Dog { operator Cat(); };

Dog d;
Cat c(d);

The crux of the issue was that we don't allow for guaranteed copy elision in this case - because we go through Cat's move constructor rather than just initializing via Dog::operator Cat() directly.
And it seems like gcc and clang both already implement the intent of the issue - which is to do overload resolution on both the constructors and conversion functions at the same time.
In your example:
Bar b2(foo);

Per the letter of the standard, we consider constructors (and only constructors) - which are Bar(X), Bar(Bar const&), and Bar(Bar&&). All three of those are viable, the first by way of Foo::operator X() const and the second and third by way of Foo::operator Bar() const. We can prefer Bar(Bar&&) to Bar(Bar const&) but we have way of disambiguating between Bar(X) and Bar(Bar&&). MSVC is following the standard in correctly rejecting this initialization. It is not a bug.
But the spirit of CWG 2327 is that this should invoke Foo::operator Bar() const directly, which is what gcc and clang do. It is hard to say that this is a bug on their side either since that's probably the behavior we actually want to happen, and will likely be the way it is specified at some point in the future.
Comment: Call this an extension then for gcc and clang?
Comment: @NathanOliver Maybe? I think of extensions as like.. things that definitely aren't in the language that compilers added anyway. Like... expression-statements are certainly an extension. This is more like, a pre-interpretation of a core language issue? It's a bit fuzzy.


How can I parse *.vector.pbf about Mapbox vector tile map?

Question:
*.pbf("Protocolbuffer Binary Format") is primarily intended as an alternative to the XML format.
There are two formats of *.osm.pbf and *.vector.pbf. What tools can I use to open these files? (I know JOSM can open *.osm.pbf files, but it can't open *.vector.pbf files.)
If I want to write own *.vector.pbf files in Mapbox, how do I work for that?

Thanks!
Answer: The Vector tiles used by Mapbox are serialized as Protocol Buffers.
Protocol Buffers allow you to efficiently compress the vector data inside the tile.
The Mapbox Tile Specification is available on github.
Esri has also adopted the same specification for their products.
You can find a list of parsers, renderers & CLI utilities here: https://github.com/mapbox/awesome-vector-tiles
In the common scenario, you can use mapbox-gl-js to render the vector tiles on the client. To generate vector tiles, you can use Mapbox Studio. This will require uploading your data online in the Studio. You can also use Mapbox Studio Classic (the older version) to generate the tiles locally.
Internally, Mapbox Studio uses the tilelive API, so you can programatically generate the tiles. In the list above there are other good  alternatives as well.
Answer: Regarding question #2, extracting PBF data
Using GDAL's ogr2ogr is the easiest method (I found).
Given a file named 1583.vector.pbf decode it to a, for example, shapefile (folder) named output:
# cmd   show prog.  output format     output name     input name
ogr2ogr -progress -f "ESRI Shapefile" output          1583.vector.pbf

Regarding question #3, creating PBF data
Use the same command as above but swap the input/outputs and output format:
# example source: https://gdal.org/drivers/vector/mvt.html
ogr2ogr -f MVT mytileset source.gpkg -dsco MAXZOOM=10


Google app engine deployment Invalid runtime or the current user is not authorized

Question: Hi I am getting this error when i try to deploy my app in gae, I have also registered my app in gae .. Please help me.
02:16 PM Scanning files on local disk.
Error 400: --- begin server output ---
Invalid runtime or the current user is not authorized to use it.
--- end server output ---
Answer: Are you deploying php? You need to register your user first there:
https://gaeforphp.appspot.com/


Ao compilar uma classe herdada em C++ dá erro no construtor

Question: Preciso criar uma classe para peças de xadrez. Criei a classe Peca e a derivada dela, Bispo.
Quando eu tento compilar a classe bispo, o compilador retorna erro de redefinição. Como posso resolver?
#ifndef PECA_H
#define PECA_H
#include <string>

using std::string;

class Peca {

    private:
        int cor; //0 para as brancas, 1 para as pretas
        bool emJogo;

    public:
        Peca(int cor);
        string desenha();
        bool checaMovimento(int linhaOrigem, int colunaOrigem, int linhaDestino, int colunaDestino);
        int getCor();
        bool estaEmJogo();
        void setForaDeJogo(bool estado);
};
#endif

Peca.h
#include "Peca.h"

using std::string;

class Bispo: public Peca {
    public:
        Bispo(int cor): Peca(cor);
        bool checaMovimento(int linhaOrigem, int colunaOrigem, int linhaDestino, int colunaDestino);
        string desenha();
};

Bispo.h
#include "Bispo.h"
#include <cmath>

Bispo::Bispo(int cor): Peca(cor){};

bool Bispo::checaMovimento(int linhaOrigem, int colunaOrigem, int linhaDestino, int colunaDestino)
{
    if (abs(linhaDestino - linhaOrigem) == abs(colunaDestino - colunaOrigem))
        return true;
    else
        return false;
}

//Minúsculo para peças brancas, maiúsculo para as peças pretas
string Bispo::desenha()
{
    if(getCor() == 0) // Peça branca
        return("b");
    else
        return("B");
}

Bispo.cpp
Answer: Na declaração da classe o método não deve ter implementação e você colocou um inicializador, tem que tirar:
class Bispo: public Peca {
    public:
        Bispo(int cor);
        bool checaMovimento(int linhaOrigem, int colunaOrigem, int linhaDestino, int colunaDestino);
        string desenha();
};

Coloquei no GitHub para referência futura.
Comment: Muito obrigado!


Problema com aspas na sintaxe de consulta no MySQL

Question: Tenho uma classe, e dentro dessa classe, tenho uma função pra atualizar um dado no banco de dados MySQL. Segue a função:
public function set_detail($id, $detail, $value) {
  $query = "UPDATE `contacts` SET $detail = '$value' WHERE `contact`.`id` = $id";
  if (parent::do_sql($query)) {
    return true;
  } else {
    return false;
  }
}

Até aí, tudo bem. Mas o problema está na variável '$value'. Se o valor recebido via $_POST for NULL, '$value' recebe uma string vazia '' e assim é enviado ao banco de dados.
Presumi que isso aconteça por causa das aspas simples em volta da variável. Por isso retirei as aspas e ao tentar realizar a consulta novamente, me aparece o erro de sintaxe:
Warning: PDOStatement::execute(): SQLSTATE[42000]: Syntax error or access violation: 1064 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 'WHERE `contacts`.`id` = 0000000839'

Presumi também que tenha sido por retirar as aspas. Porém já escrevi consultas no MySQL sem aspas e funcionaram normalmente.
O que não quero é deixar strings vazias no banco de dados. Como resolver isso? Qual a maneira correta?
Answer: Se você tira o aspas simples de SET $detail = '$value' WHERE... e $value for nulo ou vazio, ele causa esse erro por que o SQL será montado assim SET $detail = WHERE....
A forma mais simples para resolver esse problema é tratar quando $value for nulo ou vazio usando a função empty.
O código ficaria assim:
if(empty($value)){
    // Código que lida quando for nulo ou vazio.
    // Você pode colocar um simples return false, ou lançar um throw.
    // Ou colocar setar um valor padrão para $value.
}

Comment: Entendo... Mas se executar a consulta direto no phpMyAdmin, o SQL fica assim: `UPDATE 'contacts' SET 'phone' = NULL WHERE 'contacts'.'id' = 0000000839`. Como fazer isso na função?
Comment: Se você quer dessa forma, basta setar o valor de `$value` dentro do `if` por "NULL", e utilizar a query da mesma forma como estava antes.
Comment: Usei essa mesma lógica, mas dentro da função pra montar a consulta. Ficou assim: `if (empty($value) || $value == "") { $query = "UPDATE 'contacts' SET $detail = NULL WHERE 'contacts'.'id' = $id"; } else { $query = "UPDATE 'contacts_business' SET $detail = '$value' WHERE 'contacts_business'.'id' = $id"; }`
Comment: Assim mesmo. Só um adendo, não precisa fazer a comparação de `$value == ""` pois a própria função já faz essa verificação. Deixo aqui também [uma outra solução](https://stackoverflow.com/a/4620409/8741188) com a mesma pergunta só que feita em inglês.
Answer: Acredito que a melhor maneira de resolver isso é definindo as aspas da variável apenas se ela não estiver vazia. Além disso, o null tem de ser string para que o termo "null" apareça no seu código SQL.

public function set_detail($id, $detail, $value) {
 if(!empty($value)){
  $value = "'".$value."'";
 }
 else{
    $value = "NULL";
   }

 $query = "UPDATE contacts SET ".$detail." = ".$value." WHERE contact.id = ".$id;
 if (parent::do_sql($query)) {
  return true;
 } else {
  return false;
 }
}


Angular 4: Converting Http to HttpClient, config

Question: I have the following code in Angular 4:
constructor(private baseUrl: string, private http: Http) {}

get(url: string, config?: RequestOptionsArgs): Promise<any> {
    return this.http.get(this.prependBaseUrl(url), config)
        .toPromise();
}

I would like to rewrite it to HttpClient instead of Http, so i modified type of http injecting to constructor, but i don't know (and can't find anywhere) what to do with config?: RequestOptionsArgs.
Thanks for help
Comment: You shouldn't have this wrapping service in the first place. Use HttpClient directly from the functional services.
Comment: so you just want to change from using in `http` to use `HttpClient` in this code above yeah?
Comment: yes, and i want to know how to pass my config there
Comment: wrapping httpClient methods is a bad idea, because passing dynamic config confuses linter to choose right override of `get` or other http methods
Comment: Can you show your config ? What elements it contains?
Answer: Try Basic Approach:
import HttpClientModule and add it into app.module.ts in imports[]
import { HttpClientModule } from '@angular/common/http';

@NgModule({
  imports: [
    BrowserModule,
    // import HttpClientModule after BrowserModule.
    HttpClientModule,
  ],
  declarations: [
    AppComponent,
  ],
  bootstrap: [ AppComponent ]
})
export class AppModule {}

app.service.ts
import HttpClient  in component
import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';

@Injectable()
export class AppService{
  constructor(private http: HttpClient) { }
getData(): Observable<any>{

    return this.httpClient.get('request_url',RequestOptionsArgs)
    }
}

app.component.ts:
import {AppService} from './app.service.ts';

constructor(private appservice: AppService){
  this.appservice.getData().subscribe(response => {
  console.log(response)
})


Composer doesn't see that updates are needed

Question: My Drupal version is 8.5.1, and yet when I run...
<code>composer outdated drupal/*
</code>
It says "nothing to install or update".
What to do?
This is the relevant part of my composer.json...
<code>"require": {
        "composer/installers": "^1.0.21",
        "wikimedia/composer-merge-plugin": "~1.3",
        "drupal/core": "^8.5"
    },
</code>
Looks fine to me, but composer says no update is available.
Comment: This can happen when composer is working off the cache. Running `composer clearcache` will clear the cache. Deleting composer.lock is NOT the recommended thing to do, as this can cause issues if you are working with other developers. composer.lock ensures that everyone is using the same versions of libraries.
Comment: Thanks Jaypan.  I ran 'composer clearcache', but the the 'composer outdated' command still isn't working.  It's now failing to recognize that I have modules that need updating.
Comment: Actually, it now appears the module I'm trying to update is not required in composer.lock.  So I need to run 'composer require drupal/token' in this case, to require the token module.  However, that's not working.  Composer says "Could not find a version of package drupal/token matching your minimum-stab
  ility".  It says that whether I set the minimum stability to dev or to stable.  This is an issue unto itself, so I'll create a new question or see if someone else has posted a relevant question re: 'composer require' not working.
Comment: I got a resolution to the 'composer require' problem, which is perhaps also relevant to 'composer outdated': https://drupal.stackexchange.com/a/265913/8027
Comment: Don't know if it would help in this case, but I always pin drupal/core to an exact version, and also use webflo/drupal-core-strict with an exact version.  I do this out of precaution, but it can help with weirdness at times.
Comment: Running `composer clearcache` command first helped me.
Answer: Update:  This is not a good answer.  Leaving it here for reference, but this does not solve the underlying problem, whatever it is.
Fixed by deleting vendor and core directories and composer.lock and then running...
composer update drupal/core --with-dependencies
It seems there must be some circumstances when the 'composer outdated' command doesn't work, but it's still possible to upgrade.
Comment: This is a good answer.


Refer to own class in a static method

Question: Is there a shorthand for referring to its own class in a static method?
Say I have this piece of code:
class SuperLongClassName(object):

    @staticmethod
    def sayHi():
        print 'Hi'

    @staticmethod
    def speak():
        SuperLongClassName.sayHi()  # Is there a shorthand?

Comment: you should use a class method instead of a static method

[more info here][1]

  [1]: http://stackoverflow.com/questions/9744223/python-difference-between-static-methods-vs-class-method
Answer: Yes, use @classmethod instead of @staticmethod. The whole point of @staticmethod is to remove the extra class parameter if you don't need it.
class SuperLongClassName(object):

    @classmethod
    def sayHi(cls):
        print 'Hi'

    @classmethod
    def speak(cls):
        cls.sayHi()

Answer: You probably want a classmethod. It works like a staticmethod, but takes the class as an implicit first argument.
class Claaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaass(object):
    @classmethod
    def foo(cls):
         print cls.__name__

Claaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaass.foo() # prints Claaa...

Warning:
class Subclaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaass(
        Claaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaass):
    pass

Subclaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaass.foo() # prints Subclaaa...

Alternatively, define a shorter alias for your class at module level:
class Claaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaass2(object):
    @staticmethod
    def foo():
        return _cls2
_cls2 = Claaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaass2

# prints True
print (Claaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaass2 is
       Claaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaass2.foo())

Refer to own class in a static method


O que significa infixr no Haskell

Question: O que é e para que serve esse infixr 3 &&?
infixr 3 &&
(&&) :: Bool -> Bool -> Bool
True && True = True
_ && _ = False

Comment: Se voçe entende ingles, veja a resposta a esta pergunta:

http://stackoverflow.com/questions/27770118/how-does-the-infix-work
Answer: Notação infixada significa que o operador vem entre os operandos, por exemplo 1 + 1. Funções em haskell geralmente utilizam notação posfixada, como por exemplo pow 1 2.
O r ou l se refere à associatividade, r para right associativity (associatividade à direita) e l para left associativity (associatividade à esquerda). Por exemplo, a operação seta é infixr, pois A -> A -> A significa A -> (A -> A).
Mas também podemos utilizar apenas a notação infix e não fornecer a associaitividade, nesse caso se você tentar escrever um código utilizando várias vezes aquele operador sem parentesis, dará erro, pois o interpretador não saberá em que ordem interpretar.
No seu exemplo True && True && True será interpretado como True && (True && True)
O número se refere à precedência, quanto maior o número, maior a precedencia.

O que significa infixr no Haskell


Labview IMAQ WindDraw External Display Embedding

Question: I am working in labview on using multiple gig-e industrial cameras to display a set of images for a semi-automatic test system with data and human visual inspection.
The main issue that I have currently encountered with the vision software is that screen tearing corrupts the display of the video making it hard to observe the dynamic aspect of the test. There is a VI control called the IMAQ WindDraw external image display that has an anti-tearing option that appears to work but I need to embed 4-5 video displays into one window and not show the title bars/window buttons. Basically I want to tie the external displays to the front panel VI and run them in a windowed full screen mode.
The front panel VI will not need to be scrolled or be resizeable as the system is dedicated to the task.
Answer: Here's an example that uses one of the Vision DLLs to include an IMAQ WinDraw external display into the front panel of a VI.
Hope this helps.
Ah... as a new user I can't post images... Oh well.
You can use the NIVisWnd.dll (to be found in C:\WINDOWS\system32)  to get the IMAQ WinDraw external image's handle (function name is : GetWindowHandle) and then use user32.dll to make external image child of FP (function name is : SetParent).


How to use the Law of Sines to Find an Angle

Question: I am trying to figure out how to find an angle with the law of sines.
I have a triangle where:
A = $120^\circ$
B = unmarked
C = $\theta$
a = 45
b = unmarked
c = 36
How can I find the angle for C?
I have tried:
$$\frac{sin120^\circ}{45} = \frac{sinB}{b} =\frac{sin\theta}{36} $$
$$36(\frac{sin\theta}{36}) = 36(\frac{sin120^\circ}{45})$$
$$sin\theta = \frac{36sin120^\circ}{45}$$
$$ \theta = \frac{36(120^\circ)}{45} = 95^\circ$$
But, the answer is supposed to be $44^\circ$.
Comment: $$\sin(\theta)=\frac{36}{45}\sin(120^{\circ})\approx 43.853..$$
Comment: You must press the inv sin bottom on your calculator.
Comment: A sin is missed in your last line!
Comment: I just dropped the sin altogether. If that's not what I do, then I don't know how to solve it.
Comment: Hint: $$\sin(120^{\circ})=\frac{\sqrt{3}}{2}$$
Comment: I have added some comments for you!
Comment: @Graubner according to my calculator $\frac{36}{45}\sin(120^{\circ})\approx 0.6928..$
Comment: This is right! and the searched angle is given by $$\theta \approx 43.85^{\circ}$$
Comment: @Graubner I am not sure what you mean. How did you get $\theta$ from that?
Comment: ohh, so $\sin^-^1(\frac{36}{45}\sin(120^{\circ}))\approx 43.853..$
Comment: Congratulations, you got it!
Comment: thanks! This really helped!
Comment: I wish you a nice evening, good night!
Answer: The following step is completely wrong
$$\sin\theta = \frac{36 \sin120^\circ}{45} \iff \color{red}{\theta = \frac{36(120^\circ)}{45} = 95^\circ}$$
we have that $\sin120^\circ=\sqrt 3/2$ and then
$$\sin\theta = \frac{36\sin120^\circ}{45} \iff \sin \theta = \frac{36\sqrt 3}{2\cdot 45} \iff \theta = \arcsin \left(\frac{2\sqrt 3}{9}\right)$$
Comment: I'm sorry, my class hasn't covered arcsin yet. Could you please show how to get the answer in degrees?
Comment: Note that $\arcsin x$ is the inverse function of $\sin x$, we need that to find the value for $\theta$ here. You should have itnon your calculator and you should also be able to obtain the result in degree directly or convrting by radians.
Comment: Note also that in that case we can use $\arcsin x$ to obtain the result because we are sure that the angle is acute otherwise, when the angle is obtuse, we need to take $\pi - \arcsin x$.
Answer: Most of your steps are correct, but it is from the second last step you made a fundamental mistake.
Using arcsine ($sine^{-1}$ on calculator):
$$sin\theta = \frac{36sin120^\circ}{45} $$
$$\theta = arcsine(\frac{36sin120^\circ}{45}) $$
$$\theta = 43.8537^{\circ}... $$
$$\theta \approx 44^{\circ} $$
Just as @Dr. Sonnhard Graubner pointed out. The mistake you made was that you interpreted arcsine and sin$\theta$ canceling out, because sometimes it is learned to students that $arcsine = \frac{1}{sin}$. The thing is, $sin$ on itself cannot be cancelled out, as it is a trigonometric function of an angle, not $s . i . n$ as variables.
Comment: Ah, I took to long to post a comment. At least @gimusi got to it!


How to get the value of a specific element from JSON using PostgreSQl

Question: I have the following JSON object in PostgreSQL. I am trying to write a query to get me the details of "Elements"
{
  "ItineraryId": 0,
  "ForceSingleSearchForFlights": null,
  "ExcludeBasicFareBrand": null,
  "UserNodes": [
    {
      "User": {
        "Id": "-2",
        "GivenName": "Wiliam Never",
        "PreferredAirport": "",
        "TravelerGroupId": null,
        "ExternalId": null,
        "ExternalId2": null,
        "CheckCCFieldForTraveler": false,
        "NotificationEmailOverride": null,
        "PaxType": 0,
        "Title": "Dr",
        "MiddleName": null,
        "DateOfBirth": "1980-01-15T00:00:00Z",
        "PhoneNumber": null,
        "TsaInfo": null,
        "Source": "RequestEndPoint",
        "AllowBookingGuestTraveler": null,
        "GDSTravelerProfileContainsFirstName": false,
        "ProfilesFound": {
          "Agency": null,
          "Corporate": null,
          "Traveler": null
        },
        "UserId": "-2",
        "FirstName": "Wiliam",
        "LastName": "Never"
      },
      "Elements": null
    }
  ]
}

I have tried with multiple query options like
select itineraryintent -> 'UserNodes' ->> 'Elements' AS intent from Itinerary";

but i am always getting the following error
ERROR:  operator does not exist: text -> unknown
LINE 1: select itineraryintent -> 'UserNodes' AS intent from "Worksp...
                               ^
HINT:  No operator matches the given name and argument types. You might need to add explicit type casts.

SQL state: 42883
Character: 24

Comment: From the error it looks like `itineraryintent` is a string type not a json type. Add the table definition, **as text**, to your question text.
Comment: `select ((itineraryintent::jsonb -> 'UserNodes')->0)->>'Elements' AS intent from "Itinerary";`
Answer: Use json_array_elements like the following
SELECT
    elements.*
FROM
    Itinerary,
    json_array_elements(itineraryintent -> 'UserNodes') AS elements
WHERE
    elements -> 'User' ->> 'Elements' IS NOT NULL;


Proposition of complexes in Homology

Question: I have been reading Maclane's book on Homology and he talks about the following proposition :

"When the ring $R$ is regarded as a trivial complex then $Hom(R,L) \cong L$, under the natural homomorphism wich assigns to each $f_p: R \rightarrow L_p$ its image $f_p(1) \in L_p$."

I have two questions that are,
1) What does he mean by a trivial complex ?
2)This isomorphism is in the context of the category?
Thanks in advance.
Answer: (1) The trivial complex is the complex that has $R$ in degree $0$ and has $0$ in all other degrees. (2) It's an isomorphism of complexes of $R$-modules.
Comment: An isomorphism of complexes consists of isomorphisms in all degrees, commuting with the morphisms in the complexes. To make it look more category-theoretic: Complexes of modules are the objects of a category, in which a morphism consists of morphisms in all degrees commuting with the morphisms in the complexes.  Isomorphisms of complexes are exactly the isomorphisms (i.e., the invertible morphisms) in this category.
Comment: Alright thanks , how do we define the isomorphism of complexes, is it an isomorphism in every degree or do we use a category ? ( wich they probably are equivalent)

Proposition of complexes in Homology


Condition for a year having 53 ISO 8601 weeks

Question: ISO_Week_Date's wikipedia page says that there are three identical conditions for identifying whether a given year has 53 ISO 8601 weeks or not.

any year starting on Thursday (dominical letter D or DC) and any leap year starting on Wednesday (ED)
any year ending on Thursday (D, ED) and any leap year ending on Friday (DC)
years in which 1 January and 31 December (in common years) or either (in leap years) are Thursdays

Assuming this is correct, each condition has a condition for a common year and a condition for a leap year. My logic was that they can be separated. Thus for a common year, the condition should be:

the year starts on Thursday
the year ends on Thursday
the year starts and ends on Thursday

and for a leap year, the condition should be:

the year starts on Wednesday or Thursday
the year ends on Thursday or Friday
the year starts or ends on Thursday

but each condition in the triplet does not seem to be equivalent to each of the other two. What is wrong with my interpretation?
Answer: For the regular year those are equivalent:
For a regular year the weekdays of January 1. and December 31. are the same. And if they are Thursdays the weeks containing them are counted towards the year so it has 53 weeks. Thus in a regular year if it starts on a Thursday it ends on one and has 53 weeks.
For a leapyear if either Jan 1. Or Dec 31.  are a Thursday it has 53. weeks. If Jan 1. Is a Thursday Dec. 31. will be a Friday and if Dec 31 is a Thursday then January 1. was a Wednesday.
So for the regular year all rules are equivalent and for the leap year the first two are the two distinct cases of the third.
Comment: @sawa-Your conclusion is right because if 365 days of ordinary year can cover this condition because of Thursday,then obviously 365 days' of leap year will surely do the same! hence,it is purely safe to conclude that!!!
Comment: So, is it possible to combine common year and leap year cases, and simply say: if either the beginning or the end of a year is Thursday, then it has 53 weeks?


Explode em Delphi

Question: Tenho um arquivo txt em que os dados são salvos da seguinte forma:

00:46:30@21/08/2014@Carlos dos Santos@São Paulo

No PHP eu usaria o explode para transformar cada dado antes do "@" em colunas.
Como faço isso em delphi ? Preciso que cada dado separado @ vire uma coluna, assim eu posso colocá-los em um LISTVIEW.
Answer: Um possível reparo técnico1 é usar uma TStringlist:
var
   Colunas : TStringlist;

begin
   Colunas := TStringlist.Create;
   Colunas.Text := StringReplace('00:46:30@21/08/2014@Carlos dos Santos@São Paulo',
      '@',Char(13)+Char(10),[rfReplaceAll]);

A TStringlist usa internamente a sequência CR LF para separar os ítens, por isso o código acima transforma uma linha longa em vários ítens separados, ao trocar a @ pela sequência CR LF
Edit: Como bem lembrado pelo Edgar Muniz Berlinck, a TStringList tem uma propriedade para quebrar a string por outros delimitadores, ficando desta forma:
var
   Colunas : TStringlist;

begin
   Colunas := TStringlist.Create;
   Colunas.Delimiter := '@';
   Colunas.DelimitedText := Linhas[i];

1. gambiarra
Comment: obrigado pela resposta. Não entendi uma coisa, como eu vou usar isso ? tipo eu queria usar da seguinte forma $coluna1, $coluna2, para cada texto antes do @.
Comment: obrigado. Lembrando que eu tenho um arquivo chamado cliente.txt e dentro dele várias linhas dessa. Se puder me ajudar com isso também eu agradeço, ele deve percorrer todo esse arquivo.
Comment: @user7605 para ler o arquivo linha a linha eu acho que é melhor fazer uma pergunta separada.
Comment: posso testar aqui já ?
Comment: deu certinho manualmente. Agora preciso fazer através da leitura de um arquivo txt, devo fazer outra pergunta ?
Comment: @user7605 eu acho melhor, só pra não misturar os dois assuntos. Assim essa sua pergunta fica pra quem no futuro precisar do explode pra outras coisas.
Comment: Estou fazendo @Bacco, muito obrigado!

Explode em Delphi


keypress event not working in jQuery

Question: I have a text box in my web-page. I want to prevent user from entering space without entering any character. I have this now.
    $('#DivisionName').bind('keypress', function(e) {
        if($('#DivisionName').text().length == 0){
            if (e.which == 32){//space bar
                e.preventDefault();
            }
        }
        else{
            alert("if not working");
        }
    });

This is my HTML
    <input maxLength=15 name="DivisionName" id="DivisionName" size=15>

When I run the code, it is allowing user to enter space without giving any character. Where am I going wrong?
Answer: text() is use when div, span value. In case text box always use val()
Try this
$('#DivisionName').bind('keypress', function(e) {
    if($('#DivisionName').val().length == 0){
        if (e.which == 32){//space bar
            e.preventDefault();
        }
    }
    else{
        alert("if not working");
    }
});

You are not defining input type, so add type="text"
  <input type="text" maxLength=15 name="DivisionName" id="DivisionName" size=15>

Comment: It would be nice, if you can explain, what you have changed (from `text()` to `val`).
Comment: for getting values from form field use : val(); text() using for geting values from div tags etc as text. html() for as html
Answer: try it like this :
$("#DivisionName").keypress(function() {
console.log("keypress called.");
});

Answer: You have to enslose your code into
$(function() {
// CODE
}

It works - check here: http://jsfiddle.net/Dufvg/
And yes ... Replace .text() with .val()
Answer: Working Sample
HTML
<input type="text" id="DivisionName" />

Javascript
window.onload = function () {
    var inputEl = document.getElementById("DivisionName");
    inputEl.addEventListener("keydown", function (e) {
        if (inputEl.value.length == 0) {
            if (e.keyCode == 32) {
                e.preventDefault();
            }
        }
    });
}

Answer: Try this,
 <input type="text" maxLength=15 name="DivisionName" id="DivisionName" size=15>

$("#DivisionName").keypress(function(event) {
if($('#DivisionName').val().length == 0){
            if (e.which == 32){//space bar
                e.preventDefault();
            }
        }
        else{
            alert("if not working");
        }

});

keypress event not working in jQuery


how to change max upload size of media file

Question: I am using media module to add files to server and have given same access to others. Now I want to keep the upload size limit to 1 MB. Please let me know if any option to change this.
Answer: What have you tried, what are your limitations? You should be able to change your php.ini if you have access per this.
Answer: From your admin menu follow path as
 Structure >> Content types
You will see list of content types, click on manage fields for the one you have your media field to limit download size. Now you will see list of all your fields, click on edit link for the field you want to edit download size. Scroll down to find Maximum upload size textfield and set its value as 1 MB. By default it is set to a value allowed by your php.ini
Comment: Arpitr, this option is available only if the field type is image or file but not for media. I am using media file selector. See the 2nd screenshot uploaded by me.


How do I schedule a PHP function every 2 month?

Question: I need, every 2 months, to execute some rule component programmatically, but I don't know how to do this.
If I use hook_cron(), I don't know how to check 2 months are passed from the last time it was executed.
I can check 'the 10th day of the month' + 'month number is even'.
If cron tasks run twice a day, I cannot send 2 identical emails to users.
How can I achieve this?
Comment: You'll need to write some logic to check the current date/time, against a value you store the last time your cron job ran. That logic isn't Drupal-specific (just basic PHP) so we can't help you with it here; but you'll probably want to use variable_get/variable_set to store/retrieve your timestamp
Comment: Or alternatively run a system cron job (eg 0 0 1 */2 *) possibly calling a php cli script (provided you have shell access).
Answer: You can easly do this without having access to crontab/shell, by using following code in your cron_hook:
// check if current day is 10th and month is an even number
if (date('d')==10 && date('m') % 2 == 0) {
    // get todays-date (format: yyyymmdd)
    $today = date('Ymd');
    // get info about last run
    $last_run = variable_get('my_last_run', 0);
    // check last run was not today
    if ($last_run!=$today) {
        // set last run to today
        variable_set('my_last_run', $today);

        /* Place your code here */

    }
}

For more info on the modulo-operator (the % ) check:
http://www.php.net/manual/en/internals2.opcodes.mod.php
Comment: Using this method is useful install Elysia Cron
Comment: Why install a module if you can achieve this with a simple php function?
Comment: This is not work !!!
Comment: @shyghar , do u have process that execute every second and check your condtions?!!!!!!!!!!! , This is not correct way ,if you think it work in php , I tell you are mistakes, because php not run any function any second to check your condition available,if you put it in default drupal raw, it run when only cron run .by the way this is completely mistake method !!!!
Comment: Nope.. I inserted this code in a hook_cron() so this code will be executed only with mt drupal cron [once a day]..
Answer: Rules has a submodule called rules_scheduler made for that purpose.
Answer: The best way is use crontab ,create a php file as example mycorn.php trigger your rule in it and  create a crontab to run your php file every 2 month.
Just one note, please set permission  only owner can execute it.
Below  links help you , how to set cron.
http://www.adminschoice.com/crontab-quick-reference/
http://www.thegeekstuff.com/2009/06/15-practical-crontab-examples/


After ESXi update - Assignment Host to VM is lost

Question: I have a serious VMWare problem, situation as follows:

one standalone host with internal HDDs. One pair of HDDs in Raid 1 are used for ESXi. 4 HDDs in Raid 10 are used as datastore for VMs.
VirtualCenter is also a VM and on the internal storage.
a NFS share is also used, some machines are on the share

I updated the vSphere Infrastructure from version 4.1 to version 5. vCenter update and client updates went fine.
Today I updated the host and thats how the trouble began. I saw all partitions in the installation process and installed ESXi 5 on the partition where ESXi 4 was installed. After that I have a fresh installed ESXi 5 without configuration. If I connect to it with the vSphere client I can't see the VMs who were under this hosts management. I can see the internal datastore and I can browse it but i can't manage or start the machines, same goes for the NFS share (inventory under "Virtual Machines" is empty).
How can I bring back the assignment "Host to VM" so that the machines on the internal storage are managed by this host? So the vCenter is also a virtual machine and I am unable to start it because it also is on the internal HDDs. I couldn't use the Update Manager because we only have this standalone host, so I did an "interactive update" booting from the ESXi 5 CD. I thought there is some kind of migration and the host will know that it has to manage the VMs on the internal storage but it seems that did not happen...
I could kick myself in the butt for doing this, any help appreciated.
Answer: In the datastore browser, find each VM's <code>.vmx</code> file, right click, and there's a "Register" option to put the VM back in the inventory.
For future reference, yes, there is an upgrade option from the same installer CD that'll preserve all settings - it should prompt you to do so during the process.
Comment: Wooo, thanks, I'll try that tomorrow.Did not looked for further options in the datastore browser. I read about the upgrade option in the "Upgrade Guide" but it was not there. I could only choose between "install" or "abort" despite the fact the installer recognized all partitions and the like....mhh.
Comment: Is it "Register" or "Add to inventory"? Last I looked, the latter was true, but perhaps that changed in ESXi v5, which I haven't had a chance to play with yet. Either way, +1 for the correct answer.


Infinitely differentiable functions: how to prove that $e^\frac{1}{x^2-1}$ has derivative of any order?

Question: Let $f:\Bbb{R}\to\Bbb{R}$ be a function given by
$$f(x)=\begin{cases}
\exp\left(\frac{1}{x^2-1}\right) & \text{if }\vert x\vert\lt 1\\
0 & \text{if }\vert x\vert\geqslant 1
\end{cases}$$
I would like to prove that $f\in C^\infty$, that is, $f\in C^k$ for all $k\in \mathbb{N}$. I think that it can be done by induction on $k$. If $\vert x\vert\gt1$, the problem is trivial. On other points, the base case is the simplest and the only that I'm be able to do. Can someone help me?
Thanks.
Comment: Hint: we only really have to worry about a very small number of distinct points. Except at these points, show that every derivative of $f$ is a rational function multiplied by $f$ (using induction), and use that to verify differentiability by definition for those problematic points only.
Comment: @JonathanY. Is enough know that "every derivative of $f$ is a rational function multiplied by $f$" to verify differentiability at $-1$ and $1$? Or we need something more about the derivatives of $f$?
Comment: Further hint: exponentials and polynomials are in different growth classes.
Comment: I would do the derivative at $|x|=1$ manually (limit definition), then you can write $f'(x)$ again as a two-part function, and then do it again (manually).  What you cannot do is take the derivative for $|x|<1$ and take limits of that expression (because there are examples $x^2 \sin (1/x)$ where this gives you the wrong answer, when $f$ is not continuously differentiable)
Comment: @Pedro You should consider accepting one of the answers below if they satisfy you. I think Peter's answer is fabulous.
Comment: @anon, how does that help us? ie, why does the decay rate matter?
Comment: @TylerHilton You read the accepted answer below didn't you? It details how the derivatives pit polynomials against exponentials in the limit.
Comment: Could you show which part? I can't seem to figure it out.
Comment: @TylerHilton "This amounts to $P(x)e^{-x}\to0$ for any polynomial $P$." There is a **substitution** implicit in this. No typo at all. Try your hand at figuring it out.
Comment: @TylerHilton I don't know if this comment will help you, but in my final solution I used $f(x)=e^{1/x}$ and proved that, for all $x<0$, $$f^{(k)}(x)=q(x)\frac{e^{1/x}}{x^{2k}},$$ where $q$ is a polynomial. So we can use the L'Hospital rule to prove that $$\lim_{x\to 0^-} f^{(k)}(x)=0.$$
Comment: But your function is different in the question. I don't see how it is related
Comment: @TylerHilton In the question, we need to prove that $f(x)=e^{1/(x^2-1)}$ is $C^\infty$. We can see that $g(x)=x^2-1$ is $C^\infty$ and, by my last comment, we can show that $h(x)=e^{1/x}$ is $C^\infty$. Thus, $f(x)=(h\circ g)(x)=e^{1/(x^2-1)}$ is $C^\infty$.
Comment: Pedro, one last comment.Peter's answer deals with the function at x > 0 and 0 at x <= 0. How do they relate to your original question
Comment: @TylerHilton Notice that Peter defines a composite function and replaces $x$ by $1-x^2$. Thus, the conditions $x>0$ and $x\leq 0$  (that aren't the original conditions) implies $x^2<1$ and $x^2\geq 1$. But these inequalities are equivalent to $|x|<1$ and $|x|\geq1$ (that are the original conditions!). Does this comment answer your question?
Answer: Do it for $$f(x)=\begin{cases}\exp\left(-\frac 1 x\right)&x>0\\ 0&x\leq 0\end{cases}$$
Note that everywhere but in the origin, $f$ is infinitely differentiable. Moreover, for $x>0$
$$\eqalign{
   f'\left( x \right) &= \frac{1}{{{x^2}}}f\left( x \right)  \cr
   f''\left( x \right) &= \left( {\frac{1}{{{x^4}}} - \frac{2}{{{x^3}}}} \right)f\left( x \right)  \cr
   f'''\left( x \right)&= \left( {\frac{1}{{{x^6}}} - \frac{6}{{{x^5}}} + \frac{6}{{{x^4}}}} \right)f\left( x \right)\cr &\&c \cr} $$
You can thus prove inductively that for $x>0$, $$f^{(k)}(x)=P_{2k}(x^{-1})f(x)$$ where $P_{2k}$ is a polynomial of degree $2k$.
As $x\to 0^+$ this amounts to looking at $$\lim_{x\to +\infty}P(x)\exp(-x)=0$$ for any polynomial $P$.
So, for any $k$, the limit as $x\to 0$ of the derivative is $0$. Now we use a slightly underrated theorem

Theorem (Spivak) Suppose $f$ is continuous at $x=a$, that $f'(x)$ exists for all $x$ in a neighborhood of $a$. Suppose moreover that $$\lim_{x\to a}f'(x)$$ exists. Then $f'(a)$ exists and $$f'(a)=\lim_{x\to a}f'(x)$$

Proof By definition, $$f'(a)=\lim_{h\to 0 }\frac{f(a+h)-f(a)}h$$
Consider $h>0$. For $h$ sufficiently small, $f$ will be continuous over $[a,a+h]$, and differentiable over $(a,a+h)$. Thus, by Lagrange, we can find $a<\alpha_h<a+h$ such that $$\frac{f(a+h)-f(a)}h=f'(\alpha_h)$$
As $h\to 0^+$; $\alpha_h\to a$, and since the limit exists, $$f'(a)^+=\lim_{h\to 0^+}\frac{f(a+h)-f(a)}h=\lim_{h\to 0^+}f'(\alpha_h)=\lim_{x\to a}f'(x)$$
 The case $h<0$ is analogous. $\blacktriangle$.
The above lets you conclude that indeed $f^{(k)}(0)=0$ for all $k$, whence $f$ is $C^k$ for any $k$. Now, note your function is $$g(x)=f(1-x^2)$$
Comment: Is this a typo at "this amounts to looking at..." Did you mean to say $exp(-\frac{1}{x})$ in the expression?
Comment: @sunny Did you try taking the derivative of the equation for $k$ and seeing what it gives for $k+1$? Start at $k=1$, not $k=0$.
Comment: I would be very grateful if you could elaborate on how to inductively prove the formula $$f^{(k)}(x)=P_{2k}(x^{-1})f(x).$$ The base case is clear; then we simply have $f(x)=f(x)$, but how do you go about showing it holds for $k+1$?
Answer: Taking derivatives you happen to have $p(x)e^{\frac{1}{x^2 - 1}}$, where $p(x)$ is a rational polynomial function that blows up at $x = \pm 1$. What you need know is to prove the continuity of these derivatives. This, as anon suggests, turns out to be a very simple problem if you use the fact that the exponential function is way faster than every rational polynomial function. Thus, $\lim_{x \to \pm 1}p(x)e^{\frac{1}{x^2 - 1}} = 0$ $\forall p$. This means that even for $x = \pm 1$, the critical cases where the two branches need to match, every derivative of the function is continuous (in other words $\lim_{x \to \pm 1^-} f^k(x) = \lim_{x \to \pm 1^+} f^k(x)$, and this is exactly the continuity condition you were looking for).
I hope it helps :D
Comment: You will need to calculate the limit manually at $\pm 1$.


Is it possible to fit any distribution to something like this in R?

Question:
I am trying to fit a distribution to the data so I can use glm in order to predict more data. The problem is that with something like this all the tests of the distributions I know are rejected.

Edit:
Here is the ECDF that was requested.
Comment: You are dealing with some kind of mixture distribution, possibly zero-inflated distribution, but without knowing anything more about your data it is hard to say anything.
Comment: @Mr.Liu, are the hours only in whole numbers, or are there numbers like 2.5?
Comment: You have a very large N; since the underlying distribution probably doesn't match any ideal distribution exactly your large sample size will ensure that tests will reject that distribution. Even if a test rejects it you shouldn't rule it out as being a good model.
Comment: @Mr. Liu what type of data is it ? Is it time series?
Comment: No, is the number of hours to paint the damaged areas of a car, so I guess it's just a continuous variable
Comment: @Hugh so what distribution should I use for glm? normal? Or should I try all of them?
Comment: Yes, there are numbers like 2.5
Comment: @Mr.Liu I would try to model it as a bimodal normal distribution or another type of mixture distribution which you think looks right.
Answer: The spike at zero in your plot shows density at negative values. Presumably there are no negative times which also suggests that the 0-values are possibly all just exact zeros. It's important you make it explicit whether or not the data set contains exact 0-values! (In fact if the question hadn't already been answered ignoring this possibility I would have asked you to clarify before getting answers).
[A KDE is not suitable for a mixed distribution, because it leads us into erroneously using models that don't correspond to the actual data. For example, look at the suggested mixture density in the other answer -- that thought of a mixture of two continuous distributions was generated by your plot -- indeed I'd have likely thought along the same lines if I hadn't noticed these were times -- but it would lead to a prediction interval that included negative times, just as your plot suggests!  Can you show an ECDF? That would avoid suggesting times can be negative.]
If it's the case that the spike near zero is all-zero, you could use (say) zero-inflated GLMs; a gamma distribution for the non-zero portion might work. If you have suitable predictors for both the 0-time/non-zero-time process, you could also just model the 0 and non-zero values via logistic regression and then model the size of the non-zeros by a GLM or by taking logs and fitting a regression -- essentially a conditional model along the lines of a hurdle model.
Note also that in general you shouldn't judge what distributions may be reasonable in a glm or regression from the shape of the marginal distribution. Your model is for the conditional distribution; the marginal distribution may be quite different. For example, my suggestion for the times (gamma) was based more on thinking about the likely skewed shape of time - even conditionally on some predictors - for painting damage on cars rather than the shape in the picture.]

Edit: the ECDF added to the question shows that there is a substantial collection of exact 0's -- slightly more than 20% of the total. As mentioned earlier in my answer, zero-inflated or hurdle models would be one approach to this.
However, an additional issue may be the large gap to the low end of the continuous part of the distribution. It may be better to consider a shifted model that incorporates a minimum time (conditional on it being positive) of a little under an hour (this doesn't say that there aren't values in between 0 and just short of an hour -- only that there are so few of them that a model that assumed that times were either "effectively zero" or "at least n minutes" (where $n$ might be say 50 or thereabouts) might be a good approximation.
Comment: Why do you say that a KDE can't be used w/ a mixture distribution?
Comment: @gung I didn't say it can't. I said it's not suitable. When used on data with (say) exact 0's, it leads people to mistakenly model data as continuous when it isn't -- which in this case would lead us to produce prediction intervals which include *negative times* (as the other answer on this page actually suggests!). I think calling displays that lead people into predictions that include positive probability for negative times *unsuitable* is perfectly apt.
Comment: Hmmm, I guess I see what you mean. I wouldn't have a problem w/ using it myself, b/c I wouldn't be thrown off by that.
Comment: I usually try to avoid plots that might tend to mislead others -- where
"others" definitely includes "me in a couple of years time after I have forgotten the details". I might look at a KDE but, I wouldn't use it if I was keeping the plot. In this case the OP is showing a plot to other people (all of us) and failing (in the question) to actually mention that the variable is necessarily non-negative, so this issue of unsuitability definitely applies. A suitable display would avoid the potential for us to suggest models that produce prediction intervals that include negative values.
Comment: the times are not negative: Empirical CDF
Call: ecdf(hours)
 x[1:4470] =      0, 0.015779, 0.26458,  ..., 6.8447, 7.3137
Comment: @Mr.Liu I meant "please show an ecdf *plot* in your question". In R you'd do `plot(ecdf(x)))`. Your comment doesn't show whether the small values are nearly-all 0 or whether there's a substantial proportion of "a little larger than 0" values. An alternative would be to show `plot(density(x[x>0]))` .... I note that one of your times there appears to be 56.8 *seconds*. How was that measured to a fraction of a second? (And how does it take 56 seconds to paint anything?)
Comment: @Glen_b sorry, I didn't know how to upload an image in a comment, I have uploaded it here:
http://imgur.com/NNh6HsQ
Comment: @Mr.Liu Thanks, I have put it in your question so other answerers can see what's going on with the data. It is as I supposed it might be, mostly exact zeros.
Answer: First please review these post for hypothesis testing on large data. With the such a size, it is almost certain to reject any distribution.
Are large data sets inappropriate for hypothesis testing?
I would agree with Tim's comment that mixture of Gaussian can be used in this case. Here is an example.
gaussmix <- function(n,m1,m2,s1,s2,alpha) {

  I <- runif(n)<alpha
  rnorm(n,mean=ifelse(I,m1,m2),sd=ifelse(I,s1,s2))
}

s <- gaussmix(10000,0,2,0.05,0.5,0.2)

library(mixtools)
mixmdl = normalmixEM(s)
plot(mixmdl,which=2)
grid()


React hooks: How do I update state on a nested object with array with useState()?

Question: I have this form with questions and answers i get from the backend like this:
{
  "id": 0,
  "seq": 0,
  "ccid": "string",
  "topic": "string",
  "riskOutcome": "string",
  "condition": "string",
  "comment": "string",
  "visible": true,
  "created": "2021-10-14T14:12:48.911Z",
  "updated": "2021-10-14T14:12:48.911Z",
  "createdById": 0,
  "updatedById": 0,
  "parentContentTypeId": 0,
  "questionTypeId": 0,
  "subContentTypes": [
    {
      "id": 0,
      "seq": 0,
      "ccid": "string",
      "type": "string",
      "topic": "string",
      "riskOutcome": "string",
      "condition": "string",
      "comment": "string",
      "visible": true,
      "created": "2021-10-14T14:12:48.911Z",
      "updated": "2021-10-14T14:12:48.911Z",
      "createdById": 0,
      "updatedById": 0,
      "parentContentTypeId": 0,
      "subContentTypes": [
        null
      ],
      "textI18Ns": [
        {
          "id": 0,
          "text": "string",
          "languageCode": "string",
          "type": "string",
          "contentTypeId": 0
        }
      ]
    }
  ],
  "textI18Ns": [
    {
      "id": 0,
      "text": "string",
      "languageCode": "string",
      "type": "string",
      "contentTypeId": 0
    }
  ]
}

in the subContentTypes Array are the answers and within textI18Ns is the text for the answers that is shown.
I seperate the answers from the question with this
const [answerData, setAnswerData] = useState();

function getDatafromBackend = () =>{
            dispatch(getOneQuestion(data))
            .unwrap()
            .then((originalPromiseResult) => {
                var options = {};
                Object.entries(originalPromiseResult.subContentTypes).map(([key, value]) =>   {
                    options[key] = value;
                })
                console.log("answertdata ", options)

                setAnswerData(options);
               }
}

Now what I want to do is, to edit a Text from the Answer State.
My JSX looks like this:
let datalist = Object.entries(answerData).map(([key, value]) => {
return (<Paper elevation={3} style={{ margin: 10 }} key={"answerlist"+key}>
                    <Typography style={{ margin: 10}}>{"Daten zur Antwort: "}{answerData[key].ccid} </Typography>
                    {
                        Object.entries(answerData[key].textI18Ns).map(([index,value]) =>{
                            return (
                                <Paper elevation={3} style={{ margin: 10}} key={"questiontext"+index}>
                                    <TextField label={"Text ID"} disabled className="QuestionDataField" value={answerData[key].textI18Ns[index].id} fullWidth></TextField>

                                    <TextField label={"Content Typ ID"} disabled className="QuestionDataField" value={answerData[key].textI18Ns[index].contentTypeId} fullWidth></TextField>

                                    <TextField label={"Typ"} className="QuestionDataField" value={answerData[key].textI18Ns[index].type} fullWidth onChange={(event) => { updateAnswerTexts(event, 'type', key, index) }}></TextField>

                                    <TextField label={"Text"} multiline className="QuestionDataField" value={answerData[key].textI18Ns[index].text} fullWidth onChange={(event) => { updateAnswerTexts(event, 'text',key, index) }}></TextField>

                                    <TextField label={"Sprache"} className="QuestionDataField" value={answerData[key].textI18Ns[index].languageCode} fullWidth onChange={(event) => { updateAnswerTexts(event, 'languageCode', key, index) }}></TextField>

                                    <Divider/>
                                </Paper>
                            )
                        })
                    )}
setTableBody(datalist)

Here is the Problem. What i tried: Make a copy, change it and set the changed object
    const updateAnswerTexts = (event,prop,key, index) =>{
        let oldstate = answerData[index].textI18Ns[key];
        let updatedstate = {...oldstate, [prop]: event.target.value};
        let newstatetexts =  Object.assign({}, answerData);

        //Here is the Problem. Console says "Uncaught TypeError: 0 is read-only setSTate"
        newstatetexts[index].textI18Ns[key] = updatedstate;
        setAnswerData(newstatetexts)

        setAnswerData((prevState) => {
            prevState[index].textI18Ns[key] = updatedstate;
            return({
                ...prevState
            })
        })
    }
}

Another try: Here the Console says, [prop] is read only
    const updateAnswerTexts = (event,prop,key, index) =>{

         setAnswerData((prevState) => {
             prevState[index].textI18Ns[key][prop] = event.target.value;
             return({
                 ...prevState
             })
         })
    }

Another try: Here the Console says, [prop] is read only too
    const updateAnswerTexts = (event,prop,key, index) =>{
        let oldstate = answerData[index].textI18Ns[key];
        let updatedstate = {...oldstate, [prop]: event.target.value};
        setAnswerData((prevState) => {
            prevState[index].textI18Ns[key] = updatedstate;
            return({
                ...prevState
            })
        })
    }

Comment: It is not a great way to do so but you can force an update by toggling another boolean state or something.
Answer: This did it for me
    const updateAnswerTexts = (event,prop,key, index) =>{

        let allanswers = {...answerTextsData};

        let oneanwerobj = {...allanswers[key]};

        let answertexts = {...oneanwerobj[index]}

        answertexts[prop] = event.target.value;
        oneanwerobj[index] = answertexts;
        allanswers[key] = oneanwerobj

        setAnswerTextsData(allanswers);
    }

Answer: To achieve what you want you'd have to spread every single level of the object, eg.
{
  name: 'john'
  job: {
    name: "chief",
    address: {
      city: "London",
      street: "Baker street"
    }
  }
}

To modify street in useState:
setState(prevState => ({
   ...prevState,
   job: {
      ...prevState.job,
      address: {
         ...prevState.job.address,
         street: "New street"
      }
   }
}))

Sadly this is how it is, you should rather refactor youre state, use class component instead of functional, use some global store, or maybe some library for forms :)


Non-central t-distributions with different degrees of freedom

Question: I have two non-central t distributions with CDF given by $t_{n,a}$ and $t_{m,a}$ with $n>m$ degrees of freedom respectively and the same non-centrality parameter $a$.
The question is: for which values of $x$ the inverse CDF of the first is greater than the inverse CDF of the second?
I.e. for which values of $x$ is $t^{-1}_{n,a}(x)>t^{-1}_{m,a}(x)$ ?
Comment: If a numerical answer is enough, you can find it yourself inR
Comment: I know, but I'd like to have a theoretical answer, if it's possible.
Comment: @Xi'an the limit value for $x$ is that value for which the $t_{n,a}(x)=t_{m,a}(x)=0$? I.e. the answer is when $x<t_{n,a}(0)$?
Answer: Since the non-centrality parameter is irrelevant for this question, I take $a=0$.
Here is a picture of several cdfs of Student's $t$-distributions:
And an even better image from Wikipedia:

As the $t_n$ distribution has fatter tails than the $t_m$ distribution when $n<m$, hence the former is be less concentrated around its mean/mode/median zero than the latter. This means the cdf of $t_n$ will be larger than the cdf of $t_m$ for large enough negative values of $x$ and smaller for large enough positive values of $x$. As you can see on the picture, all cdf's cross at zero (the slope of the cdf at zero $F(0;n)$ is the value of the pdf at zero $f(0;n)$ which is increasing with $n$).
Comment: @xanz: your answer only mentioned the same non-centrality parameter, which is indeed irrelevant for the tail comparison. If you had different non-centrality parameters then the cdfs could cross more than once.
Comment: But in the case of a non-central t-distribution, the shift due to the non-centrality parameter does it change things?
Comment: The answer is right, I'm just answering my own previous comment: no, it doesn't. The CDF of two noncentral t-distributions evaluated in 0 is always equal to $\Phi(-a)$ if the noncentrality parameter $a$ is the same (check the CDF expression on wikipedia), regardless of the dofs. And if $n>m$ the tails of $m$ are fatter than the tails of $n$, thus if $x<\Phi(-a)$ then the requirement in the question is satisfied. Thank you!
Comment: Yeah, now I know. At first it wasn't clear to me that the noncentrality parameter is irrelevant for the number of crossings, but now I've figured it out. Thank you.


How to check a VPS virtualization

Question: How do I check whether my VPS is OpenVZ or XEN? (I ordered a while back and don't remember exactly which plan I ordered!).
OS: Linux running ubuntu.
thanks
JP
Comment: Post the output of `$ uname -a`.
Comment: Linux ......com 2.6.18-194.26.1.el5xen #1 SMP Tue Nov 9 13:35:30 EST 2010 x86_64 GNU/Linux. So looks like it is xen.
Answer: If you follow the examples of detection used by Puppet and Facter you can check the /proc filesystem for hints.
The existence of /proc/vz/veinfo would indicate you're running OpenVZ but the existence of /proc/vz/version will tell you whether it's openvzhn or openvzve.
Next you can look for either /proc/sys/xen, /sys/bus/xen or /proc/xen to see if you're running Xen but look for /proc/xen/capabilities to tell if it's a dom0 or domU.
Comment: @Rafael Check into the logic of the Facter virtual fact as it is able to determine the differences. I have an ESXi server and the VMs running Puppet are able to determine that they are vmware based.
Comment: If he's got a VPS through a host, I'd certainly hope it wasn't a dom0. :)
Comment: /proc/sys/xen is present, but /proc/vz/veinfo is not, so its Xen. /proc/xen/capabilities is empty.  Could you please tell what is dom0/domU and why is dom0 not good? :)
Comment: dom0 is the privileged instance... basically the host machine... domU is the unprivileged virtual machine.
Comment: How about checking vmware and others?
Comment: @JeremyBouse I just checked it out at http://git.io/xKacLA It looks for the video card name using lspci command, which contains vmware word in the adapter name :D thank you

How to check a VPS virtualization


R graphs, cannot paste the original R graph in a word document

Question: I have not been able to copy and then paste, or just insert an R generated graph in an MS world document. Once pasted in a word document, the graph loses its original format and design. The captions and titles change font size and the legends are dislocated.
Is there a way to import the R graph into a Word document without losing the original features which are visible in the R plotting window. I usually save my graphs as 'Metafile' because it is the only format that preserves quality of the graph but not the text i.e. annotations, legends and titles on the graph.
Any help is highly appreciated!
Comment: Is it possible that this question really belongs on [Super User SE](http://superuser.com/)? I think it may qualify under their [on topic criteria](computer software), as this does not concern programming directly but is about software and file formats.
Answer: You can hit "export" on the plots tab, save as an image (say .png), tick the "Maintain aspect ratio" box, and then up the width or height to get a very detailed plot saved as image. However, text size relative to the image will change, the same as if you zoom in to the plot and change the zoom window size. So you may want to identify what level of detail you want in your saved image (you can see how it changes in preview), and then adjust font size and legends accordingly. This way you can save an image exactly as you want it, and be sure that it will not change when you insert it into Word.


Para que serve a função addcslashes em php?

Question: Para que serve a função addcslashes? eu vi no manual do PHP mas não entendi.
Answer: De acordo com o manual:

Retorna uma string com barras invertidas antes dos caracteres que
  estão listados no parâmetro charlist.

Exemplo:
php > echo addcslashes("Ola! Meu nome é Homer. Tudo bem?", "!.?");
Ola\! Meu nome é Homer\. Tudo bem\?

Normalmente usa-se o caracter de escape () quando você deseja alterar o sentido original do caracter.
Por exemplo, se quiser imprimir o "\n". O caracter \ tem um sentido especial (escapar o caracter seguinte). No caso, ele transforma a sequencia em uma mudanca de linha. Caso seja executado:
echo "\n";

Sera impressa uma mudança de linha. Caso você desejar imprimir (literalmente) \n, você precisa usar \n. Será interpretado da seguinte forma:
: Olha, o proximo caracter não tem o sentido usual.
: Meu sentido usual é escapar o proximo caracter, mas o caracter anterior alterou meu sentido. Entao serei interpretado como apenas uma barra.
n: sou apenas um n.
E, como resultado, será impresso "\n".
Voltando ao addcslashes
Voce especifica a string e quais caracteres deseja inserir a \ na frente, de modo a alterar seu sentido usual. Normalmente é usado para escapar strings para impressao ou processamento.
Comment: Entendi, mas qual é a lógica de se usar essa função? ou seja em quais as ocasiões ela é utilizada, sou estudante em PHP e vejo muito nos códigos em PHP que estou estudando.


Confidence intervals in a mixed model

Question: Consider the following mixed model: $$(y_{ijk} \mid \mu_{ij}) \sim_{\text{i.i.d}} {\cal N}(\mu_{ij}, \sigma^2), \quad k=1, \ldots K $$ $$ \begin{pmatrix} \mu_{i1} \\ \vdots \\ \mu_{iJ} \end{pmatrix} \sim_{\text{i.i.d}} {\cal N}\left(\begin{pmatrix} \mu_{1} \\ \vdots \\ \mu_{J} \end{pmatrix}, \Sigma\right), \quad i=1, \ldots, I $$ with unknown fixed parameters $\sigma^2$, $\Sigma$, $\mu_i$.
Moreover I assume $\Sigma$ has a "compound symmetry" structure. Therefore the above model is marginally equivalent to the 2-way ANOVA model with mixed effects $$y_{ijk}=\mu + \alpha_i + \beta_j + (\alpha\beta)_{ij} + \epsilon_{ijk}$$ with $\beta_j$ and $(\alpha\beta)_{ij}$ the random effects.
I want some confidence intervals on the fixed parameters $\alpha_i$. I'm using PROC MIXED in SAS but that does not work for some datasets (that does not work with lme/lmer in R too). Do you know some confidence intervals based on least-squares instead of likelihood ? I am interested in the formulas giving these intervals and/or the way to calculate them with a software.
Answer: I have just found an answer for the ANOVA model in the book "Design and Analysis of Gauge R&R Studies" (Richard K. Burdick, Connie M. Borror, Douglas C. Montgomery).
Answer: Very amazing !!!! The confidence interval is exactly the same as the one obtained with the paired t-test on the means :
<code>> library(mvtnorm)
>
> ### SIMULATES DATA ###
> I <- 2 # positions
> J <- 6 # tubes
> K <- 5 # repeats
> n <- I*J*K
> tube <- rep(1:J, each=I)
> position <- rep(LETTERS[1:I], times=J)
> Mu_i <- 3*(1:I)
> tube <- rep(tube, each=K)
> position <- rep(position, each=K)
> sigmaw <- 2
> Mu_ij <- c(t(rmvnorm(J, mean=Mu_i, sigma=diag(I)+2)) )
> Mu_ij <- rep(Mu_ij, each=K)
> dat <- data.frame(tube, position)
> dat$y <- rnorm(n, Mu_ij, sigmaw)
> dat$tube <- factor(dat$tube)
> an <- aov(y~position*tube, data=dat)
> S2 <- summary(an)[[1]]["position:tube","Mean Sq"]
> ag <- aggregate(y~position, data=dat, FUN=mean)
> estimate <- ag$y[2]-ag$y[1]
>
> ### 95% CONFIDENCE INTERVAL BASED ON THE MIXED ANOVA MODEL ###
> ( low.bound <- estimate - sqrt(2*S2/J/K*qf(0.95,1,(J-1)*(I-1))) )
[1] -0.317764
> ( upp.bound <- estimate + sqrt(2*S2/J/K*qf(0.95,1,(J-1)*(I-1))) )
[1] 4.734348
>
> ### 95% CONFIDENCE INTERVAL BASED ON THE PAIRED T-TEST ###
> ag <- aggregate(y~position+tube, data=dat, FUN=mean)
> posA <- subset(ag, subset= position=="A")$y
> posB <- subset(ag, subset= position=="B")$y
> t.test(x=posB, y=posA, paired=TRUE)$conf.int
[1] -0.317764  4.734348
attr(,"conf.level")
[1] 0.95
</code>

Confidence intervals in a mixed model