Apache Velocity in Android("unable to find resource")

Question: I use this code to reach temp.vm, but I get this error. what should I change in code, file location or Mainfest
P.S.  It is new project, so I have standard Manifest
I have tried to save file in Resources, Assets and in main path
2021-05-20 17:11:27.617 17303-17303/com.example.printer E/org.apache.velocity: ResourceManager : unable to find resource '123/temp.vm' in any resource loader.
    VelocityEngine velocityEngine = new VelocityEngine();
    velocityEngine.init();
    velocityEngine.setProperty(RuntimeConstants.RESOURCE_LOADER, "classpath");
    velocityEngine.setProperty("classpath.resource.loader.class", ClasspathResourceLoader.class.getName());
    Template t = velocityEngine.getTemplate("123/temp.vm");
    VelocityContext context = new VelocityContext();
    context.put("name", "World");
    StringWriter writer = new StringWriter();
    t.merge( context, writer );

Answer: I'm not sure putting the template files in the java source tree is enough for them to be visible from the classpath. We would need to see your gradle script. Typically, resources meant to be in the classpath (by typically including them in the final jar) are located in a resources directory. In development mode, you can try to manually add the java directory to the classpath.


Um problema para resolver com expressões lambdas

Question: Fiz isso, para retornar uma lista. Acontece que dá erro, dizendo que não tem como transformar uma expressão anônima no tipo passado(objeto).
public List<Liberacao> PegaLiberacao()
        {
            var lista = contexto.Liberacoes.Join(
                contexto.ItensLibs,
                t1 => t1.IdOrcamento,
                t2 => t2.IdOrcamento,
                (t1, t2) => new { t1, t2 })
                .Where(a => a.t1.IdOrcamento == a.t2.IdOrcamento)
                .Select(lib => new
                {
                    lib.t1.TipoVenda,
                    lib.t1.Vencimento,
                    lib.t1.Juros,
                    lib.t1.Entrada,
                    lib.t1.Acrescimo,
                    lib.t1.Desconto,
                    lib.t1.Mensagem,
                    lib.t1.DataLib,
                    lib.t1.Vendedor,
                    lib.t1.Cliente,
                    lib.t1.Filial,
                    lib.t2.Produto,
                    lib.t2.Qtde,
                    lib.t2.Unitario,
                    lib.t2.Custo,
                    lib.t2.CustoDiario,
                    lib.t2.UltCondicao,
                    lib.t2.Total
                }).ToList();

            return lista;
        }

E o erro é esse, ao retornar a minha lista:

EDIT1:
Essa é a minha model:
public class Autoriza
    {
        InetContext contexto = new InetContext();
        Liberacao liberacao = new Liberacao();

        public List<Liberacao> PegaLiberacao()
        {
            var lista = contexto.Liberacoes.Join(
                contexto.ItensLibs,
                t1 => t1.IdOrcamento,
                t2 => t2.IdOrcamento,
                (t1, t2) => new { t1, t2 })
                .Where(a => a.t1.IdOrcamento == a.t2.IdOrcamento)
                .Select(lib => new Liberacao
                {
                    TipoVenda = lib.t1.TipoVenda,
                    Vencimento = lib.t1.Vencimento,
                    Juros = lib.t1.Juros,
                    Entrada = lib.t1.Entrada,
                    Acrescimo = lib.t1.Acrescimo,
                    Desconto = lib.t1.Desconto,
                    Mensagem = lib.t1.Mensagem,
                    DataLib = lib.t1.DataLib,
                    Vendedor = lib.t1.Vendedor,
                    Cliente = lib.t1.Cliente,
                    Filial = lib.t1.Filial
                }).ToList();

            return lista;
        }

        public List<ItensLib> PegaItensLib()
        {
            var lista = contexto.ItensLibs.Join(
                contexto.Liberacoes,
                t1 => t1.IdOrcamento,
                t2 => t2.IdOrcamento,
                (t1, t2) => new { t1, t2 })
                .Where(a => a.t1.IdOrcamento == a.t2.IdOrcamento)
                .Select(itens => new ItensLib
                {
                    Produto = itens.t1.Produto,
                    Qtde = itens.t1.Qtde,
                    Unitario = itens.t1.Unitario,
                    Custo = itens.t1.Custo,
                    CustoDiario = itens.t1.CustoDiario,
                    UltCondicao = itens.t1.UltCondicao,
                    Total = itens.t1.Total
                }).ToList();

            return lista;
        }
    }

