UDPclient in WinForms?

Question: I have used this code example, http://msdn.microsoft.com/en-us/library/tst0kwb1.aspx, to make a console UDP server capable of receiving and sending messages.
But I do not want this to a be a console application, I want to use Forms. I have successfully implemented the sending messages feature in my application, but I do not know how to make the listener work.
Here is the code for receiving messages, it doesn't do anything.
Note: I put this code right under the button click event code.
private void StartListener()
    {
        bool done = false;
        UdpClient listener = new UdpClient(listenPort);
        IPEndPoint groupEP = new IPEndPoint(IPAddress.Any, listenPort);

        try
        {
            while (!done)
            {
                this.lblMessage.Text = "Waiting for broadcast";
                byte[] bytes = listener.Receive(ref groupEP);

                this.lblRecieve.Text = Encoding.ASCII.GetString(bytes, 0, bytes.Length);
            }

        }
        catch (Exception e)
        {
            this.lblMessage.Text = e.ToString();
        }
        finally
        {
            listener.Close();
        }
    }

This code is obviously wrong, but I have never done anything in C# before and this console sample code was the only guide I could find about UDP servers.
Here is the code for sending messages, it works perfectly.
private void btnSend_Click(object sender, EventArgs e)
    {
        Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
        IPAddress broadcast = IPAddress.Parse("192.168.0.105");
        byte[] sendbuf = Encoding.ASCII.GetBytes("test");
        IPEndPoint ep = new IPEndPoint(broadcast, listenPort);
        s.SendTo(sendbuf, ep);
        this.lblMessage.Text = "Sent Message";
    }

EDIT:
I appreciate the help I have got from you, but instead of tweaking my own broken code to work, I found another code to tweak so that it works like I want.
UDP datagram code for server client application in C#
This is the code I borrowed and it works perfectly, except that stop() doesn't work properly, but it's not a major problem and shouldn't be hard to fix with google.
I still learnt a lot from the links you guys gave me.
Answer: It probably works, you just can't see it.  You hang up the UI thread with an endless loop, the form goes entirely dead.  Won't paint either so you can't see the label updates.
You'll need to either start using UdpClient.BeginReceive() or create a thread to run this code.  If you use a thread then you'll need to use Control.BeginInvoke() to update the label.
Answer: You would have to register a listener. Just check the following article.
Events Tutorial
Comment: Thanks for your answer, will look at this tutorial.

UDPclient in WinForms?


What is the correct encoding of BOSCH in NYSIIS?

Question: What is the correct encoding of BOSCH in NYSIIS?  I am building an indexing system which needs to be robust against slight differences in spelling of names.
Testing the method in R, produces "BAS":
require(phonics); nysiis('BOSCH')
The java code https://rosettacode.org/wiki/NYSIIS#Java produces "BA".
While the commons library org.apache.commons.codec.language.Nysiis class produces "B".
The "BAS" looks most correct to me as suggested by the website http://www.dropby.com/NYSIIS.html
Here are the rules as published at https://commons.apache.org/proper/commons-codec/apidocs/org/apache/commons/codec/language/Nysiis.html
Algorithm description:
 1. Transcode first characters of name
   1a. MAC ->   MCC
   1b. KN  ->   NN
   1c. K   ->   C
   1d. PH  ->   FF
   1e. PF  ->   FF
   1f. SCH ->   SSS
 2. Transcode last characters of name
   2a. EE, IE          ->   Y
   2b. DT,RT,RD,NT,ND  ->   D
 3. First character of key = first character of name
 4. Transcode remaining characters by following these rules, incrementing by one character each time
   4a. EV  ->   AF  else A,E,I,O,U -> A
   4b. Q   ->   G
   4c. Z   ->   S
   4d. M   ->   N
   4e. KN  ->   N   else K -> C
   4f. SCH ->   SSS
   4g. PH  ->   FF
   4h. H   ->   If previous or next is nonvowel, previous
   4i. W   ->   If previous is vowel, previous
   4j. Add current to key if current != last key character
 5. If last character is S, remove it
 6. If last characters are AY, replace with Y
 7. If last character is A, remove it
 8. Collapse all strings of repeated characters
 9. Add original first character of name as first character of key

Comment: A useful blog: http://ntz-develop.blogspot.com/2011/03/phonetic-algorithms.html
Answer: Based solely upon that algorithm description, the answer is "BAS".
Comment: Yes that was my assessment as well. I think the apache commons code misinterprets rule 5 as removing all trailing 'S's which then triggers rule 7.  Rule 8 as you agree is the real rule to evoke in the case of BOSCH->BASCH->BASSS->BASS->BAS


.NET Core + WCF integration with DI Problem

Question: I have an problem to declare dependency injection. I have to declare a WCF service and I did it like this:
services.AddTransient<IService, ServiceClient>();

As I will need to work with the WCF header I need to add a behavior to check the headers. Normally I would do it like this:
var client = new ServiceClient();
client.Endpoint.Behaviors.Add( new HeaderInspectionBehavior());

But I can't do it that way because I'm getting the IService injected in the constructor.
I tried to do it this way:
var client = new ServiceClient();
client.Endpoint.Behaviors.Add(new HeaderInspectionBehavior());
services.AddTransient<IService, ServiceClient>(sp => client);

But it didn't work, in the second WCF call it changes the state to "FAULT" or "CLOSED".
Does anyone know of another way to do this?
Answer: Based in this i found a solution that looks like this:
ServiceClient Config(IServiceProvider _) => new ServiceClient(..., ...);
services.AddTransient<IService, ServiceClient>(Config);

It's work for me.


Angular 2 Media Queries

Question: I want to know that does Angular 2 provides a way to determine the client's device (large screen, medium or smalls screen) or may be screen width on the basic of which some contents could be shown or hidden (removed from dom).
Answer: HostListener
One way is to use the HostListener decorator. The decorated method will be invoked when the host element emits the specified event.
@HostListener('window:resize', ['$event'])
onResize(event) {
  this.width = event.target.innerWidth;
  this.height = event.target.innerHeight;
}

Via ngZone
Another way is to import ngZone into your component. Then you can use NgZone to check the onresize event.
constructor(ngZone:NgZone) {
  window.onresize = (e) => {
    ngZone.run(() => {
        this.width = window.innerWidth;
        this.height = window.innerHeight;
    });
  };
}

After that you can use the [hidden] attribute to hide content depends from your width or height value.
Comment: Thank you so much Maximilian. One more question, does using NgZone adds any overhead or may cause any performance issue?
Comment: @NaveedAhmed My understanding is that NgZone#run can be used in the handler for some asynchronous process that runs outside of Angular change detection.  In this case, we want to react to `onresize` events which are emitted from outside of Angular, so in order to react to that event within angular's change detection cycles, we can register a listener for that event on the window and use `run` to schedule handling to be executed from within the angular zone.  TLDR while you could have performance issues if you schedule too much logic to be executed in the zone, this example looks ok to me.
Answer: There is no need to use NgZone. There are easier ways to capture the resize window event.
@HostListener('window:resize', ['$event'])
onResize(event) {
  const target = event.target;
  this.width = target.innerWidth;
  this.height = target.innerHeight;
}

or if you want to use if from the HTML
<div (window:resize)="onResize($event)"

onResize(event) {
  event.target.innerWidth;
}

Angular 2 Media Queries


Can Exchange create catch-all addresses for email@example.com?

Question: I'm not an Exchange expert, and want to see if something is feasible before I ask for this. I'm looking for two things: 1) Is this possible? 2) Is there a better way to do this?
I want to have a catch-all address setup, but I need it to act differently than a typical catch-all address. To illustrate what I need:
1) email@example.com
2) email@example.com
3) firstname.lastname@example.com
4) email@example.com
I want to setup an email address (1). That address should catch anything meeting the criteria in (2) where the . is literal, the * is wildcard. For example, both (3) and (4) should direct to (1), because they meet the criteria of (2).
The reasoning for this is we have a need to create a large number of unique email addresses that only need to receive email. We cannot rely on the default catch-all email address, because this is a smaller scope than what the default catch-all would see. We would have a few users granted access to (1) so they could monitor inbound emails when needed. We have hundreds of users who need to assign things to a certain, unique email address, and cannot feasibly create new addresses for each item.
I'm not asking for the rules to create (although if anybody knows off the top of their head, awesome), but rather is this possible in Exchange 2007/2010?
Answer: You can do this.  It is actually called a 'catch-all mailbox'.
What you will do is create a new mailbox, then create the rules you want to foward to this mailbox on your hub transport server.
More details here...
http://technet.microsoft.com/en-us/library/bb691132(v=exchg.80).aspx
There are a lot of rules you can use to forward messages as you need on the hub transport server in your Exchange manager.
It is also possible that what you are looking for is just to create your firstname.lastname@example.com mailbox and create aliases for the other email addresses to send into this same mailbox.
Comment: You'll also need to configure the SMTP domain as an "internal relay domain", as opposed to an authoritative domain; otherwise, Exchange will reject all messages addresses to non-existent users before even starting to process the transport rules.
Comment: Thanks for the quick response - that's exactly what I needed to know!

Can Exchange create catch-all addresses for address.*@domain.com?


Como chamar um método não estático dentro de uma classe estática?

Question: Eu possuo a seguinte método/função e preciso chamar o método/função criaTimerTendencia que esta dentro da classe TagAnalogicaAtiva.
private static void VerificaEnvioDeMensagensSignalR(object sender, EventArgs e)
{
    if (ExisteTendenciaParaTag)
    {
        TagAnalogicaAtiva.criaTimerTendencia();//preciso chamar este metodo/função
    }
}

Segue abaixo o código do método criaTimerTendencia()
class TagAnalogicaAtiva : TagAtiva
{
    public void criaTimerTendencia()
    {
        var tendencia = Processamento.PegaTendencia(IdTag);
        timer = new System.Timers.Timer(tendencia.TempoDeColeta);
        timer.Elapsed += insereTendenciaDB;
        timer.AutoReset = true;
        timer.Enabled = true;
     }
}

Só que esta acontecendo o seguinte erro:

An object reference is required for the non-static field, method, or property 'TagAnalogicaAtiva.criaTimerTendencia()'

Como resolvo este problema?
Comment: qual o tipo de `sender`? tenta fazer um `var tipo = sender.GetType()` para ver o tipo o `sender`.
Comment: tenta isso
`TagAnalogicaAtiva tag = new TagAnalogicaAtiva ();`
`tag.criaTimerTendencia();`

Ou muda

`public static void criaTimerTendencia()`
Comment: Onde está declarada a variável `timer`? Pode colocar mais partes desta classe, especialmente o uso do `timer`?
Comment: por quê você não criou um obj de TagAnalogicaAtiva na classe estática e acessou ele ??
Answer: Neste caso, não faz diferença se a classe "de fora" é estática ou não. O problema do código é que você está chamando um método não-estático de TagAnalogicaAtiva sem antes criar uma instância de TagAnalogicaAtiva, isso nunca vai funcionar.
Membros estáticos são acessíveis através da classe e não de instâncias. Membros não-estáticos são acessíveis através de instâncias de determinada classe.
Imagine que exista na classe TagAnalogicaAtiva os métodos FazerAlgo() e FazerAlgoEstatico() sendo eles, respectivamente, não-estático e estático.
Para chamar o método FazerAlgo() é necessário ter uma instância de TagAnalogicaAtiva, no outro caso isso não é necessário.
var tag = new TagAnalogicaAtiva();
tag.FazerAlgo();

TagAnalogicaAtiva.FazerAlgoEstatico(); // Funciona

Então é necessário criar uma instância de TagAnalogicaAtiva para acessar o método criaTimerTendencia(), já que ele é não-estático.
var tag = new TagAnalogicaAtiva();
tag.criaTimerTendencia();

Answer: para acessar o método não estático, você deve instanciar um objeto da classe:
TagAnalogicaAtiva obj = new TagAnalogicaAtiva();
obj.criaTimerTendencia();


Encode non ascii characters in C# .NET

Question: I want to add a custom header to the emails my application is sending out. The header name can only contain ASCII chars, but for the value and users could potentially enter UTF-8 characters and I have to base64-encode them. Also I have to decode them back to UTF-8 to show them back to the user in the UI.
What's the best way to do this?
Comment: Define "encode."  Do you want it to be readable when encoded?  You can strip all the non-ASCII characters but you won't be able to go back to UTF-8.  Otherwise, you can use base-64 encoding but you won't be able to read it without decoding it (or you "learn" how to read in base-64).
Comment: http://stackoverflow.com/q/497813/629926
Comment: Possible dup of http://stackoverflow.com/questions/1888066/encode-string-to-utf8
Comment: Good point, i want base64. updated the question
Answer: To convert from a .net string to base 64, using UTF8 as the underlying encoding:
string base64 = Convert.ToBase64String(Encoding.UTF8.GetBytes(text));

