Calcular integral modo trapézio

Question: Eu preciso calcular integral com o método trapézio. Acredito que o erro pode ser no for. Os havia testado passo a passo e funcionou.
    function integratrapezio(){
    var elmbasea = document.getElementById("valoresdex").value;
    var elemb = document.getElementById("valoresdey").value;
    var elemquant = document.getElementById("valoresden").value;
    var elemfuncao = document.getElementById("valordafuncao").value;

    var k = (elmbasea-elemb)/elemquant;

    var n = +elemquant+1;
    var elemk = +k/2;

    var f = "x+2";

    var cont = 0;

    for (j=1;j<n; j++){

        var i=+j-1;
                if ((i == 0)){c=1;}else{c=2;}
                var x=+elmbasea+i*+k;

                var funcao = eval(elemfuncao);

                var calculodafuncao=cont+c*funcao;
                var cont = calculodafuncao;

        alert(calculodafuncao);

    }

    var total=+elemk*+calculodafuncao;

    /*qualcular a função f = (x)       https://www1.univap.br/spilling/CN/CN_Capt6.pdf*/
    if(document.getElementById('resultFunc').style.visibility = 'Visible'){document.getElementById('resultFunc').style.visibility = 'hidden';}

    if(document.getElementById('resultFunc').style.visibility = 'hidden'){document.getElementById('resultFunc').style.visibility = 'visible';}

    document.getElementById('resultFunc').innerHTML = total;

}

Comment: Bem vindo. Qual é o seu problema? Pode explicar melhor o que não funciona no código?
Comment: Dica: Em JavaScript e em outras linguagens descendentes do C, não confunda `=` com `==`.
Comment: Ao invés de postar respostas que não respondem a pergunta, edite a pergunta. Já coloquei o conteúdo do que você postou como resposta aqui, mas fica a dica para a próxima vez.
Comment: O PDF da função que você quer "*qualcular*" não abre para mim.
Comment: Victor, nao entendi direito sua resposta.
Comment: Leonardo, não sei ainda o que nao funciona, mas deve ser no for......
Comment: Seus dois códigos têm um monte de erros. Mas não entendi que processo de cálculo você está tentando usar. O problema é que quando você faz `if (c = 0)` você não está **verificando** se `c` é zero, está **tornando-o** zero. O que você queria é `if (c == 0)`. No entanto, ainda tem vários outros erros, tal como tentar usar uma variável antes dela ter sido declarada ou inicializada.
Comment: Valew, essa daqui "if (c = 0) " ja tinha alterado. quanto, "uma variável antes dela ter sido declarada ou inicializada."  pode me ajudar..
Comment: Eu sinceramente recomendo o uso de uma biblioteca externa para executar tarefas assim complexas, como por exemplo a biblioteca http://mathjs.org
Answer: Particularmente eu achei muito esquisito o que você fez para calcular a integral no modo dos trapézios. Não tem muitos segredos ao fazer a integral com esse método. A única coisa questionável é se você define o tamanho dos trapézios ou em quantos trapézios divide o intervalo. A seguir um exemplo definindo o tamanho de cada trapézio:

function trapezio(lbda, ini, fim, delta) {
  let integral = 0.0;
  let last_lbda = lbda(ini);
  for (let i = ini + delta; i <= fim; i += delta) {
    let now_lbda = lbda(i);
    integral += delta*(now_lbda+last_lbda)/2;
    last_lbda = now_lbda;
  }
  return integral;
}

function info_trapezio_quadrado(ini, fim, delta) {
  let result = trapezio((i) => i*i, ini, fim, delta);
  console.log("função quadrada, de " + ini + " a " + fim +", delta = " + delta);
  console.log(">integral = " + result);
}

info_trapezio_quadrado(0, 2, 1);
info_trapezio_quadrado(0, 2, 0.5);
info_trapezio_quadrado(0, 2, 0.1);
info_trapezio_quadrado(0, 2, 0.01);
info_trapezio_quadrado(0, 2, 0.001);

Explicando o código:

os argumentos são uma função qualquer dos reais nos reais lbda, o intervalo [ini, fim) e o tamanho da base dos trapézios delta
o cálculo da área de um trapézio retângulo é base * (altura1 + altura2)/2
a integral é o somatório da área de todos os trapézios, começando em ini e terminando em fim

Uma versão que faz menos operações, porém menos legível, é:
function trapezio_menos_operacoes(lbda, ini, fim, delta) {
  let lbda_ini = lbda(ini);
  let somas = lbda_ini;
  let last_lbda = lbda_ini;
  for (let i = ini + delta; i <= fim; i += delta) {
    last_lbda = lbda(i)
    somas += last_lbda;
  }
  let integral = delta*(somas - (lbda_ini + last_lbda)/2.0);
  return integral;
}

Nessa versão, estou me valendo de que cada altura dos trapézios é levada em conta duas vezes na versão original (exceto o primeiro e o último). Por exemplo, para a função quadrada com delta = 0.5 (integrando de 0 a 2):
iteração | i    | f(i) | área do trapézio              | área acumulada
---------+------+------+-------------------------------+----------------
0        | 0    | 0    | 0                             | 0
1        | 0.50 | 0.25 | 0.5*(0.00 + 0.25)/2 = 0.0625  | 0.0625
2        | 1.00 | 1.00 | 0.5*(0.25 + 1.00)/2 = 0.3125  | 0.3750
3        | 1.50 | 2.25 | 0.5*(1.00 + 2.25)/2 = 0.8125  | 1.1875
4        | 2.00 | 4.00 | 0.5*(2.25 + 4.00)/2 = 1.5625  | 2.7500

Notou como valor de f(0.5) se repetiu em dois momentos? Na área do trapézio da iteração 1 e na iteração 2? E que o mesmo aconteceu para f(1.0) (iterações 2 e 3) e f(1.5) (iterações 3 e 4)? Se eu fizesse as somas na mão seria algo assim:
delta*(f(0.0) + f(0.5))/2 + [primeiro trapézio]
delta*(f(0.5) + f(1.0))/2 + [segundo trapézio]
delta*(f(1.0) + f(1.5))/2 + [terceiro trapézio]
delta*(f(1.5) + f(2.0))/2   [quarto trapézio]
-------------------------
delta/2 * (
  f(0.0) +
  f(0.5) + f(0.5) +
  f(1.0) + f(1.0) +
  f(1.5) + f(1.5) +
  f(2.0)
)

O resto foram truques matemáticos para minimizar a quantidade de operações.

Aparentemente, você deseja pegar a fórmula de algum lugar, certo? Bem, podemos pegar do input, a variável sendo x:

function faz_leitura(form) {
  let ini = Number(document.getElementById("ini").value);
  let fim = Number(document.getElementById("fim").value);
  let delta = Number(document.getElementById("delta").value);
  let equacao = document.getElementById("equacao").value;

  let pre_lambda = "(x) => " + equacao;
  let lbda = eval(pre_lambda);

  let result = trapezio_menos_operacoes(lbda, ini, fim, delta);
  document.write("
Integral de " + ini + " até " + fim + " (delta " + delta + "), para a função " + pre_lambda + ": " + result + "
");
}

function trapezio_menos_operacoes(lbda, ini, fim, delta) {
  let lbda_ini = lbda(ini);
  let somas = lbda_ini;
  let last_lbda = lbda_ini;
  for (let i = ini + delta; i <= fim; i += delta) {
    last_lbda = lbda(i)
    somas += last_lbda;
  }
  let integral = delta*(somas - (lbda_ini + last_lbda)/2.0);
  return integral;
}
<form onsubmit="faz_leitura(this); return false;">

  <input required type="text" id="equacao"/>
  equação (use 'x' minúsculo para a variável)

  <input required type="text" id="ini"/>
  ini

  <input required type="text" id="fim"/>
  fim (deve ser maior que ini)

  <input required type="text" id="delta">
  delta (deve ser positivo)

<button type="submit">Integral</button>
</form>

Notou que aqui eu separei a preocupação de cada função? Tem a função que trata da submissão do formulário, preenchendo as variáveis (faz_leitura) e a função que realmente faz o cálculo da integral na estratégia dos trapézios (trapezio_menos_operacoes). A minha separação não ficou boa, não sou o mais experiente em JavaScript + HTML, mas já separa a lógica de negócio da interface.

Olhando outra resposta, me deparo com o possível uso malicioso do eval(). Então, evite o eval(), é mais fácil. Vou editar essa questão para usar  o new Function(), mas agora estou sem condições de testar.

Referências:

classe Number
sobre o botão de submissão

Agradecimentos especiais aos seguintes usuários por me ajudarem a elaborar a resposta:
 @Anderson Carlos Woss,
@Victor Stafusa,
@rray, @pss1suporte
Observações sobre as diferenças entre os dois somatórios
Sobre as duas versões da função de integração, matematicamente elas são iguais, considerando aritmética dos números reais e dos números racionais. Porém, números de ponto flutuante obedecem outras regras.
Quando se faz uma soma em ponto flutuante, você pode perder precisão. Isso é natural e às vezes até mesmo desejável. Eu discorro mais sobre o assunto em um dos pontos desta resposta.
A abordagem de não multiplicar pela base do trapézio faz com que os números sejam maiores, já que no ideal esse valor deve se aproximar de zero. Assim sendo, possivelmente o valor da função pode ser insignificante perante o total acumulado.
Outro ponto para se chamar a atenção é que, se o valor de lbda(x) for decrescente (mesmo que o decrescimento for ficando cada vez menor) conforme x se aproxima do limite final, o valor da somatória não irá se alterar. Isso seria apenas postergado se fosse feita a multiplicação pelo valor da base.
Uma possível medida para evitar isso seria acumular os números enquanto eles forem totalmente significativos em relação à somatória. Quando houver detecção de que o número somado terá parte da precisão perdida, ele deveria iniciar uma nova somatória é assim por diante. No final, dever-se-ia ordenar do menor para o maior e somar nessa ordem. Essa seria uma das maneiras de garantir ao máximo a precisão dos cálculos usando ponto flutuante.

Calcular integral modo trapézio


Laravel 5.2: Class Category Not found

Question: I want to make a dropdownlist in laravel 5.2 application.And i want to load the category Item in my view page .But while i load the page it's showing the following Error.

FatalErrorException in routes.php line 47: Class 'Category' not found

If anyone know what's the problem, pleas help me to finish it.
Here is My Category Model:
<?php

namespace App;
use Illuminate\Database\Eloquent\Model;

class Category extends Model{
     protected $table="categories";

    protected $fillable = ['name'];
}

Here is the routes:
<?php

Route::get('/', function () {

    $categories=Category::all();
    return view('index')->with ('categories',$categories);

});

And here is the view page if it's required:

        <title>Cascading Dropwon</title>
        <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">

Categories and Subcategories Ajax

                {!! Form::open(array('url' => '','files'=>true))  !!}
                {!! Form::token(); !!}

                        Categories
                        <select class="form-control input-sm" name="">
                        @foreach($categories as $category){
                        <option value="{{$category->id}}">{{$category->name}}</option>
                        }
                        @endforeach
                        </select>

                        Sub Categories
                        <select class="form-control input-sm" name="">
                        <option value=""></option>
                        </select>

                {!!Form::close()!!}

Comment: Did you try `composer dump-autoload` ?
Answer: You are not namespacing your Model(Category) in your route.
Change it to
 Route::get('/', function () {

   $categories=\App\Category::all();
   return view('index')->with ('categories',$categories);

});

Comment: thanks..it's worked. But can you tell me why we need to add \App\Category ?
Comment: Because Category is in the App namspace (App\Category) and you are referencing it from App\Http\Controllers namespace which does not exist.

Laravel 5.2: Class Category Not found


sscanf 'conversion lacks type at end of format'

Question: I'm getting this warning from sccanf():
../../../../ext/oedipus/oedipus.c:211: warning: conversion lacks type at end of format

Which comes from this line:
sscanf(v, "%h", &s);

Here s is a short.
I know I can ignore the warning, but up to this point I was warning free, so I'd like to silence it if possible.  What is sscanf() expecting differently?
Answer: You need to use %hd for a short.  %h isn't valid by itself.  From the man page:

h
Indicates that the conversion will be one of d, i, o, u, x, X, or n and the next pointer is a pointer to a short int or unsigned short int (rather than int).

Please don't ignore warnings - they usually mean something has gone wrong.  This case is a good example - your compiler appeared to do the "right thing", but relying on undefined behaviour is always a bad idea.


A quick doubt on a step in the proof of intermediate value theorem

Question: In the proof of the intermediate value theorem there's a step I'm having difficulty inderstanding, namely, step 4) below:
Step 1) Suppose $f(x)$ is continuous on the closed interval $[a,b]$ $\\$ and $f(a)<0<f(b)$;
Step 2) Define the set $S={x∈[a,b]|f(x)≤0}$. The set is not empty since $f(a)<0$; $\\$
Step 3) Define the value $c$ to be the least upper bound of $S$;
Step 4) Since $f(x)$ is continuous, then   $\lim_{x\to c}f(x)=f(c)$;
And here's my doubt. The initial assumption was that $f(x)$ is continuous only in the closed interval $[a,b]$. For $f(x)$ to be continuous in $c$, the least upper bound of $S$, $c$ would have to be in that interval as well. How can I be sure that $c\in[a,b]$? Thanks.
(Here's the complete proof: http://www.milefoot.com/math/calculus/limits/IntValueTheorem13.htm, just in case someone wants to check it out)
Answer: By definition it holds $S \subseteq [a,b]$ and because $[a,b]$ is a closed set $\sup S \in [a,b]$ holds.
Answer: If the function $f$ is defined in an interval which strictly contains $[a,b]$, the least upper bound of $S$ is in $[a,b]$ since $[a,b]$ is closed. Anyway the function is defined on $[a,b]$ so the least upper bound is in $[a,b]$ if it exists, it exists since $[a,b]$ is compact.


Custom search results usign Search API + views

Question: I am currently using Search API for indexing my content . I use Views for displaying search results and Views exposed filter for search form. In the search results page I use facets to filter based on content type, created date etc. I need to upgrade the search feature and provide the following features. Please let me know the Modules or APIs that can help me achieve this.
1) Split the search results based on content type.
Ex: If there are any nodes of content type A, content type B in the search results, I need to display the top 2 nodes of the content type A , top 3 nodes of content type B and the rest of the results.
Formatting of the result display is based on the content type.
2)In the facets I would like to display custom group names instead of the actual content types. Ex: If there are multiple content types like 'Books', 'Articles', 'Magazines' etc I would like to display the link in Facets as a single entry 'Publications' and in the view filter based on the actual content types.
Is it possible to achieve the above 2 features using search API? I am open to changing the approach for displaying search results(alternative for Views and exposed filter if required).
Please suggest
Answer: 1) Although I can't give you the exact answer, what you're looking for is probably View Attachments (https://www.youtube.com/watch?v=s9GC-trMH0o). That allows you to display part of the view in a different way.
2) No idea.
Comment: Thanks. Will try out View attachments with Facets to see if it helps.
Answer: For 2) it seems like you can use the module Search API combined fields


