O que é boilerplate code?

Question: Tenho percebido o uso frequente do termo em alguns fóruns e fiquei me perguntando qual o seu significado e de onde surgiu tal expressão.
Answer: "Boilerplate" é um termo muito utilizado para se referir a trechos de documentos (por exemplo jurídicos) que são sempre os mesmos, de documento pra documento, de modo que não acrescentam muita coisa mas mesmo assim não podem ser omitidos. Você já deve ter visto em licenças de software, por exemplo, a parte que diz que "NÃO HÁ NENHUMA GARANTIA PARA O PROGRAMA, NO LIMITE PERMITIDO PELA LEI APLICÁVEL. EXCETO QUANDO..." etc. Todo mundo já conhece, ninguém nem lê porque já sabe de cor o que está escrito, mas o documento não estaria completo sem ela.
Quando se aplica esse termo ao código, pode ter um sentido "inocente" (como mostrado na resposta do @AndersonBS, se referindo a um padrão pronto, um esqueleto, a partir do qual você faz o resto), mas também um sentido pejorativo: é aquele código que você precisa escrever toda vez - porque a sintaxe da linguagem exige - mas que também não acrescenta muita coisa, já que é igual em todo programa. Em geral, quando se diz que uma linguagem ou plataforma tem muito boilerplate se está dizendo que ela é pouco expressiva ("fala muito pra dizer pouco").
Como exemplo, veja o programa "hello world" em Python:
print("Olá, Mundo!")

O mesmo programa em Java:
public class OlaMundo {
    public static void main(String[] args) {
        System.out.println("Olá, Mundo!");
    }
}

E o mesmo programa em C#:
using System;

namespace Teste
{
    class OlaMundo
    {
        static void Main()
        {
            Console.WriteLine("Olá, Mundo!");
        }
    }
}

Fonte: Wikipedia
Em todos os três casos há apenas uma "linha útil": aquela que imprime a string na saída. Todo o resto é boilerplate. Código que você vai ter que escrever de novo e de novo e de novo toda vez que for criar um programa. Mesmo que seu IDE (ambiente de desenvolvimento) crie o esqueleto pra você, ainda é um trecho inútil que está lá ocupando espaço, tomando tempo da compilação e distraindo sua atenção do que o código faz de útil.
Nota: a presença de algum boilerplate não torna a linguagem automaticamente ruim; ela só é um indício de que provavelmente essa linguagem te obriga a escrever mais do que o necessário para executar a mesma função, comparado a outras com menos boilerplate.
Comment: Muito boa explicação!! Obrigado
Comment: É quase uma sacanagem dar tanto espaço assim em C# para parecer que ele gera código enorme :D E hoje C# permite fazer o mesmo com apenas uma linha, e curta.
Answer: O termo deriva da fabricação de aço, onde boilerplate é o aço laminado em grandes placas para uso em caldeiras a vapor.
Em tecnologia da informação, "boilerplate code" é um trecho de código que pode ser reutilizado várias vezes sem nenhuma ou com poucas alteração em sua consistência. Presume-se que esse trecho de código já foi testado inúmeras vezes e é tão consistente quanto o aço.
Answer: Em inglês a expressão boilerplate significa um template, ou seja, uma forma padrão de se escrever algo que pode ser copiado, usado, principalmente, em contratos e documentos legais.
Quem lida com aquecedores e caldeiras (boilers) sabe que esses equipamento possuem riscos operacionais e limites bem estritos de funcionamento. Também há legislação específica para seu uso e, uma das regras mais importantes e que deve ser fixada no equipamento uma placa (plate) contendo dados importantes de seu funcionamento, como temperatura e pressão máxima de operação, tipo de combustível usado, volume, etc... Essa placa tem que conter um  mínimo de informação e estar escrita de uma determinada forma. Mas quase ninguém lê essas informações.

O que é boilerplate code?


When is it okay to label data yourself? (And semi-supervised learning)