Aqui vai
[Table("LIBERACAO")]
    public class Liberacao
    {
        [Key]
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        [Column("ID_LIBERACAO")]
        public int IdLiberacao { get; set; }
        [Column("FLAG_LIBERACAO")]
        public byte FlagLiberacao { get; set; }
        [Column("ID_ORCAMENTO")]
        public float IdOrcamento { get; set; }
        [Column("ID_VENDEDOR")]
        public int IdVendedor { get; set; }
        [Column("VENDEDOR")]
        public string Vendedor { get; set; }
        [Column("ID_FILIAL")]
        public int IdFilial { get; set; }
        [Column("FILIAL")]
        public string Filial { get; set; }
        [Column("DATALIB")]
        public float DataLib { get; set; }
        [Column("HORALIB")]
        public float HoraLib { get; set; }
        [Column("ID_CLIENTE")]
        public int IdCliente { get; set; }
        [Column("CLIENTE")]
        public string Cliente { get; set; }
        [Column("TIPO_VENDA")]
        public string TipoVenda { get; set; }
        [Column("JUROS")]
        public float Juros { get; set; }
        [Column("DESCONTO")]
        public float Desconto { get; set; }
        [Column("VENCIMENTO")]
        public float Vencimento { get; set; }
        [Column("ACRESCIMO")]
        public float Acrescimo { get; set; }
        [Column("ENTRADA")]
        public float Entrada { get; set; }
        [Column("PRAZO")]
        public float Prazo { get; set; }
        [Column("TOTAL_LIQUIDO")]
        public float TotalLiquido { get; set; }
        [Column("MIN_TOTAL")]
        public float MinTotal { get; set; }
        [Column("USUARIO")]
        public string Usuario { get; set; }
        [Column("CUSTODIARIO")]
        public decimal CustoDiario { get; set; }
        [Column("MAX_COMI")]
        public decimal MaxComi { get; set; }
        [Column("VALOR_COMI")]
        public decimal ValorComi { get; set; }
        [Column("NOVA_COMI")]
        public decimal NovaComi { get; set; }
        [Column("MENSSAGEM")]
        public string Mensagem { get; set; }
        [Column("Menssagem_RET")]
        public string MensagemRet { get; set; }
        [Column("DataRetorno")]
        public decimal DataRetorno { get; set; }
        [Column("HoraRetorno")]
        public decimal HoraRetorno { get; set; }
        [Column("TempoProcesso")]
        public decimal TempoPrecesso { get; set; }
        [Column("Tipo")]
        public int Tipo { get; set; }
        [Column("PROGRAMA")]
        public string Programa { get; set; }
        [Column("NOME_PC")]
        public string NomePc { get; set; }
        [Column("NOME_PROCEDURE")]
        public string NomeProcedure { get; set; }
        [Column("Perc_Juros_Total")]
        public decimal PercJurosTotal { get; set; }
        [Column("FLAG_CULTURAVENCIDA")]
        public byte FlagCulturaVencida { get; set; }
        [Column("CULTURA")]
        public string Cultura { get; set; }
        [Column("CULTURA_VCTO")]
        public int CulturaVcto { get; set; }
        [Column("FLAG_PRORROGADO")]
        public byte FlagProrrogado { get; set; }
        [Column("VALOR_PRORROGADO")]
        public decimal ValorProrrogado { get; set; }
        [Column("DIAS_ATRASO")]
        public int DiasAtrazo { get; set; }
        [Column("ID_VENDEDOR2")]
        public int IdVendedor2 { get; set; }
        [Column("VENDEDOR2")]
        public string Vendedor2 { get; set; }
        [Column("COMISSAO_VEND2")]
        public decimal ComissaoVend2 { get; set; }
        [Column("FLAG_COTACAO")]
        public byte FlagCotacao { get; set; }
        [Column("TipoVenda")]
        public string TipoVenda1 { get; set; }
        [Column("Flag_Receber_Atrasado")]
        public byte FlagReceberAtrazado { get; set; }
        [Column("Autorizou_Receber_Atrasado")]
        public string AutorizouReceberAtrazado { get; set; }

EDIT2:
Alterei para essa forma e funcionou
public IEnumerable<object> getAutoriza()
        {
            var lista = contexto.Liberacoes.Join(
                contexto.ItensLibs, lib => lib.IdOrcamento, itens => itens.IdOrcamento, (lib, itens) => new { lib, itens })
                .Where(a => a.lib.IdOrcamento == a.itens.IdOrcamento)
                .Select(libera => new
                {
                    libera.lib.TipoVenda,
                    libera.lib.Vencimento,
                    libera.lib.Juros,
                    libera.lib.Entrada,
                    libera.lib.Acrescimo,
                    libera.lib.Desconto,
                    libera.lib.Mensagem,
                    libera.lib.DataLib,
                    libera.lib.Vendedor,
                    libera.lib.Cliente,
                    libera.lib.Filial,
                    libera.itens.Produto,
                    libera.itens.Qtde,
                    libera.itens.Unitario,
                    libera.itens.Custo,
                    libera.itens.CustoDiario,
                    libera.itens.UltCondicao,
                    libera.itens.Total
                }).ToList();

            return lista;
        }

Answer: Altere o Select para
.Select(lib => new Liberacao
{
    TipoVenda = lib.t1.TipoVenda,
    // e assim por diante
}

Obviamente isso só vai funcionar se você realmente for devolver uma lista de Liberacao.
Comment: O problema é que eu tenho duas entidades(Liberacao e ItensLib) e o new é apenas um(Liberacao). Como eu coloco no select a outra entidade?
Comment: Como eu disse, o objeto **tem que ser** do tipo `Liberacao`, senão não faz sentido tentar devolver uma lista deste tipo.
Comment: Não resolveu meu problema. Dá esse erro: `1>C:\Labs\AutorizadorService\AutorizadorService\Models\Autoriza.cs(25,21,25,30): error CS0200: Property or indexer 'Liberacao.TipoVenda' cannot be assigned to -- it is read only
` Isso aco tece para todos os campos.
Comment: Bom, eu não tenho como adivinhar o que está acontecendo. Poste o model que eu tento ajudar.
Comment: Não, jovem. Eu preciso ver o modelo `Liberacao`


Can Cramér's V be used an effect size measure for McNemar's test?

Question: I'm using McNemar's exact test (with R's "mcnemar.exact" function). I know that giving the odds ratio or proportion would be an adequate measure of effect size (Effect size of McNemar's Test), but I was explictly asked to report Cramér's V. Is Cramér's V adequate in this (repeated measures) situation?
Pointers to R code would also be greatly appreciated.
If anyone needs more details: The same subject is measured twice, with a binary outcome in both cases. I'm interested in the difference in the probability of "true" between both measurements. Counts are rather small, e.g.:
           trial 2
trial 1  True  False
  True      9     10
  False     0      6

Answer: Cramér's $V$ doesn't correspond well to what is tested by McNemar's test.
Edit: Disclosure: the webpage and R package cited below are mine.
Probably the most common effect size statistic for McNemar's test is odds ratio, though Cohen's $g$ could be used.  Cohen (1988) also uses a statistic he calls $P$.
For defintions, quoting from here:

Considering a 2 x 2 table, with $a$ and $d$ being the concordant cells and
  $b$ and $c$ being the discordant cells, the odds ratio is simply the greater of $(b/c)$ or $(c/b)$, and $P$ is the greater of $(b/(b+c))$ or $(c/(b+c))$.  Cohen's $g$ is $P – 0.5$.

Cohen (1988) also gives interpretations ("small", "medium", "large") for his $g$ statistic.  Because $g$ is monotonically related to odds ratio, these interpretations can be extended to the odds ratio (same link).  Edit: Interpretations of effect size statistics are always relative to the field of study, specific experiment, and practical considerations.  Cohen's interpretations should not be considered universal.
Obviously, not much coding is needed to calculate any of these statistics for the 2 x 2 case.  However, if they are extended to larger tables, the math can get tricky.  In R, the cohenG() function in the rcompanion package makes this relatively easy.
Links include R code.

Reference:
Cohen, J. 1988. Statistical Power Analysis for the Behavioral Sciences, 2nd Edition. Routledge.
Comment: Would you want to tackle [this old Q](https://stats.stackexchange.com/q/468593/)?  I think the answer is McNemar-Bowker, & if I answered, I would primarily cite your book, based on Googling.
Answer: In the context of a 2x2 table, Cramer's $V$ is equivalent to the phi coefficient.  Moreover, phi is equivalent to Pearson's product moment correlation of the two columns of $1$'s and $0$'s when the 2x2 table is disaggregated.  That corresponds to a different magnitude than the one that McNemar's test is testing.  So, no, I don't think it is a good choice.
With McNemar's test, you are comparing two marginal proportions (in your case, $76\%$ true before, and $36\%$ true after).  Presenting the complete table is pretty easy, as it's just four numbers.  But it may be psychologically helpful to present those proportions and whatever magnitude derived from them makes the most sense to people in your field (e.g., the odds ratio).  You could even explicitly refer to the cells that are used by McNemar's test.  For instance:

There were 10 cases where people changed their minds; in all such cases, people switched from true to false.


Proof of Real Number Property

Question: In his introduction to Calculus, Apostol gives a foundation for the properties
 of real numbers. After laying down the field and order axioms but before stating the least-upper-bound axiom, the author uses the set $T = \{x \ : \ 0 \leq x < 1\}$ as an example of a set which has no maximum element, yet has a least-upper-bound, namely, 1.
Is the author relying on intuition to make these assertions, or can we really prove these statements even before introducing the least-upper-bound axiom?
Answer: The least upper bound axiom is not needed to prove that this specific, concretely-given set of real numbers has a least upper bound: all that's needed is to prove that $x<1$ for each $x\in T$, which is a matter of definition, and that if $u<1$, then there is an $x\in T$ such that $u<x$. The latter can be done by taking $x=\frac12(u+1)$: that $u<x<1$ can be proved from the field and order axioms.
Answer: Certainly $T$ has an upper bound, namely $1$. Now to show that $1$ is the least upper bound, let $a$ be any upper bound of $T$. Can $a$ be less than $1$? No because $T$ contains elements arbitrarily close to $1$, i.e. for any $x < 1$ there is an element $y \in T$ such that $x < y$ which is to say that $x$ is not an upper bound for $T$. Therefore the upper bound $a$ is greater than or equal to the upper bound $1$, and since $a$ was arbitrary we conclude that $1$ is the least upper bound of $T$.
Note that the exact same argument works for $T' = \{x \in \mathbb Q \mathrel| 0 \leq x < 1\}$ even though $\mathbb Q$ doesn't have the least upper bound property.
The least upper bound property of $\mathbb R$ is there to guarantee least upper bounds of "weird" sets like $T_\xi = \{r \in \mathbb Q \mathrel| r < \xi\}$. Those sets don't have least upper bounds in the rationals when $\xi$ is irrational, but they do in the reals.
Comment: Alas, the proof of that statement is the very point of my question.
Comment: While your answer is helpful, you state "for any x<1 there is an element y∈T such that x<y" without proving it.
Comment: @IsaacKleinman no, I deliberately left that out. I didn't want to write everything out in painstaking detail.

Proof of Real Number Property


Diminuir horas php

Question: Estou tendo problema para tratar a hora para diminuir ele em php.
Minha ideia pegar a hora que vem do banco de dados e diminuir com a hora atual e trazer o restante , porem n estou conseguindo.
codigo que estou usando como exemplo:
<code>$results =DB::select("SELECT HoraCriacao FROM partidas WHERE (Aceitou=2) ORDER by Id desc LIMIT 1 ");
                foreach($results as $row){
                    $Hroin=$row->HoraCriacao;
                }
                $Hroin =  strtotime($Hroin);
                $Hroin=date('H:i:s',$Hroin);
                $Hroin=date_create($Hroin);
                $Horat= date('H:i:s');
                $Horat = explode(":", $Horat);
                date_sub($Hroin, date_interval_create_from_date_string($Horat[0].' hours'));
                date_sub($Hroin, date_interval_create_from_date_string($Horat[1].' minute'));
                date_sub($Hroin, date_interval_create_from_date_string($Horat[2].' second'));
                $Hroin=date_format($Hroin, 'H:i:s');
                $Hroin = explode(":", $Hroin);
                $banco=[
                    "mod" => "3",
                    "cron" => "$Hroin[0]:$Hroin[1]:$Hroin[2]"
                ];
                return response()->json($banco);
</code>
Comment: Amigo por favor tenta explicar melhor, porque está muito confuso o seu código e não consegui entender a sua necessidade.
Comment: No Banco de dados tem uma hora do evento de quando foi criado exemplo :
`$horain="14:40:00" ;` ai quero diminuir com a hora atual
`$horaat="14:50:00";` ai quero pegar a diferença
Comment: Está usando Laravel? Esse `DB::select` é familiar
Comment: @KayoBruno, ai ele teria que voltar o resto tipo 00:10:00
Comment: @WallaceMaxters, sim estou sei bem pouco do laravel
Comment: Faltou colocar a tag então, hein
Comment: Coloquei abaixo uma resposta de como calcular a diferença entre datas. Vê se te ajuda em algo.
Comment: Cara, eu sempre procuro utilizar o https://carbon.nesbot.com/docs/ para manipulação de datas no Laravel
Answer: Não consegui entender muito bem o que você quer, mas se está precisando calcular a diferença entre datas, você pode utilizar a classe DateTime do PHP.
<code><?php

$data_one = new DateTime( '2018-06-11 12:00:00' ); // Pode ser a data que vem do seu banco
$data_two = new DateTime(); // Se você não passar nenhum parâmetro, ele pega a data atual
$interval = $data_one->diff( $data_two ); // Calcula a diferença entre as duas datas

echo '<pre>';
print_r( $interval );
die;

# Retorno do print_r
DateInterval Object
(
    [y] => 0
    [m] => 2
    [d] => 8
    [h] => 21
    [i] => 50
    [s] => 20
    [weekday] => 0
    [weekday_behavior] => 0
    [first_last_day_of] => 0
    [invert] => 0
    [days] => 69
    [special_type] => 0
    [special_amount] => 0
    [have_weekday_relative] => 0
    [have_special_relative] => 0
)
</code>
Com isso você tem a diferença entre as datas de ano, mês, dia, hora, minuto e segundo.

Diminuir horas php


Python while loop with one condition issue

Question: I am learning Python and was doing an exercise with the while loop statement and got confuse on why it works the way it does. For an exercise, I have to code a basic guessing game where u had three trys to guess a word. I know that in order to run the while loop statement, the condition has to be true. When I did the exercise, I had one condition expression in my while loop code and when I ran it, it didn't work. it seems like it didn't understand that my variable "out_of_gussess" was now true. I originally coded this:
secret_word = "giraffe"
guess = ""
guess_count = 0
guess_limit = 3
out_of_guesses = False

while guess != secret_word:
    if guess_count < guess_limit:
        guess = input("Enter guess: ")
        guess_count += 1
    else:
         out_of_guesses = True

if out_of_guesses:
    print("out of guesses, You lose!")

else:
    print("You Win!")

When I ran the code, and wasn't able to guess the word within the three attempts, my whole code breaks.
If I change the code like this below:
secret_word = "giraffe"
guess = ""
guess_count = 0
guess_limit = 3
out_of_guesses = False

while guess != secret_word and out_of_guesses != True:
     if guess_count < guess_limit:
         guess = input("Enter guess: ")
         guess_count += 1
     else:
         out_of_guesses = True

if out_of_guesses:
    print("out of guesses, You lose!")

else:
    print("You Win!")

The code rans normally without breaking and gives me an output of I lose or win depending if I guessed it or not. I am trying to understand why do I need to have my variable "out_of_gusses" to be part of the while loop condition in order for my code to work?
Comment: in your original code, the only condition that will cause the `while` loop to exit is if guess == secret_word.    If you replaced `out_of_guesses == True` with `break`, then that would force the loop to stop.
Comment: Your code doesn't "break", it just keeps repeating an infinite loop, because it has no reason to end the while loop.
Comment: Note that if guess_count >= guess_limit, is not going to ask you anymore to input the guess. So you get not output.
Answer: Your while loop in the first code snippet doesn't have a case that checks to see if the guess limit has been reached so when you make your third guess and it is incorrect, the while loop sees that your guess is incorrect and then once inside the while loop it sets out_of_guesses to True because guess_count is no longer less than guess_limit then repeats the loop infinitely because the guess is always wrong which never allows it to move past the while loop and get to tell the user whether they were right or wrong.
Your second code snippet has that condition that checks out_of_guesses which stops the loop after it's been set to True.
Comment: Thank you for the explanation, after reading your comment I can see why my code didn't work, I didn't know I was in an infinite loop in my first code snippet.
Answer: In the first version your program enters into an endless loop (the program enter the else section again and again). If you want to use the first version you must exit the loop after the else.
try this:
secret_word = "giraffe"
guess = ""
guess_count = 0
guess_limit = 3
out_of_guesses = False

while guess != secret_word:
    if guess_count < guess_limit:
        guess = input("Enter guess: ")
        guess_count += 1
    else:
        out_of_guesses = True
        break

if out_of_guesses:
    print("out of guesses, You lose!")
else:
    print("You Win!")

Comment: thanks I didn't think of using the break statement and also that I was in an infinite loop.


Is Drupal forum module suitable for a massive forum

Question: If I use the Drupal forum module (not the advanced forum module) to create a forum website (30 replies per page) and if the forum grew to a massive forum, will this module decrease the performance?
Drupal is caching the comments separately, will that going to be a problem?
Comment: Hi, I've removed the bit about asking for a list of pros and cons; that's not the sort of thing we deal with here as it'd difficult to keep responses objective
Answer: It depends on how 'massive' is your forum, what level of control you expect to have on the forum and how powerful and well configured is your server. There are Drupal forums with couple of hundred thousand users that work kind of fine, but if your main goal is to have a large and capable forum, you get much better performance and features out of specialized forum software like VB.
While Drupal forum provides rudimentary functionality, you will have hard times attaining many common specialized forum features like assigning different moderators to each forum, post thanks (which exists in D6 but not in D7), merging threads, banning users for certain amount of time, limiting posts/threads per day, and the list goes on and on.
The only pros that I can think of is integration to Drupal core, which makes sense only if you already have a Drupal site.
Answer: Try discourse, the best forum platform :).
If you don't mind running a server with a slightly different tech stack, its definitely worth it. Lots if interesting thoughts behind a great technology and a good team & community with a mission to repair the way forums work :).
There have been some attempts of integrating it with Drupal, I haven't followed for a while, but it is feasible.


How to use a referenced entity's values in a TableSort?

Question: I have a custom entity with a field which is defined as follows.
$fields['file'] = BaseFieldDefinition::create('file')
  ->setDescription('Reference to the built-in core File entity type.')
  ->setLabel('File')
  ->setRequired(TRUE)
  ->setSetting('file_extensions', 'pdf rtf doc docx')
  ->setSetting('max_filesize', '20MB')
  ->setSetting('description_field', TRUE)
  ->setDisplayOptions('form', ['type' => 'file'])
  ->setDisplayOptions('view', ['type' => 'file']);

I have no problem getting to the fields of the referenced File entity from instances of my own entity type. So for example, these lines work as expected.
$filename = $my_entity->file->entity->filename->value;
$username = $my_entity->file->entity->uid->entity->name->value;

When I try to use the fields of the referenced File entity with a TableSort, which I want to plug into an entity query on my custom entity type, the code throws an exception.
$header['name'] = [
  'data' => 'File Name',
  'field' => 'file.entity.filename',
  'specifier' => 'file.entity.filename',
];
$header['user'] = [
  'data' => 'Uploaded By',
  'field' => 'file.entity.uid.entity.name',
  'specifier' => 'file.entity.uid.entity.name',
];

// …

$query->tableSort($header);

Uncaught PHP Exception Drupal\Core\Entity\Query\QueryException: "'file' not found"

For the syntax of the $header array I'm largely relying on clues I got from Tablesort with EntityQuery, in which Berdir recommends that we look at the load() and buildHeader() methods of the UserListBuilder class. Unfortunately, that example appears to be using field values which are stored directly in the base table, so I'm falling back on the assumption that, since we're in entity query land, the same syntax described in QueryInterface::condition() would be expected.
I've looked at a number of the open issues, such as Table sort ignores "field", always adds header title as order query parameter and Tablesort cleanup, but I didn't see anything which shed any light on the problem.
Comment: It's definitely supported with the syntax you're using, as this works fine for nodes using e.g. `uid.entity.name` as the specifier. Have you had any trouble installing this file field? Or maybe changed it after installation? Changed the cardinality, that sort of thing?
Comment: @Clive - No problems installing the field, and no modification have been made to its configuration. I can populate the field perfectly well when creating or updating the entities, and can get to any of the field's properties using the standard entity field access syntax. Should I file a bug report (with a repro case), do you think?
Comment: I'm not sure if it's a bug or just something undocumented, there is a syntax which works for base file fields. I put an answer in but I'll hopefully update it when I have time to find out more
Comment: @Clive - First of all, I'm _very_ impressed that you figured this out. I have updated my [bug report](https://www.drupal.org/project/drupal/issues/3278083) to reflect this new information. Short version: it's a bug in the documentation or the software, and I believe the stronger case can be made for making the software conform to the syntax currently documented for _any_ core reference field type. I'm accepting your brilliant answer, even before you've had a chance to update it.
Answer: There's a bug in core, and for the time being a workaround is:
'specifier' => 'file.target_id.entity.filename',

The reason for this is the entity query relationship syntax started out as join support, it predates the entity reference support in core and as such while $entity->file->target_id->entity is not supported by core, file.target_id.entity is supported by entity query to indicate it should join the entity specified by the file field and the entity id should be what is specified by target_id. It's a bit clunky but at the time, it was what worked.
It should be able to figure out file.entity.filename as well because the main property name for the file field happens to be target_id and so it is able to expand it for you into file.target_id.entity.filename. However, the class in case Drupal\Core\Entity\Query\Sql\Tables is extremely convoluted and this expansion has a bug for the shared table case which will be fixed in https://www.drupal.org/project/drupal/issues/3278083
Comment: So you're suggesting it's the documentation which needs to be fixed, not the code? Wouldn't be the first time.
Comment: I'm accepting your excellent answer, though I'm not sure I understand what you mean in your explanation. I have countless examples of entity reference conditions in entity queries which rely on a reference field stored in the base table, and they work just fine with the documented syntax.
Comment: Yeah vanilla entity reference as a base field seems to work as you'd expect. If I was a betting man, without looking properly I'd say it's probably because the base entity reference field only has a single DB column (`target_id`), so there would be no need for the syntax to support the "sub-fields"; the `fieldname__target_id` column can be inferred (sub-fields is likely NOT an official term by the way :) ). File fields have 3 DB columns, so queries need to be told explicitly which `file__*` column in the base table needs to be used, hence the other syntax. Could still be something else though
Comment: Found it - `DefaultTableMapping::getFieldColumnName()` is the smoking gun. If a field has only one column, its DB column name is the name of the field. So an entity reference field with an ID of `uid`, has a DB column named `uid`. When you query for `uid.entity.*`, there's a straight match on the DB column name and everything's fine. When a field has more than one column, the DB columns are named `fieldname__property_name`, so when you query for `fieldname.entity`, there's no matching `fieldname` DB column. The extended syntax is there to bridge that gap and let you select the right column
Comment: Thanks for this excellent spelunking. I'll include a link to this page from the bug report.
Comment: This is a workaround which works but it is not the cause for `fieldname.entity.propertyname` not to work. The cause is that if 1) a field with multiple columns 2) is stored in the shared table 3) and is used in a query where specifiers follow the field name -- then the table mapping code is not called at all. There's a bug in Tables. I left an answer and filed a patch. Also, "the system simply doesn't know what file is." it certainly knows, it's a field. The code just doesn't call `$sql_column = $table_mapping->getFieldColumnName($field_storage, $column);` this is very rare edge case.
Comment: @Smartsheeteng Indeed, a bug could easily be the reason that _the system simply doesn't know what file is_ at that point (which it doesn't, the table mappings don't contain `file`, they contain `file__*`)
Comment: @Clive the system does know what file is, it's a field. You are looking at the wrong class, the bug is in Tables not the mapping class. The very bug is that class is not called in the first place for this specifier. This answer is fully wrong, I will edit it and delete mine because it's superflous.
Comment: @Smartsheeteng I didn't realise you wrote the original code, so fair enough, answer edited
Answer: The failure described above appears to be the result of a bug in the FileItem plugin. Even though the field type plugin claims it is an entity reference (the @FieldType annotation says category = @Translation("Reference")), and in all other respects that is true, the support for the documented entity query syntax is broken.
Until the bug is fixed, the workaround would be to give up the specialization implemented by the FileItem field type and use a plain entity_reference field instead. With that change the TableSort code above works correctly.


