Sirikit StartAudioCall Fail

Question: Test Background:
Xcode: Xcode8 beta6
iPhone: iOS10 beta6
Language: object-c
I have used startAudioCall sirikit in my App to test my app call. However, the sirikit will fail in some situation:
If the person's name is a first name in local contact, when I say "Call firstname myApp", siri can start myApp get this contact name successfully
But if the person's name is both first name and last name, when I say "Call firstname(or both first name and last name) myApp" , siri will call this person using phone call(not myApp)
For exsample:
if John in my phone contact, and I say "call John myApp", this will start myApp and get this contact name successfully.
But if John Smith in my phone contact, and I say "call John(or John Smith) myApp" , siri will use phone call to call this person(not myApp)
<code>- (void)resolveContactsForStartAudioCall:(INStartAudioCallIntent *)intent
                      withCompletion:(void (^)(NSArray<INPersonResolutionResult *> *resolutionResults))completion{
NSLog(@"maytest resolveContactsForStartAudioCall");

NSArray<INPerson *> *recipients = intent.contacts;

NSMutableArray<INPersonResolutionResult *> *resolutionResults = [NSMutableArray array];

if (recipients.count == 0) {

    completion(@[[INPersonResolutionResult needsValue]]);
    return;
}else if(recipients.count==1){
    [resolutionResults addObject:[INPersonResolutionResult successWithResolvedPerson:recipients.firstObject]];
}else if(recipients.count>1){
     [resolutionResults addObject:[INPersonResolutionResult disambiguationWithPeopleToDisambiguate:recipients]];
}else{
    [resolutionResults addObject:[INPersonResolutionResult unsupported]];

}
completion(resolutionResults);
}

- (void)confirmStartAudioCall:(INStartAudioCallIntent *)intent
               completion:(void (^)(INStartAudioCallIntentResponse *response))completion{

NSUserActivity *userActivity = [[NSUserActivity alloc] initWithActivityType:NSStringFromClass([INStartAudioCallIntent class])];
INStartAudioCallIntentResponse *response = [[INStartAudioCallIntentResponse alloc] initWithCode:INStartAudioCallIntentResponseCodeReady userActivity:userActivity];
completion(response);
}

- (void)handleStartAudioCall:(INStartAudioCallIntent *)intent
              completion:(void (^)(INStartAudioCallIntentResponse *response))completion{
NSUserActivity *userActivity = [[NSUserActivity alloc] initWithActivityType:NSStringFromClass([INStartAudioCallIntent class])];

INStartAudioCallIntentResponse *response = [[INStartAudioCallIntentResponse alloc] initWithCode:INStartAudioCallIntentResponseCodeContinueInApp userActivity:userActivity];
completion(response);
}
</code>
And Here is my code about audiocall.
Anyone can help ? Thx a lot
Comment: So when you say, "call John myApp" and siri uses phone instead of your app, is your resolveContactsForStartAudioCall method called?
Comment: No, it will not comes to resolveContactsForStartAudioCall this function, so, I have no idea how to control this case.
Answer: I have fixed this issue, after I changed the App name from "ST Wifi Calling" to "testApp".
Now, no matter I say "Use testApp to call John" or "Use testApp to call John Smith", it's going well on sirikit
I think it's too hard for Siri to recognize a long App name with space
Comment: This guy reported the same issue and was told to file a radar. My app "Kitchen Wall" doesn't work but if I change the display name to "KitchenWall" it works perfectly. https://forums.developer.apple.com/message/171140#171140

Sirikit StartAudioCall Fail


Finding whether an input contains a vowel

Question: The sample input contains: 3, omahgoToRuLob, OmAhgotUrulobEI, aYfun
The expected output is: ugly string
pretty string
pretty string
I received an error such as:
22:7: error: array size missing in 'string'
27:23: error: expected expression before ']' token
29:14: error: expected expression before ']' token
My code is in c programming.
#include <math.h>
#include <string.h>
#include <stdlib.h>
#include <stdio.h>

int main(){
    int i;
    char string[100];
    char vowels = {"a", "e", "i", "o", "u", "A", "E", "I", "O", "U"};

    for (i = 1; i < 4; ++i)
    {
        scanf("%99s", string[]);

        if (string[] == vowels)
            printf("lovely string \n");
        else
            printf("ugly string \n");

    }

    return 0;
}

Comment: It's hard to help you because almost none of this makes sense. Which is to say, I can't tell you how to fix what you wrote because I can't tell what you expect your code to mean. For example, where you have `if (string[] == vowels)`, what exactly do you expect to be compared to what? You do understand that `[]` is *not part of the variable name*, right? And if you want to know whether a vowel is *in* some string, how does it help you to check whether the string *is equal to* something?
Comment: Try `char string[];` --> `char string[100];` and `scanf("%s", &string[]);` --> `scanf("%99s", string);`. `string[] == vowels` --> research `strspn()`
Comment: I have edited my code like u suggest but i still received the same error.
Comment: The subscript operator `[]` is used to denote that the programmer desires to access the i-th index of an array. So, the compiler expects an index value (e.g. 0, 1, 2, etc.) before `]` token.
Comment: @Chewjunnie Looks like you skipped on researching `strspn()`.
Comment: i did researched on strspn(), but how can i use it on my code? It doesnt have a bool, thus i cant used T/F function to print the respective function
Comment: i want to compare whether the sample input contains a vowel
Answer:
You can't declare an array without defining the array size, unless you do it dynamically
You declare one char, but you assign all the vowels to this char.

char vowels[] = {'a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'};

scanf("%s", string); is the right way to use scanf() with strings. Also, you want this out of your for loop, because you just get the input once
You have a variable i in your loop that you don't use. Also, you have i<4 while the input might be larger
Read this about i++ and ++i
Also you have to compare each char of the input string with each char of the vowels array
You don't need to store both lowercase and uppercase vowels. Use the tolower(char c) function from ctype.h to convert the input characters to lowercase and compare them only to lowercase vowels.


Como um programa é carregado na memória e depois executado?

Question: Imagine que eu escrevi um "hello world" em linguagem C. Compilei e gerei um executável, depois o executei.
O resultado da compilação é um binário, que na verdade também é um conjunto de instruções que serão executadas pelo processador, correto?
Após o comando de execução, como os binários são transferidos para a memória RAM?
Após os binários estarem em memória, o sistema operacional faz uma chamada em assembler pedindo para o processador executar as instruções do binário, se sim é o sistema operacional que fornece o endereço de memoria das instruções?
Comment: Seu fluxo tá um pouco torto. Mas, independente disto, as instruções são executadas uma após a outra, quem tem o trabalho de "saber" qual o endereço da próxima instrução é o processador e não o SO.
Comment: Torto como assim?, eu sei que as instruções são executadas sequencialmente. Oque eu gostaria de saber é como o processador sabe que deve executar instruções a partir da posição de memoria "x"?, alguém deve pedir pra ele fazer isso, não seria o S.O?, imagino que sim pois após o comando de execução o fluxo passa pelo kernel do S.O antes de ir para processador.
Comment: Ele sabe isso porque tem um registrador que está sempre apontando pra posição de memória que está a próxima instrução.
Answer: Acho que vai querer saber como o computador trabalha com o código.
A maneira exata de como o sistema operacional carrega um executável despende d e qual sistema operacional estamos falando. O próprio formato do executável também depende.
Memória virtual
Nos SOs modernos existe um sistema de memória virtual. Quando um comando manda carregar um executável normalmente ele mapeia o arquivo para a memória. Então de certa forma não importa muito o que está no sistema de armazenamento de massa ou na memória RAM. Claro que precisa estar na RAM para executar, mas quando o conteúdo irá para a RAM é determinado pela necessidade e algoritmos implementados no sistema operacional. A carga é feita em páginas com tamanho 4KB (o mais comum).

Os endereços virtuais são fornecidos pelo sistema operacional. Os endereços reais são fornecidos pelo processador. Todo processador moderno de alta capacidade possui um subsistema de tradução de endereços virtuais para físicos que não impõe custo ao processamento normal.
Tudo isso pode ser melhor visto em outra pergunta aqui.
Transferência
A cópia é feita por outro serviço do sistema operacional que interage com o sistema de arquivos e o driver que entende como comandar o sistema de disco ou outra forma de armazenamento "permanente". Obviamente que ele depende da colaboração do processador principal ou algum secundário que faz o controle dos dispositivos de entrada e saída e a memória (DMA).
Quando a carga é feita é possível ir entregando as instruções para o processador.
Relocação
A carga normalmente implica em acerto de endereços diversos de símbolos globais. O código trabalha com endereços relativos. Ele não sabe bem onde ele estará de fato na memória. Sabendo os endereços relativos pode-se obter o absoluto de todos símbolos e o SO é o responsável por relocar os endereços.
Carga do executável
Claro que o executável não tem só instruções. Existem uma série de informações que ajudam o sistema operacional decidir como trabalhar com aquilo, que configura como ele precisará trabalhar, entre outras coisas.
Existem dados estáticos. O exemplo mais comum são os textos (strings) presentes código. Mas na verdade praticamente qualquer literal estará de alguma forma ou junto às instruções ou na área estática.
Podem existir também dados que não são acessados diretamente mas que são necessários para a aplicação. Na verdade dá pra enfiar qualquer coisa no executável :)
Antes de iniciar a execução é reservado uma área de memória para a stack e o heap começa ser formado, se necessário, quase sempre é. Mas isso tem mais a ver com o processo como um todo, até porque cada thread nova terá seu próprio stack.
Conclusão
Enfim, simplificadamente é isso. Dá pra escrever um livro sobre o assunto. Novas perguntas específicas podem ser feitas.
Se deseja informações sobre o funcionamento eletrônico da transferência, aqui não é o local mais adequado. Se deseja algo mais detalhado, precisaria ver o que e em que SO.
Adendo
O termo assembler é frequentemente mal usado. Na verdade, ali não era nem para usar Assembler, nem Assembly, é código de máquina mesmo.
Coloquei no GitHub para referência futura.
Comment: Obrigado pelo explicação, os links também ajudaram muito. Estou lendo o "Organização e Projeto de Computadores: A Interface Hardware/Software (David A. Patterson)". Ele tem me ajudado a entender esses conceitos, você recomenda alguma outra leitura para quem deseja se aprofundar no assunto ?.
Answer: Bom, basicamente o executável é carregado à memória pelo Sistema Operacional. Na verdade, sua pergunta tem a ver com o gerenciamento de memória e cada sistema operacional tem uma forma de gerenciá-la.
Em termos gerais, é separado para o programa, uma região de memória que será usada pelo mesmo e a forma de uso será determinada pelo compilador (ou pela forma que o programa foi escrito). Essa alocação pode ser totalmente estática ou dinâmica (se o programa usar alocação dinâmica de memória). Quando o programa está em memória (arquitetura de Von Neumann), basicamente ele acessa diretamente as rotinas, processos e registradores através de ciclos de processamento (controlado diretamente pelo processador)
Sim, o SO fornece várias "células" de memória para o programa (que será endereçado usando técnicas de gerenciamento de memória).
Ou seja, é o SO que faz o gerenciamento de memória, controlando as alocações, protegendo, limpando e controlando o acesso de programas à memória principal.
Espero ter ajudado.


Embedding Euclidean Space Into Real Projective Space

Question: I'm struggling with what I think should be a pretty straightforward proof.
Let $g:\mathbb{R}^n\rightarrow\mathbb{R}P^n$ be the map defined by $g=p\circ f$ where $p$ is the quotient map $p:\mathbb{R}^{n+1}\rightarrow\mathbb{R}P^n$ and $f(x_1,x_2,\cdots,x_n)=(1,x_1,x_2,\cdots,x_n)$. I'm trying to show that this map is an embedding.
I thought I had proved it, but I noticed that in trying to prove $g$ is an open map into its image, I assumed that the restriction of $p$ to $f(\mathbb{R}^n$) was a quotient map (which I cannot do since $f(\mathbb{R}^n)$ is not saturated). I'm having trouble figuring out how to get around this.
Comment: The domain of $p$ should be $\mathbb{R}^{n+1}\setminus\{0\}$, not $\mathbb{R}^{n+1}$.
Answer: Hint: Let $U\subset\mathbb{R}^{n+1}\setminus\{0\}$ be the set of points with nonzero first coordinate.  Then $U$ is a saturated open set, so $p(U)$ is open and $p$ restricts to a quotient map $U\to p(U)$.  Now can you show that $p|_U\circ f:\mathbb{R}^n\to p(U)$ is a homeomorphism by explicitly describing its inverse in terms of a map from $U$?
More details are hidden below.

 Consider the map $h:U\to \mathbb{R}^n$ given by $h(x_0,x_1,\dots,x_n)=(x_1/x_0,\dots,x_n/x_0)$.  Then $h$ is constant on equivalence classes and so induces a continuous map $p(U)\to \mathbb{R}^n$, which is inverse to $p|_U\circ f$.