Question: i'm pretty new to machine learning so i think this might be a realy basic question.
Let's imagine the following scenario: I want to classify projects as either active or inactive. Projects can be defined by number of contributors etc.
The goal is to identify projects with a high risk of abandonment by their owner / contributors. A project can be labeled as "inactive" by its owner.
I made the following assumption: if someone labeled his project as inactive, its very unlikely that its active. On the other hand, not having the label does not imply its active, because not everyone goes back to label a project inactive after loosing interest. For the sake of this question: lets say that 10% of the data is labaled as inactive, but in reality, 30% of projects are inactive.
At first i thought: ok, i'll just go through all the data and check for the active ones if they are inactive in reality. But, if i do that, why would i need a model anyways? I would base this labelling on something like "no activity in one year, 0 contributors etc.).
And now i am confused: is it right that in this scenario, its not okay to label the data myself? Is it only okay to let humans label data on something like images? Is there any scientific literature that i could quote on this topic?
Additional question: would semi-supervised learning be a use case for this?
My idea would be to use a supervised method to train a classifier on the 10% labelled data and then use the unlabeled data aswell (like here: http://matpalm.com/semi_supervised_naive_bayes/does_it_do_any_better.html).
But for testing, can i only use projects that are actually labeled (from the 10%)? So, lets say i use 50% of the projects that are labeled as inactive for training the classifier and 50% for testing. I could validate my model with the test data. Now i would use semi-supervised learning in my modell aswell and compare it again. Is it possible that this would get me better results?
Answer: If you are using some simple rules to determine if a project is active or inactive ("no activity in one year, 0 contributors etc"), you don't really need to use machine learning to predict the outcome of those rules. You can just apply the rules directly to the new data points.
What machine learning could be used for is to predict beforehand which projects will be labeled as inactive with your rule system. In business churn models are used to predict which customers might become inactive in the future. A simple churn model could output the probability that a project will have any activity within the next one month.
This approach is not able to use the data on the projects that have been labeled as inactive by the users. It could still be used as one of the features, but I would avoid using it as the only training data as it does not sound very reliable source of information.
Answer: I think most of your questions are answered when you more rigorously specify your problem. So let's back up and define the basics...
First, we need to define our target. It sounds like it's inactive, where inactive might be defined as "marked 'inactive' by the project owner", or "no activity in a year", or "no followers", or "0 contributors", or some combination of the above or something else entirely. Let's assume for now that inactive means that activity has been 0 for 12 months. (activity may itself be an aggregation of underlying variables, of course, but let's treat it as a single time series variable.)
Once we've firmed this up, you're correct that you don't need a model if you have the information you need about a project to see if it meets this definition or not. So if you decide that inactive means "no activity in the last year" and you have a projects activities for the last 12 months sitting in front of you, you don't need a model. (You might still want software to calculate this across many projects for you, but you don't need a model.)
So now you need to define a decision and a decision point: the purpose for a model.
At some point in time, you will have some information about a project, but not your target information (activity and hence inactive). Your model cannot use any information beyond what you expect to have at the decision point to make its prediction. In supervised training, you will have this information and the target, of course, but not at predict/score (i.e. decision) time.
So what is the decision point and what is the decision? Do you want to say, "For a project that is at least 12 months old, given the number of commits in the first 3 months, the current number of contributors, the current number of followers, and the number of forks over the last year, what is the probability that the project will be inactive a year from now?" You don't know what the activity will be for the next year so you need a model to predict. (Let's assume that activity is more than forks.)
Or you could say, "For a project that is at least 12 months old, given the number of commits in the first 3 months, the current number of contributors, and the current number of followers -- but not knowing anything about the activity for the last 12 months --  what is the probability that the project is actually currently inactive?" In this case, you're not talking about the future, so you could conceivably have activity information for the last 12 months but a model is only needed if you in general will not have that information at decision time. (Maybe activity stats are only updated at the end of the year, or maybe projects can hide activity but not the other variables.)
Say you adopt the "no activity for the previous 12 months" definition of inactive and the first statement of your problem -- the one in the future -- as your goal. If you have, say, five years of commits, contributors, followers, forks, and overall activity (your target) you can easily write a program that chunks this information up per week and creates your target based on the previous 12 months.
It will be trivial to calculate your target for the first four years, though you won't be able to calculate it for the last year. (Even hand-labeling can't do this, based on your definition of inactive. A human could guess that a project that's had no _activity` in 11 months will almost surely not have any for the next month, but that is itself a prediction.)
CAN you hand-label data? Yes, if you have the information and expertise to do so. Can you use semi-supervised learning? Yes, but it's tricky and may make things worse. Do you have to address that in your current problem? It doesn't look like it.


Limite de geração de retorno sql

Question: Tenho esse código, que gera numeros de periodos, porém eu levo esse retorno para o excel, eu consigo definir a quantidade de retornos? Eu só poderia trazer 5 cinco, retornos, consigo limitar?
DECLARE @serie INT, @ordem INT, @Periodo INT DECLARE @tbResultado TABLE ( id INT IDENTITY(1,1) ,IdCliente INT, Serie INT, Ordem INT, idPerido INT)

SET @serie = 9059 SET @ordem = 05288 SET @Periodo = 0

WHILE (@Periodo <= 670) BEGIN   IF (@serie < (SELECT nmSerieIni FROM tbSysPeriodo where id = @Periodo))
            WHILE (@serie NOT BETWEEN (SELECT TOP 1 nmSerieIni FROM tbSysPeriodo where id = @Periodo) AND (SELECT TOP 1 nmSerieFim FROM tbSysPeriodo where id = @Periodo))      BEGIN
                SET @serie = @serie + (select ABS(nmSerieIni - nmSerieFim)+1 from tbSysPeriodo where id = @Periodo)

        END

    IF (@serie > (SELECT TOP 1 nmSerieFim FROM tbSysPeriodo where id = @Periodo))
            WHILE (@serie NOT BETWEEN (SELECT TOP 1 nmSerieIni FROM tbSysPeriodo where id = @Periodo) AND (SELECT TOP 1 nmSerieFim FROM tbSysPeriodo where id = @Periodo))      BEGIN
                SET @serie = @serie - (select ABS(nmSerieIni - nmSerieFim)+1 from tbSysPeriodo where id = @Periodo)

        END
            INSERT INTO @tbResultado    SELECT TOP 10       S.idCliente,        S.nmSerie,          S.nmOrdem,      P.idPeriodo     FROM tbSorte S      JOIN tbSortePeriodo P       ON S.id = P.idSorte     WHERE S.nmSerie = @serie AND S.nmOrdem NOT IN (SELECT ORDEM FROM @tbResultado) AND P.idPeriodo = @Periodo   ORDER BY nmSerie DESC, ABS(nmOrdem - @ordem)

WHILE (@serie NOT BETWEEN (SELECT TOP 1 nmSerieIni FROM tbSysPeriodo where id = @Periodo) AND (SELECT TOP 1 nmSerieFim FROM tbSysPeriodo where id = @Periodo)) BEGIN

    SET @serie = ABS(@serie-(SELECT TOP 1  nmSerie FROM tbSorte S JOIN tbSortePeriodo P ON S.id = P.idSorte WHERE P.idPeriodo = @Periodo AND S.nmSerie NOT IN (SELECT Serie FROM @tbResultado)))

END

INSERT INTO @tbResultado    SELECT TOP 10       S.idCliente,        S.nmSerie,          S.nmOrdem,      P.idPeriodo     FROM tbSorte S      JOIN tbSortePeriodo P       ON S.id = P.idSorte     WHERE S.nmOrdem NOT IN (SELECT ORDEM FROM @tbResultado) AND P.idPeriodo = @Periodo  ORDER BY ABS(nmSerie - @serie),nmSerie DESC,ABS(nmOrdem - @ordem)

SET @Periodo = @Periodo + 1

END          SELECT * FROM @tbResultado

Answer: Boa tarde!
Ao invés de utilizar SELECT * FROM @tbResultado, porque não utiliza SELECT TOP 5 * FROM @tbResultado?
Dessa maneira, ao invés de buscar todos os registros da tabela @tbResultado, irá trazer apenas a quantidade determinada no TOP.
Abs!
Comment: Fala ai, Lucão. Essas resposta está correta mesmo ?
Comment: pq não coloca tudo numa única resposta?
Answer: Por favor, tente então o comando abaixo, alterei somente para na inserção limitar a 5 registros, ao invés de 10 que está.
DECLARE @serie INT,
        @ordem INT,
        @Periodo INT
DECLARE @tbResultado TABLE ( id INT IDENTITY(1,1) ,
                             IdCliente INT,
                             Serie INT,
                             Ordem INT,
                             idPerido INT)

SET @serie = 9059
SET @ordem = 05288
SET @Periodo = 0

WHILE (@Periodo <= 670) BEGIN   IF (@serie < (SELECT nmSerieIni FROM tbSysPeriodo where id = @Periodo))
    WHILE (@serie NOT BETWEEN (SELECT TOP 1 nmSerieIni FROM tbSysPeriodo where id = @Periodo) AND (SELECT TOP 1 nmSerieFim FROM tbSysPeriodo where id = @Periodo))
        BEGIN
            SET @serie = @serie + (select ABS(nmSerieIni - nmSerieFim)+1 from tbSysPeriodo where id = @Periodo)
        END

    IF (@serie > (SELECT TOP 1 nmSerieFim FROM tbSysPeriodo where id = @Periodo))
            WHILE (@serie NOT BETWEEN (SELECT TOP 1 nmSerieIni FROM tbSysPeriodo where id = @Periodo) AND (SELECT TOP 1 nmSerieFim FROM tbSysPeriodo where id = @Periodo))
                BEGIN
                    SET @serie = @serie - (select ABS(nmSerieIni - nmSerieFim)+1 from tbSysPeriodo where id = @Periodo)
                END
            INSERT INTO @tbResultado    SELECT TOP 5 S.idCliente,
                                                     S.nmSerie,
                                                     S.nmOrdem,
                                                     P.idPeriodo
                                        FROM tbSorte S
                                        JOIN tbSortePeriodo P
                                        ON S.id = P.idSorte
                                        WHERE S.nmSerie = @serie
                                        AND S.nmOrdem NOT IN (SELECT ORDEM
                                                              FROM @tbResultado)
                                        AND P.idPeriodo = @Periodo
                                        ORDER BY nmSerie DESC,
                                        ABS(nmOrdem - @ordem)

WHILE (@serie NOT BETWEEN (SELECT TOP 1 nmSerieIni FROM tbSysPeriodo where id = @Periodo) AND (SELECT TOP 1 nmSerieFim FROM tbSysPeriodo where id = @Periodo))
    BEGIN
        SET @serie = ABS(@serie-(SELECT TOP 1  nmSerie FROM tbSorte S JOIN tbSortePeriodo P ON S.id = P.idSorte WHERE P.idPeriodo = @Periodo AND S.nmSerie NOT IN (SELECT Serie FROM @tbResultado)))
    END

    INSERT INTO @tbResultado    SELECT TOP 5 S.idCliente,
                                             S.nmSerie,
                                             S.nmOrdem,
                                             P.idPeriodo
                                FROM tbSorte S
                                JOIN tbSortePeriodo P
                                ON S.id = P.idSorte
                                WHERE S.nmOrdem NOT IN (SELECT ORDEM
                                                        FROM @tbResultado)
                                AND P.idPeriodo = @Periodo
                                ORDER BY ABS(nmSerie - @serie),
                                         nmSerie DESC,
                                         ABS(nmOrdem - @ordem)

SET @Periodo = @Periodo + 1

END

SELECT * FROM @tbResultado

Answer: Boa tarde, mas no caso, não ajudaria, por conta que se você ver no WHILE, vai do zero ao 670, existem intervalos.

Limite de geração de retorno sql


versatile insertion method for PDO class

Question: this is my insertion method in PDO, it is working 100%. this 'insert' method accepts table, column and value but i want to make it versatile. (i want to insert values with or without the column names)
<code>public function insert($table, $pair = array()){
    try{
        $Sql = "INSERT INTO $table ( ";
        $Sql .= implode(", ", array_keys($pair));
        $Sql .= " )";
        $Sql .= " VALUES (";
        $Sql .= implode(", ", array_fill("0", count($pair), " ?"));
        $Sql .= " )";
        $array = array_combine(array_keys(array_fill("1", count($pair), ":")), $pair);
        $ready = $this->conn->prepare($Sql);
        foreach($array as $key => $value)
        {
            $ready->bindValue($key, $value, PDO::PARAM_STR);
        }
        $ready->execute();
    }
    catch(Exception $e){
        $this->trace .= " • ". $e->getMessage();
    }
}

$new = new community();
echo $new->insert("table", array("Col1" => "value1", "col1" => "value1"));
</code>
Comment: What's the use for registering new account for the every question? Just curious.
Answer: There are two problems with your function.

It is vulnerable to SQL injection.
It is not flexible. Following the pattern, you are going to have a thousand functions of this kind, which will make your code into mess. Yet it would be always limited subset against real SQL.

What you really need is a function that can create a SET statement out of array and a list of allowed fields.
As a further improvement you may devise a custom placeholder for this statement.
Having these two things you can work out a single general purpose function to run all the DML queries like this:
<code>$db->query("INSERT INTO t SET %u", array("Col1" => "value1", "col1" => "value1"));
</code>
It will cost you 3 additional words (insert, into and set), but it will be

readable. Everyone can understand SQL. While to read your function one need a documentation
flexible. It can support any queries and modifiers, not only one single-formed insert.

Every query you wish you can run with this single function:
<code>$data = array("Col1" => "value1", "col1" => "value1");
$db->query("INSERT IGNORE INTO t SET %u", $data);
$db->query("REPLACE INTO t SET %u", $data);
$db->query("DELETE FROM t WHERE id = ?", $id);
// and so on
</code>
No dedicated functions actually needed.
Also, you have to always verify a set of fields against a hardcoded white list, to let a user insert only fields they are allowed to. Do not let a user to alter privileges, messages count and so on.
But even without custom placeholder it would require no set of SQL-mapped functions but just a function to create a SET and a general purpose query execution function:
<code>$allowed = array("name","surname","email"); // allowed fields
$sql = "INSERT INTO users SET ".pdoSet($fields,$values);
$stm = $dbh->query($sql ,$values);
</code>
Comment: i have edited my code above, do you think it is secure now.. i also used some validation by depicting in dot marks;


IMCE browse server image upload button not displaying on ckeditor toolbar

Question: I just installed and enabled IMCE for drupal 7 and assigned the IMCE icon in the full html input format page, but the icon is not appearing in the ckeditor toolbar. I even set the permissions for the IMCE.
Answer: Make sure you scroll down that same page and look for file browser settings and make sure its set to IMCE. Mine was on none and after switching that, the file browser upload button showed up in the image dialog popup.
Comment: Just to add: CKEditor comes in as an iframe, and browsers aggressively cache iframe content iirc, so make sure to empty your browser cache everytime you test.
Answer: I don't have it fully functioning yet, but I am getting closer...
EDITOR APPEARANCE

Make sure you Load the sample toolbar more accurate to what you will use when you drag the button up there.
Plugins = check the box "Plugin for inserting files from IMCE without image dialog"

Once I added the plugins, it started working.
Now it isn't complete, because I get an error when I click on (an existing image's) "Image Properties" and "Browse Server" that says the requested page (ckfinder.thml?....) could not be found. So I am still working on it but at least it is partially working.
Answer: IIRC, there's no "IMCE" button on CKEditor. The "Browse Server" button however should now appear when you press "Insert/Edit Image" or "Insert/Edit Link" buttons, if you enabled IMCE in WYSWIWYG settings.


How does println! interact with multiple levels of indirection?

Question: I have the following program:
fn main() {
    let x = 0;

    println!("Example 1: {:p}", &x);
    println!("Example 1: {:p}", &x);

    println!("Example 2: {:p}", &&x);
    println!("Example 2: {:p}", &&x);
}

Here is an example output:
Example 1: 0x7ffcb4e72144
Example 1: 0x7ffcb4e72144
Example 2: 0x7ffcb4e72238
Example 2: 0x7ffcb4e72290

The outputs for "Example 1" are consistently the same, while those for "Example 2" are consistently different.
I've read Does println! borrow or own the variable?, and what I understood from the given answer is that println! takes a reference silently. In other words, this sounds like println! adds an extra level of indirection.
I had expected the outputs for "Example 1" to be different as well. Seeing that println! silently takes another level of indirection, "Example 1" is actually working with &&x, and "Example 2" is working with &&&x. This seems to agree with the answer I linked, specifically: "If you write println!("{}", &x), you are then dealing with two levels of references".
I thought that the value &&x holds would be printed for "Example 1", while the value &&&x holds would be printed for "Example 2". Both &&x and &&&x hold a temporary &x, so I thought "Example 1" would have different addresses printed as well.
Where am I wrong? Why doesn't "Example 1" have different addresses printed?
Comment: Does this answer your question? [Why does printing a pointer print the same thing as printing the dereferenced pointer?](https://stackoverflow.com/questions/27852613/why-does-printing-a-pointer-print-the-same-thing-as-printing-the-dereferenced-po)
Comment: why address of x should change ? `&&x` is the address of the address of `x`, as you create this variable temporary, two literals `&&x` value equality is unspecified. println only borrow for non copy type, all reference can be copied so they are not borrow by println.
Comment: @SCappella I don't think so, because answer for that question involves behavior of `Display` which applies to `{}` and not `{:p}`.
Comment: @Stargateur My understanding is that `println!` borrows regardless of whether it's a non-copy type or not. For example, answer of the question I linked has at the bottom: `If you write println!("{}", &x), you are then dealing with two levels of references`. Sounds like extra level of indirection is applied even to references of `x`.
Comment: @MarioIshac well, anyway you ask println to print the value of &x, so even if the macro take a &&x, it will show what you ask so &x, doesn't really matter if there is two level of indirection (and I'm pretty sure final asm would get rid of it). What you need to understand is that `&x` is very different of `&&x`.
Comment: @Stargateur yup sounds like that's what's going on, but I'm wondering how? if macro receives `&&x` then how does it get treated as `&x`?
Comment: as documented, `println!("{:p}", &x)` will print the address of `x`. what it does under the hood is irrelevant, even if it used 5 levels of indirection, it will still print the address of `x` because thats what its supposed to do. if it handles `&x` by reference, `&&x`, then all it needs is a deref, `*`, to get it back for final printing. its not complicated. the only way the first two prints could differ is if `x` moved.
Answer: Let's start with a trick question: Does this compile or not?
fn main() {
    println!("{:p}", 1i32);
}

We're asking to print an i32 as a memory address. Does this make sense?
No, of course, and Rust rightfully rejects this program.
error[E0277]: the trait bound `i32: std::fmt::Pointer` is not satisfied
 --> src/main.rs:2:22
  |
2 |     println!("{:p}", 1i32);
  |                      ^^^^ the trait `std::fmt::Pointer` is not implemented for `i32`
  |
  = note: required by `std::fmt::Pointer::fmt`
  = note: this error originates in a macro (in Nightly builds, run with -Z macro-backtrace for more info)

But we know that the macro implicitly borrow the arguments, so 1i32 becomes &1i32. And references do implement Pointer. So what's the deal?
First, it helps to understand why the macro borrows its arguments. Have you ever noticed that all the formatting traits look virtually identical? They all define exactly one method, named fmt, that takes two parameters, &self and a &mut Formatter and returns Result<(), fmt::Error>.
It is the &self that is relevant here. In order to call fmt, we only need a reference to the value, because formatting a value doesn't need ownership of that value. Now, the implementation of formatting arguments is more complicated than this, but ultimately, for an argument x, the program would end up calling std::fmt::Pointer::fmt(&x, formatter) (for :p). However, for this call to compile successfully, the type of x must implement Pointer, not the type of &x. If x is 1i32, then the type of x is i32, and i32 doesn't implement Pointer.
The conclusion is that the :p format will end up printing the value of the pointer represented by the expression written textually in your program. The borrow taken on that expression is there so that the macro doesn't take ownership of the argument (which is still useful for :p, e.g. if you wanted to print a Box<T>).

Now we can proceed to explaining the behavior of your program. x is a local variable. Local variables usually1 have a stable address2. In your Example 1 calls, the expression &x allows us to observe that address. Both occurrences of &x will give the same result because x hasn't moved between the calls. What's printed is the address of x (i.e. the address that holds the value 0).
However, the expression &&x is a bit curious. What does it mean exactly to take the address twice? The subexpression &x produces a temporary value, because the result is not assigned to a variable. Then, we ask the address of that temporary value. Rust is kind enough to let us do that, but that means we must store the temporary value somewhere in memory in order for it to have some address. Here, the temporary value is stored in some hidden local variable.
It turns out that in debug builds, the compiler creates a separate hidden variable for each of the &x subexpressions in the two occurrences of &&x. That's why we can observe two different memory addresses for the Example 2 lines. However, in release builds, the code is optimized so that only one hidden variable is created (because at the point where we need the second one, we no longer need the first one, so we can reuse its memory location), so the two Example 2 lines actually print the same memory address!

1 I say usually because there might be situations where an optimizer could decide to move a local variable around in memory. I don't know if any optimizer actually does that in practice.
2 Some local variables might not have an "address" at all! An optimizer may decide to keep a local variable in a register instead if the address of that variable is never observed. On many processor architectures, registers cannot be addressed by a pointer, because they live in a different "address space", so to speak. Of course, here, we are observing the address, so we can be pretty confident that the variable actually lives on the stack.
Comment: This is a beyond great answer! Since `std::fmt::Pointer::fmt` takes a reference to an implementer of `Pointer`, sounds like it will do some dereferencing internally to remove the extra level of indirection introduced by borrowing instead of owning (so it can print the hexadecimal-formatted value of the implementer of `Pointer` instead of the reference one level up). Is that a right way to think about it?


Interpretation of Bach's ornaments

Question: In some of Bach's works, this ornament, which contains twelve 32nd notes, seems to start once the above three 16th note have stopped, basically playing them during the rest...
At least that's the way I am reading it, in theory.
However, when I hear it played by other people, it seems there's an overlap, which I am guessing is to avoid breaking the rhythm of the right hand.
Bit confused so here's my question:
Do I play the ornament with an overlap or do I play them during the rest as I read it which means playing them super fast?
Do not take notice of the described ornament in faded script, this is the one I am using for authenticity:

EDIT
I am not looking for the scholars arguments about ornaments, I am looking for the pure theory here: as I read it, an ornament should be played during the rest of the triplet notes but most people seem to overlap.
Is it because there are too many notes in the ornament or because it's not physically possible or even sounds too fast?
Comment: if you are interested in reading up on the theory, the book "studies in musical graces" : https://archive.org/details/studiesinmusical00fowl  discusses this mark in Bach's work, roughly around page 65
Comment: Related: https://music.stackexchange.com/questions/38474/ornaments-in-j-s-bachs-4th-prelude
Answer: The well known "explanation of ornaments" by JS Bach himself shows that this is a long trill, which occupies the full duration of the ornamented note. It is not a short trill (pralltriller, or mordent).
You don't give any authority for your assertion that "an ornament should be played during the rest of the triplet notes" - and I don't expect you will find any. (And the right hand notes are not triplets here - they are ordinary 16th notes).
The number of notes in the "correct" interpretation depends on the tempo. In general, ornaments sound better if their rhythm does not match exactly with the other parts - which is probably why your picture shows triplets not straight 16th notes. Of course the number of notes you can play depends on the tempo of the piece - it would be perfectly reasonable to play this ornament with 10 notes, if 8 seems to slow and 12 seems too fast, but most of the written-out examples tend to use "simple" rhythms which are easier to read. There is no reason why the ornamental notes should all be played at the same speed - in fact trills often sound better if they accelerate towards the end.
If these details could have easily been expressed in standard notation, there would have been little need for "ornaments" at all - composers could have just "written exactly what they meant to be played"!
Comment: I didn't mean triplets I mean the triple sixteenth as you said
Answer: In my experience, it will be really difficult to come up with an interpretation that satisfies everyone; even Baroque performance scholars, who have spent countless hours studying Bach's own manuscripts sources, will have disagreements on how these are performed. Unfortunately, we just can't know what he meant with 100% accuracy.
As such, use your own musicality to determine which you think best fits your own interpretation of the work. Try to listen to as many recordings as you can to see what other performers do; maybe you'll settle on one of their interpretations and skip over what you've shown here.
Comment: Yep.  I'd just add that Bach would probably be surprised that anyone would think that there is always "the" correct interpretation of an ornament, down to the exact number of notes.
Answer: The shake (trill) should be held out for the full duration of the note, in this case the full quarter note. This does overlap with the other part.
If the intention was to have a shake during just the 16th rest, then the transcription would have a trilled sixteenth note followed by a dotted eighth rest under the top line notes.
The hook at the beginning of the shake sign indicates the trill should start below the primary note and then continue to trill to the above note.  The slash at the end indicates that the trill may conclude with the note below the primary, as shown in your example
Comment: That's what I am thinking and worked on but the theory seem to be controversial as answer below shows. I am gonna go with the first answer and work on all of the variant so I can play them as I wish the way I feel at the time.

Interpretation of Bach's ornaments


Protractor/Selenium with Angular overlay, other element would receive click

Question: our app has an angular overlay that is always in the dom (although not always visible).. and sometimes when I attempt to click on elements on the page, Selenium throws an error...

Element is not clickable at point (544, 297). Other element would
  receive the click: div class="overlay" style="transition-property:
  opacity; -webkit-transition-property: opacity; transition-duration:
  300ms; -webkit-transition-duration: 300ms; transition-timing-function:
  ease-in-out; -webkit-transition-timing-function: ease-in-out; display:
  block; opacity: 0;">

Does anyone else experience this? webdriver .isDisplayed always reports that it is false, even when it is still inhibiting clicks.
I have written some code that attaches to protractor's waitForAngular function that checks for various states of the overlay's dom element (to wait until it has a display: attribute with value "none"). This helps a lot and I no longer experience this issue unless the browser is executing in the background. If the browser is not in foreground, then I hit the overlay issue very frequently. While protractor is waiting (based on my wait for angular override), if I bring the browser to foreground, then the test immediately begins continuing to execute and the dom state changes for the overlay.
Would love any thoughts from people with insight.
I assume the .isDisplayed not working properly seems to be a webdriver issue. And I also assume that the overlay being stuck in a specific dom state in the background to be an angular issue.
Comment: Does eliminating the time taken for the transition make any difference?
Comment: I am experiencing a similar issue.  Did you ever figure out a workaround?
Answer: By what is in your css properties, your element has opacity: 0;
accordantly to this answer here, elements with opacity: 0 still receive events, so your overlay is not completely hidden.
I'd suggest you to use other css properties to hide your overlay such as visibility: hidden or display:none; instead.
Comment: Do you believe that would solve that the overlay would function properly in the background while scripts are running? Thank you for the response.
Comment: I don't know what you mean.  Have you tried changing it to display:none
Comment: this doesn't answer the question. The question asks about an overlay


How to prevent buffer seek in one window if I select in another?

Question: On VIM, I often open 2 windows on the same file, one for reading, other for writing. But when I select some text on the writing one window, the other seeks to the text I just selected, moving away from the place I was reading, annoying the hell out of me. How can I prevent such behavior?
Answer: I believe by two windows you meant split windows opened using vsplit or hsplit. If that's the case, you can turn off this behavior by disabling scrollbind.
:set scrollbind! or :set scb!
Comment: It is much worse now. Scroll position of the two windows seems connected. If I scroll one window, the other follows. The other seems to be able to scroll independently from the first, but if I change the cursor back to the first window, it scrolls back to previous position.


jquery css with object container

Question: I've probleme with
$pagContainer = $(sets.lists.container); // container: 'cart'
$bg = $($pagContainer + " li").css("background", "#FFFFFF");
$bg1 = $($pagContainer + " li:nth-child(2n)").css("background", "#767676");

I don't know if I need to put "#" before the $pagContainer like:
$pagContainer = $(sets.lists.container); // container: 'cart'
$bg = $("#" + $pagContainer + " li").css("background", "#FFFFFF");

or something like that.
who can be help me with this issue?
Thanks,
Answer: If sets.lists.container contains a reference to a DOM element, or a selector in the form #my_id, then $pagContainer will already be a jQuery object, and cannot be used as a selector. In this case, you can use .find:
$pagContainer.find("li")
$pagContainer.find("li:nth-child(2n)")

Comment: hum doesn't work
my object is:
    lists {
      id: null,
      container: 'carts'
    }
    var sets = {};
    sets.init($this);
and $(sets.lists.container) exist in object.
but I don't know how i can use it..
Comment: Then, if 'carts' is the ID for your container, your first line should be `$pagContainer = $('#'+sets.lists.container);`. The following lines can use `.find()` on `$pagContainer` as I explained on my answer.
Answer: You will use '#' if $pagContainer is the ID of an element, as in:

 ...

 ...

if $pagContainer value is 'container_id' then the result selector would be $('#container_id li').
If you were trying to change the background of the list items, your syntax is correct, if you are trying to change the background of the div element just drop the last 'li'.
if $pagContainer is a class, use a '.' instead of a '#'

jquery css with object container


BigQuery is picking the wrong sheet when linking to Google sheet for table loading. What other options to use while loading?

Question: Even if I give link to the second/third sheet in a group of Google sheets, it always picks the first sheet for loading.
Answer: BigQuery only supports reading from the first sheet/tab for now. There are ongoing work to read from any sheet.


Do all 11 fielders need to be in the field?

Question: I was just wondering if there is a rule about how many fielders need to remain in the ground during a cricket match.
Can't the fielding captain argue that we do not need the 11th man on the field, for whatever reasons?
Also, will the umpire call no ball if a fielder is standing just outside the boundary before the ball is delivered?
Comment: Seems a fair question; not sure for the reason behind the downvotes.
Answer: There is no requirement to have 11 fielders on the field at all times. Law 1 (The players) makes provision for the number of players per team to be varied by agreement of the captains:

By agreement a match may be played between sides of fewer than, or more than, eleven players, but not more than eleven players may field at any time.

A no-ball will not be called if a fielder leaves the field or fails to takes the field. Law 2.1 (Substitutes and runners) specifically states that a fielder may leave the field, thereby leaving fewer than 11 fielders on the field:

A player wishing to change his shirt, boots, etc. shall leave the field to do so. No substitute shall be allowed for him.

However, according to Law 2.5 (Fielder absent or leaving the field), she/he may not return without the consent of the umpire (which will be given as soon as possible). If she/he does so and touches the ball while in play, the umpire will award penalty runs under Law 2.6 (Player returning without permission):

If a player comes on to the field of play in contravention of 5(b) above and comes into contact with the ball while it is in play [...] the ball shall immediately become dead and the umpire shall award 5 penalty runs to the batting side.


*** No targets. Stop on Linux using C

Question: This is a very basic program because I am using Make and Linux both for the first time. I have seen other questions similarly and I have tried all: *.o
all: *.c
And clean : rm *.o h1

And here is the directory
Comment: How are pictures easier for anyone but you? Lots of posts get downvoted for posting screenshots, but you actually posted a *picture of your screen*... amazing.
Comment: There's no reason not to take the OP at their word that they thought they were trying to be helpful. They were mistaken, but not malicious or lazy.
Comment: @JonathonReinhart  I simply figured in terms of coding showing is normally better then explaining. If it makes you feel better to put me down because of it, I hope you never make any mistakes as you must be extremely hard on yourself.
Comment: @ Carl Norum I will next time, I believe I have for all my previous questions however I did not know this was a rule. Unfortunately I am not working from home and had my roommate send me the pictures.
Comment: It's considered bad SO form to post pictures - text is better.  But in the makefile, are the indented lines with spaces or tabs? They have to be tabs.
Comment: @SteveFriedl       The gcc are all indented with tabs. Also sorry I just figured pictures were easier for everyone.
Comment: Alexis, you should copy/paste/correctly format the code and listing here, instead of using images.
Answer: You have a file called makefile and one called Makefile. Delete the one that doesn't have any contents.
Comment: Yes! Thanks! I'm just used to Netbeans so a text file is all new. I have to wait a couple minutes to accept your answer but thanks again!

*** No targets. Stop on Linux using C


Gaussian Process Proofs and Results

Question: I am building a model based on Gaussian processes and want to assume something like as my sample size $n$ gets large my prediction error goes to 0.  In other words,a re there any proofs or theorems out there that show something like
$$Pr((\hat y -y)=0)\rightarrow1$$ as $n\rightarrow\infty$? Here $\hat y$ is my predicted value and $y$ is my true value.
Comment: I think you misunderstand something. As $n \rightarrow \infty$ your inference about the model (hyper)parameters will become more accurate. Not your actual predictions. If you have noisy data, well... you have noisy data, you will not be able to predict them accurately unless you overfit (which is wrong).
Comment: [_Regularity dependence of the rate of convergence of the learning curve for Gaussian process regression_](http://arxiv.org/abs/1210.2879) shows convergence of one measure of error in a standard GP regression setup.
Comment: @Dougal, Nice paper (+1) but this IMSE is not what the OP is asking for. You are talking about the BLUP, the OP is asking for his predictions error converging to zero.
Comment: @Dougal, I did not mean to imply it was not useful; if anything I upvoted the comment. I do not want the OP to misread it as an indirect proof for what it is originally asked.
Answer: Unfortunately you cannot assume that as your sample size $n \rightarrow \infty$ your prediction error will tend to zero.
Your prediction error $(\hat{y} -y)$ will never tend to zero. This is true in any statistical model that uses data that might be noisy irrespective of the dataset's sample size. Your only change is that the data are truly noiseless and therefore you will correctly infer that the noise variability is of zero magnitude and then your prediction error will also become zero (assuming your model models the true underlying dynamics). What you can expect is, that with larger sample size, your (hyper)-parameters $\hat{\theta}$ will become closer and closer your true $\theta$. This is true for any consistent estimation procedure. As a standard reference on the subject I would suggest you look at Chapter 7 from the Gaussian Process for Machine Learning by Rasmussen and Williams. Section 7.2 on the asymptotic analysis of GPs is most probably what you need;the section's extensive reference list will point you to specific papers if you need to dig a particular matter further.
Comment: Do the person that down-voted this care to explain why?
Comment: I think someone just trolled the page - you can get a +1 from me ;)
Comment: I returned the favour. :D
Answer: Let us assume that $y = f(x) + \epsilon$, as said in the comments the best we can do is to model $f(x)$ with $\bar{f}(x)$ and it seems that you want $\bar{f}(x)$ to approach $f(x)$with the limit of data. This will only happen with some kernels. If the kernel is degenerate, such as a linear kernel, then it can only model a subset of functions, such as linear functions. This means that even in the limit of data we will not be able to model the true $f(x)$. If we use a squared exponential kernel (as an example) then we can model all functions. The proof is simple just let the length scale tend to zero as data comes in.
One nicety is that as a kernel puts a probability mass over the function space, if $f(x)$ lies outside the space of functions which a kernel defines, then in the limit of data $\bar{f}(x)$ tends to the function which minimises the KL Divergence between $f(x)$ and $\bar{f}(x)$.
Comment: The -1 here is undeserved. Can the downvoter please explain why he treated this as not useful?

Gaussian Process Proofs and Results


Jetpack Compose LazyColumn Scroll Listener

Question: I want to programmatically change which tab is selected as the user scrolls past each "see more" item in the list below.  How would I best accomplish this?
Answer: Just create a NestedScrollConnection and assign it to parent view nestedScroll modifier:
val nestedScrollConnection = remember {
    object : NestedScrollConnection {
        override fun onPreScroll(available: Offset, source: NestedScrollSource): Offset {
            val delta = available.y
            // called when you scroll the content
            return Offset.Zero
        }
    }
}

Assign it to LazyColumn or to its parent composed view:
Modifier.nestedScroll(nestedScrollConnection)

Exemple:
LazyColumn(
    ...
    modifier = Modifier.nestedScroll(nestedScrollConnection)
) {
    items(...) {
       Text("Your text...")
    }
}

Comment: good and simple answer... thanks :)
Comment: If you want to get a consumed value instead of the available one, you should override ```onPostScroll``` function and take Y value from ```val delta = consumed.y```
Answer: As Ryan M writes, you can use LazyListState.firstVisibleItemIndex. The magic of Compose is that you can just use it in an if statement and Compose will do the work. Look at the following example, which displays a different text based on the first visible item. Similarly, you can select a different tab based on the first visible item.
class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        setContent {
            val listState = rememberLazyListState()