Como fornecer mais dados corretamente à um FlatList?

Question: Estou construindo um aplicativo em React Native usando os serviços do Firebase e Redux. A cada dia, vou cadastrando novos Documentos lá e assim meu banco de dados vai ficando maior.
No meu app eu estava dando um resgatando todos registros de uma coleção do Firebase ao abrir uma espécie de tela "Feed". Eu sabia que eventualmente teria que implementar uma paginação do código. Então, recentemente atingi ~35 registros no DB e as coisas ficaram estranhas: O aplicativo nem sempre carregava todos os registros, e quando carregava, ele não permitia toque no renderItems do FlatList.
Aqui o código do meu FlatList:
<FlatList
      ListHeaderComponent={/*irrelevante*/}
      data={this.props.locals}
      keyExtractor={item => item.id}
      renderItem={this.renderLocal}
/>

this.renderLocal
renderLocal = ({item, index}) => {
    return <Local {...item} goToLocal={() => this.goToLocal(item.id)}/>
}

Importante mencionar: o componente Local que é renderizado várias vezes pela FlatList, é "pesado" uma vez que contém certa estilização, duas imagens carregadas através de URI e duas imagens armazenadas localmente.
Então eu comecei o processão de criar uma paginação, fazendo algumas coisas:

Criei o paginationIndex e inseri ele dentro do state em um reducer com valor de 15.
Dei slice(0, this.props.paginationIndex) no array da propriedade data no FlatList. Optei por fazer
assim pela expectativa de meu banco de dados conter algo como 200
registros no máximo, o que seria leve ao resgatar todos e inserir no
Reducer.
Criei um botão que dá um dispatch que aumenta em 15 o paginationIndex.
Tornei o meu componente Local em um PureComponent, para melhorar a performance com o FlatList

