Registros duplicados no SQL - Oracle

Question: Bom dia, sou novo aqui e estou com um problema chato. O Distinct não resolve meu problema pois a duplicação se deve pelo fato que tive de fazer o relacionamento com outras tabelas para buscar informações. O SQL me retorna dois valores com supervisores diferentes para o mesmo IDCHAMADO, como faço pra exibir somente um IDCHAMADO de forma a não duplicar os registros?
SELECT ch.idchamado,su.nome AS nomesupervisor,
  e.nome,
  ch.dataabertura,
  ch.datafechamento,
  ta.desctipoassunto
FROM sase_chamado ch
LEFT JOIN vw_app_consulta_escolas e
ON ch.idpj = e.idpessoa_juridica
LEFT JOIN sase_tipoassunto ta
ON ta.idtipoassunto = ch.idtipoassunto
LEFT JOIN sase_escolasusuario eu
ON eu.idpj = ch.idpj
INNER JOIN sase_usuario su
ON eu.idusuario = su.idusuario
WHERE ch.dataabertura BETWEEN to_date('01/01/16', 'dd/mm/yy') AND to_date('30/07/16', 'dd/mm/yy')
ORDER BY su.nome,
  e.nome,
  ta.desctipoassunto

a danada da duplicidade é desse tipo aqui:
Comment: Você quer apenas um idchamado não importando quantos su.nome tenha? isso vale para o restante dos campos?
Comment: Sim, de forma a não trazer 2 idchamado iguais. o unico campo diferente quando duplica é o proprio nome do supervisor.
Comment: Samuel, se você não quer que gere uma linha distinta para cada supervisor você não pode mostrar o resultado do campo su.nome no seu SELECT (deve remover também da cláusula ORDER BY e aplicar o DISTINCT ou GROUP BY). Caso você queira mostrar o nome dele com esta estrutura você sempre mostrará 1 linha para cada nome de supervisor. É possível (não sei especificamente se no Oracle é) também unir o nome de N supervisores em uma única coluna e uma linha, mas ai você deve mudar consideravelmente seu SELECT.
Comment: Acontece que não posso tirar o su.nome do SELECT pois preciso dele para atribuir o chamado há o nome de um supervisor. o distinct só funciona quando o registro é totalmente igual, mas no meu caso o nome do supervisor muda quando duplica, então não funfa
Comment: Neste caso você não pode agrupar as linhas realmente e deve recuperar ambos os resultados, se você tem duas linhas (se eu entendi a lógica da consulta) é por que há duas chamadas, cada uma para um supervisor, sendo que os demais dados são idênticos.
Comment: acho q eh isso msm, so nao sei como resolver essa duplicidade kkk
Answer: Quando temos queremos apenas uma linha sem nos importar com o conteúdo usamos o MIN ou MAX e agrupamos o que é igual.
SELECT ch.idchamado AS idchamado,
  MIN( su.nome ) AS nomesupervisor,
  e.nome,
  ch.dataabertura,
  ch.datafechamento,
  ta.desctipoassunto
FROM sase_chamado ch
LEFT JOIN vw_app_consulta_escolas e
ON ch.idpj = e.idpessoa_juridica
LEFT JOIN sase_tipoassunto ta
ON ta.idtipoassunto = ch.idtipoassunto
LEFT JOIN sase_escolasusuario eu
ON eu.idpj = ch.idpj
INNER JOIN sase_usuario su
ON eu.idusuario = su.idusuario
WHERE ch.dataabertura BETWEEN to_date('01/01/16', 'dd/mm/yy') AND to_date('30/07/16', 'dd/mm/yy')
GROUP BY
  ch.idchamado
  e.nome,
  ch.dataabertura,
  ch.datafechamento,
  ta.desctipoassunto
ORDER BY su.nome,
  e.nome,
  ta.desctipoassunto

Comment: Reginaldo, se a data tive como DateTime seu group by não vai funcionar muito bem.
Comment: Verdade. Ele poderia coloca-la como fora do GROUP BY e no MIN também.
Comment: ORA-00933: comando SQL não encerrado adequadamente
00933. 00000 -  "SQL command not properly ended"
*Cause:
*Action:
Erro na linha: 19 Coluna: 3
Comment: Consegui arrumar esse erro adicionando o su.nome no GROUP BY, porém continua trazendo duplicado.
Comment: Poste o resultado para a gente ver.
Comment: postei a img da duplicidade amigo, obrigad
Comment: Nome é string o min não dá certo
Comment: nome é varchar2
Comment: Funciona sim @MarconcílioSouza. Acabei de testar. Chega ser inacreditável que o Samuel  esteja rodando esse select com o MIN e o GROUP BY.
Comment: O que você me recomenda Reginaldo para resolver isso? existe alguma forma de eu limitar a consulta a não exibir o mesmo IDCHAMADO duas vezes?
Comment: Veja assim:
SELECT MIN( ch.idchamado ) AS idchamado,
  MIN( su.nome ) AS nomesupervisor,
  MIN( e.nome ) AS nome,
  MIn( ch.dataabertura ) AS dataabertura,
  MIN( ch.datafechamento ) AS datafechamento,
  MIN( ta.desctipoassunto )  AS desctipoassunto
Comment: Tire a clausula GROUP BY toda
Comment: Repare que você esta pegando o MIN de todos os campos. Não sei a lógica de seu programa, mas pode haver situações que estará vindo mais de um registro e você estará fazendo um merge entre eles e pegando sempre o menor valor para todos os campos. Isso pode ser desejável em algumas condições porém pode ser perigoso e trazer consequências.
Comment: Mas se eu tirar a clausula group by vai dar erro pois min é função de grupo entao group by seria obrigatorio, ou estou errado?
Comment: Esta errado. MIN, MAX, SUM são funcões agregadoras e não precisam estar em GROUP BY, alias se estiver o MIN e/ou MAX não funciona.
Alias, isso me faz pensar que você colocou o GROUP BY em todos os campos e MIN da resposta não funcionou. Espero não ter te confundido. rsrs
Comment: Olá Reginaldo, dessa última forma que você falou ele só traz 1 registro dos 254 existentes, no caso ele traz apenas o IDCHAMADO 1 e mais nada.
Comment: Editei a resposta. Execute como esta lá.
Comment: Com alguns ajustes no seu último SQL consegui chegar ao resultado esperado, muito obrigado Reginaldo, tenha uma ótima semana, abraços!

Registros duplicados no SQL - Oracle


Storing a Serialized List of Items in a Resource File

Question: I am creating some unit tests for our application, and I'd like to store a serialized (XML) list of classes in a resource file to be used by some of our tests, as a mock. Some of these lists could contain hundreds or thousands of items, so an individual resource entry could be quite large. Is a C# Resource file the best approach for this? Can an individual resource in a resource file contain an item this large?
I've thought about adding the serialized lists directly in my project as a file, but then I'm not sure how I would access this file in my app, without assuming a particular directory structure, which other developers may not have, because they have their source control mappings set differently.
Answer: Why do you want to use a Resource file, do you have different versions of your list per culture you want to test?
If not, you can just as well add your XML list as an XML file straight into your Project. The maximum size of an XML file is the maximum size the OS supports; so even if you're using Windows XP, it can be up to 4 GB in length.
Comment: Thank you Roy. This seems to work. And it's a better approach than the resource file.
Comment: If I add the XML file straight into my project then how do I access it in my app? I don't want to assume any particular directory structure because other developers working on this app may not have the same TFS mapping that I do.
Comment: You mark the XML file as Content in Visual Studio; when you compile or deploy, the file will appear in the same directory as your project's DLL.


mainLayout in onCreateView is not working for 4.4 & lower