            Column {
                Text(if (listState.firstVisibleItemIndex < 100) "< 100" else ">= 100")
                LazyColumn(state = listState) {
                    items(1000) {
                        Text(
                            text = "$it",
                            modifier = Modifier.fillMaxWidth(),
                        )
                    }
                }
            }
        }
    }
}

Comment: `val firstVisibleIndex by derivedStateOf { listState.firstVisibleItemIndex }`
Accessing listState.firstVisibleItemIndex directly inside compose function might have an effect on performance.
Comment: Be careful using this property. According to documentation, this property is observable and if you use it in the composable function it will be recomposed on every change causing potential performance issues.
If you want to run some side effects like sending an analytics event or updating a state based on this value consider using "snapshotFlow"
Answer: You can use the LazyListState.firstVisibleItemIndex property (obtained via rememberLazyListState and set as the state parameter to LazyColumn) and set the current tab based on that.
Reading that property is considered a model read in Compose, so it will trigger a recomposition whenever the first visible item changes.
If you instead want to do something more complex based on more than just the first visible item, you can use LazyListState.layoutInfo to get information about all visible items and their locations, rather than just the first.
Comment: @DmytroIvanov Reading a piece of state will indeed trigger recomposition when that state changes.  That's working as intended.  What are you experiencing that you believe is a bug?
Comment: Could you provide more details on the implementation?  How exactly would I use LazyListState.firstVisibleItemIndex to changed the current tab?
Comment: The problem with `layoutInfo` is that it triggers recomposition. Probably it is a bug in compose.
Comment: Actually, I realized that it is not a bug, yeah it is basically a recomposition because we read a state.