Question about Wiener measure

Question: In this post user SM2 provides a way of constructing the Wiener measure $\nu$ on the measurable space $(C([0,\infty),\mathcal{B}(C([0,\infty))))$ where $\mathcal{B}(C([0,\infty)))$ is the Borel $\sigma$-algebra of $C([0,\infty))$ induced by the topology of uniform convergence on compact sets.
In 3), for a Wiener process $\{W_t\}_{t\in[0,\infty)}$ on the probability space $(\Omega,\mathcal{F},\mathbb{P})$, SM2 defines the measurable map $g:\Omega\to C([0,\infty))$ which I'm guessing is just $$\omega\in\Omega\mapsto g(\omega)\in C([0,\infty))$$ with $g(\omega)$ given by $$t\in[0,\infty)\mapsto g(\omega)(t)=W_t(\omega).$$ At the end SM2 defines $\nu:\mathcal{B}(C([0,\infty)))\to[0,1]$ by setting $\nu(A)=\mathbb{P}(g^{-1}(A))$ for $A\in\mathcal{B}(C([0,\infty))))$ so that $\nu$ is the Wiener measure.
My question is, if we don't work with $g$ but instead define $$\nu^*:\mathcal{B}(C([0,\infty)))\to[0,1]$$ by specifying $\nu^*(\{f\in C([0,\infty)):f(t)\leq a\})=\mathbb{P}(\{\omega\in\Omega:W_t(\omega)\leq a\})$ for each $t\in[0,\infty)$ and $a\in\mathbb{R}$ then will $\nu^*$ and $\nu$ coincide?
Comment: Did you mention the present post to SM2?
Comment: @Did When I checked SM2's profile, their last seen time was late April so I figured that the account is not active.
Answer: This does not uniquely define a measure on $\mathcal B(C([0,\infty)))$. The problem is that the marginals of a process at a single time are not enough to determine the full process. For a play example, instead of a stochastic process in contininuous time let us look at a process $X$ in discrete time $\{0,1,\ldots,N\}$. It may be tempting to say the law of $X$ is fully determined by looking at the law of $X_n$ for $n=0,1,\ldots,N$, but really we know this is not true - for a couple of extreme examples, suppose $X_m$ and $X_n$ are identically distributed for all $m,n$, then we could have $X_m=X_n$ for all $m,n$ or $X_m,X_n$ independent for $m\neq n$, and looking at each $X_n$ individually will in no way distinguish these extremely different cases.
For the finite case there is an easy work around (namely, looking at the joint distribution of $X=(X_0,\ldots,X_N)$ which is a random variable in $\mathbb R^{N+1}$), but what about the infinite case? Thankfully, the Kolmogorov consistency theorem tells us that if we know all of the finite dimensional distributions, that is, the law of $(X_{t_1},\ldots,X_{t_n})$ for any finite subset $\{t_1,\ldots,t_n\}\subset T$ (where $T=\mathbb R$ or $\mathbb N$, whatever our time scale is), and these are consistent with one another, then this uniquely determines a measure on the relevant space. For continuous processes such as the Wiener process, we typically need a slight modification of this argument to guarantee a continuous version, but it still works. This is why SM2's construction is the correct one.
Let's end with a concrete counterexample, that is, a measure on $C([0,\infty))$ with the same marginals as $\nu$ which nonetheless defines a different process. Let $Z:\Omega\longrightarrow\mathbb R$ be any measurable function which is standard normal with respect to $\mathbb P$ and define $\Gamma_t:=\sqrt{t}Z$. Then $\Gamma:\Omega\longrightarrow C([0,\infty))$ is measurable and
$$
\mathbb P(\Gamma_t\le a)=\frac1{\sqrt{2\pi t}}\int_{-\infty}^ae^{-x^2/2t}dx=\mathbb P(W_t\le a)
$$
for any $t\ge0$ and $a\in\mathbb R$. However, $\Gamma$ and $W$ have different laws. For example, $\mathbb P(\Gamma_1> 1,\Gamma_2\le 0)=0$ but $\mathbb P(W_1>1,W_2\le0)>0$. So $\nu^*$ in your question could be equal to either $\nu$ or the law of $\Gamma$.
Comment: Thanks. Your counterexample in the end convinced me that $\nu^*$ would not recover $\nu$. In your second paragraph you mentioned that if we were to know all finite dimensional distributions then the measure would be uniquely determined. Just to confirm, does that mean if we set $\nu^*(\{f\in C([0,\infty)):(f_{t_1},\dots,f_{t_n})\in B^n\})=\mathbb{P}(\{\omega\in\Omega:(W_{t_1}(\omega),\dots,W_{t_n}(\omega))\in B^n\})$ for any $n\in\mathbb{N}$, $t_1,\dots,t_n\in[0,\infty)$ and $B^n\in\mathcal{B}(\mathbb{R}^n))$ then would $\nu^*$ now correctly give the Wiener measure?
Comment: Almost - you need $\nu^*(\{f\in C([0,\infty))\,:\,f(t_1)\in B_1,\ldots,f(t_n)\in B_n\})=\mathbb P(W_{t_1}\in B_1,\ldots,W_{t_n}\in B_n)$ for any $B_1,\ldots,B_n\in\mathcal B(\mathbb R)$.
Comment: I'm having difficulty seeing why working with $\mathcal{B}(\mathbb{R}^n)$ instead of $\mathcal{B}(\mathbb{R})$ produces a different result. Is it not the case that $\mathbb{P}(\{\omega\in\Omega:(W_{t_1}(\omega),\dots,W_{t_n}(\omega)\in B^n\})=\mathbb{P}(\{\omega\in\Omega:W_{t_1}(\omega)\in B_1,\dots,W_{t_n}(\omega))\in B_n\})$ when $B^n=B_1\times\dots\times B_n$?.
Comment: I'm sorry, I thought by $B^n$ you meant $B\times B\times\ldots\times B$, but as written you are completely correct!
Comment: Thanks. I found your answer and comments very helpful.
Comment: You're welcome. As an addition, notice that the right hand side of our (new) definition of $\nu^*$ can be calculated using independent increments and the Gaussian density. Hence $\nu^*$ may be defined without reference to a specific process - which actually proves the existence of the Wiener process and measure! As I alluded to in my answer, there is a small issue of continuity (it turns out $C([0,\infty))$ is not an element of the natural $\sigma$-field on $\mathbb R^{[0,\infty)}$) but there is a standard work around, see e.g. Stochastic Calculus: A Practical Introduction by Durrett.

Question about Wiener measure


How to test homoscedasticity when the errors are DEPENDENT?

Question: I have done a linear regression and plot the residuals. I noticed that the errors are dependent(autocorrelated), how could I test homoscedasticity of this series? I read that Breusch-Pagan test only work with independent errors.
What test could I use to test if the variance is constant in this case?
Comment: augment your under-specified model with arima structure to render a set of errors that are uncorrelated and then consider testing for points in time where the error variance changes.
Answer: IrishStat gave a good comment that points to an answer. He isn't on the site any more, so I will attempt an answer.
If you have autocorrelated errors, then you have to fix those before you worry about heteroscedasticity. One way to attempt to do this is as IrishStat suggests: Don't use linear regression; use ARIMA (or another time series method). Or, if you have a short time series, you could try a multilevel model or generalized estimating equations (GEE).
All of those methods have been discussed a lot here, and there is also a huge literature about them.


Erro ao inserir loop de imagem em relatorio pdf reports.dll .net

Question: Tenho um while que irá repetir 3 vezes uma inserção de um codigo de barras
porém estou usando a lib reports.dll para criar o relatorio em pdf.
Essa lib aceita apenas imagens salvas em algum diretorio(até onde sei),
mas no momento que vou inserir novamente a imagem já criada ele me retorna um erro :

O processo não pode acessar o arquivo 'C:\cod.jpeg' porque ele está
  sendo usado por outro processo

Dim Chave = "858300000009330003101607570100361164044015053000"
Dim barcode As New BarcodeLib.Barcode()
Dim img As Bitmap = barcode.Encode(BarcodeLib.TYPE.CODE128C, Chave)
img.Save("C:\cod.jpeg", Imaging.ImageFormat.Jpeg)

linhaPreencheCont = 15

Dim i As Integer = 0
While i < 3

PDFPage.Add(35, linhaPreencheCont, New RepImage("C:\cod.jpeg", 300, 40))

linhaPreencheCont +=60
end while

Já tentei também criar um novo objeto bitmap a cada volta no laço, mas tenho um novo erro:

Erro genérico de GDI+

Dim Chave = "858300000009330003101607570100361164044015053000"
Dim barcode As New BarcodeLib.Barcode()

dim linhaPreencheCont as integer = 15
Dim i As Integer = 0

While i < 3

Dim img As Bitmap = New Bitmap(barcode.Encode(BarcodeLib.TYPE.CODE128C, Chave))
img.Save("C:\cod.jpeg", Imaging.ImageFormat.Jpeg)

PDFPage.Add(35, linhaPreencheCont, New RepImage("C:\cod.jpeg", 300, 40))

linhaPreencheCont +=60
end while

Answer: Para que isso dê certo, é preciso converter a imagem para um memoryStream
Segue o código:
Dim Chave = "858300000009330003101607570100361164044015053000"
Dim barcode As New BarcodeLib.Barcode()
Dim img As Bitmap = barcode.Encode(BarcodeLib.TYPE.CODE128C, Chave)
img.Save("C:\cod.jpeg", Imaging.ImageFormat.Jpeg)

linhaPreencheCont = 15

Dim i As Integer = 0
While i < 3
  Dim fileImg As Byte() = IO.File.ReadAllBytes("C:\cod.jpeg")
  Dim memory As New MemoryStream(fileImg)

PDFPage.Add(35, linhaPreencheCont, New RepImage(memory , 300, 40))

linhaPreencheCont +=60
end while


Como dividir uma imagem (que pode ter tamanhos diferentes) em 3 x 3 usando javascript?

Question: Critério:
- Dividir a imagem original em 9 divs (3 x 3)  de tamanhos iguais.
- Cada (uma das 9) div com a respectiva imagem espelho parcial (da imagem original) da sua respectiva posição.

#idteste.image:before {
  content: url(https://upload.wikimedia.org/wikipedia/commons/thumb/a/aa/CitroenC-Metisse21.JPG/400px-CitroenC-Metisse21.JPG);
}

#idteste2.image:before {
  content: url(https://upload.wikimedia.org/wikipedia/commons/thumb/b/b5/Citroen_GT.JPG/200px-Citroen_GT.JPG);
}