And to reverse the process:
string text = Encoding.UTF8.GetString(Convert.FromBase64String(base64));

It is perfectly possible to skip the UTF8 step. However, UTF8 typically results in a smaller payload that UTF16 and so I would recommend using UTF8 as the underlying encoding.

I'm not sure what you mean when you say that the user can enter UTF8 characters. The .net framework uses UTF16 as its working string encoding. The strings you use in .net are always encoded with UTF16. Perhaps you are just meaning that the text can contain non-ASCII characters.
Comment: I updated the question, I want base64 encoding. I don't care about human readability as long as I can decode it.
Comment: @crdx I don't know what you mean.
Answer: To encode the string:
var someUtf8Str = "ఠఠfoobarఠఠ";
var bytes = Encoding.UTF8.GetBytes(someUtf8Str);
var asBase64Str = Convert.ToBase64String(bytes);

To decode it:
var bytes = Convert.FromBase64String(asBase64Str);
var asUtf8Str = Encoding.UTF8.GetString(bytes);

Encode non ascii characters in C# .NET


Hahn Banach Theorem for Hilbert spaces: a simple questions.

Question: Consider the following extension problem: given a normed linear space $X$ subspace $M\subseteq X$ (not necessarily closed) and a bounded linear functional $f\colon M\to\mathbb{R}$, $$\text{find}\quad F\in X^*\quad\text{such that}\quad
\tag1 \begin{cases}
  F_{|M}=f \\
       \lVert F\rVert_*= \lVert f\rVert &
\end{cases}$$
Observe that a bounded linear functional $f$ defined on a subspace $M$ can be uniquely extended to the closure $\overline{M}$ by a standard completeness argument. Indedd, let $\overline{x}\in\overline{M}$ and let $(x_n)\subseteq M$ be such that $x_n\to \overline{x}$. Since $$|f(x_n)-f(x_m)|\le \lVert f\rVert_*\lVert x_n-x_m\rVert$$
$(f(x_n))$ is a Cauchy sequence in $\mathbb{R}$. So $(f(x_n))$ is convergent. Then it is easy to verify that $F(\overline{x}):=\lim_nf(x_n)$ is the required extension of the given functionl $f$ and $\lVert F\rVert_*=\lVert f\rVert_*$.

In fact, let $x\in M\subseteq \overline{M}$ then $$F(x):=\lim_n f(x_n)=f(x),$$ where $x_n=x$ for all $n\in\mathbb{N}$, furthermore $$\lVert f\rVert_*=\sup_{x\in M, \lVert x\rVert=1}|f(x)|\le\sup_{x\in\overline{M}, \lVert x\rVert=1} |F(x)|=\lVert F\rVert_*$$ How can I proceed to show that $$\color{red}{\lVert F \rVert_*\le \lVert f \rVert_*}$$

Now, we suppose that $X$ is an Hilbert space. Let us still denote by $f$ the extension of the given functional to the closure $\overline{M}$, obtained by the procedure described above. Note that $\overline{M}$ is a Hilbert space. So, by Riesz Theorem, there exists a unique vector $y_f\in\overline{M}$ such that $\lVert  y_f\rVert= \lVert f\rVert_*$ and $$f(x)=(x, y_f)\quad\forall x\in\overline{M}.$$
Define $$F(x)=(x,y_f)\quad\forall x\in X$$
Then $F\in X^*$, $F_| M=f$ and $\lVert F\rVert_*=\lVert y_f\rVert=\lVert f\rVert_*$. We claim that $F$ is the unique extension of $f$ with therse properties. Indeed, let $G$ be another solution of the problem $(1)$ and let $y_G$ be the vector in $X$ associated with $G$ in the Riesz representation.
Consider the Riesz orthogonal decomposition of $y_G$, that is,$$ y_G=y'_G+y''_G\;\text{where}\;y'_G\in\overline{M}\;\text{and}\; y''_G\in \overline{M}^{\perp}.$$ Then $$(x,y'_G)=G(x)=f(x)=(x,y_f)\;\text{for all}\; x\in\color{red}{\overline{M}}$$

My book writes $\color{red}{\overline{M}}$, but in my opinion is $\color{red}M$ who is right? Thanks!
Answer:
For your first question, I suggest to pass to the limit in the inequality $\| f(x_n) \| \leq \| f \|_\ast \| x_n \|$, where $x_n \in M$ and $x_n \rightarrow x \in \overline{M}$, to find that $\forall x \in \overline{M}, \| F(x) \| \leq \| f\|_\ast \| x \|$ which finally implies that $\| F \|_\ast \leq \| f \|_\ast$.

The same idea applies here, I agree that it is first straightforward that the equality holds for $x \in M$, but a $x \in \overline{M}$ is a limit of $(x_n) \subset M$ and you can pass to the limit in the equality has $x \in X \mapsto (x, y)$ is coninuous for all $y \in X$.

I hope it helped


ssl problems between two tomcat servers

Question: I have a Tomcat 7 server (kind of like a web server) that I am trying to have talk to a Tomcat 6 server (acting as a document server on another machine) over SSL and I keep getting this error:
java.security.cert.CertificateException: No name matching rarity64 found.

Where rarity64 is the name of the document server. I've tried exporting keys from both Tomcats keystores and importing them into the others keystores using Java keytool. I've even tried adding them to the other machines cacerts keystore.
I've also used Internet Explorer to import both keys into the other machine. But nothing I try is working.
If it matters the real web server is IIS 7.5, which the Tomcat web server talks too with ARR, and they don't use SSL. But the problem seems to between the two tomcat servers.
Does anybody have any ideas on how I can fix this?
Answer: SSL certs are usually signed for the FQDN, and the above error indicates you just used the (short) hostname. Whatever you use to connect, it has to be the CN the cert is signed for.

ssl problems between two tomcat servers


$\sum a_n$ converge but $\sum \sin(a_n)$ diverges?

Question: Problem :
Show there is $a_n$ such that
$\sum a_n$ converge but $\sum \sin(a_n)$ diverges
or show the $a_n$ doesn't exist.

My Attempt
Since $$|\sin x| \le |x|$$
$a_n$ changes its sign (If $a_n > 0$ or $a_n<0$ for all $n\in\mathbb{N}$, we know $\sum \sin (a_n)$ converge since $\sum a_n$ converge.)
I tried to use a local inverse of $f\colon x \to x - \frac{x^3}{6}$ at $x=0$ because $$\sin x \approx x - \frac{x^3}{6}$$
So I think there is $a_n = f^{-1}(x_n) \quad (x_n \to 0)$ such that
$$\sum a_n<\infty,\quad \sum \sin(a_n) \approx \sum x_n = \infty$$
But I can't construct it, or I was wrong.
So my question is I want to know an example of $a_n$ and how to construct it if $a_n$ exists.
If $a_n$ doesn't exist, I want to know how to prove it.
Thanks for help!
Comment: Take $a_{3n-2} = 1/n^{1/3}$, $a_{3n-1} = 1/n^{1/3}$, and $a_{3n} = - 2/n^{1/3}$. Then $\sum a_n$ converges (conditionally) to $0$ but, since

$$\sin(1/n^{1/3}) + \sin(1/n^{1/3}) - \sin(2/n^{1/3}) = 1/n + O(1/n^{5/3}),$$

the sum $\sum \sin a_n$ will diverge by comparison to the harmonic series.
Comment: Only a remark: notice that $\sin x= x-\frac{1}{6}x^{3}+\mathcal{O}(x^{4})$. Then using the @user994373's answer $\sum \sin a_{n}=\sum a_{n}-\frac{1}{6}\sum a_{n}^{3} +\mathcal{O}\left( \sum a_{n}^{4}\right)$ diverges because $\sum a_{n}^{3}$ diverges.
Comment: Since $\sum_{n} a_{n}$ converges then $a_{n}\underset{n\to +\infty}{\longrightarrow} 0$. Hence $\frac{\sin a_{n}}{a_{n}} \underset{n\to +\infty}{\longrightarrow}1$. Then $\sum_{n} \sin a_{n}$ converges if $a_{n}>0$ by comparision test.
Comment: @Alex OP already noticed that if $a_n>0$ then $\sum \sin(a_n)$ converges. So they are asking about the case that $\sum a_n$ is conditionally convergent.
Comment: This is also relevant: https://math.stackexchange.com/q/1332433/998310
Comment: @snaw:  Oops, sorry... comment deleted.
Answer: The example itself
To expand on the great example that was presented in the comments, if we take
$a_n=b_nc_n$ where $b_n=\lfloor n/3 \rfloor^{-1/3}$ and $c_n=1,1,-2,1,1,-2,\ldots$, then since the partial sums of $\sum c_n$ are bounded and $b_n\to 0$ monotonically, then by Dirichlet's test the series $\sum a_n$ converges.
Now for $\sum \sin(a_n)$. Notice that every $3$ consecutive terms of $b_n$ which start with $n=3k$ are equal to one another. (So that in $a_n=b_nc_n$ the sum of every consecutive triplet starting with $n=3k$ is zero). Let's see what kind of cancellations we get for $\sin(a_n)$. If we sum each $3$ consecutive terms
$$\sin(k^{-1/3})+\sin(k^{-1/3})-\sin(2k^{-1/3})$$
using the Taylor series expansion $\sin(x)=x-\frac{x^3}{3!}+O(x^5)$, we get
$$
2\cdot(k^{-1/3}-k^{-1}/3!+O(k^{-5/3})) -(2k^{-1/3}-8k^{-1}/3!+O(k^{-5/3}))$$
which simplifies to $-\frac{10}{3!}\cdot \frac{1}{k} + O(k^{-5/3})$.
This means that the partial sum $\sum_{n=1}^m \sin(a_n)$ for $m$ a multiple of $3$ equals $$-\frac{10}{3!}\sum_{n=1}^{m/3} \frac{1}{n}+\sum_{n=1}^{m/3}O(n^{-5/3}),$$ so as $m\to\infty$ the right sum converges (since it is absolutely convergent) and the left sum diverges (since it is a constant times the harmonic series). Therefore $\sum_{n=1}^{\infty} \sin(a_n)$ diverges.

Motivation for constructing this example

On first glance it seems reasonable to guess that it wouldn't be possible to construct such $a_n$, since $\sin x \sim x$ for $x\to 0$. This indeed shows that there can be no such $a_n$ with positive terms, as was mentioned in the question. However, when $a_n$ has alternating terms it is possible that we will get different kind of cancellations in $a_n$ and $\sin(a_n)$, because while $\sin(a_n)$ tends to $0$ "at the same rate" as $a_n$ does, these are of course not the exact same terms -- and so it is reasonable that we can construct a special $a_n$ such that the cancellations of $a_n$ and $\sin(a_n)$ would yield different results. This is my intuition for why it might be possible to construct such $a_n$.

In order to try and get different cancellations for $\sin(a_n)$ we use the Taylor series of $\sin x$. The idea is to try and get the linear terms to cancel out, and the $x^3$ terms not to cancel each other and to diverge, and the $x^5$ terms (and above) to converge. So other than the constants that will guarantee the cancellation of the linear terms, let's try $a_n$ which is roughly of the form $n^{-\alpha}$ but such that $3$ consecutive terms are equal (see why $3$ below) so we take $\lfloor n/3 \rfloor^{-\alpha}$. We need $n^{-3\alpha}$ to diverge and $n^{-5\alpha}$ to converge, that is, we want $3\alpha\leq 1$ and $5\alpha>1$ so any $\frac{1}{5}< \alpha\leq\frac{1}{3}$ will do, and we choose $\alpha=\frac{1}{3}$. Now in order to get the linear terms to cancel out we multiply $\lfloor n/3\rfloor ^{-1/3}$ by the constants $1,1,-2,1,1,-2,\ldots$. (The simpler choice of $1,-1,1,-1,\ldots$ and $\lfloor n/2 \rfloor$ would not work, because that would make the $x^3$ terms, and all subsequent terms, cancel out each other as well. This is clear without resort to Taylor series, $\sin x$ is an odd function, so for $a_n=(-1)^n\lfloor n/2 \rfloor^{-\alpha}$ we get that the terms of $\sin(a_n)$ cancel each other in pairs just the same way as the terms of $a_n$ do).

There is nothing special about $\sin(x)$, in the sense that for any non-linear $f(x)$ it is possible to find a convergent $\sum a_n$ such that $\sum f(a_n)$ diverges. See this question for details. I haven't read the answers yet but I believe the overall intuition should be the same-- that it is plausible that we can use non-linearity of $f(x)$ to get different cancellations for $\sum a_n$ and $\sum f(a_n)$.
Comment: Thanks for an example! But I don't know the motivation to construct it.
Comment: @bFur4list I tried adding some motivation, let me know if this makes sense. Notice that I fixed an error: the sequence should be $a_n=b_nc_n$ where $b_n=\lfloor n/3 \rfloor^{-1/3}$ as it is written now, and not $b_n=n^{-1/3}$ as it was previously written, because otherwise the calculation of the cancellation of the linear terms of $3$ consecutive terms of $\sin(a_n)$ would not be correct.
Comment: @bFur4list By the way, if you edit the question to mention that for an example you are looking not only for the formula but also for a motivation of how to construct it, then the question might get re-opened, because I don't think this is addressed in the other question which this question was marked a duplicate of. (If you do this then in your edit mark the box that says that it should be considered for re-opening.)


Bounded above/below infinite product of a group

Question: Let $G$ be a group. The set $$H =\left\{(g_i) \in \prod_{i \in \mathbb{Z}}G ~|~ \text{ there exists } N \in \mathbb{Z} \text{ such that } g_i = 0 \text{ for all } i \le N \right\}$$
is a subgroup of $\prod_{i \in \mathbb{Z}}G$. Does it have a name or standard notation?
Comment: That is not a subgroup of $G$. Observe, for example, that this group has the power of the continuum if $G$ is any finite non-trivial group.
Comment: @Pipicito Sorry, typo. I fixed it.
Comment: What about $\prod_{i\in\mathbb{N}}G\times \bigoplus_{i\in \mathbb{N}}G$ ?
Comment: It's vaguely reminiscent of cofiniteness I suppose.
Answer: This question turned out to be really simple. I am posting Dietrich Burde's observation in the comments as an answer.
There is a group isomorphism $f \colon H \to \prod_{n \in \mathbb{N}}G \times \bigoplus_{n \in \mathbb{N}}G$ given by $f(g_i)_{i \in \mathbb{Z}}= ((g_i)_{i \in \mathbb{N}},(g_{-1-i})_{i \in \mathbb{N}})$ for all $(g_i)_{i \in \mathbb{Z}} \in \prod_{i \in \mathbb{Z}}G$.


Expected value of die rolls - roll $n$, keep $1$

Question: I know how to calculate expected value for a single roll, and I read several other answers about expected value with rerolls, but how does the calculation change if you can make your reroll before choosing which die to keep?
For instance, what is the expected value of rolling $2$ fair $6$-sided dice and keeping the higher value?  And can you please generalize to $n$ $x$-sided dice?
Comment: If you wish to find distribution of $\max$ of $n$ i.i.d. random variables, then $P(\max\{X_1,..,X_n\}<x) = P(X_1<x,...,X_n<x)=$/*they are independent*/$=\prod_{i=1}^n P(X_i<x)=$/*probabilities are equal*/$=(P(X_1<x))^n$
Comment: The expectation of the sum without rerolling is (for $k$ $n-sided$ dices) : $\frac{k(n+1)}{2}$
Comment: @hcl14, thank you for the response.  Could you please show an example?  I don't understand some of the notation you are using.
Comment: @Catherine The notation means, that if you have maximum of a few variables be less or equal than some value, then every variable is less or equal than that value. That allows you to easily write the distribution function $F_{max}(x)=P(\max\{...\}\leq x)$ of the maximum as a product of distribution functions of the variables. Then expectation can be easily computed: as long as for one m-sided dice $P(X_1\leq x) = x/m$, then $F_{max}(x)=(x/m)^n$ and $P(\max \{..\}=x) = F_{max}(x)-F_{max}(x-1)$. $E[\max]=\sum_{x=1}^m x*P(\max \{..\}=x)$ which will lead to the result in Jason Carr's answer.
Answer: A start: Let $X$ be the "larger" number when you roll two fair $n$-sided dice. Then
$$\Pr(X=k)=\Pr(X\le k)-\Pr(X\le k-1).$$
But the probability that $X$ is $\le a$ is the probability both dice are $\le a$. This is $\frac{a^2}{n^2}$.
Remark: There are easier (and arguably better) ways to show that $\Pr(X\le k)=\frac{2k-1}{n^2}$. But the above trick is a useful one.
The same idea works for tossing $d$ $n$-sided dice. The probability that the maximum $X$ is $k$ is $\frac{k^d}{n^d}-\frac{(k-)^d}{n^d}$.
Answer: So to calculate this one in particular isn't all that difficult, but it's a special case of order statistics, that is, generating statistics about multiple events when they're ordered. You'd need to use that for the middle.
In this case where we take the one highest die, consider that to be less than or equal any given value, we must have both dice no greater than that value. So, it's the intersection of the probabilities that each individual die is no greater than than the value. If we have a cumulative distribution function for a die, then it describes the probability that the die will roll at most some value.
In the case of s-sided dice, we have that $P(X \le a) = \{\frac{a}{s}, a \in [1,s]\}$.
To find out what the intersection of multiple dice is, we take the intersection of their probabilities, so noting that that intersection of a number of distinct events is $\prod(P)$ we can get that our new $P(X \le a)$ is $\frac{a^n}{s^n}$ or similar equivalent expressions for the intersection of n s-sided dice
Now in order to get the expected value, we need to get the probability distribution function, that is $P(X = a)$. To do this we'll take the discrete difference. We can't really simplify this, so we'll just take $ P(X = a) = \frac{(a)^n}{s^n} - \frac{(a - 1)^n}{s^n}$ Then we can take the summation of each of these for all $a \in [1,s]$
Then the expected value is the sum $\sum_{a=1}^s{a({\frac{(a)^n}{s^n} - \frac{(a - 1)^n}{s^n})}}$
Answer: To start with two dices. You can make a table and insert the maximum values of the two dices.
$ \begin{array}{|c|c|c|c|c|c|}  \hline \text{dice 1 / dice 2 }  & 1 &2 &3 &4 &5 &6  \\ \hline\hline \hline 1 & &2 & &4 &5 & \\  \hline 2 & 2 &2 & &4 &&6  \\ \hline 3&3 &3 &3 &4 &5&6 \\ \hline 4 & & &&4&5&6  \\ \hline  5 &5 &5&5&5&5&  \\ \hline 6 &6&&&6&6&6  \\ \hline \end{array} $
I left out some values to leave some work to do for you.
The probability for each combination is $p_{ij}=\frac{1}{36}$
The expected value then is $E(x)=\sum_{i=1}^6\sum_{j=1}^6 p_{ij} \cdot max(x_i,x_j)$


distance between point and line Proof

Question: I want to proof that distance between point and line is equal to
.
So I have next system
,
first part is line formula, and second - formula of perpendicular line from point to this line.
Next we change first expression and get this
$$A (x – x_0) + B (y – y_0) + A x_0 + B y_0 + C = 0 \ .$$
And finally we get this
.
Can someone explain what calculation shall I do to get this expression
$$A (x – x_0) + B (y – y_0) + A x_0 + B y_0 + C = 0 \ .$$
Original source: http://www.mathelp.spb.ru/book1/line_on_plane.htm
Comment: Welcome to Math SE! Please see [here](http://meta.math.stackexchange.com/questions/5020/tex-latex-mathjax-basic-tutorial-and-quick-reference) for information about how to typeset your question. Generally image-based questions should be avoided.
Answer: We have Ax+ By+ C= 0.  Add and subtract $Ax_0$ and $By_0$:
$Ax+ By+ C+ Ax_0- Ax_0+ By_0- By_0= 0$.
$Ax-Ax_0+ By-By_0+ C+ Ax_0+ By_0= 0$
$A(x- x_0)+ B(y- y_0)+ C+ Ax_0+ By_0= 0$.

distance between point and line Proof


Encase a single or multiline search result PHP/regex

Question: I need to encase this string:

some text

in a table tag like this:

some text

it gets little more complicated as there could be one, two or three lines of code to be encased like this:

some text

more text

another line of text

I have given my best using PHP with following code, but it does not work :/
$doc contains string code of a html document, first I count number of lines which I need to generate needed regex, im not sure if $& can be used to say: this is what I need to encase..
$line_count=substr_count($doc, '
');

for($i=0;$i<$line_count;$i++)
{$add.='[^
]
';}

$regex='/
'.$add.'/';
$replace='

$&

';
$doc=preg_replace($regex, $replace, $doc);

Am I even close to solution?
Comment: `$&` does not work. Neither does `[^]` - that's still a character class, and not a negation. And the unescaped `/` in it will lead to an failure (at least enable `error_reporting` whenever something doesn't work).
Comment: Where does this table come from? Did you parse a document? Are you generating it?
Comment: What do you mean by encase? Are you trying to put the paragraph in the table, or are you trying to find it? What do you want to replace it with?
Comment: @mario: I have changed '[^]' to '[^<\/p>]<\/p>' now I dont have errors, but still nothing happens..
Comment: @didierc: i get document by reading htm file like this
$doc=fread($fh, filesize($myFile));
I am trying to find paragraphs with this same class and put it in one table. I was trying to find it with regex and open table tag before and close table after..
Answer: Try this code - it will pick up one or more  blocks of "someclass"
$doc = '

Jerky tri-tip pancetta t-bone beef, meatball meatloaf flank brisket beef ribs biltong short ribs capicola fatback.

Meatball short ribs venison leberkas shoulder meatloaf corned beef ham salami. Shank sirloin fatback flank pig spare ribs.

Cow hamburger leberkas drumstick jerky beef short loin tenderloin swine pork. Kielbasa short loin jerky salami.

';

$regex='/((
(?:(?!(<\/p>)).*?)<\/p>\s*)+)/is';
$replace='