How to open 'window.open' in wkwebview

Question: I developing hybrid app using cordova . . .
I write below code in WkWebvieUIDelegate.m
I can open a tag (target _blank with new window)
and i can see NSLog this code
But i can't open window.open(...) in javascript and i can't see NSLog
how can i open window.open
- (WKWebView *)webView:(WKWebView *)webView createWebViewWithConfiguration:(WKWebViewConfiguration *)configuration forNavigationAction:(WKNavigationAction *)navigationAction windowFeatures:(WKWindowFeatures *)windowFeatures
{
    webView.UIDelegate = self;
    webView.navigationDelegate = self;
    webView.configuration.preferences.javaScriptEnabled = YES;

  webView.configuration.preferences.javaScriptCanOpenWindowsAutomatically = YES;

    NSLog(@"1");
    NSURL* url = [navigationAction.request URL];
    UIApplication *app = [UIApplication sharedApplication];

    if ([app canOpenURL:url]) {
         NSLog(@"2");
        [app openURL:url];
    } else {
//        if (!navigationAction.targetFrame.isMainFrame) {
//
//            [webView loadRequest:navigationAction.request];
//        }
    }
    return nil;
}

Comment: Why don't you use the WKWebView implementation (`usewkwebview=yes`) of the existing [Cordova InappBrowser plugin](https://github.com/apache/cordova-plugin-inappbrowser)?
Answer: Firstly create an extension on WKWebView that defines a 'runJavaScriptInMainFrame:' method. In the extension method, use NSInvocationOperation

The NSInvocationOperation class is a concrete subclass of NSOperation
  that you use to initiate an operation that consists of invoking a
  selector on a specified object. This class implements a non-concurrent
  operation.

to call the undocumented '_runJavaScriptInMainFrame:' method.
 extension WKWebView {
        func runJavaScriptInMainFrame(#scriptString: NSString) -> Void {
            let selector : Selector = "_runJavaScriptInMainFrame:"
            let invocation = NSInvocationOperation(target: self, selector: selector, object: scriptString)
            NSOperationQueue.mainQueue().addOperation(invocation)
        }
    }

Now call this one:-
webview.runJavacriptInMainFrame:(scriptString: "Write Particular javascript code")

Comment: ls it work javascript in event listener ? my javascript is in event listener ... @Deviyani Swami
Comment: You need to implement the WKScriptMessageHandler protocol to receive the message.
Comment: func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
        print("message: \(message.body)")
        // and whatever other actions should be perform.
    }
Comment: Sorry but don't have idea, this one is for iOS.

How to open 'window.open' in wkwebview


How to get entity from transliterated argument in URL?