Question: I have below in one of my project
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    try {
        Log.d("errrrr", "making mainlayout-1");
        mainLayout = (RelativeLayout) inflater.inflate(R.layout.home, null);
        Log.d("errrrr", "making mainlayout-1.1");

Also I have below in inStart
if (mainLayout==null) {
    Log.d("errrr", "22--mainlayout is not okay");
} else {
    Log.d("errrr", "33--mainlayout is okay");
}
mloading.setVisibility(View.VISIBLE);

Below is the output for Android 4.2
D/errrrr: making mainlayout-1
D/errrr: 22--mainlayout is okay

Now as mainLayout is null, mloading.setVisibility(View.VISIBLE); is crashing calling NullPointerException.
This is because in createView I have below.
mloading = (ProgressBar) mainLayout.findViewById(R.id.loading);

But as mainLayout is null, nothing is defined.
Any idea what is going wrong?
Note: This is working fine for OS 5.0 & above

Edit 1
Below is the exception
E/HomeFragment  onCreate>>LineNumber: 162: Binary XML file line #14: Error inflating class org.lucasr.twowayview.TwoWayView
Home.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <RelativeLayout
        android:id="@+id/rel_cats"
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:background="#ff343431">

        <org.lucasr.twowayview.TwoWayView
            android:id="@+id/lst_newsCats"
            style="@style/TwoWayView"
            android:layout_width="wrap_content"
            android:layout_height="50dp"
            android:layout_alignParentRight="true"
            android:layout_gravity="right"
            android:background="#ff343431"
            android:choiceMode="singleChoice"
            android:drawSelectorOnTop="false"
            android:fadingEdge="none"
            android:gravity="right"
            android:layoutDirection="rtl" />
    </RelativeLayout>

    <ScrollView
        android:id="@+id/scrollView_main"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_above="@+id/pager_urgent"
        android:layout_below="@+id/rel_cats"
        android:layout_marginTop="1dp"
        android:fadingEdge="none">

        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <cn.trinea.android.view.autoscrollviewpager.AutoScrollViewPager
                android:id="@+id/pager"
                android:layout_width="match_parent"
                android:layout_height="100dp"
                android:background="@drawable/img_slider"
                android:fadingEdge="none"
                android:visibility="invisible" />

            <com.viewpagerindicator.CirclePageIndicator
                android:id="@+id/indicator"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_below="@+id/pager"
                android:layout_gravity="center"
                android:layout_marginTop="10dp"
                android:background="@android:color/transparent"
                android:gravity="center"
                android:visibility="invisible"
                app:centered="true"
                app:fillColor="#ff9e9e9e"
                app:pageColor="#ffeaeaea"
                app:radius="5dp"
                app:snap="true" />

            <com.abc.app.classes.LoadMoreListView
                android:id="@+id/lst_mainNews"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_below="@+id/indicator"
                android:layout_marginTop="10dp"
                android:choiceMode="singleChoice"
                android:divider="@android:color/transparent"
                android:dividerHeight="20dp"
                android:fadingEdge="none"
                android:visibility="invisible" />

            <TextView
                android:id="@+id/xcv"
                android:layout_width="match_parent"
                android:layout_height="50dp"
                android:layout_below="@+id/lst_mainNews"
                android:gravity="center"
                android:text="Load More"
                android:visibility="gone" />

        </RelativeLayout>
    </ScrollView>

    <cn.trinea.android.view.autoscrollviewpager.AutoScrollViewPager
        android:layoutDirection="rtl"
        android:layout_marginBottom="2dp"
        android:id="@+id/pager_urgent"
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:layout_alignParentBottom="true"
        android:background="#E41F1F"
        android:visibility="gone"
        android:fadingEdge="none" />

    <ProgressBar
        android:id="@+id/loading"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:layout_gravity="center_horizontal"
        android:indeterminateDrawable="@drawable/costum_progress_bar"
        android:visibility="gone" />

</RelativeLayout>

Edit 2
gradle file
apply plugin: 'com.android.application'

android {
    compileSdkVersion 22
    buildToolsVersion "22.0.1"
    packagingOptions {
        exclude 'META-INF/LICENSE.txt'
        exclude 'META-INF/NOTICE.txt'
        exclude 'META-INF/DEPENDENCIES.txt'
        exclude 'META-INF/LICENSE.txt'
        exclude 'META-INF/NOTICE.txt'
        exclude 'META-INF/NOTICE'
        exclude 'META-INF/LICENSE'
        exclude 'META-INF/DEPENDENCIES'
        exclude 'META-INF/notice.txt'
        exclude 'META-INF/license.txt'
        exclude 'META-INF/dependencies.txt'
        exclude 'META-INF/LGPL2.1'
    }
    defaultConfig {
        applicationId "com.abc.app"
        minSdkVersion 17
        targetSdkVersion 22
        versionCode 5
        versionName "5.0"
        multiDexEnabled true
    }
    buildTypes {
        release {
            minifyEnabled false
            multiDexEnabled true
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    compile files('libs/gcm.jar')
    compile files('libs/gson-2.2.4.jar')
    compile files('libs/gson-2.2.4-javadoc.jar')
    compile files('libs/gson-2.2.4-sources.jar')
    compile files('libs/nineoldandroids-2.4.0.jar')
    compile files('libs/PhotoView.jar')
    compile files('libs/picasso.jar')
    compile files('libs/universal-image-loader-1.8.6.jar')
    compile files('libs/urlimageviewhelper-1.0.4.jar')
    compile files('libs/volley.jar')
    compile('cn.trinea.android.view.autoscrollviewpager:android-auto-scroll-view-pager:1.1.2') {
        exclude module: 'support-v4'
    }
    compile files('libs/httpclient-4.3.2.jar')
    compile files('libs/httpclient-cache-4.3.1.jar')
    compile files('libs/httpcore-4.3.2.jar')
    compile files('libs/httpcore-nio-4.3.2.jar')
    compile files('libs/httpmime-4.3.1.jar')
    compile files('libs/twitter4j-core-4.0.4.jar')

    compile 'com.android.support:appcompat-v7:22.2.1'
    compile 'com.facebook.android:facebook-android-sdk:4.1.0'
    compile 'com.twotoasters.jazzylistview:library:1.2.1'
    compile 'com.twotoasters.jazzylistview:library-recyclerview:1.2.1'
    compile 'com.google.android.gms:play-services:8.3.0'
    compile 'eu.inmite.android.lib:android-styled-dialogs:1.2.0'
    compile 'com.daimajia.easing:library:1.0.1@aar'
    compile 'com.daimajia.androidanimations:library:1.1.3@aar'
    compile 'com.viewpagerindicator:library:2.4.1@aar'
    compile 'com.daimajia.slider:library:1.1.2@aar'
    compile 'it.sephiroth.android.library.horizontallistview:hlistview:1.2.2'
    compile 'org.lucasr.twowayview:twowayview:0.1.4'
    compile 'com.android.support:support-v4:22.2.1'
}

Comment: Are you getting any `InflateException`?
Comment: post home.xml of fragment '
Comment: can you also post `build.gradle` of your app?
Comment: @RohitArya : Done...
Comment: @FahimParkar, did it work after changing the support lib version?
Answer: This is a known issue:
trying changing:
compile 'com.android.support:support-v4:22.2.1'

to:
compile 'com.android.support:support-v4:22.1.1'

Comment: checking... give me some time


ao usar AJAX, posso enviar o conteúdo sem estar em volta da tag form?

Question: deve-se colocar os inputs, etc dentro de um <form id="algo" method="POST"></form>?
<form id="algo" method="POST">
    <input type="text" value="NADA" name="valor1" />
    <input type="text" value="TUDO" name="valor2" />
</form>

Ou posso mandar via ajax assim:
    <input type="text" value="NADA" name="valor1" />
    <input type="text" value="TUDO" name="valor2" />

O ajax:
$.ajax({
    url: "algumaurl.php",
    type: "POST",
    data: {
        valor1: $("[name='valor1']").val(),
        valor2: $("[name='valor2']").val(),
    },
    success: function(data){
        //faz algo
    }
});

Answer: Podes enviar AJAX como te convêm melhor. O que é importante é os dados que passas e como inicias o AJAX.
Os dados colocas aqui:
data: {
    valor1: $("[name='valor1']").val(),
    valor2: $("[name='valor2']").val(),
},

Assim, como fizeste está correto.
Se quiseres usar o evento submit de um <form> tudo bem, mas podes queres iniciar uma chamada AJAX de outra maneira. É irrelevante. O <form> não tem de estar presente para usares AJAX, ele faz sentido quando queres enviar um formulário para o servidor sem AJAX, e é somente útil para agrupar dados como em
data: $(form).serialize()


Representation by a quadratic binary form

Question: For $m$ a non-zero integer and discriminant $d=b^2-4ac$ congruent to either 0 or 1 modulo 4, show that m is properly represented by some binary quadratic form $f(x)=ax^2+bxy+cy^2$ if and only if the congruence $$z^2\equiv d\ (mod\ 4|m|)$$has a solution.
I have proved the forward half, but cannot prove the congruence implies the proper representation.
Comment: What is $\;z\;$ , anyway?
Comment: z is can be any integer, just a place holder to demonstrate that d is a quadratic residue
Comment: Oh...so write so! Write "...iff $\;d\;$ is a quadratic residue modulo $\;m\;$" .
Comment: How did you prove the forward result?
Answer: If $$  z^2 = d + 4mt,   $$ then $$ z^2 - 4mt = d, $$ and the binary
$$  \langle m,z,t \rangle  $$ or
$$  g(x,y) = m x^2 + z xy + t y^2  $$
gives
$$  g(1,0) = m $$
Added: note that they are not saying anything about $\gcd(m,z,t).$ The forms that are in (and contribute to $h(d)$) the form class group are primitive, but this problem may produce an imprimitive form. For that matter, they do not prohibit $d$ from being a square, which allows sort of degenerate forms that factor, such as $x^2 - y^2$


Solve for $x,y$ : $x^4+y^4+2 = 4xy$

Question:
Solve for $x,y$ : $x^4+y^4+2 = 4xy$

Obviously, the very obvious solutions are $(1,1)$ and $(-1,-1)$.
But I don't know how to reach the answer. I got the answer through hit and trial.
I tried adding and subtracting $2x^2y^2$ in the $LHS$:
$x^4+y^4+2 +2x^2y^2-2x^2y^2 = 4xy$
$(x^4+y^4)^2 = 4xy + 2x^2y^2 -2$
Giving us:
$(x^4+y^4)^2 =2(2xy + x^2y^2 -1)$
How to proceed further? I don't really think this helps. Is there a better method? Any hints or solutions would be appreciated!
Answer: Hint:
Using AM-GM  inequality for real $x^2,y^2\ge0$
$$\dfrac{x^4+y^4+1+1}4\ge\sqrt[4]{x^4y^4}$$
the equality occurs if $x^4=y^4=1$
Alternatively,
$$x^4+y^4+2-4xy=(x^2-y^2)^2+2(xy-1)^2$$
Comment: @Phymathechem, Set $n=4$ in https://math.stackexchange.com/questions/691807/proofs-of-am-gm-inequality
Answer: From your equation $x^4+y^4+2x^2y^2-2x^2y^2+2=4xy$ it follows
$$x^4+y^4-2x^2y^2=4xy-2-2x^2y^2 \Longleftrightarrow
(x^2-y^2)^2=-2(xy-1)^2$$
Over the real numbers this is possible if and only if
$$x^2=y^2 \text{ and } xy=1$$
which has only $(1,1)$ and $(-1,-1)$ as solutions.
Answer: After realizing that $x^2, y^2≥0$, then
$$x^4+1≥2x^2$$
$$y^4+1≥2y^2$$
$$x^4+y^4+2≥2(x^2+y^2)$$
$$x^4+y^4+2-4xy≥2(x^2+y^2)-4xy=2(x-y)^2≥0$$
So, the solution occurs for only $x=y$, which follows $x=y=±1.$

Solve for $x,y$ : $x^4+y^4+2 = 4xy$


Disparar e-mail automatico em determinado horário com java

Question: Meu sistema tem a parte de consultas odontológicas e preciso enviar e-mail para o cliente, caso a sua consulta seja naquele dia.
Por exemplo:
Rodar um disparador automático de e-mail sempre a meia noite em todos os dias. Esse disparador de e-mail vai verificar se possui consultas naquele dia e se tiver, vai enviar o e-mail.
Como faço para rodar essa verificação com java?
Comment: Sua dúvida é para fazer a verificação ou para agendar a execução de um código? No primeiro caso, é preciso conhecer seu modelo de dados. No segundo, varia de sistema operacional, vc precisa informar.
Comment: Quero agendar a execução da verificação de consultas. Meia noite rodar um método que verifica se há consultas naquele dia.
Comment: Então qual sistema operacional??
Comment: É Windows mesmo :D
Comment: Existem duas formas de fazer agendamentos, "jobs", em aplicações java, existe um post neste [link](http://blog.alura.com.br/agendando-tarefas-com-scheduled-do-spring/) que certamente vai te nortear.
Comment: Uma outra opção seria utilizar o EJB para fazer o agendamento no próprio java, no mesmo método você poderia fazer a verificação que você quisesse. http://blog.caelum.com.br/agendando-tarefas-com-o-timerservice-do-ejb-3-1/
Answer: Existem frameworks de agendamento de tarefas, no entanto para apenas executar um script diariamente você pode usar soluções bem mais simples. Os sistemas operacionais possuem um agendador de tarefas: no linux tem o cron, no windows tem o Agendador de Tarefas (nome menos criativo, diga-se de passagem).
Basicamente você cria um programa em java que ao ser executado envia os emails com as consultas, sem se preocupar com o horário. Para agendar, você cria um script como esse:
@echo off
REM run the program
"C:\Program Files\Java\jdk1.7.0\bin\java.exe" -jar "C:\Users\User1    \Documents\project\emailConsulta.jar"

Então, basta criar uma tarefa no Agendador de Tarefas do Windows, acessado com Win+R > digite "Taskschd.msc" > Enter. Lá você controla em quais dias da semana ele vai ser executado, em qual horário, entre outras opções.


Replacing a class with Mono.Cecil

Question: Say I have assembly A. It was modified with Mono.Cecil a little bit. Now say I have assembly B. It has a class named SomeClass. Assembly A also has a class named SomeClass. Now I want to replace SomeClass from assembly A with the one in assembly B. I tried a few things, but I know that for one of my attempts, it actually remapped a method call like this:
Console.WriteLine("Test.");

...into this:
int.WriteLine("Test.");

That can't be right. What is the correct way to replace a class with Mono.Cecil?
Answer: You're probably doing something that Cecil doesn't understand. It's impossible to tell you what without seeing any code.
Swapping a type by another is not trivial, you'd have to recreate in the target module the object model you want to inject, and replace every reference of it with the new one. Basically, you'd have to walk over every reference in the target module and make sure it's properly processed.

Replacing a class with Mono.Cecil


A propriety of the Heat Kernel on the circle from Stein's Fourier analysis Ch.4 Ex13

Question: I'm stuck with part b) of this exercise.
In this book the Heat Kernel on the circle is defined as $$H_t(x)=\sum_{ℤ }e^{-4π^2n^2t}e^{i2πnx}$$
The author gave this two proprieties as exercise and the respective hints (without introducing the Poisson summation formula)
a)$∫_{-1/2}^{1/2}|H_t(x)|^2dx$ has magnitude $1/\sqrt{t}$ as $t\longrightarrow0$
Hint: compare $\sum_{ℤ}e^{-4\pi^2n^2t}$ with $\int_{ℝ}e^{-4\pi^2x^2t}dx$
b)$\int_{-1/2}^{1/2}x^2|H_t(x)|^2dx=O(\sqrt{t})$ as $t\longrightarrow0$
Hint: majorize $x^2$ with $C(\sin\pi x)^2$ and apply the mean value theorem to $e^{-\pi x^2t}$
Part a) is quite easy (one may use Parserval's identity and prove that the discrete infinite sum and the continuous infinite integral differ no more than 1 in absolute value), but for part b) I can't really obtain the desired result.
Till now, I used Abel's summation by parts formula and got that \begin{gather}
H_t(x)\sin\pi x=\
\sum_{n≥0}(e^{-4\pi^2n^2t}-e^{-4\pi^2(n+1)^2t})[\sin(2n+1)\pi x]
\end{gather}
The problem is that while I want $t\longrightarrow0$ in the series I have $n\longrightarrow\infty$ so I find it really difficult to estimate.
Please help me if you know anything. Thank you in advance.
Answer: The source code of this answer is available at my github gist.
I use a quite different method from yours.
For (1), we see that
\begin{equation}
    \begin{aligned}
        I=&\int_{|x|\leq 1/2}|H_t(x)|^2 d x\\
        =&\int_{|x|\leq 1/2}H_t(x)\overline{H_t(x)}d x\\
        =&\int_{|x|\leq 1/2}\sum_{n}e^{-4\pi^2n^2t}e^{2\pi i n x}\sum_{k}e^{-4\pi^2k^2t}e^{-2\pi i k x}\\
        =& \sum_{n}\sum_{k}e^{-4\pi^2(n^2+k^2)t}\int_{|x|\leq 1/2}e^{2\pi i (n-k)x}d x\\
        =& \sum_{n}\sum_{k}e^{-4\pi^2(n^2+k^2)t}\mathbb{I}({n=k})\\
        =&\sum_{n}e^{-8\pi^2n^2t}
    \end{aligned}
\end{equation}
Note that
\begin{equation}
    \begin{aligned}
        I=&\sum_{n}e^{-8\pi^2n^2t}=1+2\sum_{n=1}^{\infty}e^{-8\pi^2n^2t}\\
        \leq& 1+2 \sum_{n=1}^{\infty}\int_{n-1}^n e^{-8\pi^2 x^2 t}d x=1+2\int_{0}^{\infty}e^{-8\pi^2 x^2 t}d x\\
        =&1+\int_{-\infty}^{+\infty}e^{-8\pi^2 x^2 t}d x
    \end{aligned}
\end{equation}
by the same trick, we can show that
\begin{equation}
    \begin{aligned}
        I=&\sum_{n}e^{-8\pi^2n^2t}=-1+2\sum_{n=0}^{\infty}e^{-8\pi^2n^2t}\\
        \geq & -1+2 \sum_{n=0}^{\infty}\int_{n}^{n+1} e^{-8\pi^2 x^2 t}d x=-1+2\int_{0}^{\infty}e^{-8\pi^2 x^2 t}d x\\
        =&-1+\int_{-\infty}^{+\infty}e^{-8\pi^2 x^2 t}d x
    \end{aligned}
\end{equation}
and by the Normal distribution $N(0,\sigma^2)$, we see that (the constant might be wrong, but it does not matter.)
\begin{equation}
    \int_{-\infty}^{+\infty}e^{-8\pi^2 x^2 t}d x=\int\exp\left(-\frac{x^2}{2\frac{1}{16\pi^2t}}\right)d x=\sqrt{2\pi t }\cdot 4\pi=O(t^{-1/2}).
\end{equation}
Thus $I=O(t^{-1/2})$.
For (2),by the hint we have $c_1\sin^2(\pi x)\leq x^2\leq C_1 \sin^2(\pi x)$, for $|x|\leq 1/2$, i.e., $x^2=O(\sin^2(\pi x))$, we write $x^2=C \sin^2(\pi x)$.
\begin{equation}
\begin{aligned}
    I_2=&\int_{|x|\leq 1/2}x^2|{H_t(x)}|^2d x=C\int\sin^2(\pi x)|H_t(x)|^2d x\\
    =&C\int \frac{1}{2}(1-\cos(2\pi x))\sum_{n}\sum_{k}e^{-4\pi^2(n^2+k^2)t}e^{2\pi i (n-k)x} d x\\
    =&\frac{C}{2}\sum_{n}\sum_{k}e^{-4\pi^2(n^2+k^2)t}\int e^{2\pi i (n-k)x}\left(1-\frac{e^{2\pi i x}+e^{-2\pi i x}}{2}\right)d x\\
    =&\frac{C}{2}\sum_{n}\sum_{k}e^{-4\pi^2(n^2+k^2)t}\int e^{2\pi i (n-k)x}d x\\
    &-\frac{C}{4}\sum_{n}\sum_{k}e^{-4\pi^2(n^2+k^2)t}\int e^{2\pi i (n+1-k)x}d x\\
    &-\frac{C}{4}\sum_{n}\sum_{k}e^{-4\pi^2(n^2+k^2)t}\int e^{2\pi i (n-1-k)x}d x\\
    =&\frac{C}{2}\sum_{n}\sum_{k}e^{-4\pi^2(n^2+k^2)t}\mathbb{I}({n=k})\\
    &-\frac{C}{4}\sum_{n}\sum_{k}e^{-4\pi^2(n^2+k^2)t}\mathbb{I}({n=k-1})\\
    &-\frac{C}{4}\sum_{n}\sum_{k}e^{-4\pi^2(n^2+k^2)t}\mathbb{I}({n=k+1})\\
    =&\frac{C}{2}\sum_{n}e^{-8\pi^2n^2t}-\frac{C}{4}\sum_{n}\left[e^{-4\pi^2(2n^2+2n+1)t}+e^{-4\pi^2(2n^2-2n+1)t}\right]\\
    =&\frac{C}{2}\sum_{n}e^{-8\pi^2n^2t}\left[1-\frac{e^{-4\pi^2(1+2n)t}+e^{-4\pi^2(1-2n)t}}{2}\right]\\
    =&\frac{C}{2}\sum_{n}e^{-8\pi^2n^2t}\left[1-e^{-4\pi^2t}\frac{e^{-8\pi^2nt}+e^{8\pi^2nt}}{2}\right]\\
\end{aligned}
\end{equation}
Note that $2\leq e^x +e^{-x}\leq 2 e^{|x|}$
when $0\leq x \leq \delta$,  $e^x \sim 1+x$, one can see
\begin{equation}
    1-e^{-4\pi^2t}\frac{e^{-8\pi^2nt}+e^{8\pi^2nt}}{2}\leq 1-e^{-4\pi^2t}\leq c 4\pi^2t .
\end{equation}
and
\begin{equation}
    1-e^{-4\pi^2t}\frac{e^{-8\pi^2nt}+e^{8\pi^2nt}}{2}\geq  1-e^{-4\pi^2t}e^{8\pi^2|n|t}\geq c 4\pi^2(2|n|-1)t .
\end{equation}
Finally, we have
\begin{equation}
    \begin{aligned}
        I_2\leq K t \sum_{n}e^{-8\pi^2n^2t}=t O(t^{-1/2})=O(t^{1/2}),
    \end{aligned}
\end{equation}
and
\begin{equation}
    I_2\geq Kt \sum_{n}e^{-8\pi^2n^2t}(2|n|-1)=2Kt \sum_{n}|n|e^{-8\pi^2n^2t} -O(t^{1/2}) =O(t^{1/2}).
\end{equation}
Note that
\begin{equation}
    \sum_{n}|n|e^{-8\pi^2n^2t} \sim\int |x|e^{-8\pi^2x^2t }d x=O(t^{-1/2}),
\end{equation}
which is $E(|X|)$ for $X\sim N(0,\sigma^2)$, and $E(|X|)=\sigma\sqrt{\frac{2}{\pi}}$. see this question for more details.
By far we have proved that $I_2=O(t^{1/2})$.

A propriety of the Heat Kernel on the circle from Stein‘s Fourier analysis Ch.4 Ex13


Apache config for heartbeat and proxy pass through to ELB

Question: I am running Apache 2.2.15 on Linux in AWS using ELBs.
My goal is to provide two functions:
1) Heartbeat page for my ELB to check to see if Apache is running (/healthcheck.html)
2) For all other requests, send to an ELB in the next tier via ProxyPass
I have placed a simple html file in /var/www/html named healthcheck.html.
Here's my config:
<VirtualHost *:80>
   <Directory "/var/www/html">
    allow from all
   </Directory>
    ProxyRequests Off
    ProxyPass / http://bigassawsdomainname.com:80/
    ProxyPassReverse / http://bigassawsdomainname.com:80/
    ProxyPreserveHost On