$1

';
$doc=preg_replace($regex, $replace, $doc);

Some comments:
((\s*)+) - ()+ will make it match 1 or more, \s* ensures spacing will be ignored between  and next , external () is necessary to get all matched  blocks into $1 variable
/is - modifiers which make whole doc to be treated as a single string and ignore case. May be handy.
(?:(?!(
)).*?) - that's the main part - negative conditional match to ensure there is no  inside matched string
Comment: $regex='/(((?:(?!(<\/p>)).*?)<\/p>\s*)+)/is'; - needs another set of () to group them


$\cos^{-1}x+\cos^{-1}y=\cos^{-1}\Big(xy-\sqrt{1-x^2}\sqrt{1-y^2}\Big)$ true for all $x$?

Question:
$\cos^{-1}x+\cos^{-1}y=\cos^{-1}\Big(xy-\sqrt{1-x^2}\sqrt{1-y^2}\Big)$ true for all $x$ ?

My Attempt
Let $a=\cos^{-1}x$, $b=\cos^{-1}y\implies$$\cos a=x$, $\cos b=y$ and $a,b\in[0,\pi]\implies a+b\in[0,2\pi]$
$$
\cos(a+b)=\cos a\cos b-\sin a\sin b=xy-\sqrt{1-x^2}\sqrt{1-y^2}\\=\cos\bigg[\cos^{-1}\Big(xy-\sqrt{1-x^2}\sqrt{1-y^2}\Big)\bigg]\\
a+b=\color{red}{\cos^{-1}x+\cos^{-1}y=2n\pi\pm\cos^{-1}\Big(xy-\sqrt{1-x^2}\sqrt{1-y^2}\Big)}
$$
Case 1: $a+b\in[0,\pi)$
$$
\cos^{-1}x+\cos^{-1}y=\cos^{-1}\Big(xy-\sqrt{1-x^2}\sqrt{1-y^2}\Big)
$$
Case 2: $a+b\in[\pi,2\pi]$
$$
\cos^{-1}x+\cos^{-1}y=2\pi-\cos^{-1}\Big(xy-\sqrt{1-x^2}\sqrt{1-y^2}\Big)
$$
Case 1-: $a+b\in[0,\pi)$
Note I have checked a possible solution to this in link, but it gives a different expression differ from my attempt.
Comment: See https://math.stackexchange.com/questions/3027787/expression-for-cos-1x-pm-cos-1y
Comment: @labbhattacharjee thanx. but the given post does not say anything about all cases for the expression nor the domain of $x,y$ for which the given expression is valid !. I hardly find any post on the complete expression for $\cos^{-1}x+\cos^{-1}y$ on internet.
Comment: For $x=y=-1$, the LHS is $2\pi$, the RHS is $0$.
Comment: @Andrei For $x=y=-1\implies a=b=\pi$. RHS=$2\pi-\cos^{-1}1=2\pi=LHS$, it is **case 2**. srry abt that, just edited the domain.
Comment: @labbhattacharjee could you please comment on my attempt ?
Answer: Using Principal values and  Why it's true? $\arcsin(x) +\arccos(x) = \frac{\pi}{2}$,
$\cos^{-1}x+\cos^{-1}y\le2\pi$
$$\cos^{-1}x+\cos^{-1}y=\cos^{-1}(xy-\sqrt{(1-x^2)(1-y^2)})$$
will hold true if $\cos^{-1}x+\cos^{-1}y\le\pi$
$\iff\sin^{-1}x+\sin^{-1}y\ge0\iff\sin^{-1}x\ge-\sin^{-1}y=\sin^{-1}(-y)$
$\iff x\ge -y\iff x+y\ge0$
$$\cos^{-1}x+\cos^{-1}y=2\pi-\cos^{-1}(xy-\sqrt{(1-x^2)(1-y^2)})$$
will hold true if $\cos^{-1}x+\cos^{-1}y>\pi$
$\iff\sin^{-1}x+\sin^{-1}y<0\iff x+y<0$
Comment: @ss1729, First replace $y$ with $-z$ in the identity derived in the answer. Then use https://math.stackexchange.com/questions/1224415/how-do-i-prove-that-arccosx-arccos-x-pi-when-x-in-1-1
Comment: Thanks. I just have one more query. Could u please confirm that,
$\cos^{-1}x-\cos^{-1}y=\begin{cases}\cos^{-1}\bigg(xy+\sqrt{1-x^2}\sqrt{1-y^2}\bigg),\;x-y\leq 0\\ -2\pi+\cos^{-1}\bigg(xy+\sqrt{1-x^2}\sqrt{1-y^2}\bigg),\;x-y> 0\end{cases}$