Question: I have panel, where I have argument: taxonomy term name
term names are transliterated (like "My custom taxonomy title" into my-custom-taxonomy-title)
path is like this: my-custom-list-of-nodes/my-custom-taxonomy-title
How can I get in PHP code (in some hook) original taxonomy term name from argument "my-custom-taxonomy-title"?
Original string can have diacritics, uppercase, spaces.
How can I detect Term ID from transliterated argument "my-custom-taxonomy-title" ?
Comment: Since you have the term as an argument it will be available in your list of Contexts. In the context you will find the id and the original title. If you simply want to print the original term title, use Context keyword substitutions in a custom content pane.
Comment: thanks, but i need to use term ID in hook, not in content pane.  I tried to use function menu_get_item but there is "context" key, but contains only "0".
Comment: What is it you are trying to do?
Answer: Short answer:
You can't do what you are asking.
Why is that?
While transliterating is a pretty simple procedure that follows a very specific number of steps:
- Replace every character with the corresponding-transliterated version
- If the resulting URL exists, add a -{Insert Number here} at the end until you find a URL that does not exist
reversing the transliteration is not that easy. Think of the extreme case where 5 different nodes/terms/entities have the exact same title. Their transliterated paths would be: /common-title /common-title-0 /common-title-1 /common-title-2 /common-title-3.
In this case, how do you know which transliterated title corresponds to each entity? Creation date (first one created gets the smallest index)? Besides the fact that this is extremely complex to predict, there may still be problems if a path was updated manually or one of the entities was deleted and a new one was added.

Long answer:
Even though what you are asking is not feasible, you can use a number of different approaches in order to solve the specific problem that you are facing.
Possible Solution 1:
You can use the current_path function. This will return the unaliased path of the currently viewed Drupal page. I am not exactly sure how the panels' pathing system works, but there is a very good chance that you will get something with the term id in it (that's what you need in your hook, right?).
In order to investigate this further in your code, assuming you have devel installed, you can do something like:
dpm(current_path());

Possible Solution 2:
If the above-mentioned solution does not work, you will need to do some more digging in order to figure out which variables are available. Something that can get you started is a simple:
dpm(get_defined_vars());

Depending on the results that you will get, you may be able to find the term name somewhere in the defined variables and use taxonomy_get_term_by_name() function to retrieve the tid.


Proof of Weierstrass Theorem from Rudin's-Multiple questions though the proof

Question: I am studying Stone-Weierstrass theorem. I am not understanding well and I have a multiple point that I need some help to have better understanding.

In the proof, he set $Q_n(x)=C_n (1-x^2)^2$ then $\int _{-1} ^{1} (1-x^2)^n dx \ge 2\int _{0} ^{1/{\sqrt{n}}} (1-x^2)^n \ge 2\int _{0} ^{1/{\sqrt{n}}} (1-n{x^2})dx$
I don't understand why $(1-x^2)^n \ge (1-n{x^2})$.
I understand that the inequality holds but I don't understand how this idea can come up.
And there is a part that change of variable is applied according to his explanation but I don't really understand how he got it.
We have $P_n(x)=\int_{-1}^{1}f(x+t)Q_{n}(t)dt$, where $(0 \le x \le 1)$.
Then $P_n(x)=\int_{-x}^{1-x}f(x+t)Q_{n}(t)dt=\int_{0}^{1}f(t)Q_{n}(t-x)dt$.
I don't understand the process and I don't understand how we can conclude $P_n(x)$ is a polynomial.

I think understanding in these two parts would help me understand the whole proof.
Comment: Even though this is an old post - I'm commenting for future reference. Rudin comments on the next page how to get the inequality in (1). He says to consider, for each $n\in\mathbb{N}$ and each $x\in[0,1]$, the function $F_{n}(x)=(1-x^{2})^{n}-1+nx^{2}$. Note, $F_{n}(0)=0=F_{n}(1)$. $F_{n}$ is continuous on $[0,1)$, and, on $(0,1)$ we have $F_{n}'(x)=2nx(1-x^{2})^{n-1}+2nx$. Clearly, $F_{n}'(x)>0$ on $(0,1)$, so $F$ is increasing on $[0,1)$. Overall $F_{n}(x)\geq 0$ on $[0,1]$, and the inequality easily follows.
Answer:
You can prove $(1-x^2)^n \ge 1-nx^2$ by induction.
Let $k=x+t$. (I am just calling it $k$, use any other letter besides $x$ or $t$.) Then $t=k-x$. Also, at $t=-x$, we have $k=x+(-x)=0$. At $t=1-x$, we have $k=x+(1-x)=1$. Thus, $$\int_{-x}^{1-x} f(x+t) Q_n(t) \, dt = \int_0^1 f(k) Q_n (k-x) \, dk=\int_0^1 f(t) Q_n (t-x) \, dt.$$
For the right-most equality, replace $k$ with $t$. The value of the definite integral will not change.
Comment: For point $2$, he's wondering why $P_n$ is a polynomial, not $Q_n$. The answer comes from the expression $$\int_0^1 f(t) Q_n (t-x) \, dt.$$ If $Q_n(z)=\sum a_i z^i$ then this integral will end up being a sum of powers of $z$ with coefficients the integral of $c_i f(t)t^i$ over $[0,1]$ for some appropriate $c_i$. More simply, the integral $$\int_0^1 f(t)(t-x)^j dt$$ is always a polynomial in $x$, and we're summing many of those.
Comment: Have you actually proven 1 with induction? It looks quite tedious.
Comment: @AlexH. Yes, but I want to leave it to the OP as a hint.
Answer: For 1., just look at $x >0  \mapsto (1-x)^n$ and its second derivative. You will see that it's convex and hence "above its tangent" at $x=0$.
For 2., start by thinking of the case $Q_n(u) = u^k$. If you expand $Q_n(x-t)$, you have a polynomial expression in $x$ and $t$. After multiplication by $f(t)$ and integration on $t$, you're left with a polynomial expression in $x$.
Another angle on 2., if you know the rules of derivation under the integral sign, you instantly see that if $Q$ is a polynomial of degree $\le n$, the $(n+1)$-th derivative of your integral $P_n(x)$ is nil, which proves it is also a polynomial.


How to create the branch from a specific commit in a different branch

Question: I have made several commits in the master branch and then merged them to the dev branch.
I want to create a branch from a specific commit in the dev branch, which was first committed in the master branch.
I used the commands:
git checkout dev
git branch  <branch name> <commit id>

However, this creates the branch from the master branch, not the dev branch I expected. The commit id is same in the master branch and dev branch.
So, how can I distinguish same commit id in a different branch?
PS: I made an example at GitHub.
I used the commands:
git checkout dev
git branch test 07aeec983bfc17c25f0b0a7c1d47da8e35df7af8

I expect that the test branch contains aa.txt, bb.txt, and cc.txt. However, the test branch only contains aa.txt and cc.txt. It most likely created the branch from the master branch.
Comment: Unfortunately, the original git repo on github no longer exists which makes this question and the the answers that refer to it less useful
Comment: Related: *[How do I create a new Git branch from an old commit?](https://stackoverflow.com/questions/7167645/)* (2011) and *[Branch from a previous commit using Git](https://stackoverflow.com/questions/2816715/)* (2010)
Answer: If you are using this form of the branch command (with start point), it does not matter where your HEAD is.
What you are doing:
git checkout dev
git branch test 07aeec983bfc17c25f0b0a7c1d47da8e35df7af8

First, you set your HEAD to the branch dev,
Second, you start a new branch on commit 07aeec98. There is no bb.txt at this commit (according to your github repo).

If you want to start a new branch at the location you have just checked out, you can either run branch with no start point:
git branch test

or as other have answered, branch and checkout there in one operation:
git checkout -b test

I think that you might be confused by that fact that 07aeec98 is part of the branch dev. It is true that this commit is an ancestor of dev, its changes are needed to reach the latest commit in dev. However, they are other commits that are needed to reach the latest dev, and these are not necessarily in the history of 07aeec98.
8480e8ae (where you added bb.txt) is for example not in the history of 07aeec98. If you branch from 07aeec98, you won't get the changes introduced by 8480e8ae.
In other words: if you merge branch A and branch B into branch C, then create a new branch on a commit of A, you won't get the changes introduced in B.
Same here, you had two parallel branches master and dev, which you merged in dev. Branching out from a commit of master (older than the merge) won't provide you with the changes of dev.

If you want to permanently integrate new changes from master into your feature branches, you should merge master into them and go on. This will create merge commits in your feature branches, though.
If you have not published your feature branches, you can also rebase them on the updated master: git rebase master featureA. Be prepared to solve possible conflicts.
If you want a workflow where you can work on feature branches free of merge commits and still integrate with newer changes in master, I recommend the following:

base every new feature branch on a commit of master
create a dev branch on a commit of master
when you need to see how your feature branch integrates with new changes in master, merge both master and the feature branch into dev.

Do not commit into dev directly, use it only for merging other branches.
For example, if you are working on feature A and B:
a---b---c---d---e---f---g -master
    \       \
     \       \-x -featureB
      \
       \-j---k -featureA

Merge branches into a dev branch to check if they work well with the new master:
a---b---c---d---e---f---g -master
    \       \            \
     \       \            \--x'---k' -dev
      \       \             /    /
       \       \-x----------    /    -featureB
        \                      /
         \-j---k--------------- -featureA

You can continue working on your feature branches, and keep merging in new changes from both master and feature branches into dev regularly.
a---b---c---d---e---f---g---h---i----- -master
    \       \            \            \
     \       \            \--x'---k'---i'---l' -dev
      \       \             /    /         /
       \       \-x----------    /         /  -featureB
        \                      /         /
         \-j---k-----------------l------ -featureA

When it is time to integrate the new features, merge the feature branches (not dev!) into master.
Comment: thanks. You answer my question. I am wrong in understanding of git branch mode. And do you have any suggestion for my problem. I have the master branch which has many commits timely from others(sync with perforce). I have dev branch I do personal work. I want a branch that contains all commits from master branch and dev branch, then I can easily create branch based this branch, then to start specific working.
Comment: I could not answer in a comment, so I update my answer with suggested workflows.
Comment: Hey -- thanks for the brilliant and thorough answer! Just curious: In the end, why should one `merge the feature branches (not dev!) into master`?
Comment: There is no real new development in the `dev` branch. You should keep your branches feature specific. `dev` contains only merge commits. It makes more sense to merge all new features to directly `master`, than merging together the features then merging the result into `master`.
Comment: @Gauthier You did not address the question of why. To me it sounds like merging a `dev` with just features `A` `B` and `C` merged into it into `master` is identical to individually merging `A` `B` and `C` into `master`. If not, that challenges my understanding of how git works and I would be very curious as to why!
Comment: @Steven Lu The content of the file system might probably be the same, but when you merge into dev you create merge commits which don't make much sense in the history (given that you don't fast-forward merge).
Answer: You have the arguments in the wrong order:
git branch <branch-name> <commit>

and for that, it doesn't matter what branch is checked out; it'll do what you say. (If you omit the commit argument, it defaults to creating a branch at the same place as the current one.)
If you want to check out the new branch as you create it:
git checkout -b <branch> <commit>

with the same behavior if you omit the commit argument.
Answer: You can do this locally as everyone mentioned using
git checkout -b <branch-name> <sha1-of-commit>

Alternatively, you can do this in GitHub itself, follow the steps:

In the repository, click on the Commits.

on the commit you want to branch from, click on <> to browse the repository at this point in the history.

Click on the Tree: xxxxxx in the upper left. Just type in a new branch name there. Click Create branch xxx as shown below.