</VirtualHost>

The proxy functionality seems to be working fine. However, hitting localhost/healthcheck.html returns a 404.
I am quite sure my config is not set up correctly. How should I configure this? I've experimented with location and directory with no luck.
Update:
Solution:
NameVirtualHost *:80

<VirtualHost *:80>
    ProxyRequests Off
    <LocationMatch "^(?!/healthcheck.html)">
     ProxyPassMatch http://bigassawsdomainname.com:80/
    </LocationMatch>
    ProxyPassReverse / http://bigassawsdomainname.com:80/
    ProxyPreserveHost On
</VirtualHost>

<VirtualHost *:80>
    DocumentRoot /var/www/html
    <LocationMatch /healthcheck.html>
    RewriteEngine On
    RewriteRule ^/$ /healthcheck.html [L]
   </LocationMatch>
</VirtualHost>

Answer: You can use a negative lookahead in a locationmatch block to proxy everything except healthcheck.html:
https://stackoverflow.com/questions/8545680/how-to-tell-apache-to-locationmatch-opposite-of-this
<LocationMatch "^(?!/healthcheck.html)">
  ProxyPassMatch http://bigassawsdomainname.com:80/
</LocationMatch>

(the proxypassreverse should be outside the locationmatch)


Sistema de reconhecimento facial em php

Question: Gostaria de fazer um sistema  no qual eu salvasse algumas fotos no banco de dados e a partir da webcam eu tirasse uma foto na hora e comparasse com as que tem no banco, já procurei bastante na internet porem só acho reconhecendo o rosto da pessoa, mas não dessa forma.
Comment: não é ideal fazer isso no php..
Comment: +1 não é recomendado o uso do PHP para isso. Aqui tem uma lista de API's: http://blog.mashape.com/list-of-10-face-detection-recognition-apis/
Comment: Tem esse em jquery: http://facedetection.jaysalvat.com/ github: https://github.com/jaysalvat/jquery.facedetection
Comment: Então @DanielOmine realmente vi a galera falando isso que seria melhor fazer em outra linguagem e depois fazer uma forma de ponte no php vou procurar em outras linguagens tambem.
Comment: @juniorb2ss olhei o site que você mandou porem aparentemente as API são todas pagas ou tem que colocar cartão para usar nem que seja por um tempo e eu não tenho cartão, ate consegui entrar no site de algumas e tinha umas que era exatamente o que eu queria mas..  Se tiver mais informações de como usar o site eu agradeço, talvez eu que não tenha entendido como ele funciona.
Comment: @IvanFerrer isso e o que eu mais acho na internet porem não é isso que eu to querendo, seria mais comparar uma imagem com outra, ai ele apenas localiza os rostos na imagem mas muito obrigado.
Comment: APIs de face detection é realmente pago. Encontrar uma open source é pouco complicado e desconheço a existência de alguma.
Comment: Os algoritmos de reconhecimento facial são muito complexos e há investimentos pesados nos que estão bem desenvolvidos.. Naturalmente não encontrará nada gratuito na web que seja razoável. No máximo encontrará serviços que fornecem alguma API paga. Trabalhei com isso em 2007, mas na ocasião fiz script com PHP e PHP-GD que reconhecia movimentos. Foi para câmeras de segurança. Até que funcionava bem, mas longe de ser o ideal em performance. Foi mais em conta, financeiramente, comprar um software já homologado e recomendado comercialmente.
Comment: @juniorb2ss E o problema que eu precisava uma open source, porque o que eu to fazendo é apenas um trabalho academico, vou continuar pesquisando mas se for muito dificil de encontrar algo vou pensar em outra coisa no lugar do reconhecimento facial.
Comment: @DanielOmine realmente, eu mesmo não faço minina ideia de como fazer um programa desses até porque ainda estou aprendendo, e em questão de comprar nem valeria a pena porque é apenas um trabalho academico, e não é TCC então.. Vou continuar pesquisando aqui, mas vou acabar tendo que pensar em outra forma de autenticar.
Comment: Nesse caso, apenas tome cuidado para que o seu trabalho não seja  copiado por terceiros. Normalmente em escolas e universidades, os mentores ou outros colegas se aproveitam da ingenuidade de alguem que consegue criar algo bacana e usa aquilo para fins comerciais. Se vc conseguir criar algo legal, faça registro de patente antes de apresentar. Não caia muito nessa conversa de open source porque sempre tem aproveitador sugando trabalho alheio.
Comment: @DanielOmine Ok vlw pelo aviso.
Comment: Sei que é antigo, mas uma pena ainda encontrar mensagens como essa: "não é recomendado ser feito em PHP". Por que não? ninguem explica, ninguem fala nada, só opiniões. Saibam que até em C# esse tipo de processamento é feito através de apis externas, e é perfeitamente possível o bind com PHP. Se alguém ainda tiver interesse como eu estou tendo agora depois de 3 anos da pergunta, deem uma procurada em opencv. É possível compilar a extensão para o PHP, ou até usar via linha de comando https://github.com/php-opencv/php-opencv-examples
Answer: Como já adiantaram nos comentários, o PHP não é a linguagem ideal para fazer o reconhecimento facial propriamente dito.
No entanto, como você vai desenvolver um serviço web, é interessante pensar no PHP como a aplicação web que receberá as fotos, a partir do recebimento das mesmas, você conecta com um serviço ou com uma outra linguagem que fará o reconhecimento propriamente dito.
A própria tarefa de reconhecimento de rostos a partir de imagens não é trivial – você precisa de um banco de dados de imagens, desenvolver uma rede neural, treiná-la para aí então, se tudo der certo, reunir um conjunto de atributos comuns a cada conjunto de fotos da mesma pessoa.
Óbvio que isso também depende muito dos seus requisitos: se você precisa encontrar imagens idênticas às existentes atualmente (o que eu acho difícil, já que elas virão de fotos tiradas por webcams) ou com um certo grau de similaridade.
Comment: Como eu disse ali no comentario acima realmente vi algumas pessoas falando isso, que seria melhor fazer uma especie de ponte entre o php e outra linguagem, vou começar a pesquisar em outras linguagens tambem e depois vejo uma forma de fazer essa ponte, em questão de analizar a imagem realmente teria que ser por grau de similaridade. Se achar algum projeto mesmo que em outra linguagem que faz realmente isso eu agradeço, mas claro enquanto isso vou pesquisando tambem. Vi muita galera usando uma biblioteca chamada de OpenCV  não sei exatamente em que ela facilita.