E o comportamento resultante foi sempre o mesmo: no inicio ele carrega os 15 componentes, ao clicar no botão de paginação, às vezes outros 15 aparecem mas tudo trava (como descrito no segundo parágrafo). Tentei fazer alterações para perceber o limite disso. Buscando 15 inicialmente, com uma paginação incrementando mais 10 componentes, funciona, só que na próxima paginação (que iria resultar em um total de 35 componentes) o mesmo erro ocorre.
A conclusão que tive, é que o FlatList tem essa limitação de renderização. Mas não consigo passar por ela, pra ter o efeito de "Infinite Scroll" como visto no Instagram, por exemplo.
Minha dúvida então, fica em como fazer para criar esse Infinite Scroll de forma correta.
Segue o link de algumas discussões sobre problemas semelhantes, onde tentei algumas soluções propostas, sem resultado.
https://github.com/facebook/react-native/issues/20011
https://github.com/facebook/react-native/issues/13649
Comment: https://github.com/Flipkart/recyclerlistview usa essa lib, ela é extremamente perfomatica.
Answer: Supondo que no seu backend você já tenha feito um controle de paginação e que tenha  uma chamada para retornar o total de registros.
Tendo isso em mente você teria que controlar alguns estados:

Número total de Registros.
Os Registros.
A paginação.
Chama para carregar mais itens.

Vamos nomeá-las e definir seus estados iniciais aqui:
 const [registers, setRegisters] = useState([]);
  const [total, setTotal] = useState(0);
  const [page, setPage] = useState(1);
  const [loading, setLoading] = useState(false);

detalhe a paginação que deve ser iniciada com o número 1 pois não existe pagina 0
então iniciamos fazendo uma chamada para carregar os dados ao iniciar a tela
useEffect(() => {
    loadRegisters();
  }, []);

a funcção chamada a cima será responsavel para carregar novos itens no FlatList desse jeito alterando os estados no momento que o componente é renderizado e quando for nescessario carregar mais itens.
async function loadRegisters() {
    if (loading) {
      return;
    }

    if (total > 0 && registers.length === total) {
      return;
    }

    setLoading(true);

    const response = await api.get("registers", {
      params: { page },
    });

    setRegisters([...registers, ...response.data.registers]);
    setTotal(response.headers["x-total-count"]);
    setPage(page + 1);
    setLoading(false);
  }
explicando a função loadRegisters:
primeiro ao iniciar o componente, será feito uma requisição api de seu backend trazendo os registros com sua devida paginação e o total de registros existente. Fazendo que aplicação busque apenas uma pagina por vez.
  const response = await api.get("registers", {
      params: { page },
    });

então é definimos o estado deles:
 setRegisters(response.data.registers);
 setTotal(response.headers["x-total-count"]);

isso é suficiente para iniciar seu componente, mas precisamos alterar a informação sempre que nescessario. Então sempre que o usuário pedir para trazer mais itens:

Fazemos uma restrição para que se o usuário pedir para trazer mais itens repetitivamente ele não acione afunção enquanto ela esta ativa.
  if (loading) {
      return;
    }
Após isso é feito uma segunda triagem que define se todos os registros ja foram carregados que ele não busque mais registros, pois não faria sentido fazer.

 if (total > 0 && registers.length === total) {
          return;
        }

Se a função passar pelos dois if's nós setamos o estado de busca para TRUE assim impedindo novas chamadas desnecessaris.
 setLoading(true);
Então é feito novamente a chamada api para trazer novas informações e setamos elas.
atenção apra alguns detalhes
 const response = await api.get("registers", {
      params: { page },
    });

é passado nos parametros da requisição o número da pagina que queremos.
 setRegisters([...registers, ...response.data.registers]);

setamos os registros como um array, passando os registros ja setados e os novos que estão vindo, a forma que foi espresada essa ação é a forma de setar 2 vetores dentro de 1 vetor no React ou React Native.(os 3 pontinhos descrevem a função copiar)
setPage(page + 1);

isso faz com que passamos para a proxima pagina
setLoading(false)

e agora liberamos para que o usuário busque novamente os dados
Agora no FlatList será precisso adicionar algumas propriedades primeiro temos a onEndReached que é uma função que é ativada automaticamente sempre que o usuário chegue no final da pagina:
<FlatList
      ListHeaderComponent={/*irrelevante*/}
      data={this.props.locals}
      keyExtractor={item => item.id}
      renderItem={this.renderLocal}
      onEndReached={loadIncidents}
/>

bonus: Caso queira que seja renderizado novos registros antes de o usuário chegar no fim temos a propriedade onEndReachedThreshold que é passada um numero flutuante dizendo quantos % antes do de chegar ao final deve ser trazido novos registros, exemplo: 0.1 = 10%, 0.2 = 20% antes do final e assim por diante. ficaria algo assim
<FlatList
      ListHeaderComponent={/*irrelevante*/}
      data={this.props.locals}
      keyExtractor={item => item.id}
      renderItem={this.renderLocal}
      onEndReached={loadIncidents}
      onEndReachedThreshold={0.2}
/>


About Harmonic Intervals. Can the notes have different sizes?

Question:
I need to convert a MIDI file to a sheet-like structure. In the MIDI for the duration of the C#7 (dotted-quarter) the E6 plays twice (dotted-eighth and eighth) and the F#6 plays once (sixteenth).
If it helps. While the C#7 plays the sequence occurs : {E6(1/8*) ; F#6(1/16) ; E6(1/8)}
What I don't understand is the dotted-quarter duration of the C#7 note, every other note happens as noted in the sheet.
So what I want to know is if the notes in a Harmonic Interval can have different times, and how would I count it. And if the dotted-quarter duration is correct, how do I identify it?
PS: The time signature of this measure is 12/8
Answer: The accepted answer is the correct answer to the question you asked, but your MIDI file isn't very accurate.
This is from the last movement of "Spring" in Vivaldi's "Four Seasons", and the original notation was like this:

The full score is here, if you have any more problems: http://imslp.org/wiki/Violin_Concerto_in_E_major,_RV_269_(Vivaldi,_Antonio)
Playing the C sharp as a full dotted-quarter on a real violin would be pointlessly difficult - Vivaldi knew what he was doing when he wrote the C sharp as an 8th note.
Answer: You've presumably got a double stop going here on the A and E strings at the second position. Yes, they sound at the same time, and you'll notice that the two voices actually take the same amount of time sounding together, a dotted crotchet (quarter note), although the lower voice breaks the dotted crochet into smaller pieces. If we notate it slightly differently, the relationship between the voices becomes clear:

You'll note that the metre of 12/8 is preserved. (Normally, the passage would be notated with up- and down-stems for the first beat, and the rests would omitted.)


Drupal 7 login form redirect back to page which they logged in on

Question: $node->content['my_form'] = drupal_get_form('user_login');

I am creating a form that as outputted on http://site.com/datacollection/the-data-collection
When the user successfully logs in they are redirected to users/USERNAME
In drupal 6, the user would be redirected to the same page they logged in from...How can I reproduce this behavior?
Comment: have you tried drupal_get_form('user_login_block') instead?
Comment: That worked great, that is actually what I used to solve the problem, maybe you can put an answer in so I can accept it.
Answer:
Create a action (admin/config/system/actions)

You have to use the token module and find the right token for the needed path. (Maybe someone else can point the right token for this behavior.)

Create a trigger (admin/structure/trigger/user)

AFTER A USER HAS LOGGED IN -> redirect to the path
Answer: There always a hook for that :)
_user_login(&$edit, $account)
This hook is called just after a user log in. So you can make a drupal_goto('') if you want.
Answer: If you're creating a form, you should just be able to set $form_state['redirect'] to the appropriate path in your submit handler. That's what user_login is doing. Just make sure its submit handler runs before yours.
Answer: As Jimajamma pointed out, the user_login_block form logs the user in and leaves them on the same page.  But the form is different from the normal login form.
If you want to present the normal login form on your page, and avoid the redirect, and leave the form on user/login unchanged, then the best way is probably to create your own login form which looks and behaves like the user_login form except for the redirect.  This snippet creates such a form:
function custom_user_login_form($form, &$form_state) {
  $form = user_login($form, $form_state);
  $form['#submit'][] = 'user_login_submit';
  $form['#submit'][] = 'custom_form_submit_redirect_current_path';
  return $form;
}

function custom_form_submit_redirect_current_path($form, &$form_state) {
  $form_state['redirect'] = current_path();
}

Then, you would change the form id in your code:
$node->content['my_form'] = drupal_get_form('custom_user_login_form');


Starting an activity as a Thread?