Prove that |-a| = |a|

Question: I'm struggling to understand the basic proof for the following theorem:
$\lvert -a\rvert = \lvert a \rvert$
The provided solution goes on to describe the following:
$(i)$ For $a \ge 0 $, since $-a \le 0$
        $\lvert -a \rvert = -(-a)=a, \lvert a \rvert = a$
My question: Why does $\lvert -a \rvert = -(-a)$ hold true?
Comment: Are you familiar with the (more rigorous) definition of $|\cdot|$?
Answer: The definition of $|a|$ is:
$|a| := \begin{cases} a \quad a \geq 0\\ -a \quad a\leq0 \end{cases}$
So, suppose $a \geq 0$
Then, $|a| = a$
$|-a| = -(-a) = a$. Therefore, $|-a| = |a|$
Now, suppose $a \leq 0$
Then, $|a| = -a$
$|-a| = -a$
Hence, $|a| = |-a|$
So, for all $a \in \mathbb{R}$, we find:
$$|a| = |-a|$$
Answer: The definition of $|\cdot|$ is:
$$|x| := \begin{cases}x & x \ge 0\\-x & x<0\end{cases}$$
So, for $a \ge 0$, since $-a\le 0$, we have $|-a| = -(-a)$, by the definition of $|\cdot|$.
Answer: Provided we are working the a subring $A$, of the reals (i.e. $\mathbb{Z, Q, R}$), then the absolute value function is defined for $a \in A$ as:
\begin{equation}
    |a|=
    \begin{cases}
      -a, & \text{if}\ a<0\\
      0, & \text{if}\ a=0 \\
      a, & \text{if}\ a>0
    \end{cases}
  \end{equation}
So to answer your question, in the case $a \geq 0$, $|-a|=-(-a)$ comes straight from the definition, as $-a \leq 0$ (obviously noting $0=-0$).
Answer: Let's take -a≥0 then |-a|=-a ........(1)
<code>        0<a then |a |=a  ........(2)
</code>
by (1) and (2) |-a|=|a |
Let's take -a<0 then |-a|=-(-a)=a .........(3)
<code>        0≤a then |a |=a ...............(4)
</code>
by (3) and (4) |-a|=|a |
conclusion= |-a|=|a |
NOTE:The absolute value function always gives the positive value of some number.That is why the negative number -a gives the positive number -(-a) as the absolute value.
Comment: Welcome to MSE. Your answer adds nothing new to the already existing answers.

Prove that |-a| = |a|


Dúvida em Order By com LINQ para gerar relatório

Question: Estou fazendo um relatório com o iTextSharp e ordeno pela data mas quando visualizo o relatório a empresa Empresa2XYZ aparece 2 vezes com a mesma data.
Segue o código com LINQ.
lista = context.TB_ContasPagar
                .Where(c => DbFunctions.TruncateTime(c.DataBaixa) >= dataInicial.Date && DbFunctions.TruncateTime(c.DataBaixa) <= dataFinal.Date)
                .OrderBy(c => DbFunctions.TruncateTime(c.DataBaixa)).ToList();
                //.ThenBy(c => c.ID_EmpresaConta).ToList();

Tentei usar o ThenBy mas não resolveu o problema.
Segue imagem
Comment: conseguiu chegar a alguma conclusão?
Comment: Sugiro que melhore a descrição do problema, explicando o contexto. O relatório não deveria estar ordenado também por empresa?
Answer: É bem difícil responder sem o contexto completo, mas vou tentar te guiar para como resolver esse problema.
A 1a coisa a fazer seria remover os DbFunctions.TruncateTime(c.DataBaixa). Parecem ser desnecessários. Caso não queira tem em conta o horário, a sua busca deveria ser pela data com os horários em 00:00 e 23:59:59. O mesmo para o OrderBy, a não ser que seja estritamente necessário que o seu retorno esteja ordenado pela data, ignorano o horário, e posteriormente por outra propriedade (como o nome da empresa), mas ainda assim poderia seguir uma abordagem diferente, se for o caso (não parece ser, dada a sua tentativa com ThenBy(c => c.ID_EmpresaConta)). Altere também a exibição do relatório para incluir o horário, para facilitar perceber o problema. Isso ainda não resolverá o seu problema, mas deve melhorar a sua query e facilitar a visualização dos dados.
Antes de tentar ver o problema no relatório, veja os valores presentes em lista. Imagino que existam 4 entradas para Empresa2XYZ. Para garantir que estes entradas estejam juntas no teu resultado fazer .OrderBy(c => DbFunctions.TruncateTime(c.DataBaixa)).ThenBy(c => c.ID_EmpresaConta).ToList(); deveria de fato resolver o problema, mas sem ter todo o contexto do seu modelo de dados e dos dados, não consigo saber o motivo de não funcionar. Mais uma vez isso ainda não resolve o problema, mas o ajuda a tentar identificá-lo.
Por último, de modo a garantir que os resoltados estão agrupados, você poderia usar o GroupBy e agrupar por data (sem o horário, neste caso) e ID ou nome da empresa. Isso pode ser feito assim .GroupBy(x => new { x.Column1, x.Column2 }), onde Column1 seria a sua data, sem hora, e Column2 um identificador único para as empresas.


How can I call to function that exists in other file?

Question: Given 2 files, for examples:
file1.c :
int main(){
  f();
  return 0;
}

file2.c:
void f(){
  return;
}

Why I can't call f from file1.c like that?
Answer: Because first you need to tell the compiler (declare) that it exists somewhere:
void f(); //function declaration

int main()
{
    f();
    return 0;
}