Sistema de reconhecimento facial em php


$u$ harmonic, $|u(x)|\le C(1+|x|^\theta), x\in \mathbb{R}^N$ then $u$ is constant

Question:
Let $u$ be an harmonic function in $\mathbb{R}^N$. Suppose that there
  exists constants $C>0$ and $0\le\theta<1$ such that $$|u(x)|\le
 C(1+|x|^\theta), x\in \mathbb{R}^N$$ Show that $u$ is contant. Show
  also that this conclusion is not valid for $\theta=1$

I believe this has somthing to do with the maximum principle:

if $f$ is a harmonic function, then $f$ cannot exhibit a true local
  maximum within the domain of definition of $f$. In other words, either $f$
  is a constant function, or, for any point $x_0$,
  $x_{0}$ inside the domain of $f$, there exist other points arbitrarily
  close to $x_0$ at which $f$ takes larger
  values.

However, since $u$ is defined in all of $\mathbb{R}^N$, then I think $u$ should be constant or unbounded with no local maximum points (I can only picture a function strictly increasing or decreasing).
I don't know how to proceed here. This inequality condition makes no sense to me.
Answer: If $f$ is harmonic in $\mathbb{R}^n$, then given $r>0$, there is $M>0$ such that
$$| Df(x_0)|\leq \frac{M}{r^{n+1}}\|f\|_{L_1(B(x_0,r))}. $$
That is
 $$| Df(x_0)|\leq \frac{C\cdot M}{r^{n+1}}\|1+|x|^\theta\|_{L_1(B(x_0,r))}\leq  \frac{C\cdot M}{r^{n+1}}\|1+|r|^\theta\|_{L_1(B(x_0,r))}$$
Hence
$$| Df(x_0)|\leq  \frac{C\cdot M}{r^{n+1}}\cdot(1+|r|^\theta)\cdot \|1\|_{L_1(B(x_0,r))} = \frac{C\cdot M\cdot r^n}{r^{n+1}}\cdot(1+|r|^\theta)\cdot | B(x_0,1)|. $$
So
$$| Df(x_0)|\leq \frac{C\cdot M}{r}\cdot(1+|r|^\theta)\cdot | B(x_0,1)|. $$
Since $0\leq\theta<1$ and $f$ is harmonic in $\mathbb{R}^n$, taking $r$ arbitrarily big, the righ side goes to zero. Then, for all $x_0$, we have that
$$|Df(x_0)|=0,$$ and hence $f$ is constant since $\mathbb{R}^n$ is connected.
Notice that this proof doesn't work for $\theta=1.$
Comment: Where did that first inequality come from? Is it a theorem?
Comment: Yes. In Evan's Book on Partial Differential Equations it's called 'Estimates on derivatives'. This theorem is in the section about Mean-value Formulas in the chapter about Laplace Equations.
Comment: Thanks, I just found the proof. However I don't know if I'm allowed to use it. Do you have an idea on how it would be done without this theorem?
Comment: What are you allowed to use? What were you studying when you came across with this problem?
Comment: I've already seen green functions, the representation formula, weak and strong maximum principles, mean value properties and soe other minor things. I didn't see this theorem so it's kinda strange that I should come up with it before solving the exercise. Also, what is this $||||_{L_1}$? It's a norm? What is $L_1$?
Answer: Cauchy-type estimate: There is a constant $A$ such that for all $u$ harmonic on $B(0,1)$ and continuous on $\overline {B(0,1)},$
$$|\nabla u(0)| \le A\max_{|x|=1}|u(x)|.$$
This follows from the Poisson integral representation; just differentiate through the integral sign to see each partial derivative at $0$ satisfies the above, hence so does $\nabla u(0).$
In our problem, let $u_r(x) = u(rx)$ for $r>0.$ Then by the above
$$|\nabla u_r(0)| = r|\nabla u(0)| \le A\max_{|x|=1}|u_r(x)|$$ $$ =  A\max_{|x|=r}|u(x)| \le AC(1+r^\theta).$$
It follows that $|\nabla u(0)|\le AC(1+r^\theta)/r.$ Letting $r\to \infty$ gives $\nabla u(0)=0.$
To finish, we translate $u.$ Let $x_0\in \mathbb R^N$ and define $v(x) = u(x+x_0).$ Then for $|x|\ge |x_0|,$ we have
$$|v(x)|=|u(x+x_0)|\le C(1+|x+x_0|^\theta) \le C(1+2|x|^\theta).$$
This is enough to make the previous argument work, giving $|\nabla v(0)| = |\nabla u(x_0)|=0.$ It follows that $\nabla u(x)=0$ everywhere, proving $u$ is constant.
If $\theta =1,$ then $u(x)=x_1$ is a non constant harmonic function that satisfies the inequality.


target=_blank doesn't work in IE8, running IEs side-by-side (I run the package of IEs via VirtualBox)