Now you can fetch the changes from that branch locally and continue from there.
Comment: I never knew it. This is it. GUI thing is just great and I wanted to be away from CLI.
Comment: This is what I needed.. How to do it in the web site
Answer: Try
git checkout <commit hash>
git checkout -b new_branch

The commit should only exist once in your tree, not in two separate branches.
This allows you to check out that specific commit and name it what you will.
Comment: hi I try the git log dev and git log master, I found the commit hash id is same for the commit that I merge to dev branch from master branch
Comment: it might help to use something like `gitk` to visualize your log
Comment: I newly add an example in github. And Gauthier already answer my question that I misunderstand the git branch mode. Thanks you:)
Comment: This is acutally answer I think. Thanks
Answer: You have to do:
git branch <branch_name> <commit>

(you were interchanging the branch name and commit)
Or you can do:
git checkout -b <branch_name> <commit>

If in place of  you use branch name, you get a branch out of tip of the branch.
Comment: That's not what `HEAD` means. You could say "the tip of the branch" or "the commit the branch points to" instead.
Comment: @Jefromi - To be purists, we can say the branch only, as the branch itself is pointer to, well, the tip of the branch.


DynamoDB unmarshall only unmarshalling one Map when multiple exist

Question: I am having trouble with unmarshalling information i'm retrieving from my DynamoDB table. This is t e raw format of it.
{
  "email": {"S": "firstname.lastname@example.com"},
  "name": {"S": "John Doe"},
  "clientConfiguration": {
    "M": {
      "chartTimeScale": {
        "S": "Periodic"
      },
      "naming": {
        "S": "Site"
      }
    }
  },
  "clientName": { "S": "Client" },
  "clientStatus": {"S": "Onboarding" },
  "createdDate": {"S": "2023-09-19T15:46:09.688Z"},
  "pageAccess": {
    "M": {
      "pageOne": {
        "BOOL": false
      },
      "pageTwo": {
        "BOOL": false
      },
      "pageThree": {
        "BOOL": false
      },
      "pageFour": {
        "BOOL": false
      },
      "pageFive": {
        "BOOL": false
      }
    }
  },
  "users": {
    "L": []
  }
}

When i run this through the unmarshall(data) I get the following:
{
    "email": "firstname.lastname@example.com",
    "name": "John Doe",
    "clientConfiguration": {
        "chartTimeScale": "Periodic",
        "naming": "Site"
    },
    "clientName": "Client" ,
    "clientStatus": "Onboarding" ,
    "createdDate": "2023-09-19T15:46:09.688Z",
    "pageAccess": {
        "M": {
            "Lifts": {
                "BOOL": true
            },
            "Roofs": {
                "BOOL": true
            },
            "HVAC": {
                "BOOL": true
            },
            "Refrigeration": {
                "BOOL": true
            },
            "Car Parks": {
                "BOOL": true
            }
        }
    },
    "users": []
}

I've tried using the unmarshall tool and creating my own version. but no luck.
Does anyone have any idea why and if so how to solve this. I'm using NodeJs
Comment: Strange that it would not unmarshall maps at the same level. Which SDK version is this?
Comment: I'm using the aws-cli/2.13.16
Comment: You mentioned unmarshall so you must be using an AWS SDK, not the awscli.
Comment: Your correct, I'm using the SDK, my apologies.
Answer: Easiest way to solve this issue is to use the Document Client, which abstracts you from the type descriptors that DynamoDB uses completely.
You can learn more from this blog:
https://aws.amazon.com/blogs/database/exploring-amazon-dynamodb-sdk-clients/
As you show two completely different items it's hard to tell what the issue is, but my assumption is that you've double marshalled the item while saving it.
Comment: In that case it's not working because you saved double marshalled JSON. Go have a look at the item in the console under the JSON view, my bet is that you still see the type descriptors.
Comment: This is what I have been using:
import { DynamoDBClient } from "@aws-sdk/client-dynamodb";
import { DynamoDBDocumentClient } from "@aws-sdk/lib-dynamodb";

// AWS access keys
const credentials: Credentials = {
  accessKeyId: process.env.AWS_ACCESS_KEY_ID as string,
  secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY as string,
};

// DynamoDB client
const docClient = DynamoDBDocumentClient.from(new DynamoDBClient({
  region: process.env.AWS_REGION,
  credentials,
}));
This is why I'm confused as to why it's not working♂


VB 2010 Textboxes And Buttons Enabled/Disabled

Question: i have one more question about a project in my visual basic 2010. i have 2 textboxes, one button and one progress bar. You have to type username (in tb1) and a random password (in tb2) so the button is enabled and the progress bar starts if i press it. I want the button to be disabled if i havent written any text in the textboxes and enabled if i have. I tried this code but it doesnt work.
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
        If TextBox1.Text <> "" And TextBox2.Text <> "" Then
            Button1.Enabled = True
        ElseIf Button1.Enabled = False Then
            MsgBox("Progress Fail.", MsgBoxStyle.Exclamation)
        End If
    End Sub

Have you any ideas on how can i solve this? Thanks for help
I added a list with radio buttons too. now i want button1 to be enabled if i choose one item from the radio buttons too. Thanks again
Comment: You are checking wether or not to enable/disable your button in the buttons click event, try using the Textchanged event of your TextBox's
Answer: This needs to be done in some event of the text boxes, not the button. Try this:
Private Sub TextBox_TextChanged(sender As System.Object, e As System.EventArgs) Handles TextBox2.TextChanged, TextBox1.TextChanged
    Button1.Enabled = TextBox1.Text <> "" And TextBox2.Text <> ""
End Sub

Set the Button to disabled at startup, and it should work fine.
Note that the sub is used to work for both text boxes (see the Handles part).
---EDIT---
Okay, so we include the ComboBox as well in the check.
I am a bit insecure... yes, you could just add another event to the Handles-part since the events have the same signature (= same parameters of same types). But this is getting a bit dirty in my opinion.
So let's do it rather like this:
Private Sub TextBox_TextChanged(sender As System.Object, e As System.EventArgs) _
     Handles TextBox2.TextChanged, TextBox1.TextChanged

    evaluateUserEntries()
End Sub

Private Sub ComboBox1_SelectedValueChanged(sender As System.Object, e As System.EventArgs) Handles ComboBox1.SelectedValueChanged
    evaluateUserEntries()
End Sub

Private Sub evaluateUserEntries()
    Button1.Enabled = TextBox1.Text <> "" And TextBox2.Text <> "" And ComboBox1.SelectedIndex <> -1
End Sub

Comment: wow thanks man! just something last. i want button1 to be enabled if 2 texboxes have a text in them and if the user choose a value from my combobox. we will make it something like this? Thanks again, i started VB before 1 week.

Button1.Enabled = TextBox1.Text <> "" And TextBox2.Text <> "" And ComboBox1.SelectedValue = <> ""
Comment: ah, sorry for that but i added and a radio buttons list. i want button1 to be enabled if i choose one item from the radio buttons.
Comment: This should work just similar as in the sample. Edit your original question and append your code at the bottom, and point out where you have difficulties, I will have a look at it later.


Filter product displays by parent taxonomy term

Question: I'm running a music store and have a taxonomy term field on products that that is used for the product's format. We tag the products from the following vocabulary.

Vinyl

140g vinyl
180g vinyl

CD

Jewelcase
Digipack

Digital

Mp3
FLAC

I'd like create an exposed filter on the product catalog using the parent terms, Vinyl, CD, Digital. When one of taxonomy terms is selected, the filter should display all products tagged with the child terms.
The Content: Has taxonomy terms (with depth) filter doesn't seem to work with referenced products. I'm not seeing a solution in the Taxonomy Entity Index module either (but I might be wrong).
Answer: With a view using Products as base_table:

Add a relationship using the taxonomy reference field you're using and do not require the relationship
Add an exposed filter `Content: Has taxonomy terms (with depth)
In the settings, set the depth to the level you want
In the exposed filter itself, you can configure whether multiple values can be selected or not.

But before all that, you need to make sure that only the child terms are selected on the products.
Comment: Big thanks for the contribution. However it doesn't work with a View of Product Displays which is what I need. Let me know if you think of another way or a modification of your suggestion.


Interpreting distance between classes for binomial, multinomial, and ordinal regression

Question: I would like to understand the difference between the binomial, multinomial and ordinal models when it comes to interpreting the "distance" between classes, in terms of response probabilities.
To illustrate my question, I have prepared the following graph (just for the sake of example)

Imagine I have use the logit link, and plotted the cumulative curves corresponding to 3 classes with a series of binomial regressions (first case), then I applied multinomial and ordinal regressions (cases 2 and 3, say for 4 classes, one of which is a reference class - not represented because the cumulative probability is 1).
In every case, I will be able to estimate a mean response (probabilities) for each class, $\mu_i$. But the parameters will be different - understandably, as the formulation of the odds in the link function is different.
Now what I dont understand, is how to interpret the distance between the classes (in green in my graph), in other words all the probabilities that are smaller than $\mu_2$
but greater than $\mu_1$, for example.
What are the differences in interpretation according to the model I am choosing?
Answer: For the binomial case we have just two classes. What makes the difference between classes is then the intercept. For ordinal regression this is again simple  if the proportional odds assumption holds for your data.
For a multinomial problem it is different since the apart from the intercept different functions separate classes. Have a look at the image I have attached.
Comment: So in the ordinal case, can I say that the distance between each class, or the difference between two thresholds (at $i+1$ and $i$), corresponds to the range of probabilities of $class = class_i$?
Comment: and if I understand your graph correctly this wouldnt be true for the multinomial and binary logistic cases?


XMLHttpRequest object status code of 0

Question: I have a Javascript function using an XMLHttpRequest object, but the status I keep getting returned is 0. I've done lots of searching, and all I've come up with is that 0 is an undefined error and can be caused by a myriad of reasons. As such, I'm hoping you guys can spot the error in my code.
function initiateIPP(ID, Token)
    {
        var POSTRequest = new XMLHttpRequest();
        POSTRequest.onreadystatechange = function ()
        {
            if (POSTRequest.readyState == 4)
            {
                if (POSTRequest.status == 200)
                {

                }
                else
                {
                    alert("An error has occured, response code = " + POSTRequest.status);
                }
            }
        }
        var parameters = "SessionId=" + ID + "&SST=" + Token;
        POSTRequest.open("POST", "https://demo.ippayments.com.au/access/index.aspx", true)
        POSTRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded")
        POSTRequest.send(parameters)
        window.open("IPPPage.html");
    }

Thanks in advance.
EDIT: I added a withCredentials line to my code but that doesn't seem to have made a difference.
    var parameters = "SessionId=" + ID + "&SST=" + Token;
            POSTRequest.withCredentials = true;
            POSTRequest.open("POST", "https://demo.ippayments.com.au/access/index.aspx", true)
            POSTRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded")
            POSTRequest.send(parameters)
            window.open("IPPPage.html");
Comment: Does this helps.. http://stackoverflow.com/questions/2752657/xmlhttprequest-status-always-returning-0
Comment: I did come across the issue of different origins... it could be the problem, I'm not sure, but if it is I'm not sure if it's really feasible to do something about it. Maybe I have to ask IPP how they expect me to send data to them...
Comment: If you are facing Cross Origin Resource issue, you probably should run using some server, could be apache, or another way would be to set `--disable-web-security` flag to your chrome browser...
Comment: @Rakesh_Kumar `--disable-web-security` will only solve the issue for him.
Comment: Exactly, @gabeio is correct; this needs to work WITHOUT forcing people to go fiddling with settings in their browser.
Answer: "https://demo.ippayments.com.au/access/index.aspx" this should be same domain with your javascript, otherwise, you should set :
Access-Control-Allow-Origin: *

on target page's response header to get work. See http://enable-cors.org/
For example you can put below in web.config on target server:
<configuration>
 <system.webServer>
   <httpProtocol>
     <customHeaders>
       <add name="Access-Control-Allow-Origin" value="*" />
     </customHeaders>
   </httpProtocol>
 </system.webServer>
</configuration>

Comment: @MichaelSmith for that you should search about settings response headers from your server
Comment: Yeah then the issue is you need to tell them to allow what AndyChen is saying.
Comment: Wait a sec, you're saying I need to set something in the other page's response header? How? o_O
Comment: @MichaelSmith I see you use aspx, so I guess you can set in web.config.
Comment: Adding that to web.config hasn't helped. :(
Comment: mm.... can you control the target server? you should add in target aspx's server, not the server you send the request.
Comment: What do you mean by target server? There's two servers involved here: the server with the Javascript on the page, and the IP Payments server that I'm trying to send values to.
Comment: @MichaelSmith the server you are requesting that ajax call with. (no javascript server)
Comment: Is " the IP Payments server that I'm trying to send values to."
Comment: Ah, I follow. No I can't go messing with stuff on their server. I can email them and ask if their server is setup to allow cross-domain requests, but I won't get a reply until Monday or later. I was hoping I could fix the problem myself before then, hence this question.
Comment: @MichaelSmith Can you check that this is the issue by sending a test request to see their headers and double check that they do not already have this header... (if they do already have the answer is going to be different...)
Comment: I'm not sure how to send a test sorry, can you explain and/or give me some example code? Web programming is really not my strong point. :(
Comment: Just press f12 on your browser to open your developer tool, switch to Network, select your request and see the response header.
Comment: https://www.hurl.it/ use this with just the url (don't put the authentication) and just hit send the headers are shown to you and if it says `Access-Control-Allow-Origin: *` then you have a different issue. or what Andy said...
Comment: The console said this: Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://demo.ippayments.com.au/access/index.aspx. This can be fixed by moving the resource to the same domain or enabling CORS.

I don't know if the problem is on my end or their end, will look at the headers.

EDIT: Looking at the header, I'm not seeing anything about access control. Is that the problem then?
Comment: Sorry to come back to this late, but I wanted to ask; is there another way to send POST/GET data to a server? I tried using an XMLHttpRequest object because that was the first thing I came across, but presumably that's not how it's normally done with IP Payments, otherwise this problem wouldn't exist.
Comment: You can use JSONP or Proxy to do the same things.
For payment I'll suggest you to create a proxy to do server to server request.
Comment: That seems complicated, but I'll look into it I guess, thanks.
Answer: To integrated properly with the IPPayments page at https://demo.ippayments.com.au/access/index.aspx, you need to use the Direct Post method. Instead of using the XMLHttpRequest object, use a HTML form to submit the ID and token. For example -
<form action="https://demo.ippayments.com.au/access/index.aspx" method="post">
    <input type="hidden" name="SST" value="1243123123123123123"/>
    <input type="hidden" name="SessionID" value="53535434535345"/>
    <input type="submit" value="submit" />
</form>

Comment: What I ended up doing was doing everything in the code-behind (this is an ASP.NET application/website) and just encoding the SessionID and SST as GET parameters and redirecting to the page that way.

XMLHttpRequest object status code of 0


What is the answer to this limit

Question: what is the limit value of the power series:
$$ \lim_{x\rightarrow +\infty} \sum_{k=1}^\infty (-1)^k \frac{x^k}{k^{k-m}}$$
where $m>1$.
Comment: @Ethan... I dont think so... Do you have any proof for that?
Comment: @Mamal: By the way, what's the origin of this problem?
Comment: It grows with out bound....
Comment: A [related problem](http://math.stackexchange.com/questions/401734/the-value-of-a-limit-of-a-power-series-lim-limits-x-rightarrow-infty-sum/401816#401816).
Comment: @Benghorbal your mentioned problem is for $m=0$
Comment: This problem seems to be  harder...
Answer: My solution is also similar. Let $\left\{ {a \atop b} \right\}$ be the Stirling number of the second kind, as Mhenni Benghorbal pointed out. Then from the identity
$$ x^{n} = \sum_{j=0}^{n} \left\{ {n \atop j} \right\} (x)_{j}, $$
where $(x)_{j} = x (x-1) \cdots (x-j+1)$ is the failing factorial, we obtain
$$ x^{n} = \sum_{j=0}^{n} \left\{ {n+1 \atop j+1} \right\} (x-1)_{j}. $$
This allow us to write
\begin{align*}
\frac{1}{k^{k-m}}
& = \frac{k^{m}}{k^k} = \sum_{j=0}^{m} \left\{ {m+1 \atop j+1} \right\} \frac{1}{(k-1-j)!} \frac{\Gamma(k)}{k^{k}} \\
&= \sum_{j=0}^{m} \left\{ {m+1 \atop j+1} \right\} \frac{1}{(k-1-j)!} \int_{0}^{\infty} t^{k-1}e^{-kt} \, dt.
\end{align*}
Here, we use the convention that $\frac{1}{j!}$ is zero when $j < 0$, which is compatible with the fact that the reciprocal of the Gamma function is an entire function with zeros at nonpositive integers. Then
\begin{align*}
\sum_{k=1}^{\infty} \frac{(-1)^{k-1}}{k^{k-m}} x^{k}
&= \sum_{k=1}^{\infty} (-1)^{k-1} x^{k} \sum_{j=0}^{m} \left\{ {m+1 \atop j+1} \right\} \frac{1}{(k-1-j)!} \int_{0}^{\infty} t^{k-1}e^{-kt} \, dt \\
&= x \sum_{j=0}^{m} \left\{ {m+1 \atop j+1} \right\} \int_{0}^{\infty} \left( \sum_{k=1}^{\infty}  \frac{(-1)^{k-1}}{(k-1-j)!} \left( x t e^{-t} \right)^{k-1} \right) \, e^{-t} \, dt \\
&= x \sum_{j=0}^{m} \left\{ {m+1 \atop j+1} \right\} \int_{0}^{\infty} \left( \sum_{k=0}^{\infty}  \frac{(-1)^{k+j}}{k!} \left( x t e^{-t} \right)^{k+j} \right) \, e^{-t} \, dt \\
&= x \sum_{j=0}^{m} (-1)^{j} \left\{ {m+1 \atop j+1} \right\} \int_{0}^{\infty} \left( x t e^{-t} \right)^{j} \exp \left( x t e^{-t} \right) \, e^{-t} \, dt \\
&= \sum_{j=0}^{m} (-1)^{j} \left\{ {m+1 \atop j+1} \right\} x^{j+1} \int_{0}^{\infty} t^{j} e^{-tj} \exp \left( x t e^{-t} \right) \, e^{-t} \, dt.
\end{align*}
Here, I considered the negation of your sum in order for typographical simplicity. Anyway, with the substitution $u = e^{-t}$, we obtain
\begin{align*}
\sum_{k=1}^{\infty} \frac{(-1)^{k-1}}{k^{k-m}} x^{k}
&= \sum_{j=0}^{m} (-1)^{j} \left\{ {m+1 \atop j+1} \right\} x^{j+1} \int_{0}^{1} u^{xu} (-u \log u)^{j} \, du. \tag{1}
\end{align*}
To analyze the behavior of
$$ f_{j}(x) = x^{j+1} \int_{0}^{1} u^{xu} (-u \log u)^{j} \, du, $$
we introduce two functions $g_0 : [0, 1/e] \to [0, 1/e]$ and $g_1 : [0, 1/e] \to [1/e, 1]$ ad follows:
The graph of $y = -x \log x$ on $[0, 1]$ can be divided into two parts:

the increasing part and the decreasing part. Thus on each part, we can define the inverse function $g_0$ and $g_1$ as follows:

It is clear from the slope of the graph $y = - x \log x$ that $g_{0}'(0) = 0$ and $g_{1}' (0) = -1$. Also, obviously both $g_{0}'(y)$ and $g_{1}'(y)$ are integrable on $[0, 1/e]$. Keeping these in mind, we make the change of variable as follows:
\begin{align*}
f_{j}(x)
&= x^{j+1} \left[ \int_{0}^{1/e} e^{x u \log u} (-u \log u)^{j} \, du + \int_{1/e}^{1} e^{x u \log u} (-u \log u)^{j} \, du \right] \\
&= x^{j+1} \left[ \int_{0}^{1/e} y^{j} e^{-xy} g_{0}'(y) \, dy + \int_{0}^{1/e} y^{j} e^{-xy} (- g_{1}'(y) ) \, dy \right] \\
&= \int_{0}^{\infty} x^{j+1} y^{j} e^{-xy} \left( g_{0}'(y) \mathrm{1}_{[0, 1/e]}(y) \right) \, dy + \int_{0}^{\infty} x^{j+1} y^{j} e^{-xy} \left( - g_{1}'(y) \mathrm{1}_{[0, 1/e]}(y) \right) \, dy
\end{align*}
Here, observe that the family of mappings
$$ y \mapsto \frac{1}{j!} x^{j+1} y^{j} e^{-xy} $$
serves as an approximation to the identity as $x \to \infty$. This proves that
$$ f_{j}(x) \xrightarrow{x\to\infty} j! (g_{0}'(0) - g_{1}'(0)) = j!. $$
So taking limit $x \to \infty$ to the identity $(1)$, we obtain
\begin{align*}
\lim_{x\to\infty} \sum_{k=1}^{\infty} \frac{(-1)^{k-1}}{k^{k-m}} x^{k}
&= \sum_{j=0}^{m} (-1)^{j} \left\{ {m+1 \atop j+1} \right\} j!.
\end{align*}
But it is known that the last sum is equal to
$$ \sum_{j=0}^{m} (-1)^{j} \left\{ {m+1 \atop j+1} \right\} j! = \delta_{0m} = \begin{cases} 1 & m = 0 \\ 0 & m \geq 1 \end{cases}. $$
Therefore we have
$$ \lim_{x\to\infty} \sum_{k=1}^{\infty} \frac{(-1)^{k}}{k^{k-m}} x^{k} = -\delta_{0m}. $$
The following graphs corresponds to $m = 1, \cdots, 5$ in zigzag order.

Added. Approximation to the identity is a way of justifying the concept of the Dirac delta. Consider a family of functions $\{ K_{t}(x) \}$ (parametrized by $t$ in this example) such that
$$ \int_{\Bbb{R}} K_{t}(x) \,dx = q \quad \text{and} \quad \lim_{t\to\infty} \int_{|x|\geq \eta} K_{t}(x) \, dx = 0 \quad \text{for} \ \eta > 0. $$
That is, we cant interpret $K_{t}(x)$ as a mass density with the unit total mass such that the mass concentrates to the origin as $t \to \infty$. So it is natural to expect that $K_{t}(x)$ converges to the Dirac delta $\delta(x)$ in some sense as $t \to \infty$. The theory of approximation to the identity justifies this naive idea under various assumptions and in various mode of convergence.
In our problem,
$$ K_{x}(y) = x f(xy) \quad \text{where} \quad f(y) = \frac{y^{j}}{j!}e^{-y} \quad \text{on} \ [0, \infty). $$
Thus we expect that as $x \to \infty$,
\begin{align*}
f_{j}(x)
&= j! \int_{0}^{\infty} \left\{ g_{0}'(y) - g_{1}'(y) \right\} \mathbf{1}_{[0, 1/e]}(y) K_{x}(y) \, dy \\
&= j! \int_{0}^{\infty} \left\{ g_{0}'(y) - g_{1}'(y) \right\} \mathbf{1}_{[0, 1/e]}(y) \delta(y) \, dy \\
&= j! \left\{ g_{0}'(0) - g_{1}'(0) \right\} = j!.
\end{align*}
Indeed, some simple estimation proves this.
Comment: Wow... Thats great... Thank you so much...
Comment: could you please explain a little bit more about the $y\rightarrow \frac{1}{j!}x^{j+1}y^{j}e^{-xy}$
Comment: @Mamal, I can't grasp what you are questioning. Exactly what property of that function do you want to know?
Comment: Thank you very much, It was interesting.
Answer: For $\lim_{x\rightarrow +\infty} \sum_{k=1}^\infty (-1)^k \frac{x^k}{k^{k-m}}$,
the ratio of consecutive terms is
$\begin{align}
\frac{x^{k+1}}{(k+1)^{k+1-m}}\big/\frac{x^k}{k^{k-m}}
&=\frac{x k^{k-m}}{(k+1)^{k+1-m}}\\
&=\frac{x }{k(1+1/k)^{k+1-m}}\\
&=\frac{x }{k(1+1/k)^{k+1}(1+1/k)^{-m}}\\
&\approx\frac{x }{ke(1+1/k)^{-m}}\\
&=\frac{x (1+1/k)^{m}}{ke}\\
\end{align}
$
For large $k$ and fixed $m$,
$(1+1/k)^{m} \approx 1+m/k$,
so the ratio is about
$x/(ke)$,
so the sum is like
 $\lim_{x\rightarrow +\infty} \sum_{k=1}^\infty (-1)^k \big(\frac{x}{ek}\big)^k$.
Note: I feel somewhat uncomfortable
about this conclusion, but I will continue anyway.
Interesting how the $m$ goes away (unless I made a mistake, which is not unknown).
In the answer pointed to by Mhenni Benghorbal,
it is shown that this limit is $-1$,
so it seems that this is the limit of this sum also.
Answer: Here is a start. Using the integral representation derived in a previous problem and the identity

$$ (xD)^m=\sum_{r=0}^{m}\begin{Bmatrix} m\\r \end{Bmatrix}x^r D^r, $$

where $D=\frac{d}{dx}$ and $ \begin{Bmatrix} m\\r \end{Bmatrix} $ are Stirling numbers of the second kind.
$$\sum_{k=1}^\infty (-1)^k \frac{x^k}{k^{k}}  = - \int_{0}^{1} x \cdot u^{x u} \, du .$$
$$ \implies (xD)^m\sum_{k=1}^\infty (-1)^k \frac{x^k}{k^{k}}=\sum_{k=1}^\infty (-1)^k k^m\frac{x^k}{k^{k}}=-(xD)^m \int_{0}^{1} x \cdot u^{x u} \, du.$$

$$ \implies \sum_{k=1}^\infty (-1)^k k^m\frac{x^k}{k^{k}}=\sum_{r=0}^{m}\begin{Bmatrix} m\\r \end{Bmatrix} \int_{0}^{1} f(x,u) du , $$

where $f(x,u)$ is a function in $x$ and $u$, see the note. Now, it is your job to try analyzing these integrals and see what the limit is.
Notes:
1) We used the identity

$$ D^r xe^{ax}= {a}^{r-1}{{\rm e}^{ax}} \left( ax+r \right)  .$$

For finding the $n$th derivative, see section 6.
2)

$$ f(x, u) = { {m{x}^{2\,m} \left( \ln  \left( u \right)\right) ^{m-1}{u}^{ux+m
-1}}{ }}+{x}^{2\,m+1} \left( u\ln  \left( u
 \right)  \right) ^{m}{u}^{ux}.$$
Comment: @Benghorbal: Thnk you so much... I'll be so thankful if you tell me your concolusion about the answer of the limit:)
Comment: Thank you... :)... However analyzing theseintegrals doesn't seem be easy...
Comment: @Mamal: What you are asking is not easy too!! By the way, they should not be that hard. Check asymptotic analysis of integrals. For instance, Laplace technique. I'll have a look at them when time allows.
Comment: @Benghorbal: Yes, youre right. Thank you anyway, your answer seems to be a good start to the solution.
Comment: Using some simulations I figured that the answer is perhaps $0$, But Im not sure at all.
Comment: @Mamal: The problem is almost done. It is only left one step which is analyzing the integrals.
Comment: @benghorbal sir. May I ask a question?

What is the answer to this limit


Quando usar byte, int, long, float, decimal quando usamos Enum?

Question: Já vi em vários projetos, com formas diferentes de lidar com cast de enums, exemplo básico em .NET6:
using Teste;

int pessoaFisica = 1;
int pessoaJuridica = 2;

if((byte)TipoPessoaEnum.Fisica == pessoaFisica)
{
    Console.WriteLine("Pessoa Física");
}
if ((long)TipoPessoaEnum.Juridica == pessoaJuridica)
{
    Console.WriteLine("Pessoa Juridica");
}
if ((int)TipoPessoaEnum.Juridica == pessoaJuridica)
{
    Console.WriteLine("Pessoa Juridica");
}
if ((float)TipoPessoaEnum.Juridica == pessoaJuridica)
{
    Console.WriteLine("Pessoa Juridica");
}

namespace Teste{
    enum TipoPessoaEnum
    {
        Fisica = 1,
        Juridica = 2
    }
}

Veja que cada condição if lida de uma forma diferente, logo minha pergunta é, nesses cenários, qual é melhor usar? byte, int, long, float, decimal.
Qual desses é mais adequado usar?
Influencia no desempenho dependendo da forma que é usado?
Se tiver outras referências também, seja inglês ou português.
Comment: A resposta resolveu o que estava em dúvida? Precisa que algo mais seja melhorado? Acha que é possível aceitá-la agora?
Answer: Cast de enum é amplamente utilizado, mas é muito comum não ser adequado. Um dos motivos para o enum existir é justamente não depender do seu valor.
Se ainda for usar, e o enum vai, garantidamente, até no máximo 255 tanto faz o que vai usar, se passar disso, byte não pode ser usado, e assim por diante. Mas precisa ter certeza que isso sempre será válido, cast não pode falhar.
Se vai comparar com um int, então faz sentido usar logo um int no cast, até porque o enum também provavelmente é um int, que é o tipo padrão se não for especificado outro. Assim evita promoções implícitas, que pode não ter custo, mas dificulta o entendimento, e pode eventualmente em alguma situação gerar um valor equivocado no futuro se mudar para algo um pouco mais complexo.
Se influenciar no desempenho será algo mínimo e por razões colaterais.
Dependendo do contexto pode ter até outra solução melhor, por exemplo pegar a descrição do enum.
decimal não pode ser usado.


transfer file from Mac/Pc to ios app documents without itunes

Question: I have an app that is using itunes file sharing.I use these file to get output. So users need to  use itunes to transfer file to app documents. I'd like to know how itunes do this transfer. So I can create client app for mac/pc.
Thanks.
Answer: You should be able to solve your problem with libimobiledevice.
Open-Source and widely used.


Changing the login timeout for Windows Remote Desktop Services

Question: At our school we use thin clients that connect to a Windows 2008 R2 server using Remote Desktop Services. This works very well.
One problem we still have is the login timeout for the RDP connection. When the thin client starts up, it shows the server login screen. However, after a small amount of time (one minute or so) the RDP session disconnects and the thin client shuts down (as it is configured to do). This is a problem for teachers that are used to powering up the computer at the start of the day and logging in when they first need it.
How can we change or disable this login timeout? We have looked at the various session timeout values, but there is nothing there to help us.
Comment: There is a setting in the registry named DelayConMgrTimeout. Could this have something to do with it?
Answer: After some more searching on Google, I managed to find a solution.
The login timeout is set in the registry, with the key HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Terminal Server\WinStations\RDP-Tcp
Simply add a new DWORD value for LogonTimeout, containing the timeout value in seconds. After that, restart the Terminal Services service. (If you are connected via Remote Desktop, your session will be terminated.)
Answer: For those arriving at this post, looking for a solution with a Citrix Environment the same  value can be used in the Citrix keys:
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Terminal Server\WinStations\ICA-TCP

(or ICA-SSL , ICA-CGP etc)
Answer: This works on our windows 10 machines:

HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\TerminalServer\WinStations\RDP-Tcp

Change: SecurityLayer From: 2  To: 0
Reboot
(Should only use for internal / segregated machines for security reasons)
Comment: Looking at [documentation](https://docs.microsoft.com/en-us/windows-hardware/customize/desktop/unattend/microsoft-windows-terminalservices-rdp-winstationextensions-securitylayer) of the setting I don't see how this answer should answer the OP question, which actually was answered correctly years before by the same users which asked


Expanding $\boldsymbol \nabla\phi(\mathbf{x},t)$ where $\mathbf{x} = \mathbf{x}(\mathbf{a},t)$

Question: How does $\boldsymbol \nabla\phi(\mathbf{x},t)$ expand where $\mathbf{x} = \mathbf{x}(\mathbf{a},t))$ and $\mathbf{x} =(x_1,x_2,x_3) $ and $\mathbf{a} = (a_1,a_2,a_3)$ where $\boldsymbol \nabla = (\partial_{a_1}, \partial_{a_2}, \partial_{a_3})$?
Here $x_1 = x_1(a_1)$ etc.
$$\boldsymbol \nabla \phi = (\partial_{a_1}, \partial_{a_2}, \partial_{a_3})\phi = (\partial_{a_1}\phi, \partial_{a_2}\phi, \partial_{a_3}\phi)$$
The first component: $$\partial_{a_1}\phi = \frac{\partial \phi}{\partial \mathbf{x}}\frac{\partial \mathbf{x}}{\partial a_1}$$
but writing derivative wrt $\mathbf{x}$ is a little confusing for me.
Could anyone please clarify?
Comment: @Flewer47 You should write this as an Answer.
Comment: If this makes it clearer, we have $\phi(\mathbf{x},t)\equiv\phi(x_1,x_2,x_3,t)$. Use the chain rule to this function that takes 4 arguments.
For example,
$$\partial_{a_1}\phi=\partial_t\phi\partial_{a_1}t+\sum_{i=1}^3\partial_{x_i}\phi\partial_{a_1}x_i$$
Answer: Here's an answer taken from my comment:
If this makes it clearer, we have $\phi(\mathbf{x},t)≡\phi(x_1,x_2,x_3,t)$. Use the chain rule to this function that takes 4 arguments. For example,
$$\partial_{a_1}\phi=\partial_t ϕ\ \partial_{a_1}t+\sum_{i=1}^3\partial_{x_i}\phi\ \partial_{a_1}x_i$$
If only $x_1$ depends on $a_1$, then this expression simplifies into
$$\partial_{a_1}\phi=\partial_{x_1}\phi\ \partial_{a_1}x_1$$