Usually, though, it is better to put such declarations in a separate header file (e.g. file2.h) so that later you could include this file (e.g. #include "file2.h") instead of duplicating such declaration in every other file where you need this function.
Answer: The problem is that file1.c does not "know" that the function f exists. You need to use a prototype. The standard way is to put prototypes in header files and definitions in .c files.
It could look like this:
file1.c:
#include "file2.h"
int main(){
  f();
  return 0;
}

file2.h:
#ifndef FILE2_H
#define FILE2_H
void f();
#endif

file2.c:
#include "file2.h"
void f(){
    return;
}

Comment: @PeterJ_01 You're right. I removed everything about it.


UITableView crashes on scroll when using XML plist

Question: i've been reading for hours, searched apple's doc, stackoverflow, can't understand what i'm doing wrong....
when i use this data from a XML plist on my UITableViewController:
- (void)viewDidLoad
    {
        [super viewDidLoad];

        NSString *path = [[NSBundle mainBundle] pathForResource:@"arrayofstrings"
                                                             ofType:@"plist"];
        NSData *myData = [NSData dataWithContentsOfFile:path];
        NSString *error;
        NSPropertyListFormat format;

        myArray = [NSPropertyListSerialization propertyListFromData:myData
                                                       mutabilityOption:NSPropertyListImmutable
                                                                 format:&format
                                                       errorDescription:&error];
    }

my tableview shows the first visible rows just fine but crashes when trying to scroll.
it doesn't happen when instead of the XML data i use something like this:
- (void)viewDidLoad
        {
            [super viewDidLoad];

        myArray = [[NSArray alloc] initWithObjects:@"thing1", @"thing2", @"thing3", @"thing4", @"thing5",@"thing6", @"thing7", @"thing8", @"thing9", @"thing10",
            @"thing11",@"thing12", @"thing13", @"thing14", nil];

        }

this way the tableview scrolls just fine. what's my problem?! Is the plist conversion to array supposed to be in any other way?
Answer: - (void)viewDidLoad
    {
        [super viewDidLoad];

        NSString *path = [[NSBundle mainBundle] pathForResource:@"arrayofstrings"
                                                             ofType:@"plist"];
        NSData *myData = [NSData dataWithContentsOfFile:path];
        NSString *error;
        NSPropertyListFormat format;

        myArray = [[NSPropertyListSerialization propertyListFromData:myData
                                                       mutabilityOption:NSPropertyListImmutable
                                                                 format:&format
                                                       errorDescription:&error] retain];
    }

The return value from propertyListFromData:mutabilityOption:format:errorDescription is autoreleased. Make sure you call retain so it doesn't get released out from under you at the end of the current run loop.
The second method works because creating the NSArray with alloc/init leaves the array with a retain count of 1.
Comment: i bow to your coding power! you were absolutely right, i should know better the methods i use.... THANKS!
Answer: The problem is that in the first case your call to [NSPropertyListSerialization propertyListFromData: returns an NSArray with no retain count on it (note the method doesn't have alloc, new, or copy in the name) - and then you don't retain this NSArray. Hence, the array is getting deallocated shortly after, and your code crashes trying to access garbage memory.
In the second case, you are making an NSArray using alloc - this returns an NSArray with a retain count of 1, which means it isn't deallocated (until a release gets called at some point).
To fix this, in your first case you want to assign the array as follows:
self.myArray = ...

The self. is the crucial part here (assuming you have declared the myArray property as retain).
There's plenty of resources and blog posts available concerning memory management.


let $f$ be holomorphic and bounded on $\mathbb{C}\backslash K$ with $K = \{0\}\cup\{\frac11, \frac12, \cdots\}$ and further $f(2) = 1$. Find f.

Question: let $f$ be holomorphic and bounded on $\mathbb{C}\backslash K$ with $K = \{0\}\cup\{\frac11, \frac12, \cdots\}$ and further $f(2) = 1$. Determine such f.

What we tried
Since f is bounded, points in $K$ give essential or removable singularities. If every $k \in K$ had a removable singularity, then $f$ could be extended to a holomorph function on $\mathbb{C}$, and hence by Liouville's theorem $1$ everywhere.
Now we only have to look at functions with at least one essential singularity in some $k \in K$. Any hints?
Kees
Answer: I'm not sure what this talk of Picard, Casorati-Weierstrass is all about. Suppose $|f|\le M$ on $\mathbb {C}\setminus K.$ Each $1/n, n \in \mathbb {N},$ is an isolated singularity of $f.$ Since $f$ is bounded, $f$ has a removable singularity at each of these points. Thus $f$ extends to be holomorphic on $\mathbb {C}\setminus \{0\},$ with $|f| \le M$ on this larger domain. Now $0$ wasn't an isolated singularity of $f$ at the outset, but it is now, and the boundedness of $f$ tells us this is a removable singularity after all. Thus $f$ extends to be entire, with $|f|\le M$ everywhere. By Liouville $f$ is constant, and of course $f(2)=1$ implies $f \equiv 1.$
Answer: As Kees suggests, now we only have to look at the case where there is at least one essential singularity from $K$, but by Great Picard's theorem, $f$ is unbounded in any neighborhood of an essential singularity. So any possible singularity is removable and $f$ must be constant and equal to 1.
Comment: Can use Casorati-Weierstrass aswell. It is much less deep than Picard.


Maximum overs for a bowler in reduced 14 overs match?

Question: How to calculate maximum overs for a bowler in reduced over match i.e T20 match reduces to 14 or 13 overs?
Can two bowlers play 4 overs and the other 3 bowlers play 2 overs per each in 14 over match?
Answer: As always, this depends on the playing conditions for the tournament you are in. However, we can take the current T20 International playing conditions as a guide:

In a delayed or interrupted match where the overs are reduced for both teams or for the team bowling
  second;
for innings of rescheduled length of at least 10 overs, no bowler may bowl more than one-fifth of
  the total overs allowed. Where the total overs is not divisible by 5, one additional over shall be
  allowed to the maximum number per bowler necessary to make up the balance.

or for 14 overs, 4 bowlers may bowl 3 overs each and one bowler may bowl 2 overs.


Triple Difference-in-differences

Question: I am currently trying to run a regression working out the change in the mental well-being of ethnic individuals in a set of countries after a migration policy was imposed. I have two waves of data, one before the policy and one after the policy. Essentially the control group are non-ethnic individuals in the countries while the treatment group are the ethnic individuals in the country. The model is:

Where,
Country - is the name of the country analysed
Ethnic - is a dummy variable for whether the individual is an ethnic =1 or non-ethnic=0
Post policy - Is for the individuals interviewed in the second period, after the policy had been placed. 1 if in second wave and 0 otherwise.
Given this the coefficient of interest is  δ_6 as it shows the difference in the well-being of ethnic and non-ethnic individuals after the policy had been imposed. It captures the difference-in-difference indifference.
I wondered if my model makes sense and whether the regression is correct.
Comment: How many countries do you have? Also, is the immigration policy uniform? In other words, is the "post policy" period the same across countries?
Comment: there are 9 countries and the policy is uniform
Comment: You state that the country variable is a *country identifier*, or simply the "names" of the countries you're analyzing. But this should actually be a binary treatment variable indexing those countries where the immigration policy was introduced. The second treatment group is a subgroup within your countries that is believed to be more/less sensitive to the immigration reform. Does this align with your study? Also, what is $\omega_{ict}$? I assume it's a vector of individual level control variables, but I can't be sure.
Comment: Wict is a vector of individual controls. I was wondering if my analysis is also correct so that the treatment group are the ethnics in the UK and then the ethnics in the other 8 countries. Whilst the control group are the non-ethnic individuals in the UK and in the other 8 countries. I'm specifically looking at the UK as the policy was implemented in the UK. I want to see the effect of the policy in the UK but also in the 8 other countries.
Comment: So this is only a UK policy?
Answer:
I wondered if my model makes sense and whether the regression is correct.

Seems okay, but you're missing one of the double interactions.
Assuming the policy is uniformly adopted, then the model requires the standard triple interaction term, and all double interactions. The ethnic dummy must also be multiplied with the post-policy indicator. For brevity, I re-specified your model below using abbreviated variable names:
$$
MW_{ict} = \alpha + \delta_ 1E_i + \delta_ 2C_c + \delta_3 P_t + \delta_4 (E_i \times P_t) + \delta_5 (C_c \times P_t) + \delta_6 (C_c \times E_i) + \delta_7 (E_i \times C_c \times P_t) + \epsilon_{ict}.
$$
If executed properly, software should return eight coefficients, including the regression constant.
Comment: Oh yes, that makes sense. Thank you
Comment: I was also wondering what the assumptions are for a 2-time period DiD analysis? I know you can't test the parallel trends assumption but what would we just assume the interviews of the individuals are done randomly? Is this all that we can assume? Or is there more to this? I am slightly confused based on what I have read
Comment: Also I was wondering if i need to include an individual and time fixed effects within the model

Triple Difference-in-differences


Help with linear algebra question about basis for a vector space.

Question: Let $\{u_1, u_2, u_3\}$ be a basis for a vector space $V$. Then if we define $v_1 = u_1 + 2u_3$,  $v_2 = u_1 + 2u_2 + 3u_3$,  $v_3 = u_2 - u_3$, show that $\{v_1, v_2, v_3\}$ forms a basis for $V$.
Attempt:
I honestly have no idea where to start. All I know is that a basis for a vector space is the minimum amount of vectors that represent a set of vectors and that the vectors are linearly independent.
Comment: Well you know it has enough cardinality. Just show it is linearly independent by trying to solve the linear equation that would show dependency and fail.
Answer: Since $(u_1,u_2,u_3)$ form a basis of the vector space $V$ we know dim(V)=3. This means that any linearly independent set of 3 vectors would be a basis of the vector space. Show that the defined $(v_1,v_2,v_3)$ are linearly independent. (Remember that we already know $(u_1,u_2,u_3)$ are linearly independent).
Answer: There are multiple ways of answering this, but for a lazy person with access to a computer or calculator, I'd first rewrite this in terms of matrices. For example, for $U = [u_1,u_2,u_3]$ and $V = [v_1,v_2,v_3]$, then $V=UA$ where
$A = \left[\begin{matrix} 1 &1&0\\0&2&1\\2&3&-1\end{matrix}\right]$
Since $v_i$'s is written as a linear combination of $u_i$'s, then the subspace spanned by $v_i$'s is a subset of the subspace spanned by $u_i$.
Now, if $A$ is full rank (which can be verified in a number of ways, using rank(A), SVD or rref by hand, or any other method of choice), then $A$ is invertible, so $U = VA^{-1}$. So, the subspace spanned by $u_i$'s is also a subset of the subspace spanned by $v_i$'s.
Therefore, the two span the same subspace. Since 3 $u_i$'s are all independent, they must span a vector space of dim 3, which means 3 $v_i$'s spanning the same subspace must be linearly independent. So, $v_i$'s form a basis.
Comment: What do you mean by "A is full rank" ? Rank is the number of linearly independent rows right ?
Comment: I think full rank usually refers to full column rank but in this case it doesn't matter, since for square matrices row rank = column rank.  Additionally for square matrices, full rank implies the matrix is invertible, which is the quality you need.
Answer: Since $\{u_1,u_2,u_3\}$ is a basis for $V$, it follows that $V$ has dimension $\color{red}{3}$.
You are given a set of vectors $\{v_1,v_2,v_3\}$. Clearly, this set contains $\color{red}{3}$ vectors in $V$. Hence, in order to deduce that it is a basis for $V$, all you have to do is prove that $v_1,v_2,v_3$ are linearly independent.
You can do so using the definition of linear independency as follows. Suppose that there exists three scalars $\gamma_1,\gamma_2,\gamma_3$ such that
$$
\gamma_1\color{blue}{v_1}+\gamma_2\color{green}{v_2}+\gamma_3\color{orange}{v_3}=0.
$$
(Note that the $0$ on the RHS of the equality is the zero vector.) The goal is to show that $\gamma_i=0$ (here $0$ is the zero scalar) for all $i$. We can rewrite the above equality as
$$
\gamma_1\color{blue}{(u_1+2u_3)}+\gamma_2(\color{green}{u_1+2u_2+3u_3})+\gamma_3(\color{orange}{u_2-u_3})=0,
$$
or
$$
(\gamma_1+\gamma_2)u_1+(2\gamma_2+\gamma_3)u_2+(2\gamma_1+3\gamma_2-\gamma_3)u_3=0.
$$
Now, you know that $u_1,u_2,u_3$ are linearly independent, so the coefficients must all equal zero:
\begin{align}
\gamma_1+\gamma_2=0,\\
2\gamma_2+\gamma_3=0,\\
2\gamma_1+3\gamma_2-\gamma_3=0.
\end{align}
This is a linear system that is readily solved for $\gamma_1,\gamma_2,\gamma_3$. Indeed, the first equation gives $\gamma_2=-\gamma_1$, the second one then gives $\gamma_3=2\gamma_1$ and the third one leads to $-3\gamma_1=0$. All in all, we do must have $\gamma_1=\gamma_2=\gamma_3=0$, which was to be proved.


Rudin RCA exercise 7.22. $f(x)=x^{-1}(\log x)^{-2}$ is integrable but $\int_0^1 Mf = \infty$.

Question: Define $f(x)=x^{-1}(\log x)^{-2}$ if $0<x<\frac{1}{2}$, $f(x)=0$ on the rest of $R$. Then $f \in L^1(R)$. Show that
$$(Mf)(x) \ge |2x \log(2x)|^{-1} \;\;(0<x<1/4)$$ so that $\int_0^1 (Mf)(x)dx=\infty.$
$$
(Mf)(x) = \sup_{0<r<\infty} \frac{1}{m(B_r)}\int_{B_r(x)}|f(y)|\mathrm{d}y
$$
where $B_r(z)$ is a ball centered around $x$ with radius $r$.
I am stuck with proving this lower bound for the maximality function. I would greatly appreciate any help.
Comment: What is $k?\,\,$
Comment: @zhw. My mistake I mixed up notations.
Answer: A simpler way to show $Mf\notin L^1$ is to note there is a constant $c>0$ such that $|f|>c$ on a set of positive measure $E\subset (0,1/2).$ Then for $x > 1/2,$
$$Mf(x) \ge \frac{1}{B(x,x)}\int_{B(x,x)} |f| \ge \frac{1}{2x}\cdot c\cdot m(E),$$
which is not in $L^1.$
Answer: The other answer is the slick way to go, but the hint reduces the problem to a calculation:
Take $0<x<1/4$ and $r=x$. Then,
$Mf(x)\ge \frac{1}{B_r(x)}\int_{B_r(x)} |f|=\frac{1}{2x}\int_{0}^{2x}|f(t)|dt=$
$\frac{1}{2x}\cdot \underset{\delta\to 0^+ } \lim \int_{\delta}^{2x}|f(t)|dt=\frac{1}{2x}\cdot \underset{\delta\to 0^+ } \lim \left |\frac{1}{\ln 2x}-\frac{1}{\ln \delta}\right |=\frac{1}{2x\ln 2x}$
from which the result follows.


Convert MudTextBox text to upper case when typing

Question: How can i covert MudTextBox text to upper case when typed
<MudTextField Required="true" Label="@languageContainer.Keys["FirstNameUS"]" Variant="Variant.Outlined"
                                  @bind-Value="person.FirstNamesUS" For="@(() => person.FirstNamesUS)" />

Answer: Like this:
<MudTextField Required="true"
              Label="@languageContainer.Keys["FirstNameUS"]"
              Variant="Variant.Outlined"
              T="string"
              Value="person.FirstNamesUS"
              ValueChanged="(value) => person.FirstNamesUS = value.ToUpper()"
              Immediate="true"
              For="@(() => person.FirstNamesUS)" />

TryMudBlazor


map.setCenter and map.Panto will not shift map

Question: I have tried to change the .onchange function multiple times to change map zoom level and center point. Zoom change takes affect, but the map does not change locations.
Any help would be appreciated. I've removed my api key, but otherwise the map will function on its own.


Barra de progresso em uma célula de uma tabela

Question: Estou fazendo um calendário e preciso fazer uma barra de progresso do tempo decorrido de cada dia. Montei o calendário usando tabelas do HTML.
Como eu posso fazer essa barra de progresso de cada dia separadamente?
Comment: Vc está usando Bootstrap por acaso?
Comment: Estou sim, mas a questão é que quero colocar uma barra de progresso para cada dia. É possível fazer isso? Lembrando que cada dia meu é uma célula de uma tabela
Comment: Phelipe editei a minha resposta completamente como BS etc, acho que ficou mais perto do que vc queria, leia lá que tem mais detalhes.
Answer: Editei a resposta completamente, agora que vc falou que é Bootstrap fiz esse modelo com uma barra para cada dia, com as classes originais do BS, não inclui nenhum CSS novo e acho que vai te atender. O que vc precisar customizar basta fazer um Override das Classes.
Veja o Snippet abaixo:

<!DOCTYPE html>

  <title>Bootstrap Example</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

Tabela com Borda

A classe .table-bordered coloca a borda na Table

MÊS

1

              100% Complete (success)

2

              100% Complete (success)

3

              100% Complete (success)

4

              100% Complete (success)

5

              100% Complete (success)

6

              100% Complete (success)

7

              60% Complete (warning)

8

9

10

11

12

13

14

15

16

17

18

19

20

21

        22
        23
        24
        25
        26
        27
        28

        29
        30
        31

Deixei o resto do mês pra vc mesmo terminar e ver como foi feito!
Na
 você pode trabalhar com os valores de forma dinâmica para fazer a barra ir completando ao longo do dia.
O texto que está dentro da barra é opcional pode ter ou não "100% Complete (success)"


Is it a must to include a random slope in a mixed model?

Question: I am learning about fitting mixed models and I find when it is justified to include or exclude a random slope rather confusing.
Some tutorials suggest that although the maximal random structure should be specified at the outset, the random slope should be kept only if it contributes to extra explanatory power, i.e. is significant and hence mathematically justified to stay in the model.
Other papers suggest that the random slope should be kept regardless of its significance when a cross-level interaction effect is included in the model; but does this assertion hold when no cross-level interaction but only a main effect is being investigated? Under what circumstances should I decide to keep or discard the random slope component from my model?
Comment: The following papers suggest that omitting the random slope component tends to inflate Type I error when a cross-level interaction term is included:

Bell, A., Fairbrother, M., &Jones, K. (2019). Fixed and random effects models: making an informed choice. Quality and Quantity, 53(2), 1051–1074. https://doi.org/10.1007/s11135-018-0802-x

Heisig, J. P., &Schaeffer, M. (2019). Why you should always include a random slope for the lower-level variable involved in a cross-level interaction. European Sociological Review, 35(2), 258–279. https://doi.org/10.1093/esr/jcy053
Comment: (+1) can you site some references, and summarise the reasoning, for the argument in the 3rd paragraph ?
Answer: There is considerable disagreement on this topic.
I like to keep it simple. If you have a priori reasons to believe that the fixed effect in question should vary by subject (or whatever the grouping variable is) then you should fit random slopes. Obviously, this is provided that the data supports such a model. Often a model containing random slopes will have a singular fit, either because the correlation between the slopes and intercepts is estimated close to, or at, +/- 1, or because the variance in the random slopes is estimated close to, or at, 0. In the former case, a model fitted without such correlation can be fitted, but in the latter case the only solution is usually to remove the random slopes.
If the model converges without warnings, then I would retain the random slopes. I would not do any statistical test to decide whether to retain them, because I had a priori reasons to include them in the first place and just because they weren't significant in this sample is not a reason to exclude them if I believe they should be present in the population.
Having said that, I can't really argue with the approach of testing with a likelihood ratio, and removing the slopes if they don't offer an improved fit, on the basis of model parsimony. It's just my preference to retain them.
I am not familiar with the argument to retain random slopes if a cross-level interaction is fitted in the fixed part of the model. Does this refer to random slopes for the interaction only ?
Comment: I hope that you share the results of your simulations, @RobertLong! Heisig & Schaeffer show that the problem actually gets worse at larger sample sizes. https://academic.oup.com/esr/article/35/2/258/5306121#132685273
Comment: The Heisig & Schaffer paper is the one that deals with cross-level interactions. They find in simulation work that the test for significance of the cross-level interaction when the level 1 slope is held fixed is biased in that the p-value tends to be understated  (lower) relative to a model in which the level 1 slope is treated as random. They use the term "anti-conservative" in reference to the first case (fixed slope + cross-level interaction) - one would be more likely to conclude statistical significance when there is none.
Comment: @ErikRuzek thanks. That's interesting.  I will probably do some of my own simulations. Personally I don't use p values at all, so if the effect sizes are unbiased I am not bothered.  I wonder if this p value bias goes away for larger numbers of clusters and/or cluster sizes.
Comment: Thank you for answering. So it seems that it's more important to theoretically justify the inclusion of random slopes prior to constructing the model. Now I wonder when people would decide not to fit random slopes in the model at the outset as it seems reasonable that every cluster can respond in different ways to the same stimuli/treatment...
As for the cross-level interaction question, the papers argue that the random slopes of the level-1 variables should always be included. I just attached two papers discussing this in the question.
Comment: I agree with you. It is often very easy to justify random slopes. Situations where it is more of a reach is for fixed effects like sex which obviously do not vary within subjects
Comment: As for the cross-level interaction question, this site tries to be as self contained as possible so when asking about arguments made in papers plesse try to summarise the substance of the arguments, not just link to the papers.


Como atribuir valor com jQuery a um textarea

Question: Eu tenho um formulário de planos, e gostaria que ao clicar em adquirir, ele já preencher uma breve mensagem no  do formulário.
Estou tentando dessa maneira, porém não retorna valores

window.onload = function (){

var mensagem = document.getElementById('mensagem');
var button = document.getElementById('button');
var assinatura = '\n\nParabéns!!\nEscolheu o plano basic..'

button.addEventListener('click', function() {
  mensagem.value += assinatura;

});
}
<form>
      <textarea id="name" name="testa"></textarea>
      <button id="teste" type="button">Testando</button>
</form>

(Lembrando que o trecho acima é um teste apenas)
Answer: Sim, mas, você não colocou os nomes corretamente o document.getElementById pega o elemento pela configuração do id, exemplo:
Html:
<button id="btn" />

Javascript:
var btn = document.getElementById("btn"); // btn é o id do button

Agora com as modificações no seu código:

window.onload = function() {
  var mensagem = document.getElementById('name');
  var button = document.getElementById('teste');
  var assinatura = 'Parabéns!!\nEscolheu o plano basic..'
  button.addEventListener('click', function() {
    mensagem.value = assinatura;
  });
}
<form>
      <textarea id="name" name="testa"></textarea>
      <button id="teste" type="button">Testando</button>
</form>

Observação: no seu código você colocou id="name" e fez a busca document.getElementById('mensagem') e no botão se colocou no id="teste" e fez a busca document.getElementById('button'), ou seja, errou o nome pelo qual deveria fazer a referencia no seu código javascript
Referencia:

MDN web docs - document.getElementById()
MDN web docs - addEventListener()


How do I set the title tag for the maintenance page?

Question: I need to change the default title tag for the maintenance page, which currently is "Site under maintenance | [sitename]".
I tried to set $variables['head_title'] in hook_preprocess_maintenance_page() but it doesn't work.
Also I think it can be set in hook_preprocess_html(), but I don't know how to check the served page is the maintenance page.
How can I achieve this?
Answer: TEMPLATE_preprocess_maintenance_page changes only variables for maintenance-page.html.twig. But <title> is outputted in html.html.twig, so you have to choose another preprocessor template_preprocess_html. So you can use this code(don't forget to clean cache after it):
function mytheme_preprocess_html(&$variables) {
  $maintenance_mode = \Drupal::state()->get('system.maintenance_mode');
  if (!empty($maintenance_mode)) {
    $variables['head_title'] = (string)t('My Custom Maintenance Title');
  }
}

Answer: To change this message, you can go Adm -> Config -> Maintenance page and write you own message.
If you really want do this in a preprocess function:
function TEMPLATE_preprocess_maintenance_page(&$variables) {
  $variables['head_title'] = "A custom var that YOU going to use in maintenance-page.html.twig";
  $variables['title'] = "Default var used to display title message 'Site under maintenance' ";
}

Or you can even override maintenance-page.html.twig file to put your own message, but its not the best option.
Comment: In Config -> Maintenance page I can change message only. But I need to change title tag.
And I already tried using preprocess function for it, but it doesn't affect anything. And it's the problem.
Comment: @paulanders Edit your question to provide more information about your context because there is no title tag or 'head_title' by default in `maintenance-page.html.twig`. Are you using a custom theme, module or whatever? Are you using preprocess functions in a module or a theme? My answer works ok in a clean install of Drupal 8.
Answer: On Drupal 9 with a subtheme from Bootstrap 5, I used this function to change the head title and the page title.
/**
 * Implements theme_preprocess_html().
 */
function TEMPLATE_preprocess_html(&$variables) {
  $maintenance_mode = \Drupal::state()->get('system.maintenance_mode');
  if (!empty($maintenance_mode)) {
    $title = t('My Custom Maintenance Title');
    $variables['head_title']['title'] = $variables['page']['#title'] = $title;
  }
}

Answer: If you don't want to write php code,you can try this↓
Since the maintenance setting page(/admin/config/development/maintenance) supports JS,
it may be possible to solve this indirectly by adding the following code

Comment: As it's currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer).
Answer: If you have access to the backend, you can modify the string directly for a temporary change. Change /var/www/html/ to the location of your install and other strings to fit your needs.

Login with SSH. ssh firstname.lastname@example.com
Edit the file /var/www/html/includes/common.inc with your favorite text editor and replace Site under maintenance with your new message. You could also use sed. sed -i 's/Site under maintenance/Your new title here/' /var/www/html/includes/common.inc
Clear the cache. cd /var/www/html/ && drush cc all

This will be overwritten after an update to Drupal Core.
Comment: That's a very bad idea which is why you're getting downvoted. See https://www.drupal.org/docs/7/site-building-best-practices/never-hack-core for details.
Comment: It works as a quick temporary fix. It will get overwritten with an update to core.


Cliques of complementary graph

Question: "If S is a maximal independent set in some graph, it is a maximal clique or maximal complete subgraph in the complementary graph." from Wikipedia
Does this mean, given a graph G, if it is bipartite, then it's complement G' will have 2 maximal cliques? With, Union of vertices in these two cliques = set of all vertices in G?
example -
image
Here, Gc is bipartite, we can color it with 2 colors, and the independent groups are - {a, b, c} and {d, e}.
And so graph G (it's complement) have 2 maximal cliques {a, b, c} and {d, e}, whose union is all vertices.
 So, is it true, for every graph??
Comment: An independent set in a graph is a set such that no two points in that set are connected. When you take the complement, all these points become connected to each other, that's what creates the clique. The larger the independent set, the larger the clique. I don't see what coloring has to do with this.
Comment: In a vertex coloring, the vertices of a particular color form an independent set. In the example, the nodes $a,b,c$ form an independent set in $G^c$.
Answer: Suppose that $G$ is bipartite, with vertex set $V=V_0\cup V_1$, where $V_0$ and $V_1$ are the two parts. Then $V_0$ and $V_1$ are independent sets, so they will be cliques in the complement of $G$. However, they may not be maximal independent sets in $G$, so they may not be maximal cliques in the complement of $G$. Let $W_0$ be the set of vertices in $V_0$ that are adjacent to some vertex of $V_1$, and let $W_1$ be the set of vertices in $V_1$ that are adjacent to some vertex of $V_0$. Let $I=V\setminus(W_0\cup W_1)$; $I$ contains the isolated vertices of $G$. Then $W_0\cup I$ and $W_1\cup I$ are maximal independent sets in $G$ and maximal cliques in the complement of $G$.
Answer: Yes, if the vertex set of a graph $G$ can be partitioned into two independent sets, then the vertex set of the complete graph $G^c$ can be partitioned into two cliques (and conversely).  More generally, for any subset $W \subseteq V(G)$, $W$ is an independent set of $G$ iff $W$ is a clique of $G^c$.   And $W$ is a maximal independent set of $G$ iff $W$ is a maximal clique of $G^c$.

Cliques of complementary graph


Show that $\{Z(p):p\in \mathscr P\}$ is a basis for the closed sets of some topology (Called the Zariski topology) on $\mathbb R^n$.

Question: Let $n\in \mathbb N$, and let $\mathscr P$ denote the collection of all polynomials in $n$ variables. For $p\in \mathscr P$, let $Z(p)=\{(x_1,x_2,...,x_n)|p(x_1,x_2,...,x_n)=0\}$.
Show that $\{Z(p):p\in \mathscr P\}$ is a basis for the closed sets of some topology (Called the Zariski topology) on $\mathbb R^n$.
My attempt:-
I used the result for Basis  for the closed sets of topology on X.
(I)  We need to prove that $\bigcap_{p\in \mathscr P}Z(p)=\emptyset.$ $Z(p(x_1,x_2,...,x_n)=1)=\{(x_1,x_2,...,x_n)|p(x_1,x_2,...,x_n)=0\}=\emptyset$. Which implies $\bigcap_{p\in \mathscr P}Z(p) \subset Z(p(x_1,x_2,...,x_n)=1)=\emptyset \implies \bigcap_{p\in \mathscr P}Z(p)=\emptyset.$
(II) if $Z(p_0),Z(p_1)\in\mathscr X$ and $(x_1,x_2,...,x_n) \notin Z(p_0)\cup Z(p_1)$, then there is a $Z(p_2)\in\mathscr X$ such that $(x_1,x_2,...,x_n) \notin Z(p_2)\supseteq Z(p_0)\cup Z(p_1)$.
$(x_1,x_2,...,x_n) \notin Z(p_0)\cup Z(p_1)\implies p_0(x_1,x_2,...,x_n)\neq0$ and $p_1(x_1,x_2,...,x_n)\neq 0.$ We can choose $p_2=p_0 p_1$ such that $(x_1,x_2,...,x_n)\notin Z(p_2)$. We know that $Z(p_0)\cup Z(p_1) \subset Z(p_2)$.
Have I done the proof correctly?
Comment: Define:  Z(p = 1).
Comment: $Z(p)=\{(x_1,x_2,...,x_n)|p(x_1,x_2,...,x_n)=0\}$
Comment: When we substitute $p(x_1,x_2,...,x_n)=1$ we get $Z(p=1)$. which is an empty set.
Comment: If I define like this, is my proof correct?
Comment: No, Z is defined for polynomials, it is not defined for statements like p = 1.  Thus Z(p = 1) is meaningless.
Comment: I meant constant polynomial.
Comment: Z(p) where p = 1 or Z(1) isn't geeky.
Comment: yes. You were talking about the proof of the first part. right?
Answer: $Z(p) \cup Z(q) = Z(pq)$.
Let 1 be the polynomial of $n$ variables with constant value 1.
$Z(1)$ is empty.
Comment: what about the second property?
Comment: The first line proves it.
Comment: @Mathgeek the product of two polynomials is a polynomial. So define $p_2=p_1 p_2$ in your proof attempt.
Comment: That is how I defined @HennoBrandsma. I defined $p_2=p_1p_0$.
Comment: In the second part of the proof.
Comment: But you need that $Z(p_2) =Z(p_0) \cup Z(p_1)$, because we need $x \notin Z(p_0) \cup Z(p_1)$ and that now follows. @Mathgeek Or prove separately that $x \notin Z(p_2)$.
Comment: What do you mean? Is my proof correct? How do I prove separately that $x\notin Z(p_2)$?
Answer: The set of $\{Z(I): I \subseteq \mathcal{P}\}$, where $Z(I)=\bigcap_{p \in I} Z(p)$ is in fact the whole topology, not just a closed base for it, as I showed here.
The basis fact immediately follows, by the definition of a closed base (you can write all closed sets as intersection of base elements).
Comment: No, We want to prove $\{Z(p_1),Z(p_2),...,Z(p_n),....\}$ is a basic set.
Comment: @Mathgeek if $C$ is closed, then $C = Z(I)= \bigcap \{Z(p): p \in I\}$. BTW, don't think the base is countable, it is not, though you seem to suggest so.


Prove that $\sum_{n=1}^{+\infty}\frac{(2n+1)}{(n^2)(n+1)^2}=1$.

Question: Find $$\sum_{n=1}^{+\infty}\frac{(2n+1)}{(n^2)(n+1)^2}$$
The correct answer is 1 but I can't figure out how you end up to this conclusion
Comment: Have you studied simpler sequences before? Have you used the concept of generalizing to $T_r-T_{r-1}$, then cancelling the common terms?
Comment: Hint: TLSCPC.$\phantom{}$
Answer: Since$$\frac{2n+1}{n^2(n+1)^2}=\frac1{n^2}-\frac1{(n+1)^2},$$your series is a telescoping series.


How to replace node_form() with my custom form callback?

Question: In my module, I want to override the call to node_form() for a specific node type called superpage, because I want this specific node form to allow for a confirmation step before saving.
In drupal_retrieve_form(), every node form is built by the function node_form(), which adds everything you'd expect from a node form.
I want to add an extra step to my form: First, the node form should be rendered normally; then, when the user clicks Save, I am using a custom submit handler to set $form_state['rebuild'], and to set a custom flag, signaling the need for confirmation. Now I want to rebuild the form not through node_form(); instead I want to display a confirm_form().
This means that the process starts over in drupal_retrieve_form(), which simply calls node_form() again, because the node module implements hook_forms() and defines that callback for all node forms.
I would like to replace the form callback for my custom content type, so that it returns a normal node form if confirmation is not needed, or a confirmation form if needed.
Implementing hook_forms() in my module didn't help.
/**
 * Implements hook_forms().
 */
function superpages_forms($form_id, $args) {
  $forms = array();
  if ($form_id == 'superpage_node_form') {
    // Adding this callback crashes drupal_retrieve_form().
    $forms[$form_id]['callback'] = 'superpages_wrapped_node_form';
  }
  return $forms;
}

function superpages_wrapped_node_form($form, &$form_state, $node) {
  // Build for special case: a confirmation form.
  if (!empty($form_state['values']['confirm_is_needed'])) {
    $confirm = t('You should be careful with this. Are you sure?');
    $confirm_form = confirm_form(array(), $confirm, 'node/' . $node->nid);
    return $confirm_form;
  } else {
  // Build a normal node form.
    return node_form($form, $form_state, $node);
  }
}

Answer: Variant 1. You can use hook_menu_alter and you can set your callback
/**
 * Implements hook_menu_alter.
 */
function MYMODULE_menu_alter(&$items) {
  $items['node/add/superpage']['page callback'] = 'MYMODULE_superpage_form';
}

Variant 2. You can use hook_form_FORM_ID_alter  and override/edit the form
/**
 * Implements hook_form_FORM_ID_alter()
 */
function MYMODULE_form_superpage_node_form_alter(&$form, &$form_state, $form_id){
  // your code
}

Comment: Thanks, I think I'll go with Variant 1, it should take less effort.


GridView Row Command Error

Question: I have a GridView setup with the entity framework with two TemplateFields that each call a popup and only displays text from the database. Both TemplateFields are setup as ImageButtons.
<asp:GridView ID="grvResults" runat="server" DataKeyNames="Soln_SolutionId"  OnRowCommand="grvResults_RowCommand" CssClass="dgstyle" />
<Columns>
<asp:TemplateField HeaderText="">
<ItemTemplate>
   <asp:ImageButton ID="imgPreview" runat="server" CommandName="viewDoc" CommandArgument='<%#Eval("Link")%>' ImageUrl="~/images/viewpage.gif" ImageAlign="Left" Width="25" Height="25" ToolTip="View attachment" AlternateText='<%#Eval("Link")%>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="">
<ItemTemplate>
   <asp:ImageButton ID="imgDetail" runat="server" CommandName="viewDetail" CommandArgument='<%#Eval("Soln_SolutionId")%>' ImageUrl="~/images/docview.gif" ImageAlign="Left" Width="25" Height="25" ToolTip="View details about the page" AlternateText="View details" /></ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>

Code Behind (C#)
protected void grvResults_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            int DetailID = Convert.ToInt32(e.CommandArgument.ToString());
            using (VIPCRMEntities dbc = new VIPCRMEntities())
            {
                Solution selDetail = (from c in dbc.Solutions
                                      where c.Soln_SolutionId == DetailID
                                      select c).First();
                if (e.CommandName == "viewDetail")
                {
                    InfoModal.Show();
                    lblInfoText.Text = selDetail.Soln_SolutionDetails;
                }
                else if (e.CommandName == "viewDoc")
                {
                    InfoModal.Show();
                    lblInfoText.Text = selDetail.soln_link;
                }
            }
        }

If I click the "viewDetails" image, it works perfectly.
If I click the "viewDoc" image, it fails with the following exception :
Input string was not in a correct format.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.FormatException: Input string was not in a
  correct format.
Source Error:
Line 151:         int DetailID =
  Convert.ToInt32(e.CommandArgument.ToString());

Does any one now why this will happen and how to maybe fix it?
Comment: you should `debug` your code and check the value for `e.CommandArgument` it seems that the value of `e.CommandArgument` is string which is not able to convert into `int` (**i.e it's normal string not number**)
Comment: I have done that. The e.CommandArgument is null, but it works on the other command. I need to know why?
Comment: you used CommandArgument `Link` in first `ImageButton` and you used `Soln_SolutionId` in second `ImageButton `..... it seems you should use `Soln_SolutionId` in first ImageButton also as CommandArgument
Comment: I have tried that as well, it still returns the same exception. I had from the get go the CommandArgument the same. No effect.
Answer:
Exception Details: System.FormatException: Input string was not in a correct format.

This error states that the value is either null or non nummeric. Attach the debugger an check the value you are receving
Comment: I did that and it returns a null value. The problem is that the one command works fine and the other does not. I need to know why it would do that since it is almost identical code but with different command arguments.
Comment: Does the source data (binded to grid) contain null values?
Comment: There is some null values in the database but the Soln_SolutionId is the primary key of that table and will never be null.
Answer: It was the logic error on my Row Command. The entity model doesn't like the whole idea of using shared variables in a Gridview Row Command. I'm still readin up on this.
But here is the code that works.
if (e.CommandName == "viewDetail")
            {
                int DetailID = Convert.ToInt32(e.CommandArgument.ToString());
                using (VIPCRMEntities dbc = new VIPCRMEntities())
                {
                    Solution selDetail = (from c in dbc.Solutions
                                          where c.Soln_SolutionId == DetailID
                                          select c).First();
                    InfoModal.Show();
                    lblInfoText.Text = selDetail.Soln_SolutionDetails;
                }
            }
            else if (e.CommandName == "viewDoc")
            {
                int DetailID = Convert.ToInt32(e.CommandArgument.ToString());
                using (VIPCRMEntities dbc = new VIPCRMEntities())
                {
                    Solution selDetail = (from c in dbc.Solutions
                                          where c.Soln_SolutionId == DetailID
                                          select c).First();
                    InfoModal.Show();
                    lblInfoText.Text = selDetail.soln_link;
                }
            }

Answer: You should change your code like below
int DetailID;
int.TryParse(e.CommandArgument.ToString(), out DetailID);

for more refere this link:
int index = Convert.ToInt32(e.CommandArgument.ToString()); is not working
Comment: It doesn't even invoke the select command. It gives an error at the declaration of DetailID
Comment: But that is good practices, will put that in before I go to production. Thanks a mill.

GridView Row Command Error


How do I require client certificates with a specific username / password in Apache?

Question: I have several clients certificates that my Apache httpd server requires clients to have (made using the instructions at http://www.garex.net/apache/). I would like to have an authentication that also authenticates and allows only a client certificate to match a username/password combination.
For example, if I have two client certificates with CN user1 and user2 and .htpasswd file
user1:passwordA
user2:passwordB

I would like something like
SSLUserName %{SSL_CLIENT_S_DN_CN}
AuthName "Please enter your username and password"
AuthType Basic
AuthUserFile /path/.htpasswd
require valid-user

However, trying this results in 500 errors. What can I do?
Comment: hi @cm007 did you manage to find a solution to this?
Answer: The error 500 is due to wrongSSLUserName syntax — it should be written without %{...}:
SSLUserName SSL_CLIENT_S_DN_CN

But actually if you want to require basic auth and certificate name to match, you should remove SSLUserName (so that mod_ssl would not touch REMOTE_USER) and use:
SSLRequire %{SSL_CLIENT_S_DN_CN} eq %{REMOTE_USER}

Another option which might work better when used in the config file directly (not in .htaccess):
RewriteEngine on
RewriteCond %{SSL:SSL_CLIENT_S_DN_CN} !=%{LA-U:REMOTE_USER}
RewriteRule ^ - [F]

Comment: I have

    AuthName "Please enter your username and password"
    AuthType Basic
    AuthUserFile /path/.htpasswd
    require valid-user
    SSLRequire %{SSL_CLIENT_S_DN_CN} eq %{REMOTE_USER}

but this gives a 403 error, and the authentication dialog never appears to the client. If I move the four lines about auth outside of the Location tag, then Apache says AuthName not allowed here.
Comment: Is `SSLVerifyClient require` also specified? You may also try a mod_rewrite variant added to the answer.


Stop OSX from Automatically re-Sizing JComboBox?

Question: I created a program that deals with combo boxes, and I ran across a problem a Mac user showed me. Mac apparrently resizes JComboBox's and JButton's even if I set the width. The width of all the combo boxes on Windows are different since they are supposed to, but on OSX it's all the same width and size making it impossible to read half the entries of in the combo-box because it's all cut off when you try to select a selection. How can I fix or prevent this?
So my question is, how do you stop an operating system from auto-resizing the swing tools, or how do I make the selections in the JCombBox's readable and not cut off to like "Boxes" instead of "Bo...?"
Comment: Do you set a non-default LookAndFeel?
Comment: for better help sooner edit your question with a [SSCCE](http://sscce.org/)
Comment: I don't believe I set the look and feel anywhere, I want it to have a native look for different operating systems, but not at the cost of its functionality.
Answer: As shown here, don't set the width; that is the purview of the UI delegate, com.apple.laf.AquaComboBoxUI. Instead, let the JComboBox calculate it's own preferred size based on the font metrics that inevitably vary from one platform to another.
If you still have problems, this example may form the basis for your sscce.


Where's the bug in this simple std::list?

Question: I can't understand where's the problem with this very simple list I've been testing. The idea is to get the item at position i in a list.
I know usually I wouldn't use a list to do that.
However, this works when I set item = 11, item = 12 and item = 13 (output would be, respectively, at position {1, 2, 3} there's the item {11, 12, 13}), BUT it does not work when I set item = 10, as the output is at position 0 there's the item 6.
int main(void)
{
    list<int> L;
    L.push_back(10);
    L.push_back(11);
    L.push_back(12);
    L.push_back(13);

    int item = 10;
    int pos;

    list<int>::iterator it = moveToItem(item, L, pos);

    cout << "at position " << pos << " there's the item " << *it;
}

list<int>::iterator moveToItem(int item, list<int> L, int& pos)
{
     pos = 0;
     list<int>::iterator it = L.begin();

     while(*it != item)
     {
         it++;
         pos++;
     }
     return it;
}

Answer: A copy of the list L is being made when moveToItem() is called so the returned iterator is referring to an item of a list that has been destructed. Pass the list by reference instead:
list<int>::iterator moveToItem(int item, list<int>& L, int& pos)
                                                //^

You should also protect against going past the end() of the list in the while condition, before dereferencing it.
If this is not an exercise consider using the STL algorithm std::find() and std::distance() instead:
#include <iterator>
#include <algorithm>

std::list<int>::iterator it = std::find(L.begin(), L.end(), 41);
if (it != L.end())
{
    std::cout << "at position "
              << std::distance(L.begin(), it)
              << " there's the item "
              << *it
              << "\n";
}

Answer: You should pass a reference to your list when calling the list<int>::iterator moveToItem(int item, list<int> L, int& pos) currently a copy of your list made.
So your method should be list<int>::iterator moveToItem(int item, list<int>& L, int& pos) instead. You can keep the body of your method the same.
Answer: You are taking the list by-value. Therefore the returned iterator is an iterator into the local L argument of the function and is therefore invalid once the function returned (and L got destroyed). You should take L by reference:
list<int>::iterator moveToItem(int item, list<int> &L, int& pos)

Performance-wise it's not the best idea to take such a possibly large datastructure as a list by-value, anyway.


Need help proving a mathematical induction problem

Question: I am having a bit of trouble proving assumption a & b, specifically b though. Could you guys walk me through the solutions for part a & b? Thanks.
Answer: For a).
(i) Base : $x_2 = \sqrt 6 > 0 = x_1$.
(ii) Induction step : assume $x_n > x_{n−1}$ and prove that $x_{n+1} > x_n$.
But : $x_{n+1}^2 = x_n + 6 > x_{n−1}+6$, and : $x_{n−1} = x_n^2−6$.
Thus, substituting : $x_{n+1}^2 = x_n + 6 > x_{n−1}+6 = x_n^2 + 6 − 6 = x_n^2$.
From $x_{n+1}^2 > x_n^2$ we have : $x_{n+1} > x_n$.

For b).
(i) Base : consider $n=1$, then $x_n = 0 < 3$.
(ii) Induction step : assume : $x_n < 3$ and prove it for $x_{n+1}$.
But $x_{n+1}^2 = x_n + 6 < 9$. Thus $x_{n+1} < \sqrt 9 = 3$.


LibGDX how to get button from clickListener

Question: To be honest I have no idea what I'm doing wrong. I want to get ImageButton object from ClickListener, but something goes wrong.
 public void createButton() {
    button = new ImageButton(this.skin);
    buttonUnitsList.add(button);
    button.addListener(new ClickListener() {
        @Override
        public void clicked(InputEvent event, float x, float y) {
           selectedUnit = buttonUnitsList.indexOf(this.getButton());
        }
    });
}

Comment: "Something"?  Do you get an error?  Have you tried stepping through it?
Comment: No, i have no errors, but for all buttons selectedUnit value after click is always the same.
Comment: What is `getButton()`?  I'm guessing it returns `button`, which will always be the last button created.
Comment: Oh, it's funny and i didn't even noticed that - getButton() returns int, and it's set by argument of ClickListener() method.
Answer: event.getTarget() can be dangerous to use if you have a hierarchy in the actor.
For example, imagine you have :
Group Actor <= ImageButton Actor 1 <= Label Actor 1
            <= ImageButton Actor 2 <= Label Actor 2
            <= ImageButton Actor 3 <= Label Actor 3

and you Create an eventListener on the Group Actor.
event.getTarget() will give you the actor where you click exactly
If you click on the "ImageButton Actor 2" for example, you could try event.getTarget().getParent() to get the Group Actor, but it won't work if you click on one of a Label Actor (the parent will be the corresponding ImageButton)
The best way to do, is to get the Actor which create the EventListener by event.getListenerActor()
Answer: To get Actor instance on which event was fired you need to use getTarget() Event's method. If you are sure that the listener will be used only with buttons you can upcast this from Actor to Button
selectedUnit = buttonUnitsList.indexOf((Button)event.getTarget());

Notice that if you will use the listener for another type of Actor you will get casting Exception
Comment: It worked for me. I can't cast Actor to ImageButton, but i get parent and it's working now. Thanks.
Comment: glad to help, If answer resolves your problem you can [accep it](http://stackoverflow.com/help/accepted-answer)


BindingContext in C# code

Question: Below is the binding context to the class "InqueritoViewModel", in XAML everything works fine. I can call the command "GetinqueritoCommand" without problems, but now i am trying to use C# instead of XAML for the design, but I cant call the "GetinqueritoCommand" from the "InqueritoViewModel" class.
Why can't I access the command? I am doing the Bindingcontext in the content.
<ContentPage.BindingContext>
    <viewModels:InqueritoViewModel/>
</ContentPage.BindingContext>

<StackLayout>
    <Button Command="{Binding GetinqueritoCommand}" Text="Open Inquery"></Button>

    <ListView x:Name="InqueritoView" ItemsSource="{Binding Inqueritos}" HasUnevenRows="True" ItemSelected="ListView_OnItemSelected">
        <ListView.ItemTemplate>
            <DataTemplate>
                <ViewCell>
                    <StackLayout>
                        <StackLayout>

                        </StackLayout>
                        <StackLayout Orientation="Horizontal">
                            <controls:Checkbox></controls:Checkbox>

                        </StackLayout>
                        <StackLayout Orientation="Horizontal">
                            <controls:Checkbox></controls:Checkbox>

                        </StackLayout>
                        <StackLayout Orientation="Horizontal" >
                            <controls:Checkbox></controls:Checkbox>

                        </StackLayout>
                    </StackLayout>
                </ViewCell>
            </DataTemplate>
        </ListView.ItemTemplate>
    </ListView>

</StackLayout>

InqueritoViewModel:
 public class InqueritoViewModel : INotifyPropertyChanged

{
    ApiServices _apiServices = new ApiServices();
    public List<Inquerito> _inqueritos;

    public string AccessToken { get; set; }

    public List<Inquerito> Inqueritos
    {
        get { return _inqueritos; }
        set
        {
            _inqueritos = value;
            OnPropertyChanged();
        }
    }

    public ICommand GetinqueritoCommand
    {
        get
        {
            return new Command(async () =>
            {
                AccessToken = Settings.AccessToken;
                Inqueritos = await _apiServices.GetinqueritosAsync(AccessToken);
            });
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;

    [NotifyPropertyChangedInvocator]
    protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }
}

Here is the code in C# for the design:
public class Inqueritoscode : ContentPage
{

    public Inqueritoscode()
    {

        ListView listView = new ListView
        {

            HasUnevenRows = true,

            // Source of data items.

            ItemsSource = Inqueritos,

            ItemTemplate = new DataTemplate(() => {

                // Create views with bindings for displaying each property.
                Label perguntaLabel = new Label();
                Label respostaLabel = new Label();
                Label respostaLabel1 = new Label();
                Label respostaLabel2 = new Label();
                var command = new Command(() => Debug.WriteLine("Command executed"));
                var button = new Button
                {
                    Text = "Open Inquery",
                    Command = doesnt find the GetinqueritoCommand,
                };

                respostaLabel.VerticalTextAlignment = TextAlignment.Center;
                respostaLabel1.VerticalTextAlignment = TextAlignment.Center;
                respostaLabel2.VerticalTextAlignment = TextAlignment.Center;

                perguntaLabel.SetBinding(Label.TextProperty, "Pergunta");
                respostaLabel.SetBinding(Label.TextProperty, "Resposta");
                respostaLabel1.SetBinding(Label.TextProperty, "Resposta1");
                respostaLabel2.SetBinding(Label.TextProperty, "Resposta2");

                var cb = new Messier16.Forms.Controls.Checkbox() { IsEnabled = true };
                var cb1 = new Messier16.Forms.Controls.Checkbox() {IsEnabled = true };
                var cb2 = new Messier16.Forms.Controls.Checkbox() { IsEnabled = true };

                return new ViewCell
                {
                    View = new StackLayout
                    {

                        Children = {
                            new StackLayout {
                                Children = {
                                    perguntaLabel,
                                 },
                            },
                            new StackLayout
                            {
                                Orientation = StackOrientation.Horizontal,
                                Children =
                                {
                                    cb

                                }

                            },
                            new StackLayout
                            {
                                Orientation = StackOrientation.Horizontal,

                                Children =
                                {
                                    cb1

                                }

                            },
                           new StackLayout
                            {
                                Orientation = StackOrientation.Horizontal,

                                Children =
                                {
                                    cb2

                                }

                            }

                        }
                    }
                };
            })
        };

        // Accomodate iPhone status bar.
        this.Padding = new Thickness(10, Device.OnPlatform(20, 0, 0), 10, 5);

        // Build the page.
        this.Content = new StackLayout
        {

            BindingContext = new ViewModels.InqueritoViewModel(),

            Children = {

                listView,

            }
        };

    }

}

Answer: button.SetBinding(Button.CommandProperty, "GetinqueritoCommand");

BindingContext in C# code


PineScript: Close a daytrade position at specific time of day

Question: Using TradingView's Pinescript, how can I program a backtest strategy to (on 1 Day Bar Resolution):
1) Enter a long position at market open using a market order, if the previous day's close marked a buy condition. (the buy condition is, RSI (7) is above 50, MACD line is above signal line)
2) Place a stoploss at 1X the Average Day Range (14)
3) Place a sell order at 15:55:00 Eastern Time to close the whole position before market close.
4) The stoploss trigger cancels the other sell order, and vice versa (e.g. it's an OCO order)
5) Repeat every time buy condition is present after close.
In other words, with this strategy, I hope to enter a day trade at market open with a 1X ADR stoploss, and close the trade right before close.  This will avoid the after hours gaps.
Thanks for being generous with your time!
Edit:
here's what I have so far (as requested)
    //@version=4
    strategy("Trendability Strategy", overlay=true)
    [macdLine, signalLine, histLine] = macd(close, 12, 26, 9)
    rsiLine = rsi(close, 7)
    stochLine = sma(sma(stoch(close, high, low, 14),3),3)
    signal = histLine > -0.05 and rsiLine > 40 and stochLine > 40 ? "buy" :
    histLine <= -0.05 and rsiLine <= 40 and stochLine <= 40 ? "sell" : "none"
    palette = signal == "buy" ? color.lime : signal == "sell" ? color.red :
    color.black
    plotbar(open, high, low, close, color=palette)

    strategy.entry("Long", strategy.long, when = signal == "buy")
    strategy.close("Long", when = signal == "none")

Comment: Please, show the code you've tried
Comment: //@version=4
strategy("Trendability Strategy", overlay=true)
[macdLine, signalLine, histLine] = macd(close, 12, 26, 9)
rsiLine = rsi(close, 7)
stochLine = sma(sma(stoch(close, high, low, 14),3),3)
signal = histLine > -0.05 and rsiLine > 40 and stochLine > 40 ? "buy" : histLine <= -0.05 and rsiLine <= 40 and stochLine <= 40 ? "sell" : "none"
palette = signal == "buy" ? color.lime : signal == "sell" ? color.red : color.black
plotbar(open, high, low, close, color=palette)

strategy.entry("Long", strategy.long, when = signal == "buy")
strategy.close("Long", when = signal == "none")
Answer: I'm not sure if PineScript has this capability. I do have the python code from Quantopian. I'm not sure if it would be of any help. Most brokers have an option to close all positions (or some)for day traders, so I would think this would be pretty standard function.
def initialize(context):
    # Algorithm will call myfunc every day 15 minutes before the market closes
    schedule_function(
        myfunc,
        date_rules.every_day(),
        time_rules.market_close(minutes=15)
    )

def myfunc(context,data):
    pass

Here is a sample from the user manual if you just want to avoid after-hours trading
strategy("closeEntry Demo", overlay=false)
strategy.entry("buy", true, when = open > close)
strategy.close("buy", when = open < close, qty_percent = 50, comment = "close buy entry for 50%")
plot(strategy.position_size)

Answer: Probably this will help
// close all entries after timeframe
intraday_sess = "0920-1500"
t = time(timeframe.period, intraday_sess)
sess_over = not na(t[1]) and na(t)
strategy.close_all(when = sess_over)

Answer: //@version=5
var close_hour = 15
var close_minutes = 56
var new_day = dayofmonth
var new_month = month
var new_year = year
var close_trades_at_time_of_day = na

if dayofmonth != dayofmonth[1]
    new_day := dayofmonth
if month != month[1]
    new_month := month
if year != year[1]
    new_year := year
close_trades_at_time_of_day := timestamp("GMT-4",new_year,new_month,new_day,close_hour,close_minutes)

strategy.close_all(time == close_trades_at_time_of_day)

This kind of works,
you would need to adjust close_hours and close_minutes depending on your chart's timeframe and your needs.


line for fingersettings in lilypond

Question: I have a question if the following possible in lilypond. The lines above the bar. I have not found how I can do that.
Answer: Yes and no. It can be faked, but not really done the easy way:
fingerLineStart =
#(define-music-function (n) (number?)
   #{
     -\tweak TextSpanner.bound-details.left.text \markup\fontsize #-5 #(number->string n)
     -\tweak TextSpanner.font-encoding #'fetaText
     -\tweak TextSpanner.font-features #'("cv47" "ss01")
     -\tweak TextSpanner.style #'line
     -\startTextSpan
   #})

\relative {
  e''16-4
  cis\fingerLineStart 2
  g
  <<
    { e
      e' cis g e
      e' cis g e\stopTextSpan
    }
    \new Voice {
      % Lilypond does not allow two concurrent TextSpanners in one Voice, so create a new Voice?
      s\fingerLineStart 1
      s4 s8. s16\stopTextSpan
    }
  >>
  e'-0 g e cis
}

Edit: Here's a version that matches the original a bit better in terms of spacing:
fingerLineStart =
#(define-music-function (n) (number?)
   #{
     -\tweak TextSpanner.bound-details.left.text \markup\fontsize #-5 #(number->string n)
     -\tweak TextSpanner.bound-details.left.stencil-align-dir-y #-0.3
     -\tweak TextSpanner.font-encoding #'fetaText
     -\tweak TextSpanner.font-features #'("cv47" "ss01")
     -\tweak TextSpanner.style #'line
     -\tweak TextSpanner.vertical-skylines #grob::unpure-vertical-skylines-from-stencil
     -\startTextSpan
   #})

\relative {
  e''16-4
  cis\fingerLineStart 2
  g
  <<
    { e
      e' cis g e
      e' cis g e\stopTextSpan
    }
    \new Voice {
      % Lilypond does not allow two concurrent TextSpanners in one Voice, so create a new Voice?
      s\fingerLineStart 1
      s4 s8. s16\stopTextSpan
    }
  >>
  e'-0 g e cis
}

Comment: @BartVanherck I've added a variant with closer spacing!

line for fingersettings in lilypond


DataGrid RowDetails?

Question: I have DataGrid that show list of items, each item maybe has detail, this is my code:
<DataGrid x:Name="dgItemsReceipt" CanUserAddRows="True" ItemsSource="{Binding ocItemsinInvoice,Mode=TwoWay}">
            <DataGrid.Columns>
                <DataGridTextColumn Header="Item" Binding="{Binding Item.ItemName}" Width="*" IsReadOnly="True"/>
                <DataGridTextColumn Header="Price" Binding="{Binding SalePrice,Mode=TwoWay}" Width="100" IsReadOnly="False"  />
                <DataGridTextColumn Header="Qnt" Binding="{Binding Quantity,Mode=TwoWay}" Width="100" IsReadOnly="False"  />
            </DataGrid.Columns>

            <DataGrid.RowDetailsTemplate>
                <DataTemplate>
                    <TextBlock Text="{Binding ItemsInInvoiceChoices.ChoicesId}" />
                </DataTemplate>
            </DataGrid.RowDetailsTemplate>

ItemsInInvoiceChoices is a related table with ItemsinInvoice.
Now when I add Item and add Choice for it, the Item appeare in the Data Grid but the detail now appeare?
Comment: i thing this wrong `Text="{Binding ItemsInInvoiceChoices.ChoicesId}"`, paste code of  Model of your `ocItemsinInvoice`
Answer: Try:

        <DataGrid.Columns>
            <DataGridTextColumn Header="Item Name" Binding="{Binding Item.ItemName}" Width="*" IsReadOnly="True"/>
            <DataGridTextColumn Header="Price" Binding="{Binding SalePrice,Mode=TwoWay}" Width="100" IsReadOnly="False"  />
            <DataGridTextColumn Header="Quantity" Binding="{Binding Quantity,Mode=TwoWay}" Width="100" IsReadOnly="False"  />
        </DataGrid.Columns>

        <DataGrid.RowDetailsTemplate>
            <DataTemplate>
                <ListBox ItemsSource="{Binding {RelativeSource FindAncestor, AncestorType=DataGrid}, Path=ocChoiceRecord, ElementName=myRoot}">
                    <ListBox.ItemTemplate>
                        <DataTemplate>
                            <TextBlock Text="{Binding RecordDescription}" />
                        </DataTemplate>
                    </ListBox.ItemTemplate>
                </ListBox>
            </DataTemplate>
        </DataGrid.RowDetailsTemplate>

    </DataGrid>

Comment: I updated my code. The relativesource must be at the Listbox itemssource-binding
Comment: Unfortunately, it didn't work, I'm thinking if I could filter the observablecollection ? is this good solution ?
Answer: What is myRoot here? You dont need to give ElementName here. If ocChoiceRecord is the property of item of ocItemsinInvoice collection. You can directly bind it like below. In this way, each row detail will be bound to its Item.
 <ListBox ItemsSource="{Binding ocChoiceRecord}">

Comment: I tried but it's driving me crazy, please can you help me to figure this issue
Comment: trying the answer displayed the row details?

DataGrid RowDetails?


How to compute $\lim_{n \to \infty}P(C_n>C_0)$?

Question:
The unit price of a certain commodity evolves randomly
  from day to day with a general downward drift but with an occasional
  upward jump when some unforeseen event excites the markets. Long term
  records suggest that, independently of the past, the daily price increases by
  a dollar with probability $0.45$, declines by $2$ dollars with probability $0.5$,
  but jumps up by $10$ dollars with probability $0.05$. Let $C_0$ be the price today
  and $C_n$ the price $n$ days into the future. How does the probability $P(C_n>C_0)$
  behave as $n$ goes to infinity?

My work:
Consider $\lim_{n \to \infty} (C_n>C_0)$ where $Cn=\frac{\Sigma_{i = 1}^{n}X_i}{n}$
where $X_i$ are i.i.d. random variables.
Let $\mu$ be the mean of $X_i$ and $\sigma$ be the standard deviation.
$\lim_{n \to \infty} P(C_n>C_0)=1-P(C_n<C_0)
<1-P(|C_{n-m}|<C_0)
<(1-(1-\frac{sigma^2}{nC_0^2}))=0$
Comment: I am not confident with the last part.
Comment: Also, do I compute E(X) and Var(X)?
Answer: Suppose $D_n = C_n - C_0$. Then $P(C_n > C_0) = P(D_n > 0) = P(\frac{D_n}{n} > 0)$, and $D_n = \Sigma_{k = 1}^{n} X_i$, where $X_i$ are i.i.d. random variables, such that $P(X_i = 1) = 0.45$, $P(X_i = -2) = 0.5$ and $P(X_i = 10) = 0.05$. Then by the Law of Large Numbers $\frac{D_n}{n}$ converges in probability to $EX_i = 0.45*1 + 0.5*(-2) + 0.05*10 = -0.05 < 0$. That results in $P(C_n > C_0) = P(\frac{D_n}{n} > 0) = 0$
You can find more about convergence in probability here: https://en.wikipedia.org/wiki/Convergence_of_random_variables#Convergence_in_probability


Qual a melhor forma de escrever o seguinte código jQuery/JavaScript?

Question: Eu tenho o seguinte trecho de código que, basicamente, por meio de uma requisição jQuery ($.ajax()), usa seletores para buscar elementos de uma página (com conteúdo) e coloca dentro de elementos da página atual usando seletores desta.
$.ajax({
    url: '/system/json/study/radar/uf-panorama-brasil.php?estado=' + this.sigla,
    success: function (data) {
        //retorna a tabela de #id natureza
        var natureza = $(data).filter("#natureza");
        $("#uf-natureza").html(natureza);

        //retorna a tabela de #id segmento
        var macrossegmento = $(data).filter("#macro");
        $("#uf-macro").html(macrossegmento);

        //retorna tabela de #id federal
        var federal = $(data).filter("#federal");
        $("#uf-programa-federal").html(federal);

        //retorna tabela de #id estadual
        var estadual = $(data).filter("#estadual");
        $("#uf-programa-estadual").html(estadual);

        //retorna tabela de #id municipal
        var municipal = $(data).filter("#municipal");
        $("#uf-programa-municipal").html(municipal);
    }
});

Tudo funciona perfeitamente. Minha dúvida é a seguinte: existe alguma forma mais elegante de escrever esse trecho de código? Porque na parte que retorna o resultado os trechos de código estão se repetindo.
Answer: Não há muito o que mexer, está bom - bem legível - mas em opinião pessoal eu não gosto de ficar usando variáveis, gasta memória meio que atoa. Eu faria assim:
$.ajax({
    url: '/system/json/study/radar/uf-panorama-brasil.php?estado=' + this.sigla,
    success: function(data) {
        //retorna a tabela de #id natureza
        $("#uf-natureza").html( $(data).filter("#natureza") );

        //retorna a tabela de #id segmento
        $("#uf-macro").html( $(data).filter("#macro") );

        //retorna tabela de #id federal
        $("#uf-programa-federal").html( $(data).filter("#federal") );

        //retorna tabela de #id estadual
        $("#uf-programa-estadual").html( $(data).filter("#estadual") );

        //retorna tabela de #id municipal
        $("#uf-programa-municipal").html( $(data).filter("#municipal") );
    }
});

Ou para deixar mais limpo poderia fazer uma função (acho que funcionaria):
function tabela (dado, elemento, filtro) {
    $(elemento).html( $(dado).filter(filtro) );
}

$.ajax({
    url: '/system/json/study/radar/uf-panorama-brasil.php?estado=' + this.sigla,
    success: function (data) {
        //retorna a tabela de #id natureza
        tabela(data, "#uf-natureza", "#natureza");

        //retorna a tabela de #id segmento
        tabela(data, "#uf-macro", "#macro");

        //retorna tabela de #id federal
        tabela(data, "#uf-programa-federal", "#federal");

        //retorna tabela de #id estadual
        tabela(data, "#uf-programa-estadual", "#estadual");

        //retorna tabela de #id municipal
        tabela(data, "#uf-programa-municipal", "#municipal");
    }
});

Comment: Vou adotar sua resposta! Obrigado!


Matrix positive definite if and only if the vectors a lineary independent

Question: Be $\mathbb{K}=\mathbb{R}$ or $\mathbb{C}$, be $V$ and euclidean or unitary $\mathbb{K}$-vector space and be $v_1,\ldots,v_n \in V$.
For the $n\times n$ matrix
$$A:=(\langle v_j,v_k\rangle)_{j,k=1,\ldots,n}$$
then applys $A=A^*$ and $A\succeq0$.
Then $A$ is positive definite if and only if the vectors $v_1,\ldots,v_n$ are lineary independent.
I just can't seem to find a proof for this, and can't really proof it myself. Thanks in advance for any kind of help.
edit: the linked question doesn't talk about positive definity, or does it?
Sorry if it does.
Comment: Have a look at : https://math.stackexchange.com/questions/36580/gram-matrix-invertible-iff-set-of-vectors-linearly-independent
Answer: Hint: take the definitions of positive-definiteness and linear independence and see what you can get from
$$
x^*Ax=\sum_{ij}\langle v_i,v_j\rangle \bar x_i x_j=\sum_{ij}\langle x_iv_i,x_jv_j\rangle=\left\langle \sum_i x_iv_i,\sum_j x_jv_j\right\rangle=\left\|\sum_i x_iv_i\right\|^2.
$$


Apache 2.4.6 - Sending GZIP content SOMETIMES results in "read more bytes of request body than expected"

Question: We are trying to send GZIPed content to you web application which is hosted on a Tomcat behind an Apache 2 via mod_proxy's ProxyPass and ProxyPassReverse directives. Most of the time this works but sometimes the Apache rejects these packages and we get the following errors in our Apache error logs:
[proxy_http:error] ... AH01086: read more bytes of request body than expected (got 16384, expected 1562)
[proxy_http:error] ... AH01097: pass request body failed to x.x.x.x:8080 (x.x.x.x) from x (x.x.x.x)

The code sending the data is based on the HttpsURLConnection and executed from an Android device. It looks something like this:
URL url = new URL(Constants.URL);
HttpsURLConnection con = (HttpsURLConnection) url.openConnection();

con.setRequestMethod("POST");
con.setUseCaches(false);
con.setDoInput(true);
con.setDoOutput(true);
con.setRequestProperty("Content-Encoding", "gzip");
con.setRequestProperty("Content-Type", "application/json");
con.setRequestProperty("Accept", "application/json");
con.setRequestProperty("User-Agent", "MyApp 1.0");

OutputStream outputStream = con.getOutputStream();
outputStream.write( zipStringToBytes("Some possibly long content.") );

outputStream.flush();
outputStream.close();

int responseCode = con.getResponseCode();

And this the function the create our GZIP String:
private static byte[] zipStringToBytes(String input) throws IOException {
    ByteArrayOutputStream bos = new ByteArrayOutputStream();

    //use PrintStream to avod converting a String into byte array, that can cause out of memory error
    final PrintStream printStream = new PrintStream(new GZIPOutputStream(bos));
    printStream.print(input);
    printStream.close();

    byte[] retval = bos.toByteArray();
    bos.close();
    return retval;
}

We have not been able to figure out the reason for this yet. Especially since it seems to occur sporadically. This makes us think it might be a problem with the Content-Length, or our code sending the data in general, but we don't know and cannot find and related issues. If you have any pointers on this, we would greatly appreciate it.
If you need more information, please let me know.
Update:
What we found is, that the expected size is always the same: 16384 but  the expected size varies. Maybe this helps.
Update 2:
We have currently disabled chunked mode:
     con.setChunkedStreamingMode ( 0 )
This seems to help. Can anyone maybe explain if this is a solution and why it is one. Thanks.
Comment: I'm having the same problem but don't have control of the client side code. If anyone knows a server side solution (i.e. an apache setting) I would be much obliged.
Comment: Are you using `http` or `ajp` for Tomcat connection? Do you use mod_proxy_balancer?
Answer: OK, for now we were able to solve the issue by disabling sending data in chunked mode.
con.setChunkedStreamingMode ( 0 )

While we have some ideas why this solves the issue, we have not come up with an in depth explanation.
As long as nobody has a better solution or explanation, I accept this solution.


Unable to connect to DB2 server via db2cmd

Question: I'm unable to connect to db2 server using db2cmd command
db2 connect to mydb user myuser using password
Getting the following message
SQL8002N  An attempt to connect to a host failed due to a missing DB2 Connect product or invalid license.  SQLSTATE=42968
But I have successfully connected to this database using jdbc and I can view the structure.
Has anybody experienced such issue?
Comment: did u check ur product lisence
Comment: My local license is fine as I can access another databases. I have issue with this one. The question is why it is allowed to connect using jdbc but not db2cmd. Doesn't jdbc driver use licenses?
Answer: Are you trying to connect to a iSeries o z/390? or just a LUW (Linux, Unix Windows?)
If you are trying to connect to one of the two first, you need a DB2 Connect license, because they use the DRDA architecture, and it uses a special license.
Check the license
db2licm -a

If you are trying to connect to a LUW, you do not need any DB2 connect license, but probably there is a problem in you cataloged databases. Check the
db2 list node diretory
db2 list db directory

Is the database a remote server or is it a local connection?
Also, try to attach to the remote instance, in order to check that the node catalog is right
db2 attach to remoteInstance

Comment: This is remote db running on z/os. I've added license for DB2 Connect Enterprise Edition V9.5 for Windows(R) as you adviced and it worked. Thanks!
Answer: As the error message says, you need DB2 Connect to serve as a gateway for CLI connections. The JDBC driver does not need the gateway, as it implements the required protocol.