Question: IE8 will sometimes prevent links from spawning if they have target=_blank set.
This problem appears to be limited to corrupt installs of IE, such as when installing several versions side-by-side.
I edited this question once I found the answer, and hopefully this will save someone else some time. The answer is in the comments of the first answer listed.
Comment: Might be helpful to reword the question to indicate that this is a problem when trying to run IE side-by-side.
Comment: What a huge collection of way-wrong answers... More, disturbingly, the XHTML 1.1 kids think that tacking on _target=blank through javascript is a valid hack. If a browser implimented XHTML 1.1 *only* you would expect this to not work.
Answer: This depends upon which stand-alone IE8 that you use. I found this to be a problem while using "Final Builds Site - Internet Explorer Collection" (http://finalbuilds.edskes.net/iecollection.htm) version 126.96.36.199. The developer has now fixed this bug as of Ver. 18.104.22.168, and links with target="_blank" now work as expected.
Answer: I know this is already answered, but I just wanted to tell about the jQuery's live binding functionality:
$("a.myclass").live("click",function() {
    $(this).attr("target","_blank");
});

This example sets the 'target="_blank"' attribute to any link with the class "myclass", even those created with Javascript.
Answer: What about if you use target='blank' ? I know it's not THE same, but you will get the popup/window open in a new instance, and your site could validate for XHTML Strict Mode :)
Comment: sorry, I misplaced a quote. It should been
target='blank'
Comment: for the record, it's not the '_blank' that's not allowed in XHTML 1.0 or 1.1 strict, it's the target attribute on anchor or link elements. It was (intentionally) left out of the DTD. If using target='blank' validated for you as XHTML 1.0 or 1.1 Strict then it was an error on the validator's part. That said, most browsers still accept it and process it, valid or no.
Answer: Yeah, XHTML Strict Mode doesn't accept target="_blank".
If you don't want to keep using window.open everywhere, you can use rel="external" and some extra Javascript like the following, using JQuery:
$(document).ready(function() {
    $("a[rel='external']").attr("target","_blank");
});

EDIT: To set all generated links:
 $("a[rel='external']").ready(function() {
    $("a[rel='external']").attr("target","_blank");
 });

Or, without jQuery, you can use the script, found here:
function externalLinks() {
 if (!document.getElementsByTagName) return;
 var anchors = document.getElementsByTagName("a");
 for (var i=0; i<anchors.length; i++) {
   var anchor = anchors[i];
   if (anchor.getAttribute("href") &&
       anchor.getAttribute("rel") == "external")
     anchor.target = "_blank";
 }
}
window.onload = externalLinks;

Comment: Well, this is supposed to be a collaboration site, not a "give me a solution that works out of the box" site.
Comment: This doesn't work. First of all, the links are created with javascript, and as such don't exist onload. I tried setting a.rel and a.target, but this doesn't work.
Comment: Hence my continued collaboration.
Comment: Your collaboration consists of "this doesn't work". You shouldn't downmod people because the solution "doesn't work". It works, just not exactly the way you want it to.
Answer: This is because target="_blank" is not valid under XHTML Strict Mode.  See:
http://www.8164.org/xhtml-strict/

The following should work in all cases.

I presume that as of IE8 Beta 1, the default mode is now STRICT instead of TRANSITIONAL.
Comment: "Class not registered" when opening new windows means your IE8 install is corrupt.
Comment: http://www.debugtheweb.com/test/strict.htm works properly when IE8 is installed correctly.
Comment: This doesn't work for me, though in my document I'm forcing IE7 mode as follows:
Comment: Eric, you hit the nail on the head. I have "side-by-side" IEs (6,7,8, etc.) installed on a VirtualBox instance. When I check the page through a real windows box, it works. Thanks!
Comment: Yes, sadly that's one of the reasons that we don't recommend the "side-by-side" hacks.  VPC is the only supported way to get side-by-side today. Thanks for the update!


Calling SQL System function on DataTable in C#

Question: I need to execute the sql server system function over DataTable.
DataTable has a string value e.g. "12345", in this i need a substring which is configured in Sql server table like SUBSTRING(,0,2).
I'm able to get the condition from DB table.
But how to apply this condition in DataTable?
Comment: There is a String.Substring() function in c# that does the same thing.
Comment: Are you passing the Datatable back to SQL Server?
Comment: @RossBush - No, just applying logic on the data values
Answer: There are many ways of achieving this.
1 - You can create a view that calls your function, ie:
Create View testView
As
Select
dbo.myFunction(parameter)
FROM dbo.TableName

2 - You can use C# Substring function as Ross mentioned in his comment:
DataTableString.Substring(0, 2)

Answer: You can use the SUBSTRING function in the query that is used to populate the DataTable.  SUBSTRING(0, 2) was used in your question, I'm guessing you want the first two letters letters of the column?  SUBSTRING in SQL Server starts at 1, while this same function begins at 0 in C#.  You'll need to use (Column, 1, 2) in a SQL query to return the first two characters.
string connStr = @"YourConnectionString;";
string cmd = @"SELECT SUBSTRING(ColumnA, 1, 2) AS ColumnA from YourSchema.YourTable";
using (SqlConnection conn = new SqlConnection(connStr))
{
    conn.Open();
    DataTable dt = new DataTable();
    //create data adapter from string with SQL command and SQL Connection object
    SqlDataAdapter da = new SqlDataAdapter(cmd, conn);

    //populate DataTable
    da.Fill(dt);
}


Can't handle api response by get method in angular2?

Question: i have been trying to get response from an api (http://www.cricapi.com/how-to-use.aspx) with angular2. i don't know what i am doing wrong? here's my code--
//matchlist.component.ts
@Component({
selector: 'match-list',
template: `

{{m.title}}

`,
providers: [MatchListService]
})

export class MatchList implements OnInit{

matches: Match[] = [];
object: any;
constructor(private matchservice: MatchListService){
}

ngOnInit(){

    this.matchservice.getMatchList()
        .subscribe(
            matches => this.matches = matches,
            err => {}
          );

 }
}

here's my service class-
 @Injectable()
 export class MatchListService{

private matchListUrl = 'http://cricapi.com/api/cricket/';

constructor (private http: Http) {

}

getMatchList(): Observable<Match[]>{
    return this.http.get(this.matchListUrl, [{}])
                    .map((res:any) => res.json()
                      .catch(this.handleError));
            }

please tell me if i am doing it the wrong way? this is my first ex with api!
Comment: There is no angular code here, you cant use regular javascript classes in angular. Where is the app module, controller  and/or factory?
Comment: @johan probably this is TypeScript
Comment: sry guys! i just found that angular and angular2 are completely different! and yeah its typescript!
Comment: Also my bad, I'm sure the question was marked AngularJS not 2...
Answer: I'm not sure what language you are trying to code in but with regular angular you simply assign the JSON returned result to a variable and it will hold the complete JSON object like so:
$scope.data = [];
$http({url: url}).then(function (rs) {
    console.log(rs);
    $scope.data = rs.data;
});

Comment: its angular2! thats y!


Views RSS channel properties added with hook_views_query_alter() disappear

Question: I have applied this patch to the Views module so that it will add the channel properties of pubDate and lastBuildDate.
Then I ran Drupal "Clear all caches" within /admin/config/development/performance.
The added channel properties are only available for the first page requested each time after running another Drupal "Clear all caches".
For Drupal 7 how can I ensure that views RSS channel properties that are added with hook_views_query_alter() remain?
=================================================================================
I have already tried the "Views RSS" module and after downloading and enabling this module along with its associated "views_rss_core" the "RSS Feed – Fields" radio button does not display and only the "RSS Feed" option is present which comes from the "Views" module.
Answer: You can do this with Views RSS 2 and hook_views_rss_item_elements().
As we can see in the documentation for Views RSS API views_rss_get it can :

Fetch item elements provided by other modules.

So to create your own item element do the following :

First thing, revert your hack, it won't be needed.
Download and install the module Views RSS (and Core Elements, DC Elements)
Create a default view for content and fields
Add a feed to it
Style it as RSS Feed - Fields
In the settings pubDate is avaible alerady so we don't have to worry about that.

Create a tiny module and enter the following
/**
 * Implements hook_views_rss_namespaces().
 */
function MY_MODULE_views_rss_item_elements() {
  $elements['dc:lastBuildDate'] = array(
    'description' => t('My custom lastBuildDate field.'),
    'help' => '',
  );
  return $elements;
}

Then install it and clear your cache.
Now, in the Views RSS field settings there should be a new field for your custom field (see image)

And when you view your feed it should be included (see image - last line)

Note: if you look at the snippet, it adds the field to the dc namespace. If you want to use another or provide your own namespaces have a look at the API and hooks.
Comment: I have already tried the "Views RSS" module and after downloading and enabling this module along with its associated "views_rss_core" the "RSS Feed – Fields" radio button does not display and only the "RSS Feed" option is present which comes from the "Views" module.
Comment: Have you tried clearing the cache, a lot of views options are cached. Also, have you reverted your hack ?
Comment: Yes I have cleared the drupal cache many times and the hack was also reverted.
Comment: Not sure why the radio button is not there. Maybe disable then uninstall Views Rss module to see if it reacreates it. Just to confirm this solution though, please try the above on a fresh install, it might help you track down what's wrong.
Comment: I disabled and uninstalled views rss for both the recommended and the dev version and I still don't see the radio button.
Answer: It appears to me that you have custom patched the Views modules with an extra function which calls hook_views_query_alter.  There are at least two problems with doing it this way:

Altering a module with a patch that is not being considered for commit by the maintainers will lead to trouble when the module is updated - in a few years when somebody else is maintaining the site, will they remember to apply the same or an updated patch each time?  Will you?
The views module may already have a hook_views_query_alter call and you can't call a hook more than once in any one module.  If it doesn't, maybe it will have one in later versions.

I suggest moving your code to a custom module.
Comment: I also previously tried moving the hook_views_query_alter call to a custom module but it did not make any difference.
Comment: I assume you did the usual things like changing the function name to match the module...?
Comment: Yes I have changed the function name to match the module
Comment: 2. if a module had two same hooks they would be same function names and php would throw error - Fatal error: Cannot redeclare etc. so OP would know. Also views exposes this hook (part of it's API), it doesn't implement it itself so it is available. Some good advice here but no answers.


Does shape of waveform affect sonic perception?

Question: Title says it all - does the shape of a wave have any effect on how we perceive it as a sound?
Comment: Waveform **is** sound.   that's all there is.
Comment: See my answer (that I'm quite chuffed about) related to this here:https://music.stackexchange.com/questions/69309/how-do-multiple-sound-waves-interact-physically-to-create-music/69314#69314
Answer: Yes, but not directly - instead, we perceive the different amounts of energy in different harmonics. :)
To illustrate the differences, here are some graphed waveforms, and here's a YouTube video which demonstrates some basic waveforms.
A square wave only has odd harmonics (the base frequency, 3x the base frequency, 5x, 7x, etc.) and that gives it a distinct character.  This is similar to the triangle wave (which also only has odd harmonics, but in different amounts).  They are both very tonally different to the sawtooth wave, which contains both odd and even harmonics.
However, since it's mostly determined the relative amplitude of the harmonics (we aren't very good at hearing phase, except between our two ears) it's possible for two waveforms to look different but sound basically identical, if their harmonics have the same energy.
Here is a video which demonstrates that: at 0:02 it plays a conventional sawtooth waveform, but at 0:12 it plays a different-looking waveform which has the same energy in its harmonics, so sounds the same.
Edit: as @MacTuesday mentioned, the distinction between a continuous tone and a quickly-repeating sound can be ambiguous, particularly for very low pitches.  Phase/timing information is not meaningless, but for the cases you're thinking of, harmonic energy is the primary aspect that determines timbre of continuous sounds.
Comment: @J The results of a Fourier transform are complex numbers, which have both an amplitude and a phase.  We are more sensitive to the amplitude than the phase - see the second linked video in my answer as an illustration.
Comment: The musical word here is *timbre*;  it's the quality that differs between a clarinet, a trumpet, and a violin playing middle C.
Comment: @MackTuesday: Yeah absolutely, and with lower pitches it's tied up with aspects of exactly _how_ you're performing the frequency analysis (window length, FFT or IIR stack, etc.), and human perception interpretation is another layer on top of that.  That seemed a little more detail than the question needed, but I'll add a note.
Comment: This answer misses the role of the phase spectrum in lower pitches. People will register individual transients if they repeat slowly enough, even above 40 Hz. In such cases, the waveform absolutely will affect timbre, even if the amplitude spectrum remains the same.
Answer: Of course. You can trivially prove this with programmable synthesizers or software that allows you to customize an audio wave form for output. There are distinctive differences between regular sine/cosine forms, rectangular waves, and triangular (saw) waves.
Answer: You've got it the wrong way round.  Waveform is a pictorial representation of sound.
Comment: As the saying goes in computer science: "Data is symbols plus interpretation." Both ways of looking at the topic are valid.
Answer: Duty cycle of the waves can also affect the sound. Sometimes just in the perceived volume, sometimes in the tone(s) heard.


How to Serialize and Deserialize an XMLDocument in Javascript?

Question: I am getting error on document.adoptNode as 'parameter1 is not valid node'.
Below is my code.
 $.ajax({

     type: "GET",
     url: url,
     datatype: "xml",
     success: function (results) {
         //results is a XMLDocument type object which contains a SVG information
         console.log(results);
         //need to serialize results to store it in localStorage

         localStorage.setItem('results', JSON.stringify(results));

         var results2 = JSON.parse(localStorage.getItem('results'));

         var svgnode = $('svg', results);

         var origwidth = svgnode.attr('width');

         var origheight = svgnode.attr('height');

         var docnode = document.adoptNode(svgnode[0]);
     }

 });

I need serialization and deserialization to store it in localStorage. How can i serialize and deserialize XMLDocument?
Comment: hi if your results is xml only could you try not to JSON.stringify and  JSON.parse the xml and use it direct..its for JSON not xml ..you will get parsing error
Answer: XML has its own text format, I wouldn't use JSON for the serialization/deserialization, I'd use XML.
In your ajax call, you're asking jQuery to deserialize the XML text received for you. But since you want to use that text, I'd change dataType to "text" so you receive a string with the XML in it. Then store that in localStorage and parse it when you need an XMLDocument instead of a string.
Something along these lines:
$.ajax({
     type: "GET",
     url: url,
     datatype: "text",
     success: function(results) {
         // `results` is a string
         localStorage.setItem('results', results);
         // No need to re-get it, you already have it in `results`; parse it
         var results2 = new DOMParser().parseFromString(results, "text/xml");
         var svgnode = $('svg', results);
         var origwidth = svgnode.attr('width');
         var origheight = svgnode.attr('height');
         var docnode = document.adoptNode(svgnode[0]);
     }
});

Or you can parse it with jQuery instead:
$.ajax({
     type: "GET",
     url: url,
     datatype: "text",
     success: function(results) {
         // `results` is a string
         localStorage.setItem('results', results);
         // No need to re-get it, you already have it in `results`; parse it
         var svgnode = $.parseXML(results);
         var origwidth = svgnode.attr('width');
         var origheight = svgnode.attr('height');
         var docnode = document.adoptNode(svgnode[0]);
     }
});

If you ever need to go from an XMLDocument to a string again, you can do that like this:
var xmlString = new XMLSerializer().serializeToString(xmlDocument);

Comment: changing datatype to text from xml not changing results to string. Still i am facng issues.
Comment: length of the string is 5863435


Why does this argument that sin(1/x) is not uniform continuous on (0,1) fail for [0,1]?

Question: (1): I understand that $f(x) = sin(1/x)$ is continuous at every point in the open interval (0,1), but it is not uniformly continuous on this interval (e.g. take $\epsilon=2$ and set $x_n = \frac{1}{\pi/2 + 2n\pi}$ and $y_n = \frac{1}{3\pi/2 + 2n\pi}$).
(2): I also understand that a function that is continuous on a closed, bounded interval K is uniformly continuous on K, e.g. [0,1]. (Pf: suppose f is not uniformly continuous, use B-W to find two subsequences converging to same limit, etc...).
But even if $f(x) = sin(1/x)$ is continuous on a closed, bounded interval, couldn't I still set $x_n = \frac{1}{\pi/2 + 2n\pi}$ and $y_n = \frac{1}{3\pi/2 + 2n\pi}$ still exist as in (1) above, then $|x_n - y_n| \rightarrow 0$ but $|f(x_n) = f(y_n)| \geq \epsilon$? Then, f(x) would still fail to be uniformly continuous but this contradicts (2).
Could you please help me identify the gaps in my understanding? Thank you :)
Answer: I don't understand your question. You seem to be assuming that $\sin\left(\frac1x\right)$ is continuous on $[0,1]$ and therefore uniformly continuous. It is not! First of all, it is not even defined at $0$. And if you extend it to $[0,1]$, there is no way that extension will be continuous, since $\lim_{x\to0}\sin\left(\frac1x\right)$ doesn't exist.


Programmatically adding two lines to crontab

Question: I'm trying to add two lines to the root crontab when building an AWS instance. I have a set of commands that are part of the "user data". These commands are run as root when creating the instance. I would like to add these two lines to the crontab:
@daily /home/ubuntu/db-backup-to-s3-daily.sh
@hourly /home/ubuntu/db-backup-to-s3-hourly.sh

I am using the following approach (based on an answer to this question):
(crontab -u ubuntu -l ; echo -e "@daily /home/ubuntu/db-backup-to-s3-daily.sh\n@hourly /home/ubuntu/db-backup-to-s3-hourly.sh") | crontab -u ubuntu -

However, this does not work when the instance is being created, but it does work if I log in and run this line. Is there any different way that I can append lines to the crontab?
Comment: Consider /etc/cron.d instead of /etc/crontab. /etc/cron.d is better when using system automation.
Comment: just wondering how you managed you aws secret keys with this? Specifically, how and where did you set the AWS_CONFIG_FILE variable so that cron is aware of it?
Answer: If you are trying to mange crontabs programmatically, just create a file in /etc/cron.d/ for example, /etc/cron.d/example-cron, and populate it with the aforementioned lines:
@daily ubuntu /home/ubuntu/db-backup-to-s3-daily.sh
@hourly ubuntu /home/ubuntu/db-backup-to-s3-hourly.sh

The only difference is that you have to include a user to run the cron as, as the second argument.  I set it to ubuntu in the example above, but you could set it to root for example.
Comment: The cron.d directories exist to solve issues like that. You can find a lot of *.d folders under /etc, and it makes life easier using them. I Agree with Kevin , this is best practice. And BTW crontabs they're (typically) stored uncer /var/spool/cron.
Comment: On that note, he could also place each script directly in /etc/cron.daily/, and /etc/cron.hourly/ respectively.  But I figured this way was the path of least resistance.
Comment: yeah but AFAIK those scripts they run as root only.
Comment: echo "@daily ubuntu /home/ubuntu/db-backup-to-s3-daily.sh" >> /etc/cron.d/example-cron  etc.  To get root you may need to do a sudo tee combination.


how to get the values from views in page template

Question: I created a view (page name 'Archives') to load the following values from all the posts of a particular content type.
Year = field_year
Volume = field_volume
Issue = field_issue
By using views I couldn't get the desired output. So, I created a template file (views-view--archives--page.tpl.php) and wrote the following code. Please see the attached screenshot & code below. Please help me in correcting the code. This would be a great help. Thanks

 <?php foreach ($view->style_plugin->rendered_fields as $delta => $item): ?>

    <?php print $item['field_year']." (volume - ".$item['field_volume'].")"; ?>
    <?php print "Issue ".$item['field_issue']; ?>

 <?php endforeach; ?>

Comment: The template `page--archives.tpl.php` will be used to create the overall page structure when you goto `www.example.com/archives`, so the output of your view will be placed in the content area/region in the page.  Are you needing the Year field somewhere else on that page?  If so where and in what format, eg rendered or raw or?
Answer: You should use the Views templates (under Advanced > Other > Theme: Information). It gives several output types. When you create a Views specific template file, it passes a whole bunch of variable/values that you have chosen in your Views to the Views template file. Then you are free to use it like how you want. Read more info at http://views-help.doc.logrus.com/help/views/analyze-theme
Comment: Thank you Sridhar, this helped me in reaching near my goal. but it has a problem. Please see the above modified question and the screenshot. Please help.
Answer: You shouldn't need to write a template. This can be done in the views UI.
Click on the year field and select Exclude from display. Then click the volume field and override the output. Using replacement patterns it should be something like [field_year] [field_volume]. Then click settings for your display and select Group by field_volume.
See
https://drupal.org/node/1565480


Shift values in one pandas df column down based on values of another column

Question: I have a dataframe:
{
  'Person': {
    0: 1, 1: 1, 2: 1, 3: 1, 4: 2, 5: 2, 6: 2,
    7: 2, 8: 3, 9: 3, 10: 3, 11: 3
  },
  'Year': {
    0: 2017, 1: 2018, 2: 2019, 3: 2020, 4: 2017, 5: 2018, 6: 2019,
    7: 2020, 8: 2017, 9: 2018, 10: 2019, 11: 2020
  },
  'Value': {
    0: 20, 1: 30, 2: 23, 3: 40, 4: 11, 5: 20, 6: 30,
    7: 21, 8: 12, 9: 12, 10: 15, 11: 23
  }
}

I want to shift Value column by 1 down row, but taking into account 'Author`.
I tried shift and roll, but did not get the necessary result.
Expected output:
{
  'Person': {
    0: 1, 1: 1, 2: 1, 3: 1, 4: 2, 5: 2, 6: 2,
    7: 2, 8: 3, 9: 3, 10: 3, 11: 3
  },
  'Year': {
    0: 2017, 1: 2018, 2: 2019, 3: 2020, 4: 2017, 5: 2018, 6: 2019,
    7: 2020, 8: 2017, 9: 2018, 10: 2019, 11: 2020
  },
  'Value': {
    0: 20, 1: 30, 2: 23, 3: 40, 4: 11, 5: 20, 6: 30,
    7: 21, 8: 12, 9: 12, 10: 15, 11: 23
  },
  'Value t-1': {
    0: nan, 1: 20.0, 2: 30.0, 3: 23.0, 4: nan, 5: 11.0, 6: 20.0,
    7: 30.0, 8: nan, 9: 12.0, 10: 12.0, 11: 15.0
  }
}

Comment: Try it with: `df['Value t-1'] = df.groupby('Person')['Value'].shift()`
Answer: Full credit goes to @enke
df['Value t-1'] = df.groupby('Person')['Value'].shift()


Interação do VBA com Internet Explorer e utilização do getelementsbyclassname não funciona

Question: venho tentando criar um código que me faz entrar no Internet Explorer(ie), ir no site do yahoo finance, adicionar minha pesquisa de ações e buscar, porém a parte de buscar não vai.
O meu código é esse:
linha_ticker = 2
ticker = Sheets("Ibovespa").Cells(linha_ticker, 3)

'variável com fórmula deve ser atribuida por meio do SET
Set ie = CreateObject("internetexplorer.application")
ie.navigate "https://br.financas.yahoo.com/"
ie.Visible = True

'ação para só prosseguir caso a página esteja completamente carregada
Do While ie.busy And ie.readystate <> "READYSTATE_COMPLETE"
    DoEvents
Loop

'procurar na pagina ie o input de valor 0 e colocar nele o que está na variável ativo
ie.document.getElementsByTagName("input")(0).Value = ticker
'clicar em buscar
ie.document.getElementsByClassName("Bgc($linkColor) Bgc($linkActiveColor):h Fz(s) Fw(500) H(35px) Py(0px) Px(15px) W(80px) Bdrstend(2px) Bdrsbend(2px) Ta(c)")(0).Click

E o html do botão clicar é esse:
<button type="button" id="search-button" class="Bgc($linkColor) Bgc($linkActiveColor):h Fz(s) Fw(500) H(35px) Py(0px) Px(15px) W(80px) Bdrstend(2px) Bdrsbend(2px) Ta(c)" data-reactid="63">
<svg class="H(20px) W(20px) Va(m)! Fill(white)! Stk(white) Cur(p)" width="20" style="fill:#000;stroke:#000;stroke-width:0;vertical-align:bottom;" height="20" viewBox="0 0 24 24" data-icon="search" data-reactid="64">
<path d="M9 3C5.686 3 3 5.686 3 9c0 3.313 2.686 6 6 6s6-2.687 6-6c0-3.314-2.686-6-6-6m13.713 19.713c-.387.388-1.016.388-1.404 0l-7.404-7.404C12.55 16.364 10.85 17 9 17c-4.418 0-8-3.582-8-8 0-4.42 3.582-8 8-8s8 3.58 8 8c0 1.85-.634 3.55-1.69 4.905l7.403 7.404c.39.386.39 1.015 0 1.403" data-reactid="65">
</path>
</svg>
</button>

O que pode estar acontecendo?
Abraço.
Answer: Você não passou exatamente o comportamento do erro, o que dificulta um pouco a análise (por exemplo: ele preenche o ticker e depois não faz nada? Ou ele realmente dá um erro?).
Também não dá para analisar a página. Pode ter uma iframe, o que muda tudo, pois é necessário referenciar os documentos da iframe. Pode ter outro objeto com essa mesma classe antes, então o botão não seria o item 0 da coleção.
Enfim, sem maiores informações, considerando que o botão tem um atributo ID, eu tentaria usar outro método para referenciar o botão:
ie.document.getElementsById("search-button").Click

Espero que funcione.


How does drupal updates check work?

Question: I don't have an external crontab set up for my Drupal site.  How can Drupal search for updates in this case?
Comment: @close vote reviewers - come on, how is it unclear? Broad, maybe; basic, for sure; but unclear?
Answer: There should be a crontab task for Drupal. If there is none, it falls back to Poormanscron - integrated into Drupal core since 7.x

The module inserts a small amount of JavaScript on each page of your site that when a certain amount of time has passed since the last cron run, calls an AJAX request to run the cron tasks. However, this approach requires that your site gets regular traffic/visitors in order to trigger the cron request.

When check is initiated, it loops over modules and checks their status from URLs determined in function <code>_update_build_fetch_url</code> define at line 287* of update.fetch.inc file, in update core module.
For more details, examine update core module, code is pretty well documented.

Information valid for Drupal 7.25, may slightly change with version.
Comment: Thank you! Poormanscron - that is where the magic ("The module inserts a small amount of JavaScript on each page of your site that when a certain amount of time has passed since the last cron run, calls an AJAX request to run the cron tasks. However, this approach requires that your site gets regular traffic/visitors in order to trigger the cron request")
Comment: @Alexander But please read first link - Poormanscron is a bad solution. Better than nothing, sure, but still bad. Answer expanded with the quote you suggested.
Comment: I don't understand how to setup Cron. I see on admin/config/system/cron that it is enabled "every 3 hours" - is that all?.. what differences then between Poormanscron? or I must add something to my crontab file on unix system?
Comment: @Alexander to properly set up cron task, you must understand it's something you do on the server's operating system, outside Drupal. You must make your server to regularly call your Drupal and say "the time is now" ;) If possible, talk with your sysadmin.
Comment: I'm sysadmin) I just want to understand how does it work. I see on cron page that it is enabled and it regulary works off. Is it Poormanscron mechanism?.. In other words - if I close site from outside (no visitors) - cron task will not work? I think yes - no magic. But why it is better to make crontab task in operating system (something like curl or wget special address) then just use Poormanscron mechanism if it works fine?.. Even not popular sites robots visit regulary, so...

How does drupal updates check work?


Append SQL result to HTML table via Powershell

Question: I have multiple databases from multiple SQL Servers.
I am trying a output SQL data to an HTML table using Powershell from these databases/SQL Servers, then send a mail. The script I made works, but it will output multiple tables for each result in the html report. What I want is to append the data to the same table (Only 1 table containing all data). Struggling a bit on how to concatenate the data to only 1 table.

#Set flag to 0 for email notification (if any)
$alert= 0

$List = Get-Content -Path "C:\Users\testadmin\Documents\Log\serverlist.txt"

Foreach($Server in $ServerList){

$SQL = ($Server -split '=')[0]
$ = ($Server -split '=')[1]

$Query = "select host, Service, Status from Table with(nolock)"

$Value = Invoke-Sqlcmd -ServerInstance $SQL -Database $DB -Query $Query

foreach($mylocal in $Value ){

    $hostname = $mylocal.host
    $Service= $mylocal.Service
    $Status = $mylocal.Status

         if($Status -ne 'Running'){

         $alert= 1

         $Body += "
          <meta http-equiv='Content-Type' content='text/html; charset=iso-8859-1'>

          <title>Warning</title>

Apps are Stopped !

Timestamp: $(Get-Date)

            SQL
            DB
            Service Status

            $SQL
            $DB
            $Status

          "
         }

         else{
            Write-Host ("no alert")
         }
  }

}

  if($alert-eq '1'){

          $Mail = @{
            From = 'email@example.com'
            To = 'firstname.lastname@example.com'
            Subject = 'Warning!!'
            smtpserver = 'myrelay.test.com'
            Body = $Body
            BodyAsHtml = $true
          }

          Send-MailMessage @Mail
        }

Answer: You need to create your base html (the one containing the head / body / table title / table headers) outside of the loop. In the loop, you create only the table cells.
From there, you build your complete HTML.
Example

# Just some data... I used calculated field to have the same field name as you.
$Value = Get-Service | Select @{'Name' = 'host' ; 'Expression' = { "localhost" } },
@{'Name' = 'Service' ; 'Expression' = { $_.ServiceName } }, Status

$HtmlTemplate = @{
    Base_Date_TableLoop          = @'

          <meta http-equiv='Content-Type' content='text/html; charset=iso-8859-1'>

          <title>Warning</title>

Apps are Stopped !

Timestamp: {0:Date}

                SQL
                DB
                Service Status

          {0:TableLoop}

'@
    TableLoop_SQL_DB_Status = @'

            {0}
            {1}
            {2}

'@
}

 $Date = Get-Date
$Table = [System.Text.StringBuilder]::new()

foreach ($mylocal in $Value ) {

    $hostname = $mylocal.host
    $Service = $mylocal.Service
    $Status = $mylocal.Status

    $Table.AppendLine(($HtmlTemplate.TableLoop_SQL_DB_Status -f $hostname,$Service,$Status)) | Out-Null

}

$HtmlBody = $HtmlTemplate.Base_Date_TableLoop.Replace('{0:Date}',$Date).Replace('{0:TableLoop}',$Table.ToString())

$HtmlBody | Out-File 'SomeReport.html'

Design choices
I like to have all my html elements in a single variable. In the previous example, I used $HtmlTemplate to store all the pieces. These pieces are not meant to be edited directly but serves as my building blocks.
For the elements themselves, I personally like to have something along the lines of Base_Date_TableLoop where each underscores delimit something I need to replace so it is easier later on to do the replace without having to think about what goes where.
Additional notes
I used a mix of '{0}' with the -f for the loop piece and {0:TableLoop} with .replace for the base html piece. This is because the base html contains brackets {} used for the format operator, which would need to be doubled down for the -f operator to ignore them. Since I don't want to arbitrarily modify the html, I use the .replace .Net method, which allow me to replace the things I need without having to modify the html completely. Also, .Replace is used here instead of -Replace because the latter is a Regex operator, and I don't want that.
Comment: Many thanks Sage ! It worked beautifully


How to draw curved arrows with exact start and end points?

Question: I want to draw curved arrows, unfortunately, in the function no curvature argument arrows(., curve=) is implemented.
My idea for a solution was to subset an ellipsis. Since plotrix::draw.ellipse() draws lines and I need points for subsetting, I wrote a function arrow_curved() forking the code from this great answer which gives a somewhat satisfactory result.
arrow_curved <- function(xc, yc, a, b, .xlim, .ylim, .srt, .lwd=1.25, .col=1) {
  phi <- pi/3
  t <- seq(0, 2*pi, 0.001)
  x <- xc + a*cos(t)*cos(phi) - b*sin(t)*sin(phi)
  y <- yc + a*cos(t)*cos(phi) + b*sin(t)*cos(phi)
  w <- which(x > .xlim[1] & x < .xlim[2] & y < .ylim[2] & y > .ylim[1])
  x <- x[w]; y <- y[w]
  segments(x, y, x, y, lwd=.lwd, col=.col)
  text(x[which.max(x)], y[which.max(x)], labels='>', srt=.srt, col=.col)
}

plot(c(0, 10), c(0, 10), type="n")

## red arrows
arrow_curved(xc=3, yc=8, a=10, b=6.5, .xlim=c(3.25, 8.15),
             .ylim=c(2, 4.5), .srt=20, .lwd=1.25, .col=2)
arrows(3.25, 2, 8.15, 4.5, length=.075, col=2, lty=2)  ## straight arrow

## green arrow
arrow_curved(xc=2, yc=4, a=6, b=10, .xlim=c(1, 5),
             .ylim=c(1, 10), .srt=-20, .lwd=1.25, .col=3)

However, you need a little luck to specify the arguments. Ideally, the function would work like arrows(), where we could specify a curvature curve= parameter in addition to x0, y0, x1, y1. Moreover, currently the start and end points only match approximately the values specified in the .xlim= and .ylim= arguments (compare curved red arrow to the straight reference arrow).
Can anybody see a way to improve the function in this regard? Maybe the coordinates can be easily adjusted somehow with the help of mathematics, which is beyond my knowledge.
Comment: Have you seen [this post](https://kbroman.wordpress.com/2012/10/11/curved-arrows-in-r/)?
Comment: If you can define a middle point that tells the spline how far to bend outwards, you could then use `xspline` to draw the arrow, as in this example: https://stackoverflow.com/a/28112788/1199289
Comment: @StéphaneLaurent Very interesting, thanks very much, I just feel like I'm reinventing the wheel.
Answer: Your question made me very curious about how to do this, so I had another go. Quite some geometry goes into this, but it was an interesting challenge.
Basically, I realized that if you want to maintain a circular-form to your arc, the distance traveled between two points will depend on how many degrees you specify for the arc. A small number of degrees implies nearly a straight line, while a large number of degrees implies a very round-about way to the second point. My comment regarding the use of splines may make more sense under most cases, but if maintaining a circular form to your arrow is important, then the following seems to do that.
Required functions:
# helper functions to convert between radians and degrees
deg2rad <- function (deg){
  stopifnot(is.numeric(deg))
  (rad <- (pi/180) * deg)
}

rad2deg <- function (rad){
  stopifnot(is.numeric(rad))
  (deg <- rad/(pi/180))
}

# function to calculate the points on an arc between two points
# position 1: x0, y0
# position 2: x1, y1
# number of points in resulting arc line: n
# degrees of the arc connecting the points (positive is counter-clockwise,
# negative is clockwise): arcdeg
calcArc <- function(x0 = 1, y0 = 1, x1 = 4, y1 = 6, arcdeg = 30, n = 50){

  if(abs(arcdeg)>-359.9 & abs(arcdeg)>359.9){stop("angle of arc (arcdeg) must be between -359.9 and 359.9")}

  anglerad <- atan2(y = y1-y0, x = x1-x0) # angle between points
  midpt <- list(x = mean(c(x0,x1)), y = mean(c(y0,y1))) # midpoint coordinates of chord
  arcrad <- deg2rad(deg = arcdeg) # angle of arc in radians
  chordlength <- sqrt((x1-x0)^2 + (y1-y0)^2) # length between points
  r <- abs((chordlength/2) / sin(arcrad/2)) # radius of circle

  # angle from midpoint to circle center
  lut <- data.frame(
    lessthan180 = c(TRUE, TRUE, FALSE, FALSE),
    sign = c(1, -1, 1, -1),
    rotation = c(90, -90, -90, 90))
  hit <- which(lut$lessthan180 == (abs(arcdeg) < 180) & lut$sign == sign(arcdeg))
  anglecen <- anglerad + deg2rad(lut$rotation[hit])

  # length of midpoint to circle center
  midpt2cenpt <- sqrt(r^2 - (chordlength/2)^2)

  # calculate center point
  cenpt <- list(x = midpt$x + midpt2cenpt*cos(anglecen),
    y = midpt$y + midpt2cenpt*sin(anglecen))

  # angle from circle center to arc
  anglecen2arc <- anglecen + ifelse(abs(arcdeg)<180, deg2rad(180), 0)

  # produce vector of arc with n points
  arc <- data.frame(
    rad = seq(
      from = anglecen2arc - arcrad/2,
      to = anglecen2arc + arcrad/2,
      length.out = n
    )
  )
  arc$x <- cenpt$x + r*cos(arc$rad)
  arc$y <- cenpt$y + r*sin(arc$rad)

  return(arc)
}

# function drawing the results of calcArc as a line or arrow.
# makes a conversion in plotting region units in order to maintain a circular arc
addArc <- function(x0 = 1, y0 = 1, x1 = 4, y1 = 6, arcdeg = 30, n = 50,
  t = "l", col = 1, lty = 1, lwd = 1,
  arrowlength = NULL, arrowangle = 30, arrowcode = 2,
  result = FALSE,
  ...){

  # calculate arc
  arc <- calcArc(x0 = x0, y0 = y0, x1 = x1, y1 = y1, arcdeg = arcdeg, n = n)

  # calculate arc in device units
  FROM = "user"
  TO = "chars"

  x0 <- grconvertX(x0, from = FROM, to = TO)
  x1 <- grconvertX(x1, from = FROM, to = TO)
  y0 <- grconvertY(y0, from = FROM, to = TO)
  y1 <- grconvertY(y1, from = FROM, to = TO)
  arc2 <- calcArc(x0 = x0, y0 = y0, x1 = x1, y1 = y1, arcdeg = arcdeg, n = n)
  names(arc2) <- c("rad", "xusr", "yusr")

  arc <- cbind(arc, arc2[,c("xusr", "yusr")])

  # convert back to user coordinates
  arc$xusr <- grconvertX(arc$xusr, from = TO, to = FROM)
  arc$yusr <- grconvertY(arc$yusr, from = TO, to = FROM)

  lines(yusr ~ xusr, data = arc, t = t,
    col = col, lty = lty, lwd = lwd, ...)
  if(!is.null(arrowlength)){
    arrows(x0 = arc$xusr[n-1], x1 = arc$xusr[n], y0 = arc$yusr[n-1], y1 = arc$yusr[n],
      length = arrowlength, code = arrowcode, angle = arrowangle,
      col = col, lty = lty, lwd = lwd, ...)
  }

  if(result){return(arc)}
}

Example 1 - adding several arrow arcs of differing degree between 2 points
plot(1, t = "n", xlim = c(-4, 6), ylim = c(0,10), xlab = "", ylab = "")
points(x = c(0,1), y = c(4,6), pch = 16, cex = 1)
addArc(x0 = 0, x1 = 1, y0 = 4, y1 = 6, arcdeg = 90, col = 4, arrowlength = 0.1, lwd = 2)
addArc(x0 = 0, x1 = 1, y0 = 4, y1 = 6, arcdeg = -90, col = 4, arrowlength = 0.1, lwd = 2)
addArc(x0 = 0, x1 = 1, y0 = 4, y1 = 6, arcdeg = -180, col = 4, arrowlength = 0.1, lwd = 2)
addArc(x0 = 0, x1 = 1, y0 = 4, y1 = 6, arcdeg = -300, col = 4, arrowlength = 0.1, lwd = 2)

Example 2 - arrows connecting points around a box
df <- data.frame(x = c(0,1,1,0.5,0.5,0, 0), y = c(0,0,1,1,0.5,0.5,0))
dfmid <- data.frame(x = df$x[-nrow(df)] + diff(df$x)/2,
  y = df$y[-nrow(df)] + diff(df$y)/2)
dfmid$arcdeg <- c(270, -90, 270, -270, 270, 270)
dfmid$col <- rainbow(nrow(dfmid))
plot(y ~ x, df, t = "n", xlim = c(-1,2), ylim = c(-1,2))
polygon(x = df$x, y = df$y, col = "grey70", border = NA)
points(y ~ x, dfmid)
for(i in seq(nrow(dfmid)-1)){
  addArc(x0 = dfmid$x[i], y0 = dfmid$y[i], x1 = dfmid$x[i+1], y1 = dfmid$y[i+1],
    arcdeg = dfmid$arcdeg[i], arrowlength = 0.1, col = dfmid$col[i],
    lwd = 3, lty = 1, n = 500, t = "l")
}

Comment: This is beautiful, you nailed it +1! Do you see a possibility for an additional parameter that makes the arc slightly Nike-shaped to one side or the other?
Comment: @jay.sf - In that case, then you really need to go towards the spline approach I think.
Comment: Okay, don't worry, that was pure curiosity.


How would you create a math class that centers on the cultural experiences of African American and Latino students

Question: I need to write a paper on "Ethnocentric Mathematics" and I have no idea what kind of effective teaching strategies are available. We read an article from this scholar named Tate who explained that in order to reach low achieving African American students' potential we must re-think about the current setup of mathematics education. He argues that the current math curriculum is Euro-centric, as in it reflects the cultural identities and experiences to the exclusion of other cultures. A word problem that contains the words "yacht," "spool," "crochet," etc assumes that the student is coming from a white middle class background. But after reading this article, I'm still at a loss as to how to make mathematics culturally relevant to inner city kids. How would I incorporate the students' interests and concerns (i.e the hottest rap artist, their favorite basketball players, etc) and their lives (i.e poverty, drugs, unstable families, living on welfare and institutional racism) into the math curriculum that is meaningful to them and breaks the cycle of educational inequity?
Comment: I do not see how 1+1=2 or Abelian group would be different for Chinese, white, black, Latino, ancient Mayans or modern poets, whether you comprehend it by counting the yachts or the pebbles.
Comment: Are you asking for differences between afro-american vs. latino vs. kaukasian or rich vs. poor? For example, those (presumably afro-amaerican9 rap artists and basketball players may well have yachts ...
Comment: "Spool"? People everywhere sew.  Am I missing something?
Comment: If you are going to use examples from, say, the game of cricket (or hockey or chess), you had better be sure that students understand the rules underlying the game and have somehow experienced the game as a player or frequent spectator. But I can't imagine, however, that this is a big problem in textbooks or curriculum guidelines being published these days.
Comment: There have been stories about Ivy League grads that opened schools in such neighborhoods and they are thriving (seek those out as they are having amazing results). Also, maybe read http://thefutureschannel.com/jaime-escalante-math-program/
Answer: I like the idea of introducing the history of math to students. But it might help to introduce things like the Chinese Remainder Theorem and the fact that what we call Algebra comes from Babylonians, Egyptians, Greeks, Chinese, and medieval islam. That might give them the sense that this stuff mattered to someone other than old white guys like me, and in particular to folks in what might be called the second or third world. Besides, some of the stuff those folks did is pretty nifty.
As for saying "All the problems you discuss should have to do with drug addiction rates rather than the cost of yachts," I think that this sounds like a really bad idea. Instead, perhaps you should listen to what things interest them, and use those for examples. If they talk about rap artists...do a plot of some artist's popularity vs time. If they're interested in sports, discuss the Williams sisters' accomplishments in tennis...and then introduce ideas from probability. ("If, on each point, Serena has a 52% chance of winning the point, what's the probability that she'll beat her opponent in one game? In a set? In a match?")
Answer: Abstract thinking and problem solving are difficult when basic needs are not met. Maslow's hierarchy of needs is an excellent place to start, both for you to understand and for others to know about. Mathematics is about abstract thinking and problem solving, and these are natural things for human beings whose needs are met. Some of the things you mention interfere with anyone's ability to think and reason: "poverty, drugs, unstable families, living on welfare and institutional racism". Where are they on Maslow's pyramid? Critical thinking isn't just about numbers.
Answer: I would think it would be all about the applications.
$2 + 2 = 4$ for everyone, but, as you've pointed out, certain nouns are more relevant to certain ethnic backgrounds.  So what are the relevant examples one can use to get the points across?
Maybe collaborate with teachers who are of the same ethnic background as the students you want to teach?  That way you reduce the chance of using examples that stereotype.
Answer: I think the people with MathCorp have some experience with this so you might want to contact them.  http://www.mathcorps.org/admission/


Problem #23 pg-94, Stein and Shakarchi

Question: As an application of the Fourier transform, show that
there does not exist a function $I\in L^1(R^d,m)$ such that
$f*I = f$ for all $f\in L^1(R^d,m)$.
Comment: Sara, I noticed with this, and your other two questions you had not provided attempts or any specification to where you are having difficulty.
In order for others to really help you and to show respect for their time they should be added to your questions.
Answer: If you know Fourier transform, and in particular how it behave with respect to convolution product, the question is quite easy. Indeed, if $g$ and $h$ are integrable functions, then the relationship $\widehat{f*g}(x)=\widehat f(x)\widehat g(x)$, and the Fourier transform of an integrable function is continuous .
Otherwise, you can consider mollifiers, that is, non-negative smooth function with support contained in $B(0,n^{-1})$, of integral $1$. Take $(\phi_n)$ such a sequence, and show that $\phi_n*I\to I$ converge almost everywhere to $I$.
Comment: Hey Davide, Thank you so much for answering my problem. Davide, I don't know much about Fourier Transform and its behavior w.r.t convolution. Can you please tell me, how FT works with convolution. I mean their mutual behavior. I will be very thankful to you.
Comment: @SaraTancredi I've added details.
Comment: thank you for your precious time. I understood your ideas after some Google browsing.
Thanks.
Answer: If $ I \in L^1 $ then from uniform integrability given any $\epsilon >0 $ there is a $ \delta(\epsilon) > 0 $ such that you have $ \int_E |I(x)|dm <\epsilon $ for all measurable $E$ with $ m(E) < \delta(\epsilon) $. Now choose characteristic function $ f_\delta = \chi_{B(0,\delta)}\in L^1 $ and assume your statement is true for some $ I \in L^1 $. Then you have to have $$\int_{\mathbb{R}^d} f_\delta(x-y)I(y)dy = f_\delta (x) $$ Take $ x = 0 $ in the above and choose $ \delta$ such that $ m(B(0,\delta))= \delta(\epsilon)/2 $ you have the contracdiction
$$ 1 = f_\delta(0) = \int_{\mathbb{R}^d} f_\delta(-y)I(y)dy = \int_{B(0,\delta)}I(y)dy <\epsilon $$
Comment: Hey, thanks a ton, I fully understood the core idea of your beautifully written proof.
Thanks again for your time.
:)
Comment: @SaraTancredi You're welcome :) Would you mind accepting it as an answer by clicking on the tick mark beside ?

Problem #23 pg-94, Stein and Shakarchi


How to hide Intro/Index Page in TOC of Jupyterbook?

Question: The Documentation of Jupyter Book is not showing the Intro/Index Page in the TOC on the left sidebar. That's what I want for my book.
The Documentation does not explain how to do this. Does anyone know?
Jupyterbook: Structure the Table of Content
Answer: In the _config.yml file, you should add the following entry:
html:
  home_page_in_navbar: false  # Whether to include your home page in the left Navigation Bar

You can see the full configuration file and its defaults in the JupyterBook documentation:

https://jupyterbook.org/en/stable/customize/config.html
Comment: Should be marked as answer!


Converter Jquery para Javascript

Question: Boa tarde,
Gostaria de converter este código abaixo para Javascript:
                $('.circles > div').click(function () {
                    let index = $('.circles > div').index(this);
                    $('.circles > div').removeClass('active');
                    $(this).addClass('active');
                    $('.steps-carousel').css('transform', 'translateX(' + (index * -20) + '%)');
                });

Alguém poderia me auxiliar?
Comment: Já tentaste alguma coisa? Percebes esse código jQuery e o que ele faz? quais as linhas que não percebes?
Comment: Esse código foi um steps que criei com um carousel, porém criei ele em Jquery e onde irei implantar não utiliza o Jquery.
Comment: O que ele faz: Quando eu clico no círculo, ele remove a classe active e adiciona no círculo que cliquei e muda o item do carousel. Só que ele não funciona pois no sistema que vou implantar, ele não possui JQuery, dai tem que ser javascript puro
Comment: Sabes por exemplo o que `$('.circles > div').index(this);` faz?
Comment: Vamos lá:

dentro da classe "circles", possui divs sem nenhuma classe ou id, apenas div.

este "$('.circles > div').index(this);" armazena dentro da variável index (let index) a div que eu cliquei.
Answer: Aqui fica uma sugestão, não testada mas com referência a que linha de código corresponde. Não tenho a certeza se no teu HTML carousel é só um elemento ou vários... mas corrige caso não seja.

const carousel = document.querySelectorAll('.steps-carousel');
const divs = document.querySelectorAll('.circles > div');

divs.forEach((div, index) => {
  // aqui o index é o mesmo que let index = $('.circles > div').index(this);
  div.addEventListener('click', () => { // $('.circles > div').click(function() {
    div.forEach(el => el.classList.remove('active')); // $('.circles > div').removeClass('active');
    div.classList.add('active'); // $(this).addClass('active');
    carousel.forEach(el => el.style.transform = 'translateX(' + (index * -20) + '%)'); //$('.steps-carousel').css('transform', 'translateX(' + (index * -20) + '%)');
  });
});
Answer: document.querySelectorAll para utilizar queries como JavaScript.
Para atribuir classes/atributos a cada elemento você tem que iterar sobre cada um deles, utilizando forEach por exemplo.
Então é só utilizar os métodos nativos do JavaScript para fazer o que você precisa.
const circleDivs = [...document.querySelectorAll('.circles > div')];
const stepsCarousel = [...document.getElementsByClassName('steps-carousel')];

circleDivs.forEach(el => el.addEventListener('click', (e) => {
  const index = circleDivs.indexOf(el);

  circleDivs.forEach(el => el.classList.remove('active'));
  el.classList.add('active');
  stepsCarousel.forEach(el => el.style.transform = 'translateX(' + (index * -20) + '%)');

}));

Converter Jquery para Javascript


Individual slopes for many zip codes over time

Question: I have a dataset where I am interested in calculating a slope for each observation / row.
I have dependent variable $Y$ that is continuous. Every $Y$ is unique to a zipcode.
and my independent / predictor variables are measured over time for every $Y$,
say $x_1$ to $x_{20}$. I am looking for a slope for each $Y$ for each zip code for each row. I am not sure if I can do this by linear regression because I only have one observation for $y$.
I cannot average $x_1$ to $x_{20}$, because I will lose the information on the slope.
The goal here is to measure change in $x$ ($x_1$ to $x_{20}$) on $Y$, and since $x_1$ to $x_{20}$ is measured over time I like to retain the slope information and not simply take the average. I am trying to answer the question 'how severe is the change in $x$ on a zipcode which has a value $Y$'.
Answer: You will want to use a mixed effects model / multi-level model (these are ultimately the same thing, but they have different terminology and historical development, and constitute different ways of thinking about the situation).
The idea behind these is that you are sampling your zip codes from a population, and you can fit distributions of slopes and intercepts associated with your zip codes over time.  The primary output of such analyses is a population mean slope and intercept, but you can get predicted slopes for each zip code as well.
Your question is rather vague, but I'm guessing you will actually want to take your $x$'s as the dependent variable and $Y$ as the predictor variable. ${\rm Time}$ will also be a predictor variable and your data will be nested within zipcodes.
If you want to explore the threads on CV related to this topic, you can search under the mixed-effect, mixed-model, and multilevel-analysis tags.  In my opinion, the best overall book is:

Fitzmaurice, G.M., Laird, N.M., & Ware J.H. (2011).  Applied Longitudinal Analysis.  Wiley.
For a practical guide to fitting them with different software, you can pair that with:

West, B.T., Welch, K.B., & Galecki, A.T. (2006).  Linear Mixed Models: A Practical Guide Using Statistical Software.  Chapman and Hall / CRC.
Comment: unfortunately I do not have lots of data on all zip codes. but your idea is definitely worth trying. Thanks.


Libgdx's Matrix4#translate() doesn't work as expected

Question: I'm trying to draw a NinePatch using a transform matrix so it can be scaled, rotated, moved etc. So I created a class that inherits from LibGDX's NinePatch class and which is responsible of the matrix.
This is how I compute my transform matrix (I update it each time one of the following values changes) :
this.transform
    .idt()
    .translate(originX, originY, 0)
    .rotate(0, 0, 1, rotation)
    .scale(scale, scale, 1)
    .translate(-originX, -originY, 0)
;

and how I render my custom NinePatch class :
drawConfig.begin(Mode.BATCH);
this.oldTransform.set(drawConfig.getTransformMatrix());
drawConfig.setTransformMatrix(this.transform);
this.draw(drawConfig.getBatch(), this.x, this.y, this.width, this.height); // Libgdx's NinePatch#draw()
drawConfig.setTransformMatrix(this.oldTransform);

Case 1
Here's what I get when I render 4 nine patches with :
Position = 0,0 / Origin = 0,0 / Scale = 0.002 / Rotation = different for each 9patch

I get what I expect to.
Case 2
Now the same 4 nine patches with :
Position = 0,0 / Origin = 0.5,0.5 / Scale = same / Rotation = same

You can see that my 9 patches aren't draw at 0,0 (their position) but at 0.5,0.5 (their origin), like if I had no .translate(-originX, -originY, 0) when computing the transform matrix. Just to be sure, I commented this instruction and I indeed get the same result. So why is my 2nd translation apparently not taken into account?
Answer: The problem is probably your scaling. Because it also scales down the translation, your seccond translate actually translates (-originX*scale, -originY*scale, 0) since scale=0.002, it looks like there is no translate at all. For instance for the x coordinate, you compute :
x_final = originX + scale * (-originX + x_initial)

Comment: You're right except I had to write a different code.
Answer: I had to change the code computing my transform matrix to take the scale into account when translating back as pointed by Guillaume G. except my code is different from his :
this.transform
    .idt()
    .translate(originX, originY, 0)
    .rotate(0, 0, 1, rotation)
    .scale(scale, scale, 1)
    .translate(-originX / scale, -originY / scale, 0);
;


Normaliser of Wreath Product of Matrix Group

Question: I was reading and doing some problems on wreath products. The groups are matrix group in my case.

Let $G_s=GL(2^s,R)$ denotes the group of invertible matrices over $R$ and suppose $M\le G_s$ for some positive number $s$ and some $R$ which is commutative with identity. Also suppose $C_2$ be the cyclic group of order $2$ generated by the permutation $(1,2)$. Then we consider the wreath product $M'=M\wr C_2 \le G_{s+1}$.

Now my question is

If $N$ and $N'$ are the normaliser of $M$ and $M'$ in $G_s$ and $G_{s+1}$ respectively, then is it true that $N'\le N\wr C_2$? Even if not true in general, is it true for some special case, say, when the base group of $M'$ is characteristic in $M'$?

Any help will be really appreciated. Thanks in advance.
Addendum: From the answer of Derek Holt, it is clear that the above is not true even if the base group of $M′$ is characteristic in $M'$.
Answer: For a counterexample, let $M = C_3 \times C_3 \le {\rm GL}(2,7)$, where $M$ consists of diagonal matrices, and $M' = M \wr C_2$.
Then $N'$ contains, for example, the permutation matrix that interchanges the first and third basis vectors and fixes the second and fourth, and this does not lie in ${\rm GL}(2,7) \wr C_2$.
Note that the base group of $M'$ has order $3^4$ and is of index $2$ in $M'$, so it is characteristic.
Comment: There is no need for the field to be finite. The counterexample works in any field containing a cube root of $1$. Isn't the answer to your new question clearly yes by the definition of characteristic subgroup?
Comment: Thanks. I understand. A quick question, sorry. So is the reason that this counter example works because field is finite? I mean can we get same type of counter example even in infinite fields/rings?
Comment: May be I should rephrase the original question, it seems that if the base group $B$ of $M'$ is characteristic in $M'$ then $N'\le N_{GL(2^{s+1},R)}(B)$, is it true? I have checked in GAP for the above counter example and it happens to be true. Sorry again for another question.
Comment: Thanks. Oh yes, I get it, I will remove the new question, I missed the argument. Thanks again.