Answer: Encontrei uma forma para dividir uma imagem usando javascript. Para tal deve ter um pouco de conhecimento em canvas. https://stackoverflow.com/questions/21933043/split-an-image-using-javascript
Alternativamente,  existe uma forma de uma forma de chegar ao pretendo usando o css. Para tal primeiro tens que idealizar uma matriz 3x3:
CSS

    .celula-img {
        /*Atenção  ao redimensionar a imagem: O tamanho da célula deve ser proporcional a imagem do background. Caso contrario, a imagem aparecera distorcida*/
        width: 100px;
        height: 75px;

        background-image: url(https://upload.wikimedia.org/wikipedia/commons/thumb/a/aa/CitroenC-Metisse21.JPG/400px-CitroenC-Metisse21.JPG);
        float: left;
    }

    .celula-img.img-11{
        clear:both;/*quebra linhas*/
        background-position: 0px 0px;

    }
    .celula-img.img-12{
        background-position: 33.333% 0px;
    }
    .celula-img.img-13 {
        background-position: 66.666% 0px;
    }

    .celula-img.img-21{
        clear:both;/*quebra linhas*/
        background-position: 0px 33.333%;
    }
    .celula-img.img-22{
        background-position: 33.333% 33.333%;
    }
    .celula-img.img-23 {
        background-position: 66.666% 33.333%;
    }

    .celula-img.img-31{
        clear:both;/*quebra linhas*/
        background-position: 0px 66.666%;
    }
    .celula-img.img-32{
        background-position: 33.333% 66.666%;
    }
    .celula-img.img-33 {
        background-position: 66.666% 66.666%;

    }

Comment: Só que a imagem não está no tamanho original @emiafe, essa parte do canvas ainda não entendi, fiz um update no post seu e meu dá uma olhada se puder. Grato
Answer:

 var tmpImg = new Image();
 tmpImg.src = "https://upload.wikimedia.org/wikipedia/commons/thumb/a/aa/CitroenC-Metisse21.JPG/400px-CitroenC-Metisse21.JPG";
 $(tmpImg).one('load', function() {
   widthImg = tmpImg.width;
   heightImg = tmpImg.height;
   //alert(widthImg + "x" + heightImg);
   $("#idteste2").css("width", widthImg);
   $("#idteste2").css("height", heightImg);

   var resWidth = parseInt(Math.floor(widthImg / 3));
   var resHeight = parseInt(Math.floor(heightImg / 3));
   resWidth = resWidth - 1.5;
   resHeight = resHeight - 2;

   $("p").html(resWidth + " " + resHeight);
   link = "https://upload.wikimedia.org/wikipedia/commons/thumb/a/aa/CitroenC-Metisse21.JPG/400px-CitroenC-Metisse21.JPG";

   //Inserir as divs
   valuePxl = 0;
   count = 0;
   for (var i = 0; i < 3; i++) {
     for (var j = 0; j < 3; j++) {
       if (count == 0) {
         $("#idteste2").append("

");
         $(".box" + count).css("background", "url('" + link + "')");
         $(".box" + count).css("margin-left", "-1px");
       };

       if (count == 1) {
         $("#idteste2").append("

");
         $(".box" + count).css("margin-left", "-1px");
         $(".box" + count).css("background", "url('" + link + "')");
         valuePxl = ((parseInt(resWidth)) * 2);
         $(".box" + count).css("background-position", valuePxl + "px 0px");
       };

       if (count == 2) {
         $("#idteste2").append("

");
         $(".box" + count).css("margin-left", "-1px");
         $(".box" + count).css("background", "url('" + link + "')");
         valuePxl = resWidth;
         $(".box" + count).css("background-position", valuePxl + "px 0px");
       };

       if (count == 3) {
         $("#idteste2").append("

");
         $(".box" + count).css({
           "margin-left": "-1px",
           "margin-top": "-1px"
         });
         $(".box" + count).css("background", "url('" + link + "')");
         valuePxl = resHeight * 2;
         $(".box" + count).css("background-position", "0px " + valuePxl + "px");
       };

       if (count == 4) {
         $("#idteste2").append("

");
         $(".box" + count).css({
           "margin-left": "-1px",
           "margin-top": "-1px"
         });
         $(".box" + count).css("background", "url('" + link + "')");
         valuePxlWidth = ((parseInt(resWidth)) * 2);
         valuePxlWeight = ((parseInt(resHeight)) * 2);
         $(".box" + count).css("background-position", valuePxlWidth + "px " + valuePxlWeight + "px");
       };

       if (count == 5) {
         $("#idteste2").append("

");
         $(".box" + count).css({
           "margin-left": "-1px",
           "margin-top": "-1px"
         });
         $(".box" + count).css("background", "url('" + link + "')");
         valuePxl = resWidth;
         valuePxlWeight = ((parseInt(resHeight)) * 2);
         $(".box" + count).css("background-position", valuePxl + "px " + valuePxlWeight + "px");
       };

       if (count == 6) {
         $("#idteste2").append("

");
         $(".box" + count).css({
           "margin-left": "-1px",
           "margin-top": "-1px"
         });
         $(".box" + count).css("background", "url('" + link + "')");
         valuePxlWidth = ((parseInt(resWidth)) * 3);
         valuePxlWeight = Math.floor((parseInt(resHeight)) * 1);
         console.log(resHeight+" "+valuePxlWeight);
         $(".box" + count).css("background-position", 0 + "px " + valuePxlWeight + "px");
       };

       if (count == 7) {
       $("#idteste2").append("

");
         $(".box" + count).css({
           "margin-left": "-1px",
           "margin-top": "-1px"
         });
         $(".box" + count).css("background", "url('" + link + "')");
         valuePxlWidth = ((parseInt(resWidth)) * 2);
         valuePxlWeight = ((parseInt(resHeight)) * 1);
         $(".box" + count).css("background-position", valuePxlWidth + "px " + valuePxlWeight + "px");
       };

       if (count == 8) {
         $("#idteste2").append("

");
         $(".box" + count).css({
           "margin-left": "-1px",
           "margin-top": "-1px"
         });
         $(".box" + count).css("background", "url('" + link + "')");
         valuePxl = resWidth;
         valuePxlWeight = ((parseInt(resHeight)) * 1);
         $(".box" + count).css("background-position", valuePxl + "px " + valuePxlWeight + "px");
       };

       count++;
     };
   };

   $(".box").css("width", resWidth);
   $(".box").css("height", resHeight);
   $(".box").css("border", "1px solid black");

 });
#idteste1 {
  content: url(https://upload.wikimedia.org/wikipedia/commons/thumb/a/aa/CitroenC-Metisse21.JPG/400px-CitroenC-Metisse21.JPG);
  border: 1px solid yellow;
}

/**
#idteste2 {
  background: url(https://upload.wikimedia.org/wikipedia/commons/thumb/b/b5/Citroen_GT.JPG/200px-Citroen_GT.JPG);
  border: 1px solid yellow;
}
**/

/**
#idteste2 {
  background: url(https://upload.wikimedia.org/wikipedia/commons/thumb/a/aa/CitroenC-Metisse21.JPG/400px-CitroenC-Metisse21.JPG);
  border: 1px solid yellow;
}
**/

/**
.box0 {
  background: url(https://upload.wikimedia.org/wikipedia/commons/thumb/b/b5/Citroen_GT.JPG/200px-Citroen_GT.JPG);
}
**/

.box1 {
  background: url(https://upload.wikimedia.org/wikipedia/commons/thumb/a/aa/CitroenC-Metisse21.JPG/400px-CitroenC-Metisse21.JPG);
}

.box {
  border: 1px solid black;
  width: 0px;
  height: 0px;
  float: left;
}


SQLAlchemy - Relationship with "indirect" Foreign Key

Question: Context
I'm using SQLAlchemy (v2) to set up a database for an application, and I'm trying to model some relationships on my data.
The relationships look similar to this diagram.

So I have these hierarchical many to one relationships, where Clusters belong to SubSubtypes, which in turn belong to a Subtype.
Samples are similar, but they might only have a Subtype and not a SubSubtype.
Problem
Now I have the problem, that in my cluster table, I only want one reference to the subtype_id (preferably on subsubtype.subtype_id), and similarly in my Sample table I only want to reference subtype_id once.
This should be no problem, when specifying an alternate join condition or a custom FK-relationship, which I've tried.
I have some code (can be found close to the bottom), that does that, but when I run it, it successfully creates the database schema, but fails on inserting the objects.
I get a NoForeignKeysError, and SQLAlchemy tells me that

there are no foreign keys linking [the subtype and cluster] tables.

and to

Ensure that referencing columns are associated with a ForeignKey or ForeignKeyConstraint, or specify a 'primaryjoin' expression.

And while indeed, there is no direct connection, I specified a primaryjoin expression and the foreign_keys to use (in various combinations, with and without).
Also, when I subsequently visualize the database schema in the generated file, I get the following Diagram, which seems to suggest, that what I want should work.

This actually seems like a bug with SQLAlchemy to me (bad error message at the very least), but I've learned that things like these are usually user errors, so I'm coming here for second opinions first.
I've put the full error message (excluding the generated SQL) at the end, since details tags don't seem to work on SO.
I also tried to use the hybrid_property decorator for subtype (and/or subsubtype), which would work for Cluster, but afaics not for Sample, because I still don't see how I could get at the SubSubtypes without the
Question
How can I model these relationships in SQLAlchemy without duplicating the references, and preferably using a declarative style.
Changing the schema would be okay iff it is necessary to achieve the goal.
Similar Questions
I've had a look at these other questions, and while somewhat similar, they don't really help me here.

Sql - Indirect Foreign Key
Different setup, not SQLAlchemy specific.
SQLAlchemy - How to add indirect relationships through more than one model?
Somewhat related, but using old imperative style from v1.4 and no answer.
SQLAlchemy Association Proxy - Preventing Duplicate Entries
Different problem and old-style imperative code.
SQLAlchemy Relationships No Foreign Key
Similar error message, but different setup, and also old-style imperative code.

I haven't found much more that seems relevant, but would be happy about someone pointing me to an applicable solution.
Code
Here's a (somewhat) minimal reproducible example:
from pathlib import Path
from typing import List, Optional

from sqlalchemy import ForeignKey, String, create_engine, event, Engine
from sqlalchemy.orm import Mapped, mapped_column, relationship, DeclarativeBase, Session

class Base(DeclarativeBase):
    pass

@event.listens_for(Engine, "connect")
def sqlite_pragma_enforce_foreign_keys(dbapi_connection, _):
    """
    This is necessary to enforce foreign key constraints on SQLite.
    Cf. `SQLAlchemy docs <https://docs.sqlalchemy.org/en/20/dialects/sqlite.html#foreign-key-support>`_.

    :param dbapi_connection: The database connection.
    :param _: connection_record?
    """
    cursor = dbapi_connection.cursor()
    cursor.execute("PRAGMA foreign_keys=ON")
    cursor.close()

class Sample(Base):
    __tablename__ = "sample"

    id: Mapped[str] = mapped_column(String(16), primary_key=True)
    """A unique identifier for the sample, aka. the "scount"."""

    sequence: Mapped[str] = mapped_column()
    """The actual genome data/consensus sequences. May only contain valid characters, cf. :meth:`_validate_sequence`."""

    subtype_id: Mapped[str] = mapped_column(ForeignKey("subtype.id"))
    """The ID of the sub- or sub-subtype of this sample."""

    subsubtype_id: Mapped[Optional[str]] = mapped_column(ForeignKey("subsubtype.id"))
    """The ID of the sub-subtype of this sample."""

    subtype: Mapped["Subtype"] = relationship(back_populates="samples")
    """The :class:`Subtype` of this sample."""

    subsubtype: Mapped[Optional["SubSubtype"]] = relationship(back_populates="samples")
    """The :class:`SubSubtype` of this sample."""

class Subtype(Base):
    __tablename__ = "subtype"

    id: Mapped[str] = mapped_column(String(3), primary_key=True)
    """The id of this subtype."""

    subsubtypes: Mapped[List["SubSubtype"]] = relationship()
    """A list of :class:`SubSubtype` clades under this subtype."""

    clusters: Mapped[List["Cluster"]] = relationship()
    """A list of :class:`Cluster` objects under this sub-subtype."""

    samples: Mapped[List[Sample]] = relationship()
    """All :class:`Sample` objects of this subtype."""

class SubSubtype(Base):
    __tablename__ = "subsubtype"

    subtype_id: Mapped[str] = mapped_column(ForeignKey("subtype.id"), primary_key=True)
    """Sub-subtypes belong to a :class:`Subtype`, which is their "parent", this is identified by the ``subtype_id``."""

    id: Mapped[str] = mapped_column(String(16), primary_key=True)
    """The sub-subtype specific part of the id."""

    subtype: Mapped[Subtype] = relationship(back_populates="subsubtypes")
    """Sub-subtypes have a :class:`Subtype` as parent."""

    clusters: Mapped[List["Cluster"]] = relationship()
    """A list of :class:`Cluster` objects under this sub-subtype."""

    samples: Mapped[List[Sample]] = relationship()
    """All :class:`Sample` objects of this subtype."""

class Cluster(Base):
    __tablename__ = "cluster"

    subtype_id: Mapped[str] = mapped_column(ForeignKey("subsubtype.subtype_id"), primary_key=True)
    """The ID of the sub- or sub-subtype of this cluster."""

    subsubtype_id: Mapped[str] = mapped_column(ForeignKey("subsubtype.id"), primary_key=True)
    """The ID of the sub-subtype of this cluster."""

    id: Mapped[str] = mapped_column(String(10), primary_key=True)
    """The cluster specific part of the name/id, e.g., in case of "A1_1", it would be "1"."""

    subtype: Mapped["Subtype"] = relationship(
        primaryjoin=subtype_id == Subtype.id,
        foreign_keys=[subtype_id],
        back_populates="clusters",
    )
    """The :class:`Subtype` of this cluster."""

    subsubtype: Mapped["SubSubtype"] = relationship(back_populates="clusters")
    """The :class:`SubSubtype` of this cluster."""

if __name__ == '__main__':
    engine = create_engine("sqlite:///:memory:", echo=True)
    Base.metadata.create_all(engine)

    subtype = Subtype(id="A")
    subsubtype = SubSubtype(subtype_id="A", id="1")
    cluster = Cluster(subtype_id="A", subsubtype_id="1", id="1")

    with Session(engine) as session:
        session.add_all([subtype, subsubtype, cluster])
        session.commit()

Exception

Full output
Traceback (most recent call last):
  File "/home/fynn/Desktop/HIV/HIV-Clustering/venv/lib64/python3.11/site-packages/sqlalchemy/orm/relationships.py", line 2418, in _determine_joins
    self.primaryjoin = join_condition(
                       ^^^^^^^^^^^^^^^
  File "/home/fynn/Desktop/HIV/HIV-Clustering/venv/lib64/python3.11/site-packages/sqlalchemy/sql/util.py", line 123, in join_condition
    return Join._join_condition(
           ^^^^^^^^^^^^^^^^^^^^^
  File "/home/fynn/Desktop/HIV/HIV-Clustering/venv/lib64/python3.11/site-packages/sqlalchemy/sql/selectable.py", line 1358, in _join_condition
    raise exc.NoForeignKeysError(
sqlalchemy.exc.NoForeignKeysError: Can't find any foreign key relationships between 'subtype' and 'cluster'.

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "/home/fynn/.config/JetBrains/PyCharm2023.2/scratches/scratch_6.py", line 138, in <module>
    subtype = Subtype(id="A")
              ^^^^^^^^^^^^^^^
  File "<string>", line 4, in __init__
  File "/home/fynn/Desktop/HIV/HIV-Clustering/venv/lib64/python3.11/site-packages/sqlalchemy/orm/state.py", line 561, in _initialize_instance
    manager.dispatch.init(self, args, kwargs)
  File "/home/fynn/Desktop/HIV/HIV-Clustering/venv/lib64/python3.11/site-packages/sqlalchemy/event/attr.py", line 487, in __call__
    fn(*args, **kw)
  File "/home/fynn/Desktop/HIV/HIV-Clustering/venv/lib64/python3.11/site-packages/sqlalchemy/orm/mapper.py", line 4391, in _event_on_init
    instrumenting_mapper._check_configure()
  File "/home/fynn/Desktop/HIV/HIV-Clustering/venv/lib64/python3.11/site-packages/sqlalchemy/orm/mapper.py", line 2386, in _check_configure
    _configure_registries({self.registry}, cascade=True)
  File "/home/fynn/Desktop/HIV/HIV-Clustering/venv/lib64/python3.11/site-packages/sqlalchemy/orm/mapper.py", line 4199, in _configure_registries
    _do_configure_registries(registries, cascade)
  File "/home/fynn/Desktop/HIV/HIV-Clustering/venv/lib64/python3.11/site-packages/sqlalchemy/orm/mapper.py", line 4240, in _do_configure_registries
    mapper._post_configure_properties()
  File "/home/fynn/Desktop/HIV/HIV-Clustering/venv/lib64/python3.11/site-packages/sqlalchemy/orm/mapper.py", line 2403, in _post_configure_properties
    prop.init()
  File "/home/fynn/Desktop/HIV/HIV-Clustering/venv/lib64/python3.11/site-packages/sqlalchemy/orm/interfaces.py", line 579, in init
    self.do_init()
  File "/home/fynn/Desktop/HIV/HIV-Clustering/venv/lib64/python3.11/site-packages/sqlalchemy/orm/relationships.py", line 1636, in do_init
    self._setup_join_conditions()
  File "/home/fynn/Desktop/HIV/HIV-Clustering/venv/lib64/python3.11/site-packages/sqlalchemy/orm/relationships.py", line 1881, in _setup_join_conditions
    self._join_condition = jc = JoinCondition(
                                ^^^^^^^^^^^^^^
  File "/home/fynn/Desktop/HIV/HIV-Clustering/venv/lib64/python3.11/site-packages/sqlalchemy/orm/relationships.py", line 2305, in __init__
    self._determine_joins()
  File "/home/fynn/Desktop/HIV/HIV-Clustering/venv/lib64/python3.11/site-packages/sqlalchemy/orm/relationships.py", line 2439, in _determine_joins
    raise sa_exc.NoForeignKeysError(
sqlalchemy.exc.NoForeignKeysError: Could not determine join condition between parent/child tables on relationship Subtype.clusters - there are no foreign keys linking these tables.  Ensure that referencing columns are associated with a ForeignKey or ForeignKeyConstraint, or specify a 'primaryjoin' expression.

Comment: `cluster` shouldn't have a FK to `subtype`, since the subtype is implied by `subsubtype_id`. When you need the subtype details, you use another join.
Comment: @Barmar there is no explicit FK to `subtype`, it's specified as `ForeignKey("subsubtype.subtype_id")`, and `subsubtype_id` doesn't imply subtype, because it's only one part of the composite primary key of `SubSubtype`, so it alone is not enough to reference that. Thanks for taking a look anyways!
Comment: In that case you don't want two separate ForeignKey declarations from Cluster to SubSubType, you want to create a composite ForeignKeyConstraint as illustrated [here](https://stackoverflow.com/a/7506168/2144390).
Comment: @GordThompson I think you're right. I kept going back to the basics and re-reading the docs, and it seems, that defining [composite FKs is not possible with declarative style](https://docs.sqlalchemy.org/en/20/core/constraints.html#defining-foreign-keys). Thanks for the comment.
Comment: It is indeed possible, we just need to use `ForeignKeyConstraint()` like [this](https://gist.github.com/gordthompson/8d540f8b84c4460b1e3097e2898f4674).
Comment: @GordThompson THANK YOU! This looks exactly right. If you turn this into an answer (two sentences is enough), I will gladly accept!
Answer: Since SubSubType has a composite Primary Key, Cluster needs a composite Foreign Key. Instead of using ForeignKey() separately on each column, use ForeignKeyConstraint() in __table_args__, like this:
from sqlalchemy import create_engine, ForeignKey, ForeignKeyConstraint, String
from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column

engine = create_engine("sqlite://")

class Base(DeclarativeBase):
    pass

class SubType(Base):
    __tablename__ = "subtype"

    id: Mapped[str] = mapped_column(primary_key=True)

class SubSubType(Base):
    __tablename__ = "subsubtype"

    subtype_id: Mapped[str] = mapped_column(
        ForeignKey("subtype.id"), primary_key=True
    )
    id: Mapped[str] = mapped_column(String(16), primary_key=True)

class Cluster(Base):
    __tablename__ = "cluster"

    subtype_id: Mapped[str] = mapped_column(primary_key=True)
    subsubtype_id: Mapped[str] = mapped_column(primary_key=True)
    id: Mapped[str] = mapped_column(String(10), primary_key=True)

    __table_args__ = (
        ForeignKeyConstraint(
            [subtype_id, subsubtype_id], [SubSubType.subtype_id, SubSubType.id]
        ),
    )

engine.echo = True
Base.metadata.create_all(engine)
"""
CREATE TABLE subtype (
    id VARCHAR NOT NULL,
    PRIMARY KEY (id)
)

CREATE TABLE subsubtype (
    subtype_id VARCHAR NOT NULL,
    id VARCHAR(16) NOT NULL,
    PRIMARY KEY (subtype_id, id),
    FOREIGN KEY(subtype_id) REFERENCES subtype (id)
)

CREATE TABLE cluster (
    subtype_id VARCHAR NOT NULL,
    subsubtype_id VARCHAR NOT NULL,
    id VARCHAR(10) NOT NULL,
    PRIMARY KEY (subtype_id, subsubtype_id, id),
    FOREIGN KEY(subtype_id, subsubtype_id) REFERENCES subsubtype (subtype_id, id)
)
"""

Here's an example for a similar situation from the SQLAlchemy docs.
Comment: Thanks a lot! I didn't even know you could pass those `__table_args__`. That neatly solves it, while retaining the declarative mapping


How Do I Configure SQL Server 2005 Backend?

Question: I am trying to develop an inventory/payroll system for a factory. The information will be stored on a server, Windows Server 2008 R2, and SQL Server 2005. I'm going to store the records on the server, but will develop several front-end client forms in MS Access 2010. The information is currently in an MS Access 2010 database(local), and I'll eventually need to get this data on the server. I currently have a remote desktop access with username and password, however I can't figure out how to get things set up. I have SQL Server 2005 installed on my computer as well. How do I start to make a few test tables, things like that, etc.
Could one of you guys recommend an SQL Server 2005 tutorial? I'm just having a lot of trouble getting started on this project, not really sure what to do. I need to configure the database in such a way that it will allow MS Access 2010 to be the front end.
Thanks for any help I receive, if I need to clarify something please just ask.
Comment: I'd truly like to know the backstory to this. 1) Inventory/Payroll system, 2) Factory, 3) No one with significant experience in development, database architecture or systems administration is working on a project that touches the most important digital workflows and assets for the company. I haz a sad. =(
Comment: There isn't much story, I'm being hired to develop these systems. I have lots of experience with database design, however I've never done it using these microsoft products. I always programmed them in the past(MySQL mostly, but a few others as well).

Will you explain why you downvoted my thread and why it makes you sad?
Comment: I didn't downvote, but likely it was downvoted for being off topic. Tutorial requests and extremely broad questions or questions that don't have a well scoped topic are closed in double-time.
Comment: Where should I post this then? I posted it over at StackOverflow and they directed me here.

Tell me why this makes you sad, or why you don't believe me. I posted a similar thread last week and there was a guy who said the same thing. This is disheartening because I have to complete this job for this guy, on top of full time university and a part-time web-developer/admin job. I'm just looking for help man.
Comment: 1) Tutorial requests are always off topic for all StackExchange sites. 2) Overly broad topics are off topic for most if not all StackExchange sites. 3) It makes a lot of ServerFaulters frustrated / sad to see huge, important systems being worked on and developed by people whose questions reveal an enormous lack of understanding that jeopardizes the very solvency of the company. 4) We all started somewhere, so props for that.
Comment: In the end, StackExchange might not be the best bet for something like this. Try a more discussion oriented site like DaniWeb or a SQL Server specific forum. Remember, Stack Exchange is not a forum, thus anything approaching discussion oriented questions aren't usually allowed. In the end Mark answered, but that was after he and I discussed the situation a bit. That's not a usual response. BTW, StackOverflow is ***horrible*** at knowing what belongs here on ServerFault, in spite of us communicating with them.
Comment: Alright, I'll try to find a better forum for my question. Thanks for the help.
Comment: Here's my $0.02: EITHER: Find some off-the-shelf package that you can modify as a starting point, Convince the business owner that hand-rolled is NOT the way forward, OR Find someone you can subcontract to on oDesk, or something.  Send it overseas for cheap labour to do the hard work, then take the top 10% or so for yourself.

This is a *big* project, and it could take you years to find all the bugs in it.  Why not just buy something? Is their use-case *that* specific?
Answer: Ok, I don't normally do this (post tutorials or hand-hold), but it sounds like you're at least trying to do the right thing by your employer, and I can respect that.
I suggest you start with a free version of SQL Server. Unless your software is wildly popular or you generate massive amounts of payroll data, you will probably never out-grow it.
The free version is called SQL Server 2008 R2 Express.
Now, SQL Server Express ships by default with TCP/IP connections disabled (don't stress too much about what that is, just know you need to enable them). You can find out how to do that here.
Now, what to do about that tutorial? Well, to be honest, a tutorial for SQL Server doesn't really cut it. Databases are very complex, and you need to understand at a bare minimum 3rd normal form and primary keys. Indexes and foriegn keys come a very close second.
There's an eBook from MSDN that might help, but it might be a bit too hardcore for a beginner and has a bit of assumed knowledge. Otherwise, Google might be able to help.

Accessing SQL Server from within Microsoft Access is actually very straight forward. It's even got a very useful scale-out wizard that will even copy your Access database into SQL Server and update all your links and copy all your data. Your first point of call (after installing SQL and enabling TCP/IP connections) might actually be looking at SQL server through the eyes of Access. It's likely to make things a bit less fuzzy.
The point of that is, although I could never condone using an Access back-end database in a work environment (I've just seen too many of those projects outgrow what an Access back-end can handle), if you need to hit the ground running, you can just start in Access and get developing, and then let Access take care of the migration to SQL for you.
Comment: Thank you for the help. I already have the SQL server 2005 Express installed, I'll check if TCP/IP is enabled, if not I'll enable it. The thing is, I actually have a decent amount of experience with databases(I have a CS degree). I just haven't ever used these Microsoft products. The part that is making this difficult is having to use all the business's software, and making sure that everything will remain compatible. I know what 3rd normal form, primary keys, Indexes, and foreign keys are. I want to find the best configuration for a database of my needs.

Thanks Again
Comment: May I suggest not starting with SQL 2005 unless you specifically have to? It's already 7 years old. SQL 2008 R2 is 2 years old (damn Microsofts naming schemes) and SQL Server 2012 has just hit the market, which will makes SQL Server 2005 *four* versions ago.
Comment: I feel like my employer is pretty strict as far as what we use, he is already using the SQL 2005 for other things on the same server. Do you think it's worth converting to 2008? I might be able to convince him if it's going to make a large difference.

The database won't be very complex, there will be about 5 tables total, and the vast majority of queries will be uploading barcodes one at a time. I think there are around 50 employees max. I'm just giving you a little more information in case it helps you picture the whole setup.

Thanks.
Comment: To go from 2005 to 2008 or 2012 is actually no work at all. You just install the newer version, unmount the database, and mount it in the new version. If you keep your instance name the same, you don't even need to configure your apps. Note: Once you attach a DB to a newer version, you can *never* attach it to the old version again. SQL Server has compatibility modes which are kept in-tact from the source version that ensures that any depreciated TSQL will still operate. Although 2005 was a mature product, there *are* three service packs for it.
Comment: Admittedly we only left 2005 last year, and there's not a huge difference for most applications, but the risk of EOL does make me nervous (and was the driving factor behind moving platforms). Once a Microsoft product hits EOL, it doesn't even get critical security updates.
Comment: [I just looked it up](http://support.microsoft.com/lifecycle/search/?sort=PNα=SQL), SQL Server 2005 became unsupported in April 2011, and will become EOL in 2016. SP3 hit unsupported in January of 2012.
Comment: Alright, I think then I'll talk to the server manager and see if we can do it. I assume if we move to 2008/2012, and I back up the old databases, we can still go back by restoring the backups? I'm all for using a newer version, I just want to do what will be easiest/smoothest without sacrificing security/functionality.

Thanks, you've been a lot of help, you seem to know a lot about databases.
Comment: Yep, take a backup before you upgrade and you'll be able to restore the backups into 2005. I work with medium sized databases for a living (in the 20-100gb range). There's some guys on here who work with databases in the terrabyte range.


polynomials over a local Artinian (or finite) ring

Question: In this question " Zero-divisors and units in $\mathbb Z_4[x]$ " it looks like it has been shown that the set of zero divisors of $\mathbb{Z}_4[x]$ coincides with its nilpotent elements.
Since the nilpotent elements coincide with the non-units in $\mathbb{Z}_4$ itself, and do so more generally for any commutative Artinian local ring, I wanted to follow up with these questions.

Does anyone know if this is true for $R[x]$ where $R$ is a commutative finite local ring?

If that was too easy:

Is it the case for commutative Artinian local rings?
Comment: Hint: see my answer there.
Comment: Every commutative finite local ring is Artinian. As the ring is finite, there can only be a finite number of ideals. Thus $R$ satisfies the descending chain condition.
Comment: @DrKW Thanks for playing.
Answer: Let $R$ be a commutative ring in which every zero-divisor is nilpotent. I claim that the same is true for $R[x]$.
First, I'll mention a theorem of McCoy: if $S$ is a commutative ring, then $f(x) \in S[x]$ is a zero-divisor if and only if there exists a nonzero $c \in S$ such that $cf(x) = 0$.
Back to our ring $R$. If $f(x) \in R[x]$ is a zero-divisor, then the theorem of McCoy above shows that all of the coefficients in $f(x) = a_0 + a_1 x + \dots + a_n x^n$ are zero-divisors. Thus every coefficient $a_i$ is nilpotent by our assumption on $R$. Since the nilpotent elements of the commutative ring $R[x]$ form an ideal, we conclude that $f(x)$ is nilpotent.
Comment: Well McCoy certainly clears things up doesn't he :)
Comment: Indeed he does! :)


Is parametric equivalent to linear?

Question: Some supervised learning techniques, such as GLM (e.g., logistic regression), are linear and parametric. On the other hand, one of the claimed advantages of nonparametric supervised learning algorithms such as CART and ensemble of trees (Bagging/Boosting) is the ability to capture nonlinear interactions among predictors, and among predictors and predictand.
I also know (for example) that Kernel regression is nonparametric and nonlinear.
That brings me to my question: does parametric always go hand in hand with linear? (and nonparametric with nonlinear ?)
What are the limitations of linear models VS nonlinear models? For instance, what are the common advantages of using a tree over logistic regression? Kernel PCA instead of regular PCA?
Sorry it seems like a lot of questions, and I am a bit confused, but I think everything is closely related.
Comment: *Is parametric equivalent to linear?* ... no. Nor is nonparametric in all senses equivalent to nonlinear.
Answer: Linear is always parametric for all practical purposes. What does linear mean? It means that you're stating linear relationships between variables, such as $y=\beta_0+\beta x$. Your parameters are $\beta_0,\beta_1$. So, by stating that the relationship is linear, you are declaring the parameters.
When you say non-parametric, you don't state any particular form of the relationship. You may say $y=f(x)$, where $f(.)$ is some function, which could be linear or non-linear.
The limitations of linear models exist only when the true relationship is non-linear. For instance, the force is equal to the product of mass and acceleration $F=ma$, i.e. linear function of acceleration for a given mass. So, by modeling this as $F=f(a;m)$ you are not gaining anything relative to the linear form.
The trouble is that in social sciences we don't know what are the relationship, whether they are linear or not. So, we may often gain by not restricting ourselves t the linear models. The drawback is that non-linear models are more difficult to estimate, usually.
In non-linear model we usually assume some sort of non-linear relationship, e.g. $v_t=v_0\sqrt{t}$. In this case it's a square root function of time, and the parameter is $v_0$, i.e. this is a parametric model.
Non-parametric is even more loose, it doesn't even specify the form of the relationship in this detail. It'll just say $v_t=f(t)$, some function of time. An example is value-at-risk calculation, where the VaR is the $\alpha$ quantile of the losses of the portfolio. Here, we don't specify what is the loss distribution, we simply get the quantile of whatever the distribution is of the losses.
Comment: to summarize: (1) linear models specify an explicit equation relating input and output variables, and therefore always require estimating the parameters (the coefficients) of this equation. So linear => parametric. (2) when the true relationship between input and output variables is unknown, nonparametric models are more appropriate because we don't restrict ourselves by imposing any formal models. But nonparametric models can capture both linear and nonlinear relationships. In your second example, the equation is nonlinear but it is parametric (mu_0), so (nonlinear => nonparametric) is false
Comment: is my summary above correct?
Comment: Yes, but note my qualification "for practical purposes". I'm sure you can come up with a situation where something non-parametric and linear and so on, it's just you don't see this stuff done usually.
Comment: I guess that when the underlying physical process is known, it is better to use a parametric model, regardless of whether the relationship is linear or nonlinear. When it is unknown and we use a nonparametric model (e.g., Boosted trees), we are learning the relationship directly from the data, but this relationship can be linear or not (it's just that we don't know), so indeed you can have nonparametric AND linear
Comment: I'm about to accept your answer which has been very helpful, but could you please mind to give me your feedback regarding my comment above?
Comment: I think it's a fair comment, except that if the relationship was linear you would have *noticed* it. How? I personally don't like to shoot in the dark, so to speak. I like models that are interpretable and trackable. I'd try linear model first, or something simple and parametric before venturing in black-box type of models. You get the result out the tree, how do you know it's reasonable? One needs some point of reference. That's why in practical situation, before starting non-linear non-parametrics estimation on a linear process you'd notice that the process is linear.
Comment: "usually" is a function of what things you tend to look at. If you're reading books on nonparametric statistics (where the *distributions* are infinite-parametric, not the functional relationships), nonparametric-but-linear certainly occurs frequently.
Comment: I wanted to write this, but then thought it's too far from the topic. To me non-parametric vs. parametric is like calculus vs. variational calculus. In former, you mostly assume known function or its derivatives, and you might be finding the optimal parameters of the function. In latter you define general class of function, but necessarily its form, then solving variational equations you find the form of the function often implictlty
Answer: Parametric and linear: You know this one, it includes a bunch of things. (Ordinary least squares linear regression is an obvious example, but there are others)
Parametric and nonlinear: Nonlinear regression methods are an obvious example.
Nonparametric and nonlinear: again, you know this one; there are a bunch of things. splines or local regression methods are examples, as are things like ACE and AVAS (though the ones I mention all approximate nonlinear relationships via linear methods).
Nonparametric and linear: Since "nonparametric" can also refer to the infinite-dimensionality of the distributional form rather than the functional relationship (see the huge area of nonparametric statistics -- the term 'nonparametric' originates here, by the way, in Wolfowitz, 1942 [1]), and it's possible to fit linear relationships without assuming any parametric model, 'nonparametric and linear' is a thing.
This answer has some explicit examples, of which I reproduce a plot here:

(Blue is least squares, red is the linear fit whose slope is based on the Spearman rank correlation, and green is the linear fit whose slope is based on Kendall's tau.)
[1]: Wolfowitz, J. (1942),
"Additive Partition Functions and a Class of Statistical Hypotheses,"
Ann. Math. Statist., Volume 13, Number 3, 247-279.

Is parametric equivalent to linear?


Get the density of noncentral chi squared by using the chi-square and poisson mixture

Question: Let $X \sim N(\mu, 1)$. $Y=X^2$. What is the pdf of $Y$?
I use the usual transformation to get my answer:
$f_Y (y) = \frac{1}{2 \sqrt{2 \pi y}}         (e^{-\frac 12    (-\sqrt{y}- \mu)^2} + e^{-\frac 12    (\sqrt{y}- \mu)^2})$
I hope my above attempt is correct.
Now the question is: the pdf of $Y=X^2$ can be expressed as the
marginal pdf of $Y$ obtained from the joint distribution of the pair $(Y, J)$, with $J$ being discrete, as stated below:
$Y|J = j \sim \chi_{1+2j}^2$
$J \sim Poisson (\lambda /2)$, where $\lambda = \mu^2$
I want to get the density of $Y$ by using the above mixture. How to do this?
The formula $\frac{(2j)!}{j!} = \frac{2^{2j}   \Gamma (j+\frac 12) }{\sqrt{\pi}}$ is given
Answer: You just use Bayes rule to find the joint distribution and then marginalize over $j$: for any $y > 0$:
\begin{align*}
f_Y(y) = \sum_{j = 0}^\infty f_{Y, J}(y, j) = \sum_{j = 0}^\infty f_Y(y \ | \ j)f_J(j) &= \sum_{j = 0}^\infty \frac{y^{j - 1/2}e^{-y/2}}{2^{j + 1/2}\Gamma(j + 1/2)} \frac{(\mu^2/2)^je^{-\mu^2/2}}{j!} \\
&= \frac{e^{-(y + \mu^2)/2}}{\sqrt{2y}} \sum_{j = 0}^\infty \frac{(\sqrt{y}\mu)^{2j}}{ \underbrace{ 2^{2j}\Gamma(j + 1/2)j!}_{\text{use given identity here}} } \\
&= \frac{e^{-(y + \mu^2)/2}}{\sqrt{2\pi y}} \underbrace{ \sum_{j = 0}^\infty \frac{(\sqrt{y}\mu)^{2j}}{(2j)!} }_{\text{series of }\cosh(\sqrt{y}\mu)} \\
&= \frac{e^{-(y + \mu^2)/2}}{\sqrt{2\pi y}} \Big(\frac{e^{\sqrt{y}\mu} + e^{-\sqrt{y}\mu}}{2}\Big) \\
&= \frac{e^{-(\sqrt{y} + \mu)^2/2} + e^{-(\sqrt{y} - \mu)^2/2}}{2\sqrt{2\pi y}}
\end{align*} and of course $f_Y(y) = 0, y \leq 0$. This is exactly what you found earlier through the other method.


Continuity of unique solution to differential equation

Question: Let $f$ be a continuous function on $G$, where $G \subseteq \mathbb{R}^2$ is an open set containing $I \times [a,b]$ where $I:=[x_0-d,x_0+d]$, for some $a,b,d \in \mathbb{R}$ s.t. $a<b$ and $d>0$.
Suppose that $\forall t \in [a,b]$, the initial value problem $g'(x)=f(x,g(x)) \wedge g(x_0)=t$ has a unique solution for $g:I \rightarrow \mathbb{R}$ (differentiable up to the endpoints of $I$), which we will call $F(t):=g$.
Is $F:[a,b] \rightarrow C(I)$ always a continuous mapping, where $C(I)$ refers to the continuous functions on $I$ with metric $\rho(f,g):=\sup{\{|f(t)-g(t)|:t \in I\}}$?
Specifically, do we need an extra condition that $G$ contains the entire strip $I \times \mathbb{R}$?
If we have that extra condition, then we can show that $R:=\{F(t):t\in [a,b]\}$ is uniformly bounded, equicontinuous and closed. So it is compact, and then as $F^{-1}$ is continuous, it follows that $F$ is also continuous.
(Note: I do not have the condition that $\exists M\in\mathbb{R}$ s.t. $\forall (x,y_1),(x,y_2)\in G$, we have $|f(x,y_1)-f(x,y_2)|\le M|y_1-y_2|$, which is the usual Lipschitz condition.)
Comment: And the topology in $C^\infty(I)$ is...?
Comment: $C^\infty(I)$ is the metric space of all continuous functions on $I$ with metric $\rho(x,y)=\text{sup}{\{|x(t)-y(t)|:t \in I\}}$. Sorry, I forgot that it is not a standard notation.
Answer: With the usual (k-Lipschitz) condition if $g_t$ is the solution with initial condition $t$,
$$\|g_t(x)-g_s(x)\|\le K\|t-s\|.$$
(for another $K$ that depends only of $k$ and the interval), i.e.,
$$\rho(g_t,g_s)\le K\|t-s\|.$$
See, for example, Differential Calculus by Henry Cartan, II.1.10.
Comment: I don't have the Lipschitz condition on $f$, but what is given is that there are solutions and the solutions are unique. So I'm asking whether there is a counter-example. If $G$ contains the entire strip $I\times \mathbb{R}$, then I think I have a correct proof of this.
Comment: @user1537366, post your proof.
Comment: The formal proof is really long to type out, so I only edited the question to give the idea of the proof.


Erro android studio, error: Error retrieving parent for item: No resource found that matches the given name 'android:Theme.Holo.Light'

Question: Alguém saberia qual é esse erro:
error: Error retrieving parent for item: No resource found that matches the given name 'android:Theme.Holo.Light'.
Comment: Por favor, complete sua pergunta.
Comment: Em qual momento ele ocorre?  Qual é a minSdkVersion da sua aplicação?
Answer: Seria melhor se postasse seu Styles.xml aqui.
Provavelmente é o nível de sua API está abaixo de 11, o tema Holo só está disponível a partir da API 11.
Aumente o nível de sua API ou retire o "Holo".
<code>"android:Theme.Light"
</code>
Answer: Em algum momento você referencia o tema Holo, parent="@android:style/Theme.Holo"
mas pra usá-lo é necessário definir o API level para 11 em seu manifest.
Você também deve colocar o style.xml que faz uso do holo dentro da pasta values-11.
Veja isto:
https://stackoverflow.com/questions/12295018/error-error-retrieving-parent-for-item-no-resource-found-that-matches-the-give


Deducing Flow between Parallel Plates from Poiseuille Flow in tube of Elliptical cross-section

Question: Applying the appropriate simplifications to the Navier-Stokes equation yields the following:
$$(\partial_x^2+\partial_y^2)v_z=\frac1\mu \partial_zp$$
And assuming that the velocity profile is going to be an elliptic paraboloid we can easily find $v_z(x,y)$ (keeping in mind the no-slip condition). We can then deduce the volumetric flow rate: $$Q_e=-\frac \pi {4\mu}\frac{a^3b^3}{a^2+b^2}\partial_zp$$
Now, what I'd like to do, is deduce the Poiseuille law for two parallel plates: $$\frac {Q_p} l=-\frac 1 {12\mu}c^3\partial_zp$$
from $Q_e$. Dividing $Q_e$ by the $2a$ then computing the limit as $a$ approaches $\infty$ doesn't work since the quantity $Q_e /2a$ is not equivalent to $Q_p/l$. I then tried to compute the mean velocity: $$\bar{V_e}=\frac {Q_e}{\pi a b}$$
then its limit, but it didn't work either. I then imagined a parabolic function $f$ such that: $$\int_{-b}^bf(x)2adx=Q_e$$
which yielded: $$f(x)=\frac{3Q_e}{8ab}\left(1-\frac{x^2}{b^2}\right)$$
finding its limit yields a velocity distribution that doesn't correspond to the case of two parallel plates. I'm stumped at this point! Is there a way to directly deduce $Q_e$ from $Q_p/l$ without having to go through $v_z(x,y)$? In other words, without finding the limit of $v_z$ as $a$ approaches $\infty$ then finding $Q/l$. Suppose we're only given $Q_e$!
Answer: Let $v_{z}^{(e)}(x,y)$ denote the axial velocity in the elliptical tube (with semi-major and semi-minor axis lengths $a$ and $b$, respectively), and let $v_{z}^{(p)}(y)$ denote the velocity between infinite parallel plates separated by a distance $c = 2b$. Let $G = -p_z$ denote the (constant) pressure gradient.
The exact solutions to the Navier-Stokes equations for unidirectional, laminar flow are
$$v_z^{(p)}(y) = \frac{Gb^2}{2 \mu}\left(1 - \frac{y^2}{b^2}\right), \\ v_z^{(e)}(x,y) = \frac{Gb^2}{2 \mu}\frac{a^2}{a^2 + b^2 }\left(1 - \frac{y^2}{b^2}- \frac{x^2}{a^2 + b^2}\right), $$
and it is true that with fixed coordinates $(x,y)$
$$\tag{*} \lim_{a \to \infty}v_z^{(e)}(x,y) = v_z^{(p)}(y).$$
However, it would not be possible to deduce the precise equality given by (*) simply by examining the volumetric flow rates, which are definite integrals of the velocity fields over different cross-sectional areas.  Furthermore, there is no easy way to "discover" $Q_p$ given $Q_e$.
To elaborate, note that on a per unit area basis the volumetric flow rate between parallel plates is
$$\frac{Q_p}{2bl} = \frac{1}{3}\frac{G}{\mu} b^2.$$
This represents the average of $u_z^{(p)}(y)$ over a rectangle with dimensions $2b \times l$.
The volumetric flow rate in the elliptical tube is
$$Q_e = \frac{\pi ab}{4} \frac{G}{\mu} \frac{a^2b^2}{a^2 + b^2}.$$
As  $a \to \infty$ with $b$ fixed, we have $Q_e \to \infty$ since the cross-sectional area becomes infinite and the average velocity does not tend to zero if the pressure gradient is maintained (requiring, of course, infinite energy).
Considering instead the volumetric flow rate per unit area (i.e., the average velocity over the elliptical cross-section), we find
$$\lim_{a \to \infty} \frac{Q_e}{\pi a b} = \lim_{a \to \infty} \frac{1}{4} \frac{G}{\mu} \frac{a^2b^2}{a^2 + b^2} = \frac{1}{4} \frac{G}{\mu} b^2 = \frac{3}{4} \frac{Q_p}{2bl}.$$
Thus, we essentially recover the result for flow between plates (on a per unit area basis) up to a scaling factor of $3/4$.  This factor represents the impact of averaging one velocity field over an elliptical area and averaging the other over a rectangle where the ellipse is inscribed in the rectangle. This persists in the limit as $a \to \infty$, even though the differences in velocity converge to zero.
Addendum
The $3/4$ factor is an artifact of computing the average velocity over an elliptical rather than rectangular cross section.  The limit of the velocity profile for the elliptical tube is the parallel-plane velocity $v_z^{(p)}(y)$, which independent of the $x-$coordinate.  The average over an elliptical cross-section $E(a,b)$ is
$$\bar{v}_z^{(p)} = \frac{1}{\pi a b} \int \int_{E(a,b)}v_z^{(p)}(y) \, dx\,dy =  \frac{1}{\pi a b} \frac{G b^2}{2 \mu} \int \int_{E(a,b)}(1 - y^2/b^2)\,dx\,dy. $$
Changing variables with $x = ar \cos \theta $ and $y = b r \sin \theta$ we get
$$\begin{align}\bar{v}_z^{(p)} &=  \frac{1}{\pi a b} \frac{G b^2}{2 \mu} \int_0^{2\pi} \int_0^1\left(1 - \frac{b^2r^2 \sin^2 \theta}{b^2}\right)\,a b \,r \, dr \, d\theta \\ &= \frac{1}{\pi a b} \frac{G b^2}{2 \mu} \frac{ab}{2}\int_0^{2\pi} \left(1 - \frac{\sin^2 \theta}{2}\right) \, d\theta \\ &= \frac{G b^2}{2 \mu}\frac{1}{2\pi} \left( 2 \pi - \frac{1}{2}\int_0^{2\pi}\sin^2 \theta \, d\theta \right) \\ &= \frac{G b^2}{2 \mu}\frac{1}{2\pi} \left( 2 \pi - \frac{\pi}{2}\right) \\ &= \frac{3}{4} \frac{G b^2}{2 \mu}\end{align},$$
and it is apparent how the $3/4$ factor arises.
Comment: Excellent answer. That factor, as @RRL points out cannot possibly be gotten rid of. In the elliptical case, no matter how big $a$ is, the velocity has to go to 0 at both ends of the major axis, while a 2 d flow would continue to maintain its full velocity.  The best that can be hoped for, is that the velocity field near the origin inthe case of very large a looks locally like the 2 d case and converges to it in the limit of infinite a.
Comment: I completely agree! That's why I tried to find a function $f(x)$ that is related to $Q_e$ but instead of having an elliptical geometry, we have a rectangular one. Anyway, I agree with you and @Mathemagical on the physical implications, but when I asked the question I thought there was maybe some mathematical subtlety that I was missing. However it seems that it isn't really possibly to deduce one quantity from the other. Thank you both!
Comment: So what you're saying is that effectively there is no easy way to go from $Q_e$ to $Q_p$ without using the velocity profile. But that's a bit strange don't you think? One would believe that the two cases would have the same mean velocity, but then there's that pesky $3/4$ factor! Have you considered the function $f$ I proposed? It also has that same factor...
Comment: @GyörgyvonFeszület:  I added a bit to the answer.   The averaging is taking place over an ellipse inscribed inside a rectangle for $Q_e$ and over the larger rectangle for $Q_p$.  It is somewhat surprising.
Comment: @GyörgyvonFeszület: You're welcome.  I added further explanation to show that the $3/4$ factor is just a geometrical artifact that persists in the limit as $a \to \infty$.
Comment: @Mathemagical: Thanks for the comment.  I think the factor has more to do with the geometry rather than the end effect of the no-slip condition.


$d$-dimensional Fourier transform of $\cos|x|$

Question: What is the $d$-dimensional Fourier transform of $\cos|x|$? More specifically, what does
$$
\int_{\mathbb{R}^d}\text{d}^dx\cos|x|e^{-i\vec{k}\cdot\vec{x}}\ ,
$$
where $|x|=\sqrt{x_1^2+\dots+x_d^2}$,
evaluate to?
I know that the Fourier transform of $e^{-t|x|}$ with positive $t>0$ gives me the Poisson kernel (c.f. this answer on MO) and I would like to know if there exists a generalization to imaginary $t$.
Addendum
For $d=1$ the above integral reduces to the Fourier transform of the ordinary cosine. It can be expressed via the delta distribution
$$
\int_{-\infty}^{\infty}\text{d}x\cos x\,e^{-ikx}=\pi\big(\delta(k-1)+\delta(k+1)\big)\ ,
$$
as can be seen by applying the inverse transformation to the r.h.s.
$$
\frac{1}{2\pi}\int_{-\infty}^{\infty}\text{d}k\,\pi\big(\delta(k-1)+\delta(k+1)\big)e^{ikx}=\frac12\big(e^{ix}+e^{-ix}\big)=\cos x\ .
$$
For completeness I include here a dodgy calculation for the $d=3$ case. Help from someone who actually knows about distributions is needed.
We can use spherical coordinates to obtain
\begin{align}
\int_{\mathbb{R}^3}\text{d}^3x\cos|x|e^{-i\vec{k}\cdot\vec{x}}=&\,2\pi\int_{0}^{\infty}\text{d}r\int_{-1}^{1}\text{d}(\cos\theta)\,r^2\cos r\,e^{-ikr\cos\theta}\nonumber\\
=&\,2\pi\int_0^\infty\text{d}r\,r^2\cos r\,\frac{1}{ikr}\big(e^{ikr}-e^{-ikr}\big)\nonumber\\
=&\,\frac{4\pi}k\int_{0}^\infty\text{d}r\,r\cos r\sin kr\nonumber\\
=&\,\frac{4\pi}k\int_0^\infty\text{d}r\,-\frac{\partial}{\partial k}\frac12\Big[\cos\big(r(1+k)\big)+\cos\big(r(1-k)\big)\Big]\nonumber\\
=&\,-\frac\pi k\frac{\partial}{\partial k}\int_{-\infty}^\infty\text{d}r\,\frac12\Big[e^{ir(1+k)}+e^{-ir(1+k)}+e^{ir(1-k)}+e^{-ir(1-k)}\Big]\nonumber\\
=&\,-\frac{2\pi^2} k\frac{\partial}{\partial k}\big[\delta(1+k)+\delta(1-k)\big]\ .
\end{align}
Thus we finally obtain
$$
\int_{\mathbb{R}^3}\text{d}^3x\cos|x|e^{-i\vec{k}\cdot\vec{x}}=\frac{2\pi^2}{k}\big(\delta'(1-k)-\delta'(1+k)\big)\ .
$$
Comment: The function is not integrable.
Comment: @Aruralreader maybe I should have mentioned that I am aware of the $d=1$ case.
Comment: For those of us, me especially, who don't know this from that, please tack that result and derivation onto your question.
Comment: I'm a bit confused over the term $\delta'(1+k)$ in the $d=3$ case. Since $k\geq 0$ that term will vanish. Yet I'm not confident with just dropping it.
Comment: This has to be done in a distributional sense. Maybe try it in  $\mathbb{R}$ first.
Comment: @Aruralreader I have added the 1-dimensional case. As you mentioned, it results in a distribution.
Comment: @md2perpe I was wondering about that term too and it indeed just vanishes when we apply the inverse Fourier transformation to obtain $\cos |x|$. It does, however, make the distribution even under $k\to-k$ as it should be right? (since $\cos$ is even.)
Comment: Haven't we already assumed that the Fourier transform is spherically symmetric, i.e. that it only depends on the norm of $\vec k$?
Answer: I found an answer to my question which I would like to share with those interested.
For odd dimension $d$ we have
$$
\int_{\mathbb{R}^d}\text{d}^dxe^{ifx}e^{-i\vec{k}\cdot\vec{x}}=(-2\pi)^{\frac{d-1}{2}}\left(\frac{1}{k}\frac{\partial}{\partial k}\right)^{\frac{d-1}{2}}\left[\pi\big(\delta(f+k)+\delta(f-k)\big)-\frac{2if}{f^2-k^2}\right]\ ,
$$
where $x=|\vec{x}|$ and $k=|\vec{k}|$.
It might even be applicable to all dimensions if one defines the fractional derivative in some way.
Derivation
Starting with
$$
I(\vec{k})=\int_{\mathbb{R}^d}\text{d}^dxe^{ifx}e^{-i\vec{k}\cdot\vec{x}}=(2\pi)^{\frac{d}{2}}\int_{0}^{\infty}\text{d}r\,\left(\frac{r}{k}\right)^{\frac{d-2}{2}}re^{ifr}J_{\frac{d-2}{2}}(kr)\ ,
$$
where $J_\nu$ denotes the $\nu$-th Bessel function of the first kind, we can use
$$
J_{\nu+m}(z)=(-1)^{m}z^{\nu+m}\left(\frac1z\frac{\partial}{\partial z}\right)^{m}\big(z^{-\nu}J_\nu(z)\big)
$$
with $\nu=-1/2$ and $m=(d-1)/2$ to write
$$
I(\vec{k})=(-1)^{\frac{d-1}{2}}(2\pi)^{\frac{d}{2}}\sqrt{\frac{2}{\pi}}\frac{1}{k^{d-1}}\int_{0}^{\infty}\text{d}r\,r^{d-1}e^{ifr}\left(\frac1r\frac{\partial}{\partial r}\right)^{\frac{d-1}{2}}\cos(kr)\ .
$$
Expanding
$$
\left(\frac1r\frac{\partial}{\partial r}\right)^{n}=\sum_{j=1}^{n}a_j^{(n)}r^{-(2n-j)}\frac{\partial^j}{\partial r^j}\ ,
$$
where the coefficients $a_j^{(n)}$ satisfy the relation
$$
a_j^{(n)}=a_{j-1}^{(n-1)}-\big[2(n-1)-j\big]a_j^{(n-1)}\ ,\quad a_1^{(1)}=1\ ,\ a_0^{(n)}=a_{n+1}^{(n)}=0\ ,
$$
we can calculate (using the shorthand $n=(d-1)/2$)
\begin{align}
\left(\frac{r}{k}\right)^{2n}\left(\frac1r\frac{\partial}{\partial r}\right)^{n}\cos(kr)=&\,\left(\frac{r}{k}\right)^{2n}\sum_{j=1}^{n}a_j^{(n)}r^{-(2n-j)}(ik)^{j}\frac12\big(e^{ikr}+(-1)^{j}e^{-ikr}\big)\nonumber\\
=&\,\sum_{j=1}^{n}a_j^{(n)}k^{-(2n-j)}\frac{\partial^{j}}{\partial k^{j}}\frac12\big(e^{ikr}+e^{-ikr}\big)\nonumber\\
=&\,\left(\frac1k\frac{\partial}{\partial k}\right)^{n}\cos(kr)\ .
\end{align}
(Is there a more obvious way to see this?)
With that we obtain
$$
I(\vec{k})=(-1)^{\frac{d-1}{2}}(2\pi)^{\frac{d-1}{2}}\left(\frac1k\frac{\partial}{\partial k}\right)^{\frac{d-1}{2}}\int_0^\infty\text{d}r\,e^{ifr}\big(e^{ikr}+e^{-ikr}\big)\ .
$$
For the integral over $r$ we now use
$$
\int_0^\infty\text{d}r\,e^{iar}=\pi\delta(a)+\frac{1}{ia}
$$
to finally arive at
$$
I(\vec{k})=(-2\pi)^{\frac{d-1}{2}}\left(\frac1k\frac{\partial}{\partial k}\right)^{\frac{d-1}{2}}\left[\pi\big(\delta(f+k)+\delta(f-k)\big)+\frac{1}{i(f+k)}+\frac{1}{i(f-k)}\right]\ ,
$$
which gives the desired result.
Connection to the Poisson kernel
One nice thing about the above result is that it can be connected to the Poisson kernel mentioned in my original question. To see this we let $f=i\beta$ for some positive $\beta>0$ such that
$$
\int_{\mathbb{R}^{d}}\text{d}^dxe^{-\beta x}e^{-i\vec{k}\cdot\vec{x}}=(-2\pi)^{\frac{d-1}{2}}\left(\frac1k\frac{\partial}{\partial k}\right)^{\frac{d-1}{2}}\left[\pi\big(\delta(i\beta+k)+\delta(i\beta-k)-\frac{2\beta}{\beta^2+k^2}\right]\ .
$$
Focusing on what used to be the imaginary part of the answer and using
$$
\frac1k\frac{\partial}{\partial k}=2\frac{\partial}{\partial(k^2)}
$$
we obtain
$$
\int_{\mathbb{R}^{d}}\text{d}^dx\,e^{-\beta x}e^{-i\vec{k}\cdot\vec{x}}=-\frac{(2\pi)^d}{\pi^{\frac{d+1}{2}}}\Gamma\left(\frac{d+1}{2}\right)\frac{\beta}{(\beta^2+k^2)^{\frac{d+1}{2}}}\ ,
$$
which is precisely the Poisson kernel (up to a negative sign which I would be very happy if someone can point to where it comes from).
Comment: @Aruralreader I added the derivation.
Comment: You might add a reference or derivation.
Comment: Thank you very much.


Youtube API V3 how can i get channel username

Question: I need to use youtube username in a javascript script that retrieves data from youtube API with username
the problem is that this channel has a custom url in format:
https://www.youtube.com/c/myname
but from tutorial and video i found i need to get the user from a custom url like this
https://www.youtube.com/user/myname
since, as far as i know, is not possible to set an url and surname based on second url for newer channel how can i found the username?
any way to get it with API?
Comment: Do you have an example of the custom url? I don't recall seeing /c/ for YouTube.
Comment: @johnh10 e.g. https://www.youtube.com/c/annacavalli
Answer: youtube.channels.list does NOT provide the username. you have to use Google+ API to get it.
Answer: tube_dl is the answer.
pip install tube_dl

This module is a great video downloader and youtube parser.
Here's the sample code:
from tube_dl import Youtube
yt = Youtube('your video id').channelUrl

For tube_dl documentation, visit Github Page of tube_dl
Answer: You can try out the Channels.list method on the YouTube Data API. You can pass the username and it will return the list of channels that said user have.
The YouTube Data API developer site has more information if you want to learn more about it.
Comment: If I get it right he is trying to get the username of a custom youtube url. In this case youtube.channels.list will not help.


Radon measure taking integer values has discrete support

Question: Let $X$ be a Polish space and $M(X)$ be the set of Radon measures on $X$. Can you explain why if $L \in M(X)$ is integer valued, then $L$ is supported on a discrete set?
Answer: A Radon measure is inner regular. This means that if $A$ is Borel then $L(A)=\sup\{L(K): K\text{ is compact}, K\subset A\}$.
If $L\neq0$ then there is a ball $U$ (use a metric on $X$ which makes it complete) with $L(U)\neq0$. By inner regularity there is a compact $K\subset U$ such that $L(U)-\frac{1}{3}<L(K)\leq L(U)$. Since $L$ takes only integer values then $L(K)=L(U)$.
Now we begin chasing the support points inside these compact. Stand on a point $a\in K$.
If for all balls $V$ centered at $a$ we have $L(V)\neq0$ then $L(\{a\})=\lim L(V_n)\neq0$, where $V_n$ is a decreasing sequence of balls with $a$ as intersection. The inequality follows since the $L(V)$ are non-zero integers. Moreover, there is some $n_0$ such that for $n>n_0$ we have $L(V_n)=L(\{a\})$. Therefore $a$ is isolated from other density points.
If there is a ball $a\in V\subset U$ such that $L(V)=0$ we consider $K\setminus V\subset K$ as the new compact which satisfies $L(K\setminus V)=L(K)=L(U)$. The intersection of all compacts found in this way is non-empty. So, some point in that intersection falls in the previous case of having all balls around it with non-zero measure.


Google Analytics cant find tracking code

Question: I have a problem with google analytics:
I implemented the tracking code like this:
<code> var _gaq = _gaq || [];
      _gaq.push(['_setAccount', 'UA-XXXXXXXX-X']);
      _gaq.push(['_setDomainName', 'ransoft.at']);
      _gaq.push(['_trackPageview']);

      (function() {
        var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
        ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
        var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
      })();
</code>
just the way it should be implemented (according to goole).
The tracking code is on the side, but google analytics can't find it (Google Analytics: Tracking Info: Tracking not installed!)
Just see for yourself: http://www.ransoft.at
Google Analytics says, that i dont have the tracking code installed on my website.
Google Analytics: Property Settings:

Default URL: http://www.ransoft.at

The website is powered by Vaadin7 and is running on tomcat7.
Pleas help me, i am quite lost here.
Comment: Are you seeing data in your GA account? If so, the implementation is probably fine and GA is just not detecting the installation because of the unconventional setup.
Comment: I'm actually not seeing any ga.js code on ransoft.at. Have a look at the live source code yourself. Are you seeing it? Has the code been uploaded and the server been refreshed?
Comment: I'm seeing the ga.js in the header. Its embedded like this:
Comment: OK, I see that gets added at some point. I'm not seeing the rest of the code get executed though - the part you have saved as myLibrary.addGoogleAnalytics(). Do you just define that function, or do you actually execute it somewhere? Also, this particular website is probably well suited to a setup with [virtual pageviews](https://developers.google.com/analytics/devguides/collection/gajs/asyncMigrationExamples#VirtualPageviews) since the links lead to areas that act like new pages but do not actually cause a page refresh.
Comment: the myLibrary.addGoogleAnalytics() is being executet on startup. Like this:

Page.getCurrent().getJavaScript().execute("myLibrary.addGoogleAnalytics();");

This is a Vaadin 7 feature and this works just fine.
This code is also being executet, because otherwise the ga.js would not be there. I dont know about virtual pageviews...but i doubt that this is the problem of the ga integration.
Comment: unfortunately not. i just read that sometimes ga needs some time to check if the tracking code is installed. Additionally I found some other bug in my webapp:  is missing, maybe that is the problem after all?
Comment: The GA debuggers shows no calls to the utm.gif-file that's used for tracking, so I'd say the code does not work.  It might simply be that asynchronous google code and loading via bootstrapping do not mix very well.
Comment: ok...now i see data in my ga account. i changed the ga integration with a add-on: https://vaadin.com/directory#addon/googleanalyticstracker... now i can see data, but it still says that the tracking is not installed. Maybe it need some time to detect it?
Answer: So, I finally managed to get google analytics running.
Google Analytics was not able to find my tracking code in the website. With the GoogleAnalyticsTracker Add-on the data was sent to GA, but the tracking information did say that the tracking code was not installed.
The problem was the missing tracking code in the Bootstrap Page.
The solution was to create a new VaadinServlet, where i created a new BootstrapListener. Something like this:
<code>public class MyVaadinServlet extends VaadinServlet {

    /**
     *
     */
    private static final long serialVersionUID = 1L;

    @Override
    protected void servletInitialized() throws ServletException {
        super.servletInitialized();
        getService().addSessionInitListener(new SessionInitListener() {

            /**
             *
             */
            private static final long serialVersionUID = 1L;

            @Override
            public void sessionInit(SessionInitEvent event) throws ServiceException {
                event.getSession().addBootstrapListener(new BootstrapListener() {

                    /**
                     *
                     */
                    private static final long serialVersionUID = 1L;

                    @Override
                    public void modifyBootstrapPage(BootstrapPageResponse response) {
                        // Adding Google Analytics to BootstrapPage header
                        head.append("<script type=\"text/javascript\">" +
                                      "var _gaq = _gaq || [];"+
                                      "_gaq.push(['_setAccount', 'UA-XXXXXXXX-X']);" +
                                      "_gaq.push(['_setDomainName', 'mydomain.com']);" +
                                      "_gaq.push(['_trackPageview', '/']);" +
                                      "(function() { " +
                                        "var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;" +
                                        "ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';" +
                                        "var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);" +
                                      "})();"+
                                    "</script>");

                    }

                    @Override
                    public void modifyBootstrapFragment(BootstrapFragmentResponse response) {

                    }
                });
            }
        });
    }
}
</code>
For further Information see: Customizing Startup page in a Vaadin Application
With this solution the data is being send to Google Analytics and the tracking code is also being recognized by Google Analytics.
There are probably some easier ways to do that in a Vaadin 7 Application, but this works for me. Thought I let you know that.
regards


What is the internal behaviour of exception handling?

Question: If there is exception, then an exception object is created.
If the exception was not handled, what happen to that exception object and what is the internal mechanism?
Answer: You can check How uncaught exceptions are handled:

Java actually handles uncaught exceptions according to the thread in
  which they occur. When an uncaught exception occurs in a particular
  thread, Java looks for what is called an uncaught exception handler,
  actually an implementaiton of the interface UncaughtExceptionHandler.
  The latter interface has a method handleException(), which the
  implementer overrides to take appropriate action, such as printing the
  stack trace to the console. As we'll see in a moment, we can actually
  install our own instance of UncaughtExceptionHandler to handle
  uncaught exceptions of a particular thread, or even for the whole
  system.
The specific procedure is as follows. When an uncaught exception
  occurs, the JVM does the following:

it calls a special private method, dispatchUncaughtException(), on    the Thread class in which the exception occurs;
it then terminates the thread in which the exception occurred1.
Answer: If Exception object exist AND IS THROWN, then Rahul has already answered nicely.
Interesting what to do with new Exception object, not throwed. It's a programming technique to get some runtime info, like stack, place of call Exception constructor, etc.
<code>            e= new Exception();
            StackTraceElement[] st = e.getStackTrace();
            for(StackTraceElement s:st)
            {
                s.getLineNumber()
            }
// NO throw
</code>


Statistical analysis: how does one account for recruitment differences between study sites in a biomedical study?

Question: How does one account/control for differences between study sites during the analysis? In my study 2/3 of all participants across the two age groups strata came from 1 of my 2 study sites. Moreover,  there are some differences in the level of experience of the health providers between the sites. 2/3 of the study participants were enrolled in the site with more experienced participants.
Is there a way of controlling for this e.g. when calculation the time it took to perform a procedure. Thought that come to mind are the mantel-Haenszel but I don't find it quite appropriate as I am not calculating any Odds ratios.
Answer: If I understand the question correctly, you are trying to assess the relationship of some treatment/exposure on an outcome. However, you're worried that the site in which the patient is recorded can be confounding this relationship.
If you believe there is such a confounding issue, then including site fixed effects may be appropriate. If you believe that there's no confounding, you still need to address the site-level heterogeneity in your model because its presence violates the independence assumption of most models (i.e. you don't have independent patient observations since patients are observed within sites). You can handle this using random effects.
For a good review of random effects and fixed effects see the following sources:

https://stablemarkets.wordpress.com/2016/08/20/fixed-effects-random-effects-and-first-differencing/
https://www.ncbi.nlm.nih.gov/pmc/articles/PMC4208783/


Xcode 7 - Building framework fails during attempt_symlinks phase

Question: Running into this after updating to Xcode 7. Building a static framework both from the command line and from Xcode itself and getting the following error:
<code>UFW (M iphoneos): INFO: Cmd /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/libtool -static -arch_only armv7 -syslibroot /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS9.0.sdk -L/Users/ME/Library/Developer/Xcode/DerivedData/SDK_I_AM_BUILDING-bkuozmamressjqcrnhntirossihk/Build/Products/Debug-iphoneos -filelist /Users/ME/Library/Developer/Xcode/DerivedData/SDK_I_AM_BUILDING-bkuozmamressjqcrnhntirossihk/Build/Intermediates/SDK_I_AM_BUILDING.build/Debug-iphoneos/SDK_I_AM_BUILDING.build/Objects-normal/armv7/SDK_I_AM_BUILDING.LinkFileList -o /Users/ME/Library/Developer/Xcode/DerivedData/SDK_I_AM_BUILDING-bkuozmamressjqcrnhntirossihk/Build/Intermediates/SDK_I_AM_BUILDING.build/Debug-iphoneos/SDK_I_AM_BUILDING.build/Objects-normal/armv7/SDK_I_AM_BUILDING.ufwbuild
UFW (M iphoneos): INFO: Cmd /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/libtool -static -arch_only arm64 -syslibroot /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS9.0.sdk -L/Users/ME/Library/Developer/Xcode/DerivedData/SDK_I_AM_BUILDING-bkuozmamressjqcrnhntirossihk/Build/Products/Debug-iphoneos -filelist /Users/ME/Library/Developer/Xcode/DerivedData/SDK_I_AM_BUILDING-bkuozmamressjqcrnhntirossihk/Build/Intermediates/SDK_I_AM_BUILDING.build/Debug-iphoneos/SDK_I_AM_BUILDING.build/Objects-normal/arm64/SDK_I_AM_BUILDING.LinkFileList -o /Users/ME/Library/Developer/Xcode/DerivedData/SDK_I_AM_BUILDING-bkuozmamressjqcrnhntirossihk/Build/Intermediates/SDK_I_AM_BUILDING.build/Debug-iphoneos/SDK_I_AM_BUILDING.build/Objects-normal/arm64/SDK_I_AM_BUILDING.ufwbuild
UFW (M iphoneos): INFO: Cmd /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/libtool -static /Users/ME/Library/Developer/Xcode/DerivedData/SDK_I_AM_BUILDING-bkuozmamressjqcrnhntirossihk/Build/Intermediates/SDK_I_AM_BUILDING.build/Debug-iphoneos/SDK_I_AM_BUILDING.build/Objects-normal/armv7/SDK_I_AM_BUILDING.ufwbuild /Users/ME/Library/Developer/Xcode/DerivedData/SDK_I_AM_BUILDING-bkuozmamressjqcrnhntirossihk/Build/Intermediates/SDK_I_AM_BUILDING.build/Debug-iphoneos/SDK_I_AM_BUILDING.build/Objects-normal/arm64/SDK_I_AM_BUILDING.ufwbuild -o /Users/ME/Library/Developer/Xcode/DerivedData/SDK_I_AM_BUILDING-bkuozmamressjqcrnhntirossihk/Build/Products/Debug-iphoneos/SDK_I_AM_BUILDING.framework/SDK_I_AM_BUILDING
UFW (M iphoneos): ERROR: Build failed
Traceback (most recent call last):
  File "/Users/ME/Library/Developer/Xcode/DerivedData/SDK_I_AM_BUILDING-bkuozmamressjqcrnhntirossihk/Build/Intermediates/SDK_I_AM_BUILDING.build/Debug-iphoneos/SDK_I_AM_BUILDING.build/Script-0BCB59941B65EF6A005216E2.sh", line 812, in <module>
    run_build()
  File "/Users/ME/Library/Developer/Xcode/DerivedData/SDK_I_AM_BUILDING-bkuozmamressjqcrnhntirossihk/Build/Intermediates/SDK_I_AM_BUILDING.build/Debug-iphoneos/SDK_I_AM_BUILDING.build/Script-0BCB59941B65EF6A005216E2.sh", line 787, in run_build
    add_symlinks_to_framework(project)
  File "/Users/ME/Library/Developer/Xcode/DerivedData/SDK_I_AM_BUILDING-bkuozmamressjqcrnhntirossihk/Build/Intermediates/SDK_I_AM_BUILDING.build/Debug-iphoneos/SDK_I_AM_BUILDING.build/Script-0BCB59941B65EF6A005216E2.sh", line 675, in add_symlinks_to_framework
    attempt_symlink(os.path.join(base_dir, "Versions", "Current"), os.environ['FRAMEWORK_VERSION'])
  File "/Users/ME/Library/Developer/Xcode/DerivedData/SDK_I_AM_BUILDING-bkuozmamressjqcrnhntirossihk/Build/Intermediates/SDK_I_AM_BUILDING.build/Debug-iphoneos/SDK_I_AM_BUILDING.build/Script-0BCB59941B65EF6A005216E2.sh", line 493, in attempt_symlink
    os.stat(os.path.abspath(os.path.join(link_path, "..", link_to)))
OSError: [Errno 2] No such file or directory: '/Users/ME/Library/Developer/Xcode/DerivedData/SDK_I_AM_BUILDING-bkuozmamressjqcrnhntirossihk/Build/Products/Debug-iphoneos/SDK_I_AM_BUILDING.framework/Versions/A'
Command /bin/sh failed with exit code 1
</code>
This seems to have been an issue previously with framework that were using iOS-Universal-Framework, but since we're not using that and this issue was introduced by the update to Xcode 7 I figured that isn't part of my problem.
Has anyone run into this issue with Xcode 7 yet? Any tips to debug further for an issue like this?
Comment: The `No such file or directory` of `SDK_I_AM_BUILDING.framework/Versions/A` leads me to believe that Xcode thinks it's building a dynamic library as I don't *think* static frameworks use the `Versions` directory.
Answer: This seems to have been an issue with Xcode 6 framework projects not updating correctly when updating to Xcode 7.
My team members created a new Xcode 7 static framework project and copied over everything from the existing project. They then diffed the two project.pbxproj files and copied over any relevant changes to the existing project.
There were many changes so it's not simple to post everything here. I suggest going through with the above process if you run into this issue.


Are complete statistics always sufficient?

Question:
I know that a complete sufficient statistic $T$ is such that
  1) $T$ is sufficient for $\theta$, unknown parameter and 2) $T$ is complete.

So, is it always the case? If the answer is not, what could be an example of a complete but not sufficient statistic? Instead is it true in exponential family distributions?
Answer: For completeness you need to consider only the distribution of the statistic $T$ (more correctly, the family of distributions indexed by $\theta$), whereas for sufficiency you need to consider the complete likelihood for $\theta$ as a function of the sample $X$; so it's trivial to come up with examples where $T$ isn't sufficient but is still complete:

The constant statistic $T(X)=7$.
Throw some of your data away & calculate your (previously complete &
sufficient) test statistic on what's left. Suppose you've four
observations $X_1,\ldots,X_4$ from a Gaussian with mean $\theta$ (& known standard deviation):
$T(X)=\frac{X_1+X_2}{2}$ isn't sufficient for $\theta$ but is
complete.
Twice the sample mean from a random variable uniformly distributed between
$0$ & $\theta$, $T(X)=\frac{2\sum_{i=1}^n X_i}{n}$ (the method-of-moments estimator), is complete, but we know the sufficient statistic for
$\theta$ is the sample maximum $X_{(n)}$.

See Complete sufficient statistic for a more interesting example—of a sufficient statistic that isn't complete.