what is the angle here in this cyclic triangle?

Question:
If I join the chord then I am getting the angles of the triangle are $45,45,90$ so $\theta=180-2x$ where $x$ is the angle of the other triangle whose angle is $\theta$
Comment: Hint: Inscribed Angle Theorem. (It may help to draw the full circle.)
Comment: The central angle is twice the inscribed angle.  http://en.wikipedia.org/wiki/Inscribed_angle#Theorem
Answer: If you draw a line from the center of the circle to your angle, you get 2 isoscele triangles, so your angle is the sum of those 2 other angles in this quadrangle. the sum of all angles of quadrangle is $$360^{\circ}$$ so your angle is $$\frac{360^{\circ}-90^{\circ}}{2} = 135^{\circ}$$
Explanation:

$$AD = AB = AC$$
$$\angle{ADB} = \angle{ABD} ; \angle{ADC} = \angle{ACD}$$
$$\angle{BDC} = \angle{ADB} + \angle{ADC} = \angle{ABD} + \angle{ACD}$$
$$\angle{BAC} + \angle{ABD} + \angle{BDC} + \angle{ACD} = 360^{\circ}$$
$$90^{\circ} + 2\angle{BDC} = 360^{\circ}$$
$$\angle{BDC} = \frac{360^{\circ}-90^{\circ}}{2} = 135^{\circ}$$
Answer: Draw the rest of circle (complete the circle),
<code>Inscribed Angle =(1/2)Intercepted Arc
</code>

$$m(\widehat{CDB})=\frac{1}{2}m( \stackrel \frown{CEB})$$
$$m(\widehat{CDB})=\frac{1}{2}270^{o}=135^{o}$$


Stepwise bass movement/intermediate (passing) harmony technique

Question: A song I like adds great motion to an otherwise simple progression by adding passing tones in the bass line, leaving the other harmonies unaltered.  Please see the following transcription:

Does this pattern only work in certain progressions? Notice the movement never jumps more than one whole step — is that an important aspect of this bass line?  If the bass was more disjointed, or if the accompanying chords harmonized with the bass tone (rather than remaining static), would the progression lose its flow and become uncoordinated?
Does this technique have a name?  My primary question is whether this technique applies better to some progressions than others.
Comment: As Max says, they're passing tones. ('Passing notes' in UK). It's extremely common. If the bass notes were G A F instead of F G A, the G would be an 'accented passing tone'. As it is it's an unaccented one. "Does this technique have a name?" It's not a technique. Pop/rock/folk singers do it all the time, it's omnipresent in Common Practice music and it's what a walking bass does all day long. There's a good article about non-harmonic notes [here](https://en.wikipedia.org/wiki/Nonchord_tone#Escape_tone) Yes - it adds some movement. Music with only chord-tones in the bass would be a bit dull.
Comment: @286642 Your kind comment is ample reward :-)
Comment: I think a thorough analysis of this passage will depend on the genre and tempo. If it's fast, I would think of those bass notes as passing tones, but if it's slow, you could argue for analyzing them as slash chords. Perhaps you could provide more contextual information about the song in question. As for whether you can use this device over other chords, the laconic answer is, "Try and see."
Comment: Thanks.  Gentle rock song--approx 120 bpm.  Looking for a theory rather than "try and see" here.  If theory has nothing to say, then that's cool too.
Comment: Thank you @OldBrixtonian -- I'd like to accept your response as the answer but it is a comment, so I dont think I can right now?
Answer: The question suggests a viewpoint in which the chords are the "main" thing, with the bass line in a purely supporting role. But consider the bass line as "the melody" (or a melody, anyway). A vocalist singing what is currently the bass line wouldn't raise any eyebrows: it would just be a melody accompanied by chords. Those roles just happen to be flipped here insofar as we tend to think of melodies as being above their accompaniment.
If the bass was more disjointed, or if the accompanying chords harmonized with the bass tone (rather than remaining static), would the progression lose its flow and become uncoordinated?
Thinking of the bass line as the melody leads to the recognition that a more disjointed bass line, or a bass line harmonized even more closely by the chords, can maintain (or lose) its flow and harmonic coordination in the same manner as any melody can.
Does this technique have a name?

This is a straightforward example of a "walking" bass line — mostly movement by step, connecting chord tones. (See Old Brixtonian's comment on the OP.)
It also has characteristics of a sequence: the bass always uses scale degrees 1, 2, and 3 of the corresponding chord; however, it's not a true sequence in that the transpositions are not of equal intervals. (That is, the second measure is up a step from the first, but the third measure is up a fourth from the second. In a true sequence, each measure would be shifted by the same intervals.)

My primary question is whether this technique applies better to some progressions than others.
There's nothing particularly special about the chord progression itself. One can construct a walking bass line (or independent melody) for most any chord progression, even maintaining the same basic pattern as in the OP, though adjustments to rhythm or note-direction might facilitate the greatest smoothness.

A beautiful example of the interchangeability of bass line and melody is in John Coltrane's A Love Supreme. The bass establishes itself early on (0:31).

But the final minute-plus of Coltrane's solo (4:55 – 6:05) is the continual repetition of that initial bass part, played at various pitch levels, sometimes complimented by the piano chords, sometimes contrasting sharply, yet maintaining cohesiveness throughout. This is immediately followed by another 45 seconds of voice and bass in unison with the same melody, bringing the entire piece full circle.


How to customise UITabBar text label?

Question: does anybody know how to use the Appearance proxy object
[[UITabBar appearance] set....];

to customise the color,font and shadow for the selected/unselected label of an UITabBar?
thanks a lot.
Answer: By accessing the tab-bar item object of the UITabBar for each UIViewController
This only works for iOS5.0 or later.
if ([self.tabBarItem respondsToSelector:@selector(setTitleTextAttributes:)]) {
    NSLog(@"*** Support method(iOS 5): setTitleTextAttributes:");
    [self.tabBarItem setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:
                                                [UIFont fontWithName:@"AmericanTypewriter" size:20.0f], UITextAttributeFont,
                                                [UIColor blackColor], UITextAttributeTextColor,
                                                [UIColor grayColor], UITextAttributeTextShadowColor,
                                                [NSValue valueWithUIOffset:UIOffsetMake(0.0f, 1.0f)], UITextAttributeTextShadowOffset,
                                                nil]];
}

Below 5 https://github.com/boctor/idev-recipes/tree/master/CustomTabBar

How to customise UITabBar text label?


Making an interactive blender tool to pick vertex pairs from two seperate objects

Question: I want to build a tool which can let me open two objects in blender and associate every vertex in one object to another vertex in the other objects forming vertex pairs and later write the related indices to a file.
Is there any way i can do this with blender python scripting?
Answer: You may find the MultiEdit addon of interest. This addon "merges" multiple meshes to allow editing them at the same time and then replaces the object meshes when you finish.
You may also find CGCookies retopoflow inspirational as well. You can view the retopoflow code on github. I haven't looked through the code but it appears they use the bgl module to draw custom controls over the mesh. In a similar fashion you could read object.data.mesh.vertices and draw points over both objects that the user could pair up.


How do I implement hook_views_pre_render()?