Question: I'm currently struggling to create a mobile (Android) version of a "battleship" program I recently coded. While my GUI is finished by now and most parts of the program should work, I have (at least) one main problem left: the main part of my program besides the server part (which will react to user input, etc.) relies on Java NIO, i.e. network access. However, since it's running on the main thread, I receive
java.lang.RuntimeException: Unable to start activity ComponentInfo{x.battleship/x.battleship.BattleshipMain}: android.os.NetworkOnMainThreadException`

(I replaced the package name with x for privacy reasons).
Hence, my question is: how can I start an activity as a new Thread? so far, i have used
Intent i = new Intent(getApplicationContext(), BattleshipMain.class);
startActivity(i);
i.putExtra("ip",joinip);
i.putExtra("port",joinport);

at first, i thought this would be an alternative:
new Thread(new Runnable() {
                        @Override
                        public void run() {
                            Intent i = new Intent(getApplicationContext(), BattleshipMain.class);
                            startActivity(i);
                            i.putExtra("ip",joinip);
                            i.putExtra("port",joinport);
                        }
                    });

However, it doesn't seem to work - I get a message in the console, that BattleshipMain has been started, but nothing actually shows up on the display (except whatever was there already).
does anybody have an idea what to do? I really don't know how to solve this; I'm still new to Android, though, and not really a long-term expert in java either.
Thanks in advance!
//edit: I'm not too familiar if I'm supposed to do this, but after I moved the networking code to a separate thread, it seems to me that I'm unable to connect the app on my phone to a server running on my PC. They're in the same network & the server should be compatible with the mobile app, but considering the errors / freeze screens I receive, I don't see what else could be the problem.
Does Java NIO work normally on android at all / could I possibly connect a client on my phone (which is a Galaxy S3, btw -> API 18) to a server on a PC with Windows?
Thank you! :)
//edit: nevermind, the error was 100% dumb. When using an Intent to create a new activity, i created the intent, launched it, and THEN used intentname.putExtra(key, value) - which obviously didn't work. Right now, I got another error because I tried to change a checkBox from a different thread, but the network part worked, so I guess I'll be done soon.
Comment: @Knossos I believe you mean you need to move your network code off the UI thread.
Comment: You cannot run the Activity on a non-UI thread. You need to move your network code onto a UI thread. The network code that you have inside your Activity.
Comment: I presume you are not a native android developer but you should be familiar with restclients (like Spring).So why not try using something like retrofit/okhttp ?
Comment: The keyword is Network in `NetworkOnMainThreadException`, meaning you are doing some network access stuff, and Android doesn't like that. If you added more code, we could solve your [XY Problem](http://meta.stackexchange.com/questions/66377/what-is-the-xy-problem)
Comment: Oops! Yes! Network code needs to be moved onto a BACKGROUND thread.
Comment: well, that was what i feared i'd have to do ... the network stuff worked so nicely in the windows application, i'm not really eager to separate it. well, i guess i'll have to now :(
Thank you anyways, though! :)
Comment: See my answer here for a detailed example. http://stackoverflow.com/a/35210468/2308683
Comment: @droidekas: well, considering the battleship program is my first ever java program (except for hello world) ... no, i'm not familar with restclients ^^
although i've found that there's another error (that might solve the network problem) - when launching an activity, i used and intent & intentName.putExtra(key, value) for the parameters. later, i used Bundle b = intentname.getExtras() in the new activity, and b.get(key) to get the values. however, this doesn't seem to work. i guess i'll google the usage of "intent extras", and not do it the way i read it somewhere else ^^
Answer: The problem you're having is that you're doing networking on the main thread, which is prohibited. Move all networking and network/api calls into AsyncTasks and it should be good to go.
EDIT:
apart from that, please, abandon the idea of starting activities as threads, as Activities have their own lifecycle which is described here
EDIT2: perhaps if you manage to turn off StrictMode (available in developer options) you could do networking on the main thread but... i wouldn't count on it.
Comment: It is considered bad practice to do networking on the main thread because that will cause a bad user interface experience. The main thread is also called the UI thread because the user interface is driven from that thread. If you do a long-running operation on the main thread, you will block the system from doing updates to the UI and thus your app freezes until the operation is over. So you can do short operations on the main thread, but not long ones like networking operations that may take seconds or even minutes.
Comment: I appreciate your worries, @Droidman, but I can assure you I have no intentions of utilizing any "hacks" so I don't have to move my networking to a separate thread. a) that's probably more work than actually moving the network part, and b) since I know now that I'm not allowed to do network stuff on my main thread, I won't structure my program this way in the future. Aside from that, I'd be interested in why exactly using these hacks would be bad - i guess there's some reason why Google disabled that, right?
Comment: P.S. To quantify short and long operations on the main thread: a long operation is roughly anything that takes more than 10 or 15 milliseconds. A smooth user interface experience is achieved when the screen is refreshed at 60 frames per second. Meaning there is 16 milliseconds per frame to do that (1 second divided by 60 frames). If you eat up all the time available to draw a frame then the system will have to skip that frame. The user will notice this as screen jitter.
Comment: Incidentally, a UI blocking operation lasting more than 5 seconds will cause an [ANR](http://developer.android.com/intl/ru/training/articles/perf-anr.html). These should be avoided like the plague. This is why Google introduced the NetworkingOnMainThreadException (in API level 11). It is so bad, they forced Apps to just crash instead of letting bad code into Apps in the first place.
Comment: `networking on the main thread` please forget those words and never ever say them again
Comment: @Droidman why? the man had a `NetworkOnMainThreadException` show up in the logcat - he's the one that should forget about them, not me :)
Comment: because of the beginner folks that see such hints and start looking for "hacks" to run network on the main thread instead of "bothering" with background networking. This results in crappy software and total misunderstanding of how Android works.
Comment: Maybe I don't understand what's written up there, but I can still clearly see

"The problem you're having is that you're doing networking on the main thread, which is prohibited. Move all networking and network/api calls into AsyncTasks and it should be good to go."
Comment: I didn't say your answer is incorrect, I just don't like the idea of mentioning the ways to allow network on the main thread, at least *without explaining why this is bad and strongly recommending not to do so*. But nvm, this is just my personal opinion
Comment: I'm sorry but our opinions differ - if it were **that** terrible, it would've been prohibited just like writing to `/system` is. But because there is a way, obviously someone figured it would be nice to address that need. And since there is a way, you might as well use it.
Comment: @Misteradi1 different people will give you different answers, but I found out that sometimes the answer pretty much devolves to "because the tutorials say so!"... Truth is, nothing bad happens if you allow networking on main thread, you (as a regular user/developer) just can't do it. So better get used to doing it properly and fall back to alternative "hacky" solutions when the default one simply can't solve the issue. Because they are allowed **just for those special occasions when nothing else will work** :D Perhaps droidman will explain why it's really bad.
Comment: @RobMeeuwisse got the point. Networking is a **blocking** operation that will cause your UI to freeze, possibly for a long period of time. `you can do short operations on the main thread` - you should also avoid CPU-intensive operations on the UI thread, no matter whether they are short or not
Comment: Yes, I remember when that started to happen, somewhere around ICS... They're not exactly crashing, per see, as clicking 'wait' usually lets them finish their business. While I do agree that non responsiveness should be avoided, sometimes those happen due to insufficient testing :/
Answer: You can't. You have exactly one UI thread.

Starting an activity as a Thread?


When the table row is clicked, give me the value of groupno. but i cant find any solution

Question: PHP code:
$data= $db->prepare("select * from user");
$data->execute();
if($data -> rowCount()) {
    echo "
 ";
    foreach ($data as $row) {
        echo "
".$row["name"]."	"
             .$row["lastname"]."	"
             .$row["phone"]."	"
             .$row["officephone"]."	"
             .$row["homephone"]."	"
             .$row["GrupNo"]."	"."
";
     }
}

I use the groupno value I get from the database
 The data I get from GroupNo,i will transfer inputs*
Comment: i suggest you start buy [looking at the manual, maybe `->fetchAll()` would be a good thing to use here](http://php.net/manual/en/pdostatement.fetchall.php)
Comment: You seem to have forgotten to actually FETCH the result rows before attempting to process them
Answer: you need to add $result = $data->fetchAll(PDO::FETCH_OBJ);
Comment: Why should the OP ___try this___? **Good answers** will always have an explanation of what was done and why it was done that way,
not only for the OP but for future visitors to SO that may find this question and be reading your answer.
Comment: Also this would require some code refactoring in the output to make this simple line of code be any use to the OP


Has anyone been "guaranteed" a Super Bowl ring because they played for both teams during the season?

Question: I was reading this answer to the question "Who gets Super Bowl rings?" which says

Also, in some cases, players traded during the season will get them too, if they suited up and played during they regular season. This is also by ownership's decision

Was ever a time when a player was guaranteed a Super Bowl ring because they are in the final game but they started the season for their opponents team?
Answer: A player can not be guaranteed a Super Bowl ring because the ownership makes the decision whether or not someone gets a ring if they did not play in the Super Bowl
(according to Who gets Super Bowl rings?).
Comment: Replying to user16493
I think he just means played on both superbowl teams at one point during the season. I couldnt find any player who has done this sadly


What is the difference between the limit as $x$ approaches zero and an infinitesimally small number?

Question: When $x$ approaches zero, doesn't it become infinitesimally small or in other words, an infinitesimal?
I have been told that limits and infinitesimals are distinct concepts. For example, Wikipedia states that there are two types of calculus : standard and non standard.
It states that in non-standard calculus, infinitesimals are used instead of limits, which are used in standard calculus. Wikipedia also states that the idea of limits resolved many debates on the logical validity of infinitesimals.
I am unable to understand how infinitesimals and limits are different.
Comment: Sentenced start with a capital letter and end with a period. You put no effort into your question, yet you expect effort from us to answer it.
Comment: Why did you ask exactly the same question as vipin rawat but 9 hours later? https://math.stackexchange.com/questions/3330639/just-perception
Comment: Your question lacks [context](https://math.meta.stackexchange.com/questions/9959/how-to-ask-a-good-question). Where does this problem come from? Who told you there was a different and in what situation was this in?
Comment: The limit of $x$ as $x$ approaches zero is exactly zero, not an infinitesimally small number. There are no infinitesimally small numbers in the real number system.
Comment: Possible duplicate of [Are infinitesimals equal to zero?](https://math.stackexchange.com/questions/1894930/are-infinitesimals-equal-to-zero)
Comment: In addition [this question](https://math.stackexchange.com/questions/1894930/are-infinitesimals-equal-to-zero) is almost exactly the same as what you are asking.
Comment: im sorry im very new at this, please excuse me forgetting a period her and there.
Comment: Complete coincidence. Please don't lash out at me I just wanted to ask a question.
Comment: I don't understand why this question was closed. It makes sense to me and conveys everything pretty clearly...
Answer: An infinitesimal is an infinitely small number. One way you could define this is that $\omega$ is an infinitesimal if for all real numbers $r\in\mathbb{R}_{>0}$ we have $0<|\omega|<r$. i.e. $\omega$ is non-zero, but it's absolute value is smaller than any positive non-infinitesimal number.
A sequence $(x_{n})$ in the real numbers converging to $0$ becomes arbitrarily small, not infinitesimally small. So for every real number $\varepsilon\in\mathbb{R}_{>0}$ we can find some $N\in\mathbb{N}$ such that for all $n\geq N$ we have that $|x_{n}|<\varepsilon$. Note though that every sequence element $x_{n}$ is still a non-infinitesimal numbers (except if $x_{n}=0$, but that does not really count in this context).
That being said one way to construct infinitesimal numbers is to look at certain equivalence classes of sequences converging to $0$, so your intuition that a sequence converging to $0$ is somehow linked to an infinitesimal number is not completely wrong.


csv.DictReader prints out only obj

Question: For some reason the following code only prints out  <csv.DictReader object at 0x7f2ee79531c0>. This is what states on the Python official website but for some reason it doesn't work here, neither with data = csv.DictReader(file)  nor data = csv.DictReader(file, delimiter=',').
The file data.csv  and the code is structered as follows. Where is the error?
data.csv's structure:
col1, col2, col3
val1, val2, val3

The code:
file_path = r'data.csv'
    with open(file_path) as file:
        data = csv.DictReader(file)
    print(data)

Comment: The DictReader is iterable, so you can get the data using for example `data = list(csv.DictReader(file))`
Comment: What kind of a output do you want?
Answer: In the example we find in the docs, they're using a for-loop to iterate over the csv.DictReader object (see here). So, you need to do the same and you might also want to turn on skipinitialspace in order to ignore the spaces after the delimiter (,).
file_path = r'data.csv'

with open(file_path) as file:
    data = csv.DictReader(file, skipinitialspace=True)
    for row in data:
        print(row)

    #another variant
    # print(*data)

Output :
{'col1': 'val1', 'col2': 'val2', 'col3': 'val3'}
{'col1': 'val4', 'col2': 'val5', 'col3': 'val6'} # <-- in case you have more rows
{'col1': 'val5', 'col2': 'val6', 'col3': 'val7'} # <-- in case you have more rows
...

Comment: It doesn't seem like there's a skipinitialspace parameter but was solved with the for loop thanks

csv.DictReader prints out only obj


Drupal 7 multisite setup white screen

Question: I have attempted to set up a Drupal 7 multi site set-up. I followed the instructions online and have one site (site1) that is setup like a regular single install Drupal site and a second site (site2) set up in the sites/sites2 directory. The sites use separate databases.
The issue I am having is that while site1 displays and operates normally, site2 only displays a white screen. When I executed the install.php script for site2, everything seemed to go normally until I actually try to view the site. Any ideas as to what the issue could be? I am sure that settings.php file in both installations is set up correctly so I am a bit lost.
Thanks.
Comment: WSODs are thoroughly covered on Drupal.org - read [article about fixing them](https://drupal.org/node/482956) and if it will not be enough, provide data you collected in 1a and 2b steps.
Answer: It is impossible to tell you exactly what is wrong with the information that is given.  I run several multi-sites using separate databases, and they work as advertised when I set them up following the standard instructions.
The White Screen of Death is usually caused by some error in the PHP.  To see the error message, you need to turn on PHP error reporting.  To do this, add the following to the settings.php, just below the initial <?php:
error_reporting(E_ALL);
ini_set('display_errors', TRUE);
ini_set('display_startup_errors', TRUE);

This will usually show an error message that tells you where you've left out a semicolon or some other trivial PHP-error.
See also: https://drupal.org/node/1056468 and https://drupal.org/node/158043
Comment: Thanks, that helped identify the issue! In my case it was a library file being used on site1 that was throwing an exception when site2 was trying to use it. I now have something to investigate.
Comment: I was pulling my hair out trying to find a decent error message - tried pasting these php settings in several places but what ultimately worked for me was vising subsite.yourdomain.com/update.php and seeing which modules I was missing.

Drupal 7 multisite setup white screen


apache redirect only root slash homepage

Question: I need to redirect only http://example.org/ to http://www.something-other.org/ in Apache 2.4.
Just the homepage. Nothing else. I.e. http://example.org/?page=blog or http://example.org/contact.html should NOT redirect.
All I could find was redirecting a page completely to another site like:
Redirect "/" "http://www.something-other.org/"

This is a bit better:
RewriteEngine On
RewriteRule ^/$ http:// www.something-other.org/ [L,R=301]

It redirects only the homepage, but also, if there is a query string.
Comment: The solution of "this question already has an answer" points to a page that is essentially like reading a whole book about redirects.  That is the problem with this voodoo and that is why people would like to ask one simple specific case question.  Pointing them to a book type of FAQ is no answer.  The real answer is very short and it is a time saver to find only that answer for the specific question of redirecting only /
Comment: [Server Fault is a site for information technology professionals](http://serverfault.com/help/on-topic) -- as such we have certain professional expectations when people ask a question here, and one of those expectations is that your question shows you did some **research**, found and **read the vendor documentation** and/or **tried a solution** before asking the internet for help. You're not expected to solve everything yourself, but then at least you can [write a great question](http://meta.serverfault.com/a/3609/37681) that we can help you answer.
Comment: I stated the question accordingly to http://serverfault.com/questions/491007/ so I thought this would be fine
Comment: That Q&A isn't very stellar either but might have been better received because 4 years ago nginx was not nearly as popular (or well documented) as today, and even more surprisingly that already has a answer for Apache as well... (thank you for the edit BTW)
Comment: @rubo77 Why would you even care about the query string?
Comment: Why the downvotes? What could be enhanced in this question?
Answer: You need to use mod_rewrite:
RewriteEngine On
RewriteCond "%{QUERY_STRING}" "^$"
RewriteRule "^/$" http://something-other.org/ [L,R=301,QSD]

The QSD flag discards the query string.
Enable mod_rewrite and restart apache:
root@host:~# a2enmod rewrite
root@host:~# service apache2 restart

Comment: But I found out something a bit better: `^/$` does only redirect the homepage, but also if there is a querystring. How can I not redirect, if there is a querystring?
Comment: @rubo77 this should do it.
Comment: QSD seems redundant to me, since this rule only matches if there is no query string at all, due to its RewriteCond


Linha limite Google Charts

Question: estou enfrentando um problema que não acho a solução rs
Preciso adicionar uma linha limite em meu gráfico, vou colocar uma imagem a baixo de como está agora e como deve ficar. Conseguem me orientar nisto?
google.charts.load('current', {'packages':['bar']});
google.charts.setOnLoadCallback(drawChart);

function drawChart() {
    var data = google.visualization.arrayToDataTable([
        ['2017', 'Minima', 'Máxima', 'Média'],
        ['Jan', 15, 23, 21],
        ['Fev', 17, 25, 20],
        ['Mar', 18, 30, 22],
        ['Abr', 20, 27, 27],
        ['Mai', 21, 23, 21],
        ['Jun', 23, 28, 26],
        ['Jul', 27, 32, 28],
        ['Ago', 22, 25, 24],
        ['Set', 26, 30, 28],
        ]);

    var options = {

        title: 'Relatório Temperatura Mensal',
        colors: ['#cfcfcf', '#1c1c1c', '#828282'],
    };

    var chart = new google.charts.Bar(document.getElementById('columnchart_material'));

    chart.draw(data, google.charts.Bar.convertOptions(options));

Atual:

Como deve ficar:

Desde já. agradeço.
Comment: Vc quer a media? Ou não quer que o grafico cruze a linha vermelha?
Comment: Olá amigo, não, a média já tenho em um gráfico de barra. Oque eu preciso é de uma linha fixada num limite, por exemplo, 23ºC, essa linha vai ficar fixa neste local sempre, dai os gráficos em barra vão cruzar este "limite" e vou conseguir ter alguma visualização no relatório.
Answer: Podes sempre usar este gráfico e usares o "Average" para colocares lá o valor da média média.
https://developers.google.com/chart/interactive/docs/gallery/combochart
google.charts.load('current', {'packages':['corechart']});
  google.charts.setOnLoadCallback(drawVisualization);

  function drawVisualization() {
    // Some raw data (not necessarily accurate)
    var data = google.visualization.arrayToDataTable([
     ['Month', 'Bolivia', 'Ecuador', 'Madagascar', 'Papua New Guinea', 'Rwanda', 'Average'],
     ['2004/05',  165,      938,         522,             998,           450,      614.6],
     ['2005/06',  135,      1120,        599,             1268,          288,      682],
     ['2006/07',  157,      1167,        587,             807,           397,      623],
     ['2007/08',  139,      1110,        615,             968,           215,      609.4],
     ['2008/09',  136,      691,         629,             1026,          366,      569.6]
  ]);

var options = {
  title : 'Monthly Coffee Production by Country',
  vAxis: {title: 'Cups'},
  hAxis: {title: 'Month'},
  seriesType: 'bars',
  series: {5: {type: 'line'}}
};

var chart = new google.visualization.ComboChart(document.getElementById('chart_div'));
chart.draw(data, options);
}

Comment: Obrigado Adelino, deu super certo ;D

Linha limite Google Charts


The numbers from 1 to 1000 are each written on a slip of paper

Question: The numbers from 1 to 1000 are each written on a slip of paper and placed in a box and one slip is removed from it. What is the probability that the number drawn is a multiple of 5?
Answer: 1 in 5 numbers are divisible by 5 (200 numbers between 1 and 1000), so the probability is 20%.


I cannot insert a word to mysql

Question: if(isset($_POST['zodis'])) {
strpos($_POST['zodis'], ' ');
if($pos > 0) {
    print '
 Only 1 word.
';
} else {
        $query = "INSERT INTO `zodziai` (`id` ,`zodis` ,`date`)VALUES (NULL , '"$_POST['zodis']"',CURRENT_TIMESTAMP);";
        mysql_query($query) or die(mysql_error());

    }
}

Where i made a mistake? Im new in PHP
it shows

Parse error: syntax error, unexpected T_VARIABLE in
  C:\wamp\www\php_mysql.php on line 19
Comment: sorry, line 19 is $query = "INSERT INTO `zodziai` (`id` ,`zodis` ,`date`)VALUES (NULL , '"$_POST['zodis']"',CURRENT_TIMESTAMP);";
Comment: what kind of field type is your date column?
Answer: $query = "INSERT INTO zodziai (id,zodis,date)VALUES (NULL, '".$_POST['zodis']."',".time().");";

your id field isn't autoincreament?
what kind of type field is your date field?
Answer: You forgot the ..
    $query = "INSERT INTO `zodziai` (`id` ,`zodis` ,`date`)VALUES (NULL , '" . $_POST['zodis'] . "',CURRENT_TIMESTAMP);";

Comment: Also, don't use the `mysql_*` functions. They are in the process of becoming deprecated. If you are learning PHP, do yourself a favour and use the `mysqli_*` functions or PDO objects instead.
Answer: If you mix strings and variables, you should use "." to concatenate them:
...VALUES (NULL , '".$_POST['zodis']."',CURRENT_TIMESTAMP)...
(Note the point (.) before and after $_POST variable).
That is what I've seen taking a fast look, maybe there is something more.
Answer: You are not initializing $pos. Try this :
$pos = strpos($_POST['zodis'], ' ');

You have also forgotten the concatenation operator (.), in your query.
$query = "INSERT INTO `zodziai` (`id` ,`zodis` ,`date`)VALUES (NULL , '" . $_POST['zodis'] . "',CURRENT_TIMESTAMP);";

Also avoid using mysql_ functions, PHP discourages using mysql_ functions and mysql_ functions will soon be deprecated, rather, use mysqli class or PDO.
Another suggestion, rather than sending CURRENT_TIMESTAMP in the query, create the table field using the following constraint
`date` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP

and then pass NULL in the query, this will automatically set the date field in the corresponding row as CURRENT_TIMESTAMP.

I cannot insert a word to mysql


php javascript - add remove dynamic form (with datepicker input)

Question: i use some code to clone form elements but i dont know how it works with  with datepicker.
Can someone update the code that i can use datepicker by input what can be clone? With query ui?

//define template
var template = $('#sections .section:first').clone();

//define counter
var sectionsCount = 1;

//add new section
$('body').on('click', '.addsection', function() {

    //increment
    sectionsCount++;

    //loop through each input
    var section = template.clone().find(':input').each(function(){

        //set id to store the updated section number
        var newId = this.id + sectionsCount;

        //update for label
        $(this).prev().attr('for', newId);

        //update id
        this.id = newId;

    }).end()

    //inject new section
    .appendTo('#sections');
    return false;
});

//remove section
$('#sections').on('click', '.remove', function() {
    //fade out section
    $(this).parent().fadeOut(300, function(){
        //remove parent element (main section)
        $(this).parent().parent().empty();
        return false;
    });
    return false;
});

    <fieldset>
        <legend>test form - delete</legend>

            number1:
            <input type="text" name="number1[]"/>

number2:
            <input type="text" name="number2[]"/>

            selcet1:
  <select name="select1[]" required>
  <option value="1" >1</option>
    <option value="2" >2</option>
  </select>

selcet2:
        <select name="selcet2[]" required>
   <option value="1" >1</option>
      <option value="2" >2</option>
   </select>

Date:
 <input type="text" name="date[]" required />

            text:
<textarea rows=3 type="text" name="text[]" > </textarea>

    </fieldset>

       add form

I dont know how to add a datepicker by the
// input type="text" name="date[]" required // that i can clone and use.
Please can someone help me that it works?
Answer: JqueryUI solution

//define template
var template = $('#sections .section:first').clone();

//define counter
var sectionsCount = 1;

//add new section
$('body').on('click', '.addsection', function() {

    //increment
    sectionsCount++;

    //loop through each input
    var section = template.clone().find(':input').each(function(){

        //set id to store the updated section number
        var newId = this.id + sectionsCount;

        //update for label
        $(this).prev().attr('for', newId);

        //update id - THIS CAUSES JqueryUI Datepicker to bug, also you shouldn't use numerical only IDs
        //this.id = newId;

    }).end()

    //inject new section
    .appendTo('#sections');
    //initialize datePicker on last name=date[] element in HTML DOM
    $("input[name='date[]']").last().datepicker();
    return false;
});
//init original datePicker in HTML DOM
$("input[name='date[]']").last().datepicker();
//remove section
$('#sections').on('click', '.remove', function() {
    //fade out section
    $(this).parent().fadeOut(300, function(){
        //remove parent element (main section)
        $(this).parent().parent().empty();
        return false;
    });
    return false;
});

<link rel="stylesheet" type="text/css" href="https://code.jquery.com/ui/1.12.0/themes/smoothness/jquery-ui.css">

    <fieldset>
        <legend>test form - delete</legend>

            number1:
            <input type="text" name="number1[]"/>

number2:
            <input type="text" name="number2[]"/>

            selcet1:
  <select name="select1[]" required>
  <option value="1" >1</option>
    <option value="2" >2</option>
  </select>

selcet2:
        <select name="selcet2[]" required>
   <option value="1" >1</option>
      <option value="2" >2</option>
   </select>

Date:
 <input type="text" name="date[]" required />

            text:
<textarea rows=3 type="text" name="text[]" > </textarea>

    </fieldset>

       add form
Comment: Ok thank you very much! I will try your solution tomorrow at work and give you feedback
Comment: Hey @Adam K. your Solution works for me =) Thank you very much
Comment: hey @Adam K. ok now? i have tick =)
Comment: @Peisi Found a bug in your code... ID shouldn't be numerical only. Also setting ID for the datepicker causes bug even after initializing it, since DatePicker will set it's own ID. Now question is - do you need your own custom ID to distinct input fields? I'd suggest using input names instead.
Comment: I will use the form to Save the Inputs in mysql Database. I Can try it tomorrow at work. Java Script is Not easy for me. You mean i dont Need the id's for what i will do?
Comment: @Peisi it all comes to the question "How will you choose to do it" - if you use , then the php $_POST["fieldName"] uses `input name`, to select values. If you choose to use ajax post - then you are pretty much free to choose how you will handle the data, that you will post. You can create javascript object/array and loop through all input elements, set the key based on input names etc... If all input field names are unique, you shouldn't have problems in both scenarios.
Comment: @Peisi glad to hear that, please tick my answer as solution. I'd appreciate it... With rep over 50 i will finally be able to comment anywhere :)
Comment: @Peisi I don't want to spam you, but please tick the answer as solution. - Having rep below 50 is somewhat frustrating, when i can't ask for details in comments of original question and even when i'd need more information, i can interact only via answers.
Comment: @Peisi Cheers mate. Happy coding best of luck :)
Comment: @AdamK. its possible add previous row data to dynamically generated row ? what part of code i can modify to solve ?
Answer: HTML5 DatePicker Solution
Native HTML5 datepicker is supported only in modern browsers and not even all of them.
Simply use type="date" instead of type="text"

If you want 100% working datepicker, you will have to look at JqueryUI.
If you want JqueryUI datepicker to work with cloned elements, you will have to initialize new date input fields as datepicker jquery input element after cloning them.

//define template
var template = $('#sections .section:first').clone();

//define counter
var sectionsCount = 1;

//add new section
$('body').on('click', '.addsection', function() {

    //increment
    sectionsCount++;

    //loop through each input
    var section = template.clone().find(':input').each(function(){

        //set id to store the updated section number
        var newId = this.id + sectionsCount;

        //update for label
        $(this).prev().attr('for', newId);

        //update id
        this.id = newId;

    }).end()

    //inject new section
    .appendTo('#sections');
    return false;
});

//remove section
$('#sections').on('click', '.remove', function() {
    //fade out section
    $(this).parent().fadeOut(300, function(){
        //remove parent element (main section)
        $(this).parent().parent().empty();
        return false;
    });
    return false;
});

    <fieldset>
        <legend>test form - delete</legend>

            number1:
            <input type="text" name="number1[]"/>

number2:
            <input type="text" name="number2[]"/>

            selcet1:
  <select name="select1[]" required>
  <option value="1" >1</option>
    <option value="2" >2</option>
  </select>

selcet2:
        <select name="selcet2[]" required>
   <option value="1" >1</option>
      <option value="2" >2</option>
   </select>

Date:
 <input type="date" name="date[]" required />

            text:
<textarea rows=3 type="text" name="text[]" > </textarea>

    </fieldset>

       add form
Comment: Hey thanks Can you Tell me how it works with query ui? In example by my code ?
Comment: @Peisi you mean something like `var section = template.` changed to `var section = $('#sections .section:last-of-type').clone().` ?
just keep in mind, that you'll have to put there an if clause to use template, when there are no sections left.
Comment: @Peisi added JqueryUI solution
Comment: Hey my friend, i work with your solution. But now i found i bug for my insert into table code. Can you tell me why only the first and the last section of your code goíng into my mysql table? i work with "foreach $_POST as $value
Comment: Hello @Peisi - use Dev tools in Chrome to determine what do you really send from client. Then you can determine whether your error is on your client side or server side.

Chrome - Dev tools - network - document request - click - and discover headers values... If all data is sent - your problem is in your server code, if data is missing THEN:
Your inputs are dynamic - if you use a POST via javascript (not html form), then you have to loop through dynamic inputs at the moment you press the submit btn... My guess is that you init inputs on page load - leaving dynamic inputs lost. (My guesses)
Comment: In short - Determine whether you are *NOT PASSING* the data -or- *NOT PROCESSING* the data
Comment: Hey @Adam K. i have a new question to your solution =) Is it possible to clone the entry from input 1 and input 2 to next clone div section? Can you help to figure it out? =)
Comment: Thanks @Adam K. , your solution works fine for me ^^


Let $\{W_t\}_{t\geq0}$ be a Brownian motion. Define $Y_t=e^{\frac{t}{2}}\sin(W_t)$. Show that $\{Y_t\}_{t\geq0}$ is a martingale

Question: I know one way to do this but my TA mentioned that there is a method that involves applying Ito's formula. I did this and obtained: $$dY_t=e^{\frac{t}{2}}\cdot \cos(W_t)\:dW_t$$
I know that $W_t$ is a martingale by nature of the fact that it is a Brownian motion. But how is it possible to conclude that $Y_t$ is a martingale as well?
I am very new to It's formula. If you can provide me with an understanding with why we decide to apply it in the first place I would be very appreciative. In the world of normal calculus I would never think to take a derivative here so why do it when dealing with stochastic calculus? I know this shows how little I understand the material so any explanation will have me in a better position.
Comment: Sorry but what happened [there](https://math.stackexchange.com/q/2434051/)? You received specific suggestions, did you do something with them, do you plan to?
Answer: $Y_t=\int \text{something } dW_t$ and is thus a martingale. See: https://fabricebaudoin.wordpress.com/2012/08/30/lecture-17-some-properties-of-the-ito-integral/ for example.


How to add breadcrumb?

Question: How can I add breadcrumb to a page in my attendance module.
I have used the following hook, but it changed the breadcrumb for all pages in other modules also.
function attendance_init() {
// set the breadcrumb
$breadcrumb = array();
$breadcrumb[] = l('Home', '<front>');
$breadcrumb[] = l('People', 'group/node/'. arg(2) .'/people');
$breadcrumb[] = l('Attendance', 'group/node/'. arg(2) .'/people/attendance');
drupal_set_breadcrumb($breadcrumb);

}

Comment: "to a page" - but to which page? Is it a specific node with a given node id or something else?
Comment: this is bound to happen with `hook_init`, like the posts below choosing the appropriate condition for page helps decide the hook better.. perhaps if you could edit your query to describe the specific case we could suggest you the hook
Comment: yep, please describe the use case better!
Answer: Could you get what you want from the Custom Breadcrumbs module?

Allows administrators to set up parametrized breadcrumb trails for any
  node type. This allows CCK-style node types to have "Home > User Blog
  >2005 > January" style breadcrumbs on the node view page itself, synchronizing cleanly with custom views or pathauto aliases.
  Breadcrumb visibility can be customized via a php snippet.
Answer: About breadcrumb If you want to change in a node you can use hook_node_view to change breadcrumb an you can check $node->tyoe
function hook_node_view($node)
{
   if($node->type=="page")
    {
       drupal_set_breadcrumb();
    }
}

if you want to use it in a page
you can check arg or $_GET['q'] in any of hook_page
Hope it can help you
Comment: You forgot to define the $breadcrumb array mentioned in the question, and passing it to [drupal_set_breadcrumb](https://api.drupal.org/api/drupal/includes%21common.inc/function/drupal_set_breadcrumb/7). So at the end, it should look like this: `drupal_set_breadcrumb($breadcrumb);`.

How to add breadcrumb?


'How to read a file content until 'n' occurrences of a character and write it into a variable", using javascript?

Question: I have a text file that is being written by Apache Flink Tool.
1. I want to extract this file's contents until it encounters the 999th "},"
2. Delete the last comma(,)
3. Add "[" and "]" at the beginning and end of the read content.
4. Write this modified content into a variable.
All of these are to be written into a variable.
Is the entire operation possible through Javascript?
The purpose of this action is to make it resemble an JSON array used to plot Highcharts that can load upto 1000 points only, at once.
Contents of txt file Flink is writing into:
{"temperSensorData":"28.489084691371996","temperSensorUnit":"celsius","timestamp":"1493270171424","timestamp2":"1493270171454","timestamp3":"1493270171454"},
{"temperSensorData":"28.48908469137112","temperSensorUnit":"celsius","timestamp":"1493270171426","timestamp2":"1493270171522","timestamp3":"1493270171523"},
{"temperSensorData":"28.489084691371186","temperSensorUnit":"celsius","timestamp":"1493270171426","timestamp2":"1493270171523","timestamp3":"1493270171524"},
{"temperSensorData":"28.489084691371595","temperSensorUnit":"celsius","timestamp":"1493270171426","timestamp2":"1493270171524","timestamp3":"1493270171525"},
{"temperSensorData":"28.48908469137168","temperSensorUnit":"celsius","timestamp":"1493270171428","timestamp2":"1493270171529","timestamp3":"1493270171529"},
{"temperSensorData":"28.489084691371684","temperSensorUnit":"celsius","timestamp":"1493270171428","timestamp2":"1493270171529","timestamp3":"1493270171529"},

The (JSON) format in which the contents are to be written after all the above listed actions are performed:
[
    {
        "temperSensorData": "28.489084691371996",
        "temperSensorUnit": "celsius",
        "timestamp": "1493270171424",
        "timestamp2": "1493270171454",
        "timestamp3": "1493270171454"
    },
    {
        "temperSensorData": "28.48908469137112",
        "temperSensorUnit": "celsius",
        "timestamp": "1493270171426",
        "timestamp2": "1493270171522",
        "timestamp3": "1493270171523"
    },
    {
        "temperSensorData": "28.489084691371186",
        "temperSensorUnit": "celsius",
        "timestamp": "1493270171426",
        "timestamp2": "1493270171523",
        "timestamp3": "1493270171524"
    }
]

Comment: Yes it is possible with Javascript.So, what you have tried so far ?
Show the code .
Comment: FYI: Highcharts can load up to millions of points at once. To load more than 1k, start with setting [`series.turboThreshold`](http://api.highcharts.com/highcharts/plotOptions.series.turboThreshold).
Answer: How's that, that will return an array that looks like this:
[
    [
        {999 ENTRIES}
    ],
    [
        {999 MORE ENTRIES}
    ]
    ...
]

var input = '{"temperSensorData":"28.489084691371996","temperSensorUnit":"celsius","timestamp":"1493270171424","timestamp2":"1493270171454","timestamp3":"1493270171454"}\n{"temperSensorData":"28.48908469137112","temperSensorUnit":"celsius","timestamp":"1493270171426","timestamp2":"1493270171522","timestamp3":"1493270171523"}\n{"temperSensorData":"28.489084691371186","temperSensorUnit":"celsius","timestamp":"1493270171426","timestamp2":"1493270171523","timestamp3":"1493270171524"}\n{"temperSensorData":"28.489084691371595","temperSensorUnit":"celsius","timestamp":"1493270171426","timestamp2":"1493270171524","timestamp3":"1493270171525"}\n{"temperSensorData":"28.48908469137168","temperSensorUnit":"celsius","timestamp":"1493270171428","timestamp2":"1493270171529","timestamp3":"1493270171529"}\n{"temperSensorData":"28.489084691371684","temperSensorUnit":"celsius","timestamp":"1493270171428","timestamp2":"1493270171529","timestamp3":"1493270171529"}'

splitInput = input.split('\n')
output = splitInput.map((item) => {
  return JSON.parse(item)
})

splitOutput = []

var chunk = 999;
for (var i=0,j=output.length; i<j; i+=chunk) {
    splitOutput.push(output.slice(i,i+chunk))
}

console.log(splitOutput)
Comment: Can you exclude the outer square brackets and update your answer? I only need one set of square brackets outside of my {..},{..},{..},...{..} elements :)
Comment: Also, you have manually added "\n" after each "}". This is not possible in real-time to manually go and change the txt file's content as Flink is continuously writing into the txt file. Can you suggest anything else?
Comment: The reason as to why those outer brackets are there is because if you split the list at every 999 items, you will have multiple lists of 999 entries, and where would you store those lists? the easiest thing would be to store them in another list like what I've done. that way if you want the outer brackets gone you just access the first list `splitOutput[0]` or the second list `splitOutput[1]`
Comment: in regards to the manually adding \n. a new line is represented by either `\n` or `\r` so if flink is creating new lines, it isn't actually creating a new line, rather it is putting in the character `\n` or `\r`
Comment: Sorry, but i missed adding the commas following every {..} element (here in the post) as written by Flink into txt file. You mean to tell you didnt edit the structure to include "\n" while writing into a variable?
Comment: is the flink file also wrapped in `[` `]` tags? should be an easy change, just need to know all of the parameters
Comment: Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/142907/discussion-between-inchara-raveendra-and-anis-jonischkeit).


Gerar componentes HTML com PHP e estes atribuírem características do javascript

Question: Eu criei um formulário que possui um painel e nesse painel tem um input de data com um jquery datepicker. Caso possui dados inseridos no banco, o meu PHP cria mais linhas neste painel (através do ajax) com outros input para inserir data, porém esses novos input não estão habilitando a possibilidade de escolher a data com o datepicker.
Acredito que seja pela ordem do processamento do javascript e do PHP na aplicação.
Como posso fazer esse novos input também atribuir o meu datepicker?
Obs.: os novos input também estão definidos com class="data"
datepicker
$('.data').datepicker({
    dateFormat: 'dd/mm/yy',
    dayNames: ['Domingo','Segunda','Terça','Quarta','Quinta','Sexta','Sábado'],
    dayNamesMin: ['D','S','T','Q','Q','S','S','D'],
    dayNamesShort: ['Dom','Seg','Ter','Qua','Qui','Sex','Sáb','Dom'],
    monthNames: ['Janeiro','Fevereiro','Março','Abril','Maio','Junho','Julho','Agosto','Setembro','Outubro','Novembro','Dezembro'],
    monthNamesShort: ['Jan','Fev','Mar','Abr','Mai','Jun','Jul','Ago','Set','Out','Nov','Dez'],
    nextText: 'Próximo',
    prevText: 'Anterior',
    maxDate: new Date,
});

(1) Linhas geradas pelo meu PHP quando encontra dados no banco
(2) Input com class="data" que não pega as característica do jquery datepicker.
(3) Input que já carrega quando solicito a página
Answer: Quando você executa o $('.data').datepicker({...}) pela primeira vez, o jQuery DatePicker cria instâncias do para todos os elementos .data disponíveis no DOM nesse exato momento.
Quando você cria novos componentes com Ajax o DatePicker não tem como saber que esses elementos foram criados e instanciar eles automaticamente.
Para resolver esse problema você deve, logo assim que você cria um input de data novo (preferencialmente com id único), instanciar o DatePicker novamente apenas para esse elemento.
Answer: Você pode tentar resolver este problema usando a função "ajaxSuccess" da jQuery, esta função recebe como parâmetro uma função anônima que é executada todas as vezes que uma requisição ajax é concluída com sucesso. Esta é um evento do Ajax.
$(document).ajaxSuccess(function () {
    $('.data').datepicker({
        dateFormat: 'dd/mm/yy',
        dayNames: ['Domingo', 'Segunda', 'Terça', 'Quarta', 'Quinta', 'Sexta', 'Sábado'],
        dayNamesMin: ['D', 'S', 'T', 'Q', 'Q', 'S', 'S', 'D'],
        dayNamesShort: ['Dom', 'Seg', 'Ter', 'Qua', 'Qui', 'Sex', 'Sáb', 'Dom'],
        monthNames: ['Janeiro', 'Fevereiro', 'Março', 'Abril', 'Maio', 'Junho', 'Julho', 'Agosto', 'Setembro', 'Outubro', 'Novembro', 'Dezembro'],
        monthNamesShort: ['Jan', 'Fev', 'Mar', 'Abr', 'Mai', 'Jun', 'Jul', 'Ago', 'Set', 'Out', 'Nov', 'Dez'],
        nextText: 'Próximo',
        prevText: 'Anterior',
        maxDate: new Date,
    });
});

Veja a documentação oficial Global Ajax Event Handlers desta API.


Is collection of subsets of $\Omega$ that are determined by first n number of coin tosses a $\sigma$-algebra?

Question: Let $F_n$ be the collection of subsets of $\Omega$ whose occurrence can be decided by looking at the first n tosses. How can I show $F_n$ is a $\sigma$- algebra?
Comment: This problem seems to require you to do two things. First, say exactly what $F_n$ is --- not "for example" as in your comment but a mathematically precise definition. Second, combine that and the definition of "$\sigma$-algebra" to determine exactly what you need to prove. Technically, there's a third step, namely to prove those things, but I think that, once you've got the goals written down exactly, they will be very easy to prove.  (P.S. I'm not saying that your "For example" comment won't clarify for @DanielWainfleet what you intended, but something more precise is needed for a proof.)
Comment: I don't understand what "determined by the first n tosses" means.
Comment: For example,Let $A_1$ be the set of all elements of Ω such that there are exactly 2 heads during the first 4 coin tosses. Then, $A_1 ∈ F_4$.
Answer: So, $\Omega$ is the infinite product $\Pi_{i\in \mathbb{N}} \{H, T\}$. The sets you're looking at are such that if $x \in A \in F_n$ then $y \in A$ if $x_i = y_i$ for all $i <= n$.
These are finite collections of sets. You should be able to find most of the proof yourself. I would suggest proving that they're an algebra and then using something that says "finite algebras are $\sigma$-algebras".