Question: I need to alter the result of a view. I read I can use hook_views_pre_render(), but in a custom module. I don't have any custom module implemented and I would like to know where and how should I put the code in my project.
Comment: Nope, @clive, I even looked it up to make sure that it does (comment:  `// Let the themes play too, because pre render is a very themey thing.`) in Views' `includes/view.inc`
Comment: See [Module developer's guide](https://drupal.org/developing/modules).
Comment: Quite welcome.  Interestingly enough, there is no `theme_implements()` so this doesn't even need a cache clear to be picked up. Not that I just threw together a quick "hello world" `bartik_views_pre_render()` to be doubly certain or anything...
Comment: You can also put this in a theme, so, if you are already doing custom work there, and don't "need" a custom module, it can be added to this theme's template.php or other appropriate php file.  Realize, of course, that this pre_rendering would only apply when this theme is active.
Comment: @Jimajamma I'm pretty sure this hook doesn't get called for themes - are you thinking of `_alter` hooks or have I got it wrong?
Answer: You need to read and understand the Module developer's guide first, then it's as simple as adding the following to your .module file:
function MYMODULE_views_pre_render(&$view) {
  // Do stuff with the $view object.
}

Comment: Also if you are really going to get into developing custom modules (which I found pretty useful pretty early on in my Drupal experience) I found the book [Pro Drupal 7 Development](http://www.drupalbook.com/code-drupal-like-a-pro) very helpful.

It not only explains how to set up your own modules, more importantly for me it gives you an overview of the drupal workflow so you can get an idea of how and where the hook function are being called.
Answer: Views hooks should be implemented in a .views.inc files not in .module file


if $p_L=\sum_{i=1}^{L}|a_i|\cdot \sum_{j=1}^{L} |b_j|$ is a Cauchy sequence then $\sum_{i\text{ or }j>L}|a_i|\cdot |b_j|<\varepsilon$

Question: I don't understand how inequality $(1)$ is derived in the following proof (where $\{a_n\}$ and $\{b_n\}$ are assumed to converge absolutely).

PROOF
Notice that the sequence
$$p_L=\sum_{i=1}^{L}|a_i|\cdot \sum_{j=1}^{L} |b_j|$$
converges, since $\{a_n\}$ and $\{b_n\}$ are absolutely convergent, and since the limt of a product is the product of the limits. So $\{p_L\}$ is a Cauchy sequence, which means that for any $\varepsilon>0$, if $L$ and $L'$ are large enough, then
$$\left| \sum_{i=1}^{L'}|a_i|\cdot \sum_{j=1}^{L'} |b_j|-\sum_{i=1}^{L}|a_i|\cdot \sum_{j=1}^{L} |b_j|\right|<\frac{\varepsilon}{2}.$$
It follow that
$$\sum_{i\text{ or }j>L}|a_i|\cdot |b_j|\leq\frac{\varepsilon}{2}<\varepsilon. \tag{1}$$
$[\dots]$

(Calculus 3rd edition, Michael Spivak. Theorem 23-9, PROOF.)
I must be missing something very simple but can't seem to understand how $(1)$ follows from what came before it.
Answer: WLOG assume $L' > L$. Writing as a double sum and splitting into four blocks,
$$\sum_{i=1}^{L'}|a_i| \sum_{j=1}^{L'}|b_j|= \sum_{i=1}^{L'}\sum_{j=1}^{L'}|a_i||b_j| \\=  \sum_{i=1}^{L}\sum_{j=1}^{L}|a_i||b_j|+ \sum_{i=1}^{L}\sum_{j=L+1}^{L'}|a_i||b_j|+ \sum_{i=L+1}^{L'}\sum_{j=1}^{L}|a_i||b_j|+ \sum_{i=L+1}^{L'}\sum_{j=L+1}^{L'}|a_i||b_j|, $$
Hence,
$$\sum_{i=1}^{L'}|a_i| \sum_{j=1}^{L'}|b_j|- \sum_{i=1}^{L}|a_i| \sum_{j=1}^{L}|b_j|\\ =  \underbrace{\sum_{i=1}^{L}\sum_{j=L+1}^{L'}|a_i||b_j|+ \sum_{i=L+1}^{L'}\sum_{j=1}^{L}|a_i||b_j|+ \sum_{i=L+1}^{L'}\sum_{j=L+1}^{L'}|a_i||b_j|}_{i \text{ or }j > L}$$
Comment: If you make a drawing of an $L' \times L'$ matrix with elements $|a_i||b_j|$ and partition into four blocks it should be very clear.


Every right $R$-module is finitely cogenerated module.

Question: Let $R$ be a ring such that every right $R$-module is simple or decomposable module.
Is it true that every right $R$-module is finitely cogenerated module?
Thanks for any help.
Answer: There are no (ordinary) rings whose modules are all finitely cogenerated. Every nontrivial ring with identity has a simple module, and an infinite direct sum of copies of that module is not finitely cogenerated.
If you restrict to say finitely generated modules are finitely cogenerated, then that would imply the ring is right Artinian. I'm led to believe you know of a non right Artinian ring with the module properties you speak of.
Comment: Thank you very much for your help. @rschwieb I am thinking about the ring with this property (i.e. every right $R$-module is simple or decompasable), and I think that $R$ can be right semiartinian ring (i.e. every right $R$-module contains a simple submodule). What do you think of that?
Comment: @Mf.math Earlier it sounded like you knew of such an example, and I am guessing it is not right Artinian, but I don't know. If the paper you read has it, I'd be interested in seeing it.
Comment: I don't have a paper explains a ring with this property, but I try to discuss such a ring.
Comment: @Mf.math YOu may as well just formulate a question and post it.


Minimum set of features that can distinguish all objects

Question: My input is a set of objects having different values with respect to a set of features (F1, F2, F3, F4, F5). The output should be a set of minimal features allowing to distinguish all these objects or if not possible, the features that distinguishes most of these objects.
For example F1 distinguishes objects 4 (value of 2) and 5 (value of 11) from the rest of objects. We need to distinguish obj1, obj2 and obj3. F2 distinguishes Obj2 (value of 4) from the obj1 (value of 6) and Obj3 (value of 6). After combining both features F1 and F2, we can distinguish obj4, obj 5, obj4. I need an additional feature that allows to distinguish obj1 from obj3. F4 would do the job, since obj1 (value of 9) and obj 3 (value of 10). Our set allowing to distinguish all objects is then F1, F2, F4. Note that F6 is useless since it does not help distinguish our objects.
Is there a way to obtain this set of features that allows to distinguish all objects, knowing that I have more than 500 features and more than 500 objects.
Thanks.
Comment: Clarification: Given a set of distincts objets (Obj1, Obj2, ...etc.), each has a certain number of characteristics (F1, F2, ...etc). I would like to know what is the subset of features (minimal subset) that allows to distinguish all objects from each other. For the example above F1+F2+F4 allows to distinguish obj1 (F1=1, F2=6, F4=9) from Obj2 (F1=1, F2=4, F4=10), from obj3 (F1=1, F2=6, F4=10), from obj4 (F2=1, F6=6, F4=9). This set may not be unique. Ideally, the output would be a set of subsets with a score for each telling the percentage of distinguished objects.
Answer: You can try to fit a decision tree on your data with 'Objects' being your response variable. There are some different decision tree algorithms that you can try out. You can do this by hand or using software such as R (rpart library).
Comment: Nice approach, but this does only work in case all variables have only two levels (as in the above example), otherwise the set of variables used for splits may be sub-optimal.
Comment: The feature values can take any value, not just two values as in the example above.


Xcode quit unexpectedly in interface builder

Question: I started a new project in Xcode (Cocoa App OSX, Objective-C). Every time I try to add a button to a window in Interface Builder(drag and drop) I receive the following error and Xcode quits.
"UNCAUGHT EXCEPTION (NSUnknownKeyException): [ valueForUndefinedKey:]: this class is not key value coding-compliant for the key springLoaded."
Xcode Version 6.3 (6D570) on Yosemite 10.10.3
Anyone experienced such behavior?
part of the crash:
<code>Crashed Thread:        0  Dispatch queue: com.apple.main-thread

Exception Type:        EXC_CRASH (SIGABRT)
Exception Codes:       0x0000000000000000, 0x0000000000000000

Application Specific Information:
ProductBuildVersion: 6D570
UNCAUGHT EXCEPTION (NSUnknownKeyException): [<NSButton 0x7fb46e18f090> valueForUndefinedKey:]: this class is not key value coding-compliant for the key springLoaded.
UserInfo: {
    NSTargetObjectUserInfoKey = "<NSButton: 0x7fb46e18f090>";
    NSUnknownUserInfoKey = springLoaded;
}
Hints: None
Backtrace:
  0  0x00007fff90a4c4f4 __exceptionPreprocess (in CoreFoundation)
  1  0x00000001050ee184 DVTFailureHintExceptionPreprocessor (in DVTFoundation)
  2  0x00007fff90d1976e objc_exception_throw (in libobjc.A.dylib)
  3  0x00007fff90a4c0a9 -[NSException raise] (in CoreFoundation)
  4  0x00007fff8dc77d25 -[NSObject(NSKeyValueCoding) valueForUndefinedKey:] (in Foundation)
  5  0x00007fff8db4cccb -[NSObject(NSKeyValueCoding) valueForKey:] (in Foundation)
</code>
Update:
Xcode now somehow survived the button add but when I try to save I get this Alert:
Unfortunately this happens with Xcode 6.3.1
Answer: Finally I got an answer from apple devforums.
The reason for this is that I use OSX seed build OS X 10.10.3 (14D87h).

This is new API related to Force Touch trackpads. It was added in OS X
  10.10.3, but only in seed builds


Solve this PDE $xu_x+yu_y+xyu_z=0,u(x,y,0)=x^2+y^2$ (problem with general solution)

Question: Find the particular solution of the partia differential equation $$
xu_x+yu_y+xyu_z=0
$$
that satisfies the Cauchy condition
$$
u(x,y,0)=x^{2}+y^{2}
$$
So:
$$
\frac {dx}{x}=\frac {dy}{y} = \frac{dz}{xy}
$$
which in turn implies
$$
\begin{split}
\int \frac{dx}{x} =\int \frac{dy}{y} &\implies \ln(x)=\ln(C_1y) \\
& \implies C_1=\frac{x}{y} \vee \int \frac{dx}{x}=\int \frac{dy}{y} \\
&\implies \ln(C_1x)=y \Rightarrow C_1=\frac{y}{x}
\end{split}
$$
Now I have a problem: I could proceed by using two different approaches

I don't know if this is a good approach:
$$
\frac{dz}{xy}=\frac{dx+dy}{x+y} \implies \int dz=\int \frac{xy}{x+y} d(x+y)$$
and what is the solution of the integral on the right side $\to$ Is it possible to integrate over $d(x+y$) on Wolfram Alpha?
Moreover is it true that
$$\int \frac{xy}{x+y} d(x+y) \iff \int \frac{xy}{x+y} dx + \frac{xy}{x+y} dy$$ or not?

Maybe this second approach works better $\to$ but I don't know if it's possible:
$$
\begin{split}
\frac{dz}{xy}=\frac{dx\cdot dy}{x\cdot y} & \implies\int{dz}=\int{\left(\int{1\,dx}\right)dy} \\
& \implies z=xy+C_2y+C_3 \\
& \implies C_3=z-xy-C_2y
\end{split}
$$
So it's a problem with two constants and Wolfram Alpha gives this general solution for the query x*D[u[x,y,z],x]+y*D[u[x,y,z],y]+x*y*D[u[x,y,z],z]=0 $$
\implies u(x,y,z)=F\left(\frac{y}{x},z-\frac{xy}{2}\right)
$$
so from Wolfram integration the result would be like $z=\frac{xy}{2}+C_{2}$

Maybe I should use approach 1, but how to calculate this integral? I know that
$$
\int \frac{d(x+y)}{x+y}=\ln(x+y)+\ln(C_2),
$$ but I have $xy$ in numerator $\implies \int \frac{xy}{x+y} d(x+y)$.
I think there could be even a third approach:

I can write
$$
\begin{split}
\frac{dz}{xy}=\frac{dx}{x}+\frac{dy}{y} & \implies \int(dz)=\int(y dx)+\int(x dy) \\
& \implies z=2xy+C_2 \\
& \implies C_{2}=z-2xy
\end{split}
$$
But it doesn't agree with the Wolfram Alpha solution and I don't think it's mathematically correct to do so.

Please help me.
Comment: In cylindrical coordinates the equation reduces to $$u_r+\frac{r\sin 2\theta}{2}\cdot u_z = 0$$
Comment: Hint: $$\frac{dz}{xy}=\frac{ydx+xdy}{2xy}=\frac{d(xy)}{2xy}$$
Comment: $u(x,y,z)=(y/x+x/y)(-2z+xy)$
Comment: where I make mistake? can you write step by step your method to get this particular solution?
Comment: To identify the function $F$, you need to have $F(x',y')$ expressed in terms of $x',y'$ alone. But $F(x',y')=(y/x')^2+(-2y'/x)^2$ still includes $x$ and $y$, so these need to be fully eliminated using $(x',y')=(y/x,-xy/2)$.
Comment: We use only this method on class/study (what it's in topic).
Comment: Ok, so $$\int(dz)=\frac{1}{2} \int d(xy) \Rightarrow z-\frac{xy}{2}=C_{2} $$

General Solution $$u(x,y,z)=F(\frac{y}{x},z-\frac{xy}{2})$$

Particular solution $u(x,y,0)=x^{2}+y^{2}$: $$F(\frac{y}{x},-\frac{xy}{2}) \Rightarrow x'=\frac{y}{x},y'=-\frac{xy}{2} \Rightarrow F(x',y')=(\frac{y}{x'})^{2}+(-\frac{2y'}{x})^{2}$$

So:
$$u(x,y,z)=(\frac{y}{\frac{y}{x}})^{2}+(\frac{-2*(z-\frac{xy}{2})}{x})^{2}=x^{2}+(\frac{-2z+xy}{x})^{2}$$
Comment: Ehh i don't know how replace "y" and "x" in your equation, when I want use my early substition $x'=\frac{y}{x} \Rightarrow y=x'x$ and $y'=-\frac{xy}{2} \Rightarrow x=-\frac{2y'}{y}$ I will get x,y regardless of whether I put it in 1 or 2 -> how to deal with this? I think that $$x'y'=\frac{y}{x} \cdot \frac{-xy}{2} = \frac{-y^{2}}{2} \Rightarrow -2x'y'=y^{2}$$ but what now with $x^{2}$?
Answer: The method of characteristics gives the following ODEs:
\begin{eqnarray}
x'(t)&=x,\\
y'(t)&=y,\\
z'(t)&=xy,\\
u'(t)&=0
\end{eqnarray}
The first two ODEs solve to $x(t)=x_0 e^t$, $y(t)=y_0 e^t$ where $x_0=x(0),y_0(0)$. Therefore the third solves as $$z'(t)=x_0 y_0 e^{2t}\implies \frac12 x_0 y_0(e^{2t}-1)$$
where I have taken $z(0)=0$ for future convenience. The last ODE then yields $$u(x,y,z)=u(x_0,y_0,0)=x_0^2+y_0^2=e^{-2t}(x^2+y^2)$$
It remains to eliminate the $t$-dependence in favor of $x,y,z$. But from the above work we have $$z=\frac12 x_0 y_0 (e^{2t}-1)=\frac12 xy (1-e^{-2t}),$$ so $e^{-2t}=-2z/(x y)$. Hence
$$u(x,y,z)=\left(1-\frac{2z}{xy}\right)(x^2+y^2)=(x y-2z)\left(\frac xy+\frac yx\right).$$
Answer: The Lagrange-Charpit equations for the PDE $xu_x+yu_y+xyu_z=0$ are given by
$$
\frac {dx}{x}=\frac {dy}{y} = \frac{dz}{xy}=\frac{du}{0}, \tag{1}
$$
the last expression meaning that $u=C_1$. The equation $\frac{dx}{x}=\frac{dy}{y}$ implies $y=C_2x$. Another independent equation is given by $\frac{dz}{xy}=\frac{ydx+xdy}{2xy}=\frac{d(xy)}{2xy}$, which has as solution $z=\frac{1}{2}xy+C_3$. Combining these three solutions we obtain
$$
u(x,y,z)=F(C_2,C_3)=F\left(\frac{y}{x},z-\frac{1}{2}xy\right). \tag{2}
$$
The function $F$ is determined by the condition $u(x,y,0)=x^2+y^2$, which implies
$$
F\left(\frac{y}{x},-\frac{1}{2}xy\right)=x^2+y^2. \tag{3}
$$
Let $\frac{y}{x}=t$ and $-\frac{1}{2}xy=s$; then
$$
ts=\frac{y}{x}\left(-\frac{1}{2}xy\right)=-\frac{1}{2}y^2 \implies y^2=-2ts \tag{4}
$$
and
$$
\frac{t}{s}=\frac{y}{x}\left(-\frac{2}{xy}\right)=-\frac{2}{x^2}
\implies x^2=-\frac{2s}{t}. \tag{5}
$$
Equations $(3)$-$(5)$ imply $F(t,s)=-2s\left(t+\frac{1}{t}\right).$ Combining this result with Eq. $(2)$ we finally obtain
$$
u(x,y,z)=(-2z+xy)\left(\frac{y}{x}+\frac{x}{y}\right). \tag{6}
$$
Comment: Can you explain me how we get $$\frac{dz}{xy}=\frac{ydx+xdy}{2xy}$$ How we received 2xy in denominator?
Comment: And I don't know why/how $ydx+xdy=d(xy)$, we have this equation in class $2xdx+2ydy+2zdz=0 \Rightarrow $d(x^{2}+y^{2}+z^{2})=0$ and I don't know why either?
Comment: Ok product rule -> $ydx+xdy=d(xy)$, but how rule for this (what we get in class) -> $2xdx+2ydy+2zdz=0 \Rightarrow d(x^{2}+y^{2}+z^{2})$ I'm more concerned about this that $dx^{2}$ means $\int dx^{2} = 2x \cdot dx$ we shouldn't write it like that $d^{2}x = 2x dx$?
Comment: So using the "identity" and after product rule for this -> $$\frac{dx}{y}=-\frac{dy}{x}=\frac{du}{2xy}$$ I can write $$\frac{du}{2xy}=\frac{xdx+ydy}{xy-xy}=\frac{xdx+ydy}{0}$$ So $xdx+ydy=0$ product rule implies $\frac{dx^{2}}{2}=\frac{d(xx)}{2}=\frac{xdx+xdx}{2}=xdx$ and similarly for $ydy$ so $$xdx+ydy=0 \Rightarrow \frac{d(x^{2}+y^{2})}{2}=0 \Rightarrow C=\frac{1}{2}(x^{2}+y^{2})$$ it is correct?


LDA cutoff (decision boundary) value

Question: I have run a linear discriminant analysis for the simple 2 categorical group case using the MASS package lda() function in R. With priors fixed at 0.5 and unequal n for the response variable of each group, the output basically provides the group means and the LD1 (first linear discriminant coefficient) value. There is no automatic output of the cutoff (decision boundary) value estimated that is later used to classify new values of the response variable into the different groups. I have tried various unsuccessful approaches to extract this value. It is obvious that in the simple 2 group case the value will be close to the mean of the 2 group means and that the LD1  value is involved (perhaps grand mean * LD1?). I am probably missing (misunderstanding?) the obvious and would appreciate being educated in this matter. Thanks. Regards,BJ
Comment: Please explain what is "LD1 value" in MASS output
Comment: LD1 is the first linear discriminant coefficient
Comment: If the OP could explain precisely what LD1 is, there would probably not be a question. As I see it, you are not supposed to use the components of an `lda`-object from an `lda`-call directly, but rather use the `plot` or the `predict` methods implemented for these objects. That does not mean that it is not interesting to figure out what the components are, and I have tried to give some explanation and further references in my answer.
Answer: In the 2-group situation, the cut-off value of the discriminant function scores is simply the mean of the means of the scores for the groups (those means are also called "function's values at group centroids"). Say, if for group 1 the mean score is -.742 and for group 2 it is .576, then the cut-value for classifying is their average, -.083. This is true when prior probabilities are set to .5 and when discriminant function scores used aren't normalized in some way).
Note that my answer is "general": I'm not R-user and don't know how it is all in MASS.
Comment: Thanks for confirming part of my understanding. The MASS lda function uses normalized scores.  In this simplest of cases, is there a hand-calculation way to adjust the groups grand mean (weighted by different n) for the within-groups covariance matrix? I will look for such a formula.
Comment: The above classification rule very arbitrarily assumes a cost/utility/loss function that may not be applicable.  Surely the fact that the loss is assumed to be constant over subjects is suspect.  You can get posterior probabilities from LDA but logistic regression is more robust as it does not assume a distribution for the Xs whereas LDA assumes multivariate normality.
Answer: The LD-vectors, which are in the scaling entry of the list returned by ldain R, are not so easily comprehended. The help page says that scaling is
      a matrix which transforms observations to discriminant
      functions, normalized so that within groups covariance matrix
      is spherical.

which is not super informative. Inner products with these vectors give the coefficients for a projection to a $K-1$ dimensional space (with $K$ groups, that is, a one-dimensional space if there are two groups). Everything is centered using the total mean of the predictors before projection. In this projection, classification happens to the group with the nearest mean, as measured by the usual euclidean distance, if the prior probabilities are equal. Perhaps the best thing to do to understand precisely how the computation of the predictions work is to read the R-code in MASS:::predict.lda. The MASS book by Ripley and Venables may also be useful, but I find that Chapter 3 in Ripley's other book Pattern Recognition and Neural Networks is more complete. Here you will find the complete explanation behind the computations implemented in the R function lda, and a more detailed description of what the projection actually is.
For the two group case things simplify, the LD1 vector is then proportional to $\hat{\Sigma}^{-1}(\hat{\mu}_2 - \hat{\mu}_1)$, and the linear discriminator is given by taking inner product with LD1. In the case of equal prior probabilities on the two groups you don't need to know the constant of proportionality and the cutoff is $\frac{1}{2}(\hat{\mu}_2 + \hat{\mu}_1)^T\text{LD1}$. With unequal priors it seems to me that you need to know the constant of proportionality to compute the cutoff in this formulation. In the alternative, and this is essentially what MASS:::predict.lda does, you can for a given $x$ compute the inner products $c = x^T \text{LD1}$ and $c_i = \hat{\mu}_i^T \text{LD1}$ for $i=1,2$ and then
$$d_i = \frac{1}{2}(c - c_i)^2 - \log \pi_i.$$
Finally, you classify to the group with the smallest $d_i$.
Comment: Thanks for the references.  In the simple 2 categorical group case that I am concerned with I had hoped that the lda function in R would allow easy extraction of the discriminant function threshold value that is calculated and used in the classification process applied to new data.  Apparently it is not directly available.  I have done the discrimination and classification steps on my data. I need the decision boundary value (in this simple case, a single value) for another purpose and general interest. In this simple case, if lda() does not provide it, how can I calculate it by hand?
Comment: @BJessop, I have tried to provide a more detailed explanation for the two group case.

LDA cutoff (decision boundary) value


When does a torsion $\mathbb{Z}_p$-module have unique maximal submodule?

Question: Consider the ring of $p$-adic integers $\mathbb{Z}_p$.
Let $M$ be a $\mathbb{Z}_p$-module with cardinality powers of $p$ and consisting of $p^n$-torsion points for some $n \in \mathbb{N}$.
In other words, for any $m \in M$, we get $p^n \cdot m=0$.

I want to know when $M$ can be cyclic $\mathbb{Z}_p$-module ?

Since $M$ is finitely generated, it would be cyclic if we show $M$ has an unique maximal submodule.

Let us arrange the elements of $M$ with an indexing $\{m_1,m_2,\cdots, m_i, \cdots \}$ in the sense that $m_i$ has order $p^i$.

If we assume $pm_i=m_{i+1}$, then I think $M=\left\langle m_1 \right\rangle$. In that case $M$ is cyclic.

Do we have other way to show that $M$ is cyclic or $M$ has unique submodule which is maximal ?
Thanks
Comment: Is it clear to you that the only (up to isomorphism) cyclic $\mathbb Z_p$-modules are $\mathbb Z_p$ itself and all $\mathbb Z/p^k$? Is it not obvious which ones of these have $p^n$-torsion? -- Or alternatively, you are aware of the structure of finitely generated torsion modules over a PID?
Comment: Also, I do not understand how your "arranging" of the elements of $M$ is supposed to work. In general, a nonzero module will contain more than one element of a given order, so we cannot have $pm_i = m_{i+1}$ for all $i$ and at the same time assume that the set of all $m_i$ exhausts $M$.
Comment: @TorstenSchoeneberg, I am assuming $pm_i=m_{i+1}$.
Comment: I can read that. But as I said, then we cannot have $M = \{m_1, m_2, ... \}$ except in trivial cases. --- I really do not know what you are asking for. A module is cyclic if it is cyclic, there are a few equivalent definitions of that. As said in my first comment, in the case at hand the cyclic modules are known as explicitly as one could hope for, certainly more explicit than "assuming" some kind of ordering. Are you given some module via some definition which does not make it immediately clear whether it is one from the list in my first comment? Then you should say how it *is* given.
Comment: @TorstenSchoeneberg, yes I assuming too much.  I understand $M$ is cyclic iff $M \cong \mathbb{Z}_p$.  But can you please explain your 1st comment where you said $M$ is isomorphic all $\mathbb{Z}/p^k$ ?
Comment: @TorstenSchoeneberg, when I said "arrange", I don't mean a sequence. I wrote this for simplicity. Indeed, there are more than one element of exact order $p$ or $p^2$, so on. I am representing all $p$-torsion points by $m_1$, all $p^2$-torsion points by $m_2$, so on.  But it seems the answer can not be true in general even if the number of $m_i$'s  are equal to that of $m_{i+1}$'s.
Answer: As said in coments, it is not clear what exactly you are asking. Maybe the following reminder helps:
For a unital commutative ring $R$, every cyclic $R$-module is isomorphic to $R/I$ for some ideal $I$ of $R$.
The only ideals of $\mathbb Z_p$ are $(0)$ and all $(p^n)$ for $n \in \{0,1,2,...\}$.
Hence up to isomorphism, the only cyclic $\mathbb Z_p$-modules are $\mathbb Z_p$ itself and $\mathbb Z_p/(p^n)$ for $n \in \{0,1,2,...\}$.
It is well-known that $\mathbb Z_p/(p^n) \simeq \mathbb Z/(p^n)$.
If you have a $\mathbb Z_p$-module $M$ which is torsion and has finite cardinality ($p^c$, say), then in particular it is finitely generated, and hence by the structure theory of f.g. torsion modules over PIDs (or an easier version thereof in this case of a DVR), it is a direct sum of cyclic modules. So here:
$$M \simeq \bigoplus_{n \ge 0} (\mathbb Z/p^n)^{i_n} \qquad \qquad (*)$$
where $(\mathbb Z/(p^n))^{i_n}$ is short notation for $\underbrace{\mathbb Z/(p^n) \oplus ... \oplus \mathbb Z/(p^n)}_{i_n \text{ times}}$, and only finitely many $i_n$ are $\neq 0$. Actually, for $M$ to have cardinality $p^c$, we need $\prod_{n \ge 0} n \cdot i_n = c$.
Obviously the cyclic ones among these are the ones where $i_n=1$ for $n=c$ and $i_n=0$ for all $n \neq c$.
Or in other words, if the module has cardinality $p^c$ and is cyclic, it must be $\simeq \mathbb Z/p^c$. So: If we know the module has cardinality $p^c$, then for it to be cyclic it suffices to show, for example, that it has an element of order $p^c$ (which is nearly trivially equivalent to being cyclic, if you think about it).
As regards torsion, if we know that $M$ has exact torsion $p^t$ (i.e. $p^t \cdot m=0$ for all $m$ but there is $m \in M$ with $p^{t-1} \cdot m \neq 0$), then in $(*)$  this only imposes the restriction that $i_t \neq 0$ and $i_{t+1}=i_{t+2}= ... =0$. As said above, such module is cyclic iff $i_t=1$ and all other $i_n=0$ i.e. iff $M =\simeq \mathbb Z/(p^t)$ i.e. iff it has cardinality $p^t$. (It would suffice to show its cardinality is $\le p^t$.)
As said in comments, I find it hard to imagine how you are given a module $M$ for which you can decide at all whether it is cyclic, but without that decision being kind of immediate via any of the criteria above.
Comment: thanks. I think this is enough to make everything clear.


Como atualizar uma DIV com Ajax/JS?

Question: Eu estou no desenvolvimento de uma página, porém sou completamente leigo em questão de JS...
O site possui a div com a ID #content, e dentro dela um botão de refresh.
Como posso fazer para quando alguém clicar ele dar um refresh somente na div, e não na página toda?
Atualmente estou utilizando o código:

Porém, ele ataliza a página toda...
Agradeço desde já a ajuda de todos!
Answer: Rodrigo, para atualizar uma pagina por AJAX, você primeiro vai precisar de uma URL que lhe sirva o conteudo parcial que irá alimentar a sua div.
para fins deste exemplo, irei utilizar a tag <template> e o método URL.createObjectURL para criar uma URL em mémoria.
Uma vez que você tenha definido a sua URL, então teremos de usar o objeto XMLHttpRequest para realizar a requisição AJAX (Asynchronous JavaScript and XML), apesar de tanto o objeto quanto a tecnologia mencionarem XML, ela tambem pode servir HTML, JSON e outros.

var tmpl = document.getElementById("tmplContent").innerHTML;
var blob = new Blob([tmpl], { type: "text/html" });
var url = URL.createObjectURL(blob);

var updateContent = document.getElementById("updateContent");
var content = document.getElementById("content");

updateContent.addEventListener("click", function (event) {
  var request = new XMLHttpRequest();
  request.open("GET", url, true);
  request.addEventListener("readystatechange", function (event) {
    if (request.readyState == 4 && request.status == 200) {
      content.innerHTML = request.responseText
    }
  });
  request.send();
});

<input id="updateContent" type="button" value="Atualizar Conteudo" />

<template id="tmplContent">

    Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras laoreet aliquam ex vel eleifend. Aenean hendrerit cursus fermentum. Nam ornare imperdiet odio, non hendrerit risus eleifend vel. Nam nec augue consectetur, condimentum nulla ut, lacinia odio. Etiam tempus ligula ac accumsan tempus. Sed a diam non purus sodales tincidunt. Proin accumsan suscipit facilisis. Cras in placerat nulla. Ut eleifend massa eget gravida vestibulum. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae;

</template>

note que no retorno do XMLHttpRequest, estou verificando duas propriedades, a readyState (que determina a que passo está requisição) e o status (que diz qual a situação da requisição).
Segue abaixo um pequeno glosario para o readyState:

0    Requisição não enviada
1    Requisição Enviada
2    Headers recebidos (pode ser util para uma requisição com Http Method HEAD)
3    Carregado Parcialmente (responseText parcialmente disponivel)
4    Completo (requisição finalizada)

o HTTP status code 200 significa que a requisição foi concluida com sucesso, você pode ver os demais status em Http Statuses, porem os mais comuns são 301 (Movido), 400 (Requisição mal formada), 401 (não autorizado), 403 (proibido), 404 (Não encontrado), 500 (Erro no servidor) e 501 (não implementado).

Como atualizar uma DIV com Ajax/JS?


Firebaes CNAME brought down website?

Question: I am adding firebase authentication to a website, it was working well so I decided to get the domain verified to add some more functionality.
On the firebase documentation, it says you need to add two CNAME and two TXT records to the domain, I did that but it didn't work the first time around and it also brought the website down, it seems as though the records weren't fully propagated.  I got in touch with Firebase and they said to try again, once they were fully propagated I got the green tick on Firebase but the next morning the website went down again.
What could be the cause of the website going down?
here is the CNAME & TXT records that brought the website down

Here is a screenshot of the records currently registered (minus the records above which had to be removed)

Here is a text file with the DNS records:
Comment: What do the other records look like? Were you relying on a wildcard record which used to match those names until you started adding more specific records?
Comment: Well, it's effectively impossible to read your screenshot, so I'll let you judge if that is the problem. Personally I suspect that is it.
Comment: Well, it's not that I can't see or open the image, it's that the text is effectively gone. Sorry, but this is pointless.
Comment: @Aindriú If you want people to assist, please stop censoring the website's domain. It's very difficult to diagnose DNS stuff without the real address.
Comment: Thos two CNAME and TXT records will not bring your website down - not from the DNS POV.
Comment: Well they did and had to be removed
Answer: My impression from the question is that for your domain example.com (whatever it is), what you refer to is the web site no longer working specifically means that you can no longer navigate to www.example.com in a browser as this name no longer has address records.
You have a wildcard *.example.com A, which covers any non-existent names, but as you describe in your question, you added records for the names www.example.com (TXT) as well as firebase1._domainkey.www.example.com (CNAME).
The side-effect here is that when you add these records, the name www.example.com now actually exists, hence the wildcard no longer applies here!
If you are going to add these other records while still having address records at www.example.com, you will need to add address records at www.example.com specifically (side by side with the TXT).

Firebaes CNAME brought down website?


Normal derivative of the autonomous single layer potential

Question: Let $G$ be the fundamental solution of the Laplace equation. Let $\Omega$ be an open and bounded subset of $\mathbb{R}^n$ regular enough. It is known that:
\begin{equation}
\int_{\partial \Omega}\frac{\partial G(x-y)}{\partial \nu(y)}d\sigma(y)=
\begin{cases}
-1 \mbox{ if } x\in \Omega,\\
-1/2 \mbox{ if } x\in \partial\Omega,\\
0 \mbox{ if } x\in \mathbb{R}^n\setminus\bar\Omega.\\
\end{cases}
\end{equation}
Where $\nu(y)$ is the unit outer normal to $\partial \Omega$ in $y$. In other words this is the jump formula for the double layer potential when the density is constant.
How about the value of the normal derivative of the single layer potential? Let $x_0\in\partial\Omega$. I want to compute:
\begin{equation}
\int_{\partial \Omega}\frac{\partial G(x-y)}{\partial \nu(x_0)}d\sigma(y)
\end{equation}
Comment: This is covered in Taylors second PDE book, proposition 11.3, page 37. It involves the normal derivative of the single layer potential. If you can access that book, I suggest it, otherwise I can write down the formula for it.
Comment: Thank you. Now I can't access that book, but I will in these days. If you can, could you only tell me the values of the integral, without the proof?
Answer: OK, here is the formula (slightly different notation than yours):
Let
$$
\mathcal{Sl}f(x)=\int_{\partial\Omega}f(y)E(x,y)\,dS(y).
$$
Then
$$
\frac{\partial}{\partial \nu}\mathcal{Sl}f_{\pm}(x)=\frac{1}{2}\bigl(\mp f+N^{\#}f\bigr),
$$
where
$$
N^{\#}f(x)=2\int_{\partial\Omega}f(y)\frac{\partial E}{\partial \nu_x}(x,y)\,dS(y).
$$
Comment: This is the jump formula for the single layer potential, right? I need, with this notation, to compute explicitly $$N^\#1(x)\int_{\partial \Omega}\frac{\partial E}{\partial \nu_x}dS(y).$$ It follows from the jump relation?
Comment: I have missed a $=$
Comment: Yes, then you have to compute $\frac{\partial}{\partial\nu}\mathcal{Sl}1(x)$.
Comment: And for this term, is there an explicit formula as for the double layer potential with constant density?


How to use Views & Entity Reference to create dynamic URLs that are based title from the referenced node

Question: Here's my situation:
I have two content types: Procedure, and Testimonial. Testimonial has an entity reference field where you can point to one or more procedures.
My goal is to create a view of testimonials with a dynamic URL like 'example.com/testimonials/procedure1', where procedure1 is the title of the node that is referenced from the testimonial. So, the idea is that this page would exclusively show testimonials that reference the procedure1 node.
So, I created the view. I added a relationship "Entity Reference: Referenced Entity". I then created a contextual filter that uses this relationship.
At this point, if I do not use a relationship in the contextual filter, I can get this working by using the following pattern: example.com/testimonials/7, where 7 is procedure1's node ID. But, I'd like to use the title in the URL- not the node ID.
Does anyone know where to go from here?  Am I going about this the wrong way?
Thank you!
Answer: This is how I solved a similar problem:  Create a filter on the title and use the relationship: entity.  Then, in a custom module put something similar to:
<code>    function MYMODULE_views_pre_view(&$view, &$display_id, &$args){
      switch($view->name) {
        case 'view_name':
          $value = arg(x);
          $view->display['default']->handler->options['filters'['field_name']['value'] = $value;
        break;
      }
    }
</code>
I'll probably go ahead and build a more universal module out of this because of how often I use it.  The benefit is you can inject an argument as a filter.  I use dashes for spaces and include a str_replace(); to replace dashes with spaces for the filter.  You loose some validation, etc. but there's a bunch of modules that provide filters but no contextual relationship.  This binds the two in a hacky way.
Answer: Try one of these modules:

Sub-pathauto
Extended path aliases

They will allow you to create looking good alias 'estimonials/PROCEDURE_NAME' for pages as 'testimonials/PROCEDURE_ID'.
Answer: What about Automatic Nodetitles?
http://drupal.org/project/auto_nodetitle/
Base the title on the referenced entity and then the path on the title of the Testimonial, which will be automatically set.


Como validar data inicial e data final para um mesmo atributo do Model

Question: Descrição do problema:
Preciso criar um form com uma data inicial e data final para listar as vendas de um produto por período.
Tenhamos como exemplo este model:
public class Produto
{
    [Display(Name = "ID")]
    public int IdProduto { get; set; }

    [Display(Name= "Descrição")]
    public string Descricao { get; set; }

    [Display(Name= "Data Venda")]
    public string DataVenda { get; set; }
}

No form, teremos somente um campo de texto com a datainicial, outro com a datafinal, e o botão submit.
A minha dúvida é a seguinte: Neste caso, como eu faria para fazer as validações no formulário dos campos datainicial e datafinal, na VIEW, usando Html.BeginForm, tendo em vista que os campos datainicial e datafinal são o mesmo atributo no Model?
Answer: Em alguns casos a sua classe de domínio/modelo do banco de dados é facilmente adaptável à view, em outros casos não.
Recomenda-se que se crie modelos de visão para cuidar de casos específicos.
Por exemplo, quando você cria uma nova aplicação web com o template que contém o "Individual User Account" você terá uma classe LoginViewModel para a tela de Login, outra classe RegisterViewModel para a tela de registro, etc. Tudo dentro do arquivo AccountViewModels.cs na pasta Model do template do Asp.Net MVC.
Logo, digo, e é recomendado, que você crie um modelo padrão para cada view.
Então, você teria algo como:
public class ProdutoVendasPorPeriodoViewModel // nome nada exagerado
{
    [Required(ErrorMessage = "Informa a data inicial")]
    [Display(Name= "Data Inicial")]
    [DataType(DataType.Date)]
    public DateTime DataInicial { get; set; }

    [Required(ErrorMessage = "Informa a data final")]
    [Display(Name= "Data Final")]
    [DataType(DataType.Date)]
    public DateTime Final { get; set; }
}

E em sua view, ficaria mais ou menos assim:
@model App.Web.Model.ProdutoVendasPorPeriodoViewModel
...
@Html.TextBoxFor(x => x.DataInicial)
....
@Html.TextBoxFor(x => x.DataFinal)

Seguindo esse padrão, você teria vantagens como:

não precisar criar gambiarras para views que não representam o mesmo modelo da classe de domínio;
Também não teria os atributos DisplayAttribute "sujando" sua
classe de domínio;
Poderá ter classes bem customizadas com atributos que lhe ajudariam na validação e modelagem da view, como o exemplo que dei, exigindo os valores de Data Inicial e Data Final com o atributo RequiredAttribute e o DisplayAttribute que passou a ter um valor mais "apropriado" para a view.

Meios paliativos
Você pode ainda criar uma view não "tipada", ou seja, sem informar o @model.
Os campos você poderia criar manualmente ou com o uso de helpers também.
Exemplo:
<input type="text" id="DataInicial" name="DataInicial" .. />
...
<input type="text" id="DataInicial" name="DataInicial" .. />

... ou

@Html.TextBox("DataInicial", "")
@Html.TextBox("DataFinal", "")

Para isso sua Action deveria ser assinada como esse exemplo:
public ActionResult Relatorio (string DataInicial, string DataFinal)
{
    ...
}

Ou seja, tendo os parâmetros com o nome dos campos.
Dessa forma você receberia os valores nos parâmetros e a validação ficaria por sua conta.
Comment: Obrigado @TiagoSilva. A minha dúvida era justamente se era comum criar várias classes além da Model do Produto. Muito obrigado pelo esclarecimento. Eu estava já iniciando o "Meio Paliativo" que você falou na resposta acima. Mas acho que vou aproveitar que ainda estou no início do projeto e fazer da forma correta mesmo.
Comment: Eu posso estar utilizando em alguns casos o próprio model e para outros o viewmodel? Ou é recomendável que eu sempre use o viewmodel?
Comment: Estou no meio de um projeto no qual não conta com o ViewModel. Então utilizo DisplayAttribute por exemplo, direto no domínio. Porém agora para uma classe iria precisar utilizar viewmodel, e seria um retrabalho estar alterando tudo que já fiz para viewmodels.


Incorrect output with counting and tallying bits in C

Question: This is only my 2nd programming class. There are 30 rooms.  We have to see what is in each room and tally it. I already used the for loop to go through the 30 rooms and I know I have tried to use a bit counter to see what is in each room.  I am not getting the correct sample output after I redirect the sample output.  When I printf("%d", itemCnt[loc]);, my output is 774778414trolls
When I printf("%d", itemCnt[0]);, my output is 0trolls. I'm just trying to get one output right so I can figure out how to get the rest of the 8 outputs. From the sample output, the first number is supposed to be 6, followed by 6, 1, 4, 4 ... and so on. Below are sample inputs/outputs and what I have so far in code.
Sample input:
1   20  @@
2   21  @A
3   22  @#
4   23  @1
5   22  @@
6   22  @@
7   22  @@
8   22  @@
9   23  @Z  Here be trolls � not!
10  23  @+
12  23  @@
13  24  @@
11  22  @@
14  22  @2
15  21  @1
16  20  @@
17  19  @@
18  20  @@
19  19  @@
20  18  @@
21  17  @*
22  16  @*
23  15  @%
0   14  @7
0   gold_bar
1   silver_bar
2   diamond
3   copper_ring
4   jumpy_troll
5   air
6   angry_troll
7   plutonium_troll

Sample Output:
6   gold_bar
6   silver_bar
1   diamond
4   copper_ring
4   jumpy_troll
8   air
15  angry_troll
0   plutonium_troll

code
int main()
{
    // contains x and y coordinate
    int first, second;
    char third[100];
    char fourth[100];
    char Map[30][30];

    // map initialization
    for(int x=0; x<30; x++){
        for(int y=0; y<30; y++){
            Map[x][y] = '.';
        }
    }

    while(scanf("%d %d %s",&first, &second, third) != -1) {
        // Condition 1: a zero coordinate
        if (first==0 || second==0) exit(0);
        // Condition 2: coordinate out of range
        if (first<0 || first>30 || second<0 || second>30){
            printf("Error: out of range 0-30!\n");
            exit(1);
        }

        Map[second-1][first-1] = third[1];
        fgets(fourth, 100, stdin);

        // bit counter
        int itemCnt[8] = {0};         // array to hold count of items, index is item type
        unsigned char test;           // holds contents of room.
        int loc;
        for(loc = 0; loc < 8; loc++)  // loop over every bit and see if it is set
        {
            unsigned char bitPos = 1 << loc;  // generate a bit-mask
            if((test & bitPos) == bitPos)
                ++itemCnt[loc];
        }
        // print the map
        for(int h=0; h<30; h++){
            for(int v=0; v<30; v++){
                printf("%c", Map[h][v]);
            }
            printf("\n");
            }
        // print values
        printf("%d", itemCnt[0]);

    }

    return 0;
}

Comment: Please do some research on your own. stack overflow is no tutorial site. You got answers already for the similar question some hours ago. If you have problems with the answers, comment.
Comment: You need to describe your problem in more detail than "not getting the correct sample output". What exactly are you getting? And what have you done to debug the problem on your own and what exactly don't you know how to do? "It doesn't work, fix it for me" type questions tend not to be received well.
Comment: 0) `0   14  @7` => `if (first==0 || second==0) exit(0);` => exit program. 1) `if((test & bitPos) == bitPos)` : `test` isn't initialize and never set.
Comment: when i printf("%d", itemCnt[loc]); my output is 774778414trolls
when i printf("%d", itemCnt[0]); my output is 0trolls
i'm just trying to get one output right so i can figure out how to get all 8 outputs.
sample output is supposed to be : 6   gold_bar
6   silver_bar
1   diamond
4   copper_ring
4   jumpy_troll
8   air
15  angry_troll
0   plutonium_troll
Comment: Please do not put important question information into the comments. It can be easily missed and also does not allow for proper formatting. Update your question description with all the relevant information that a reader would need to know.
Comment: Have you got this working, yet?
Answer: test is not initialized.  It looks like you intended to assign 'third[1]' to test.
Also, 774778414 = 0x2E2E2E2E in hex, and 0x2E is the numeric value of ASCII '.', your initial value for map locations.  (Tip:  when you see wild decimals like that, try Google.  I entered, "774778414 in hex" without the quotes.)
I would also suggest breaking down the code into two functions:  the first reads from stdin to populate Map (like you do), and the second reads from stdin to populate 8 C strings to describe your objects.  It's important to note, the first loop should not go until end of input, because your posted input continues with descriptions, not strictly 3 fields like the beginning.


Erlang gen_server with long-running tasks

Question: Good day,
I have a gen_server process which does some long-running state-updating tasks periodically in
handle_info:
handle_info(trigger, State) ->
    NewState = some_long_running_task(),
    erlang:send_after(?LOOP_TIME, self(), trigger),
    {noreply, NewState}.

But when such task runs, then whole server gets unresponsive and any call to it leads to whole server crash:
my_gen_server:status().
** exception exit: {timeout,{gen_server,call,[my_gen_server,status]}}
     in function  gen_server:call/2

How it is possible to avoid blocking of gen_server ?
And when one call my_gen_server:status() at any time, the result should be something like:
{ok, task_active}
Answer: execute the long running task in a separate process. Let this process inform the gen_server of its progress with the task (that is if the task's progress can be tracked) OR let the process complete the task or fail but at least inform the gen_server of the results of the task.
Let the gen_server be linked with the process doing this long running task, and let the gen_server know the PID or registered name so that in case of exit signals, it can isolate the death of that important process from the Rest.
handle_info(trigger, State) ->
    Pid = spawn_link(?MODULE,some_long_running_task,[State]),
    NewState = save_pid(Pid,State),
    {noreply, NewState};
handle_info({'EXIT',SomePid,_},State)->
    case lookup_pid(State) == SomePid of
        false -> %% some other process
            {noreply,State};
        true ->
            %% our process has died
            %% what do we do now ?
            %% spawn another one ?
            %% thats your decision to take
            ....
            ....
            {noreply,State}
    end;
handle_info({finished,TaskResult},State)->
    .....%% update state e.t.c.
    erlang:send_after(?LOOP_TIME, self(), trigger),
    {noreply,NewState}.

some_long_running_task(ServerState)->
    ....do work
    ....return results
Comment: Remember that you can always keep data in the server State. The best way is to have a server state as an erlang `record` , makes your code readable and easilly `pattern matcheable` e.g. if your state is: `-record(state,{field1,field2,...,long_running_pid}).` you would easilly pattern match its exit signal like: `handle_info({'EXIT',Pid,_},#state{long_running_pid = Pid} = State) ->`
Comment: this looks like interesting solution if i want to return extended status(not just `{ok, task_active}`), but the code finally getting harder to read and understand
Answer: This call does not lead to a crash, but simply to an exception which can be caught:
status() ->
  try gen_server:call(my_gen_server, status)
  catch
    exit:{timeout,_} -> {ok, task_active}
  end.

However, the call will remain in the server's queue, and after it finishes handling the current message, it will send a reply message: {ServerRef, Reply}, which should be discarded by the calling process.
The only way to avoid blocking of any process in Erlang (whether gen_server or not) is not to run blocking tasks on it. So another alternative could be to run your long tasks on a different process which only talks to your server, so nobody cares that it's blocked.
Comment: Thank you! This really helped me alot with that specific "exit:{timeout,_}" case.


Does lilypond have the ability to typeset bars in free or open time?

Question: I'm using lilypond to arrange a new part for concert band by combining/picking and choosing from a couple of different parts that need to be covered, but we don't have instruments for on the originally scored instrument.
Does lilypond have the flexibility / a way to enter into a period of open or free time?
I'd like to mimic the X that is typically shown in concert band score when entering/changing into free or open time and using annotations to indicate the guidance the composer has provided.  I realize this will not be part of the midi that lilypond can be asked to produce, but that's fine, at the moment, I'm just typesetting a couple of parts.
I've pored through the documentation for time signatures and special concerns but I've not found any indication that this is possible. I've seen questions that ask how to hide the time signature, but this isn't quite the same.
Answer: Usually this is done via cadenzas. The lilypond index term is "unmetered music", described here.
Note that this will only turn off barline insertion and bar counting. It doesn't do anything else; for instance, if you want a smaller font size during the cadenza or some markup text, you have to insert it yourself.


Algebra question about Triangle Interiors

Question: I was reading about Triangle Interiors on Wolfram Alpha:
http://mathworld.wolfram.com/TriangleInterior.html
and they have a simple equation:
$$\mathbf{v} = \mathbf{v}_0 + a\mathbf{v}_1 + b\mathbf{v}_2,$$
and then they solve for $a$ and $b$, but I wasn't sure about the steps of how they went about doing that.
My algebra is rusty...
Comment: Note that $\mathbf{v}$, $\mathbf{v}_0$, $\mathbf{v}_1$, and $\mathbf{v}_2$ are **vectors**, not numbers; you really need some analytic geometry to understand the expressions, not merely algebra at the precalculus level.
Answer: The page defines a binary function $\times$ which maps vectors in $\mathbb{R}^2$ to real numbers, $\mathbb{R}$.  This function is given as $\mathbf{v} \times \mathbf{w} = v_xw_y - w_xv_y$.  It can be shown that it is a bilinear function, since
$$(\mathbf{a} + \mathbf{b}) \times \mathbf{c} = (\mathbf{a} \times \mathbf{c}) + (\mathbf{b} \times \mathbf{c})$$
$$\mathbf{a} \times (\mathbf{b} + \mathbf{c}) = (\mathbf{a} \times \mathbf{b}) + (\mathbf{a} \times \mathbf{c})$$
$$(\lambda\mathbf{a})\times\mathbf{b}=\mathbf{a}\times(\lambda\mathbf{b})=\lambda(\mathbf{a}\times\mathbf{b})$$
$\forall\mathbf{a},\mathbf{b},\mathbf{c}\in\mathbb{R^2},\forall\lambda\in\mathbb{R}$ (to see this, set $\mathbf{a}=(a_x,a_y),$ $\mathbf{b}=(b_x,b_y),$ and $\mathbf{c}=(c_x,c_y),$ then substitute into the above).  Using the above equations
$$\mathbf{v}\times\mathbf{v_1}=(\mathbf{v_0} + a\mathbf{v_1} + b\mathbf{v_2})\times\mathbf{v_1}$$
and
$$\mathbf{v}\times\mathbf{v_2}=(\mathbf{v_0} + a\mathbf{v_1} + b\mathbf{v_2})\times\mathbf{v_2}$$
can be manipulated to obtain the desired results, so long as $\mathbf{v_1}\times\mathbf{v_2}\ne0$.


How to restrict the user from entering a value below certain value?

Question: I have an html file with input field
<input type="text" allow-decimal="true" allow-negative="false"
ng-model="amount"
and i have a controller.js file with scope variables
$scope.amount=40000; and have one more scope variable $scope.minAmount= 2000;
So, what i want to do is I want to restrict the user from entering any value below 2000.
User should not be allowed to enter anything below the value 2000.
can anyone help me with this?
Answer: You can set attributes max and min for maximum and minimum values inside an input element in html itself
<code><input type="number" name="id" min="2000">
</code>
This will set the minimum value for input as 2000. Similarly you can set a maximum value using max attribute.
Comment: Is there any way to do it with type as text? i.e type="text" instead of type as number
Comment: That is not the right way to do things but nevertheless you can find the answer here. (https://stackoverflow.com/questions/37435529/proper-way-to-restrict-text-input-values-e-g-only-numbers). If you find this helpful please accept the answer :)


How to solve issue in jest unit test?

Question: I have a unit test for a ReactJs/Typescript project that has a reference to a module called nock.js, and using jest:
import nock from 'nock'
...

afterEach(() => {
   nock.cleanAll();
})

When I run the test I get an error in the .cleanAll statement:
TypeError: nock_1.default is not a function

However when I change the import statement to :
var nock = require('nock');

The issue is solved. How can I still use import instead of require ? Is this an issue with the jest configuration? This is the config:
"jest": {
    "transform": {
      "^.+\\.(ts|tsx)$": "<rootDir>/node_modules/ts-jest/preprocessor.js"
    },
    "moduleFileExtensions": [
      "ts",
      "tsx",
      "js"
    ],
    "testRegex": "/__tests__/.*\\.(ts|tsx|js)$"
  },

Comment: Maybe this issue? https://github.com/node-nock/nock/issues/584 (Jest tries to mock 'nock'…)
Comment: @helb did not work for me this one
Answer: If a module has a default export, you can use:
import nock from 'nock'

But if it doesn't have a default export, you'll need to use:
import * as nock from 'nock'

Answer: I met the same exact issue, and fixed it by adding the following config to my tsconfig.json:
{
...
"esModuleInterop": true
...
}

How to solve issue in jest unit test?