Does the series $ \sum_{n=1}^{\infty}\left( 1-\cos\big(\frac{1}{n} \big) \right)$ converge?

Question: I'm having trouble determining whether the series:
$$
\sum_{n=1}^{\infty}\left[1-\cos\left(1 \over n\right)\right]
$$
converges.
I have tried the root test:
$$\lim_{n\rightarrow\infty}\sqrt[n]{1-\cos\frac{1}{n}}=\lim_{n\rightarrow\infty}\left(1-\cos\frac{1}{n}\right)^{1/n}=\lim_{n\rightarrow\infty}\mathrm{e}^{\frac{\log(1-\cos\frac{1}{n})}{n}}=\mathrm{e}^{\lim_{n\rightarrow\infty}\frac{\log(1-\cos\frac{1}{n})}{n}}$$
Now by applying the Stolz–Cesàro theorem, that upper limit is equal to:
\begin{align}
\lim_{n\rightarrow\infty}\frac{\log(1-\cos\frac{1}{n+1})-\log(1-\cos\frac{1}{n})}{(n+1)-n}&=\lim_{n\rightarrow\infty}\left(\log(1-\cos\frac{1}{n+1})-\log(1-\cos\frac{1}{n})\right)
\\&=\lim_{n\rightarrow\infty}\log{\frac{1-\cos{\frac{1}{n+1}}}{1-\cos{\frac{1}{n}}}}
\end{align}
Now I'm totally stuck, unless that quotient is actually 1, in which case the limit would be 0, the Root test result would be $\mathrm{e}^0=1$ and all this would have been to no avail.
I'm not sure this method was the best idea, the series sure seems way simpler than that, so probably another method is more appropriate?
Comment: The quotient is almost $1$, the root test _is_ inconclusive. The best method is always to see whether you can get a grip on the size of the terms first. Here a Taylor expansion of $\cos$ immediately yields $$1 - \cos \frac1n = 1 - \left(1 - \frac{1}{2n^2} + \frac{1}{4!n^4} +\dotsc\right) = \frac{1}{2n^2} + O\left(\frac{1}{n^4}\right).$$
Comment: Sign doesn't matter in Landau notation. That's all absorbed in the big unknown constant. Note that also the $4!$ vanished in the $O(\cdot)$.
Comment: Oh true that's pretty intuitive, wouldn't it be a substraction though? (I haven't worked with Landau notation yet so I'm not sure about it).
Comment: Ah ok thanks for the info Daniel ;)
Comment: The general term $\large\sim{1 \over 2n^{2}}$ when $\large n \gg 1$ like the Basel Problem.
Answer: Note that
$$
0\le 1-\cos\frac{1}{n}=2\sin^2\frac{1}{2n}\le 2\cdot\left(\frac{1}{2n}\right)^2=\frac{1}{2n^2}.
$$
We have used above that $$1-\cos (2x)=2\sin^2 x,$$ and also that $0 \le \sin x\le x$, whenever $x\in [0,\pi/2]$.
Comment: $1-\cos(2x)=2\sin^2 x$.
Comment: Oh that yields the convergence pretty straightforwardly, but I'm unsure on how you found that expression for $1-\cos{\frac{1}{n}}$.
Comment: Oh I see now, that was pretty elegant. Thanks Yiorgos.
Comment: (+1) Your approach is the one I would have used.
Answer: We can apply the Limit Test with  $\rho =2$,
$$\lim_{k \to \infty} k^2\left( 1 - \cos{\frac{1}{k}}\right) = \lim_{u \to 0}\frac{1 - \cos{u}}{u^2} = \frac{1}{2}$$
and thus the series converges absolutely.
Comment: Limit test for positive series: If the limit $\;\lim\frac{a_n}{b_n}\;$ exists and it is finite *and* non-zero, then the series $\;\sum a_n\;$ converges iff $\;\sum b_n\;$ converges. In this case, Ayesha is using $\;b_n=\frac1{n^2}\;$
Comment: The one I had in mind says that for $\sum u_k $, if $\lim_{k \to \infty}\,\,k^\rho u_k < \infty$ for any $\rho > 1$, then $\sum u_k $ converges absolutely. I read about in in a text from 1947, and it was called the Limit Test, so I apologize if that causes confusion - it follows easily from what DonAntonio mentioned.
Comment: Wow that seems really simple, I hadn't heard about that test before. Searching for _limit test_ doesn't yield anything interesting on Google, could you give me some info about it? Or maybe some other name that test is also known as?
Comment: Oh it's _that_ test, true I hadn't realized, thanks for your help DonAntonio. Also thank you Ayesha of course, the solution is pretty elegant as well, I love those.
Comment: What Ayesha is calling the "limit test" is a consequence of what is often called the "limit *comparison* test" in modern-day US calculus classrooms.
Answer: A small addendum. It has already been pointed out that the series is clearly convergent, since $1-\cos\frac{1}{n}$ behaves like $\frac{C}{n^2}$ for large values of $n$, hence asymptotic comparison and the p-test are conclusive. In explicit terms,
$$ \sum_{n\geq 1}\left(1-\cos\tfrac{1}{n}\right)=2\sum_{n\geq 1}\sin^2\tfrac{1}{2n} $$
can be efficiently approximated through Bhaskara's $\cos y\approx \frac{\pi^2-4y^2}{\pi^2+y^2}$ and Poisson's summation formula, leading to
$$ S=\sum_{n\geq 1}\left(1-\cos\tfrac{1}{n}\right)\approx \frac{5}{e^2-1} $$
whose relative approximation error is already less than one part in two hundreds. An exact representation is provided by
$$ S = \sum_{m\geq 1}\frac{(-1)^{m+1}}{(2m)!}\zeta(2m)=\sum_{m\geq 1}\frac{(-1)^{m+1}}{(2m)!(2m-1)!}\int_{0}^{+\infty}\frac{z^{2m-1}}{e^z-1}\,dz\\= -\int_{0}^{+\infty}\frac{\text{ber}_1(2\sqrt{z})+\text{bei}_1(2\sqrt{z})}{(e^z-1)\sqrt{2z}}\,dz$$
where $\text{ber}$ and $\text{bei}$ are Kelvin functions. The last integrand function is concentrated in a right neighbourhood of the origin, where it behaves like $\frac{1}{2}\exp\left(-\frac{x}{2}-\frac{x^2}{18}\right)$. The error of the resulting approximation
$$ S\approx \frac{3}{2} e^{9/8} \sqrt{\frac{\pi }{2}} \text{Erfc}\left[\frac{3}{2 \sqrt{2}}\right]$$
essentially has the same magnitude of the previous one.
Answer: We know:
$$\cos t \sim 1-\dfrac{t^2}{2}$$
Hence, for $n \to +\infty$
$$\sum_{n=1}^{+\infty}\left(1-\cos\left(\dfrac{1}{n}\right)\right)\sim \sum_{n=1}^{+\infty}\dfrac{1}{2n^2}=\frac{\pi^2}{12}$$
Thus it converges
Answer: I am a student too so I hope my answer is correct.
$1-\cos(1/n)=\cos(0)-\cos(1/n)=-2\sin(1/2n)\sin(-1/2n)=2\sin^2(1/2n)$
Now as $\sin(1/2n)<1/2n \; \forall n \in \mathbb{N} \Rightarrow \sin^2(1/2n)<1/4n^2$
Hence $ |\sum_{n=1}^{\infty }(1-\cos(1/n))| \leq \sum_{n=1}^{\infty }|(1-\cos(1/n))|=\sum_{n=1}^{\infty }|2\sin^2(1/2n)| \leq \sum_{n=1}^{\infty }|(2/4n^2)|< \infty $. Because we all ready know that $\sum_{n=1}^{\infty }1/n^2$ converge


Erro em atualizar Registro com EF

Question: Estou com dificuldades de fazer uma atualização em um registro, usando ef. Da erro de conflito de chave com relacionamento. Como se estive tentando add e não atualizar.

Additional information: A referential integrity constraint violation occurred: The property value(s) of 'Endereco.EnderecoId' on one end of a relationship do not match the property value(s) of 'Cliente.EnderecoId' on the other end.

public class Cliente
{
    public Int64 ClienteId { get; set; }
    public String Nome { get; set; }
    public String Email { get; set; }
    public String Cpf { get; set; }
    public String Rg { get; set; }
    public String TelFixo { get; set; }
    public String Celular { get; set; }
    public Int64 EnderecoId { get; set; }
    public virtual Endereco Endereco { get; set; }

}

public class Endereco
{
    public Int64 EnderecoId { get; set; }
    public Int64 CidadeId { get; set; }
    public Int64 EstadoId { get; set; }
    public String Rua { get; set; }
    public String Complemento { get; set; }
    public String CEP { get; set; }
    public String Bairro { get; set; }
    public String Numero { get; set; }
    public virtual Cidade Cidade { get; set; }
    public virtual Estado Estado { get; set; }
    public virtual ICollection<Cliente> ClienteList { get; set; }
}

Comment: Um endereço possui vários clientes? Um cliente pertence a apenas um endereço? Está certo isso?
Comment: Cigano, tirei esse relacionamento, mantive somente do cliente e continuou o erro.
Answer: Está incorreta sua modelagem. Um Cliente possui um ou mais Endereços, portanto:
[DisplayColumn("Nome")]
public class Cliente
{
    [Key]
    public Int64 ClienteId { get; set; }

    [Required]
    public String Nome { get; set; }
    [EmailAddress]
    public String Email { get; set; }

    public String Cpf { get; set; }
    public String Rg { get; set; }
    public String TelFixo { get; set; }
    public String Celular { get; set; }

    // Isto indica que 1 Cliente pertence a 1 Endereço.
    // public Int64 EnderecoId { get; set; }
    // public virtual Endereco Endereco { get; set; }

    // Isto indica que 1 Cliente tem N Endereços
    public virtual ICollection<Endereco> Enderecos { get; set; }
}

Endereco fica assim:
public class Endereco
{
    [Key]
    public Int64 EnderecoId { get; set; }
    public Int64 CidadeId { get; set; }
    public Int64 EstadoId { get; set; }

    // Este índice serve para dizer que um mesmo cliente não pode
    // ter dois endereços do mesmo tipo.
    // Se quiser, apenas remova a anotação daqui e de TipoEndereco (mais abaixo).
    [Index("IXU_Endereco_ClienteId_TipoEnderecoId", Order = 1, IsUnique = true)]
    public Int64 ClienteId { get; set; }

    // Como boa prática para Endereco, crie uma enumeração que indica
    // o tipo do endereço.
    [Index("IXU_Endereco_ClienteId_TipoEnderecoId", Order = 2, IsUnique = true)]
    public TipoEndereco TipoEndereco { get; set; }

    public String Rua { get; set; }
    public String Complemento { get; set; }
    public String Cep { get; set; }
    public String Bairro { get; set; }
    public String Numero { get; set; }

    public virtual Cidade Cidade { get; set; }
    public virtual Estado Estado { get; set; }

    // Isto indica que 1 Endereço tem N clientes, o que está errado.
    // public virtual ICollection<Cliente> ClienteList { get; set; }

    // Isto indica que 1 Endereço pertence a 1 Cliente.
    public virtual Cliente Cliente { get; set; }
}

TipoEndereco:
public enum TipoEndereco
{
    Residencial,
    Comercial,
    Entrega,
    Cobranca
}

Comment: vlw Cigano, muito obrigado pela ajuda.
Comment: @RicardoSoares [Veja aqui como usar o site](http://pt.stackoverflow.com/tour). Obrigado!

Erro em atualizar Registro com EF


Is there a difference between compact and closed?

Question: Off course there is a difference between 'compact' and 'closed', but
here I am asking for something deeper. Whether a set in a topological
space deserves label 'closed' is somehow depending not only on the
set itself but also on its surroundings. Set $F$ can be closed when
you look at it as a subset of $A$ while it can loose this label again
when it is looked at as a subset of $B$. This can be disturbing.
With label 'compact' that problem does not exists. "I
am compact" declares the set firmly,.."and
nobody can take that from me!" I like that attitude. When
I deal with 'closed' then I tend to use 'set' and when I deal with
'compact' then 'space'. The concepts 'compact' and 'closed' are only
used here to make myself clear. It is not more than an example. For the rest I rely on your intuition.
Is there some mathematical/topological theory in which this distinction is caught?
Comment: Well, sure. Closedness is a property of sets (and depends on the topology you use) whereas compactness is a property of topological spaces. I don't think there's more to it than this.
Comment: Just to highlight: Consider $\mathbb{R}$ endowed with the standard Euclidean topology. Then, it's a closed set but it's not compact. More generally, compactness intuitively depends on the surroundings of a set, too, but in a more subtle
Comment: When I want a lot of views, then from now on I know the key to that: ask something that everybody knows.
Answer: I don't know, if the following is what you are after, but: Compactness is an intrinsic property, that is what you call "nobody can take it from me". We can state it as follows:

Let $X$, $Y$ be topological spaces, $A \subseteq X$, $B \subseteq Y$. Let $f \colon A \to B$ be a homeomorphism, than $A$ is compact iff $B$ is.

Closedness is extrinsic, it depends on the surrounding space (that's why we say $A$ is closed in $X$, not $A$ is closed), that is the above reads for closedness:

Let $X$, $Y$ be topological spaces, $A \subseteq X$, $B \subseteq Y$. Let $f \colon X \to Y$ be a homeomorphism with $f[A] = B$, than $A$ is closed in $X$ iff $B$ is closed in $Y$.

So compactness is preserved by homeomorphisms of the subsets, closedness only by homeomorphisms of the surrounding spaces.
Answer: As alluded to in the question, if interpreted literally the answer is trivially "yes, there is a difference."  However, if we consider locally compact Hausdorff spaces then the answer is "no" in the following sense.  Namely, every compact subspace of a Hausdorff space is closed, and on the other hand, every non-compact locally compact Hausdorff space is a non-closed subspace of its one-point compactification (which is a compact Hausdorff space.)
Answer: Being "closed" is a property of a subset of a topological space, while being "compact" is a property of a topological space itself. While you can talk about a subset of a topological space being compact, this just means that the subspace topology of that set is compact. This, as you said, depends only on the set itself (together with its topology - you can't use topological language without topologies on your sets), while the property of being closed (the complement is open) depends on the topology of the whole space.
For some intuition about why compact subspaces of topological spaces are quite often closed, think about the conditions imposed on the set of open sets in a topological space. Fundamentally, compactness is a finiteness property: it means, in a very precise way, "not too big." However, in a topological space, arbitrary unions of open sets must be open. When we take a union of lots of things that are "not too big," there's no reason to expect the union to share that property. This doesn't mean, however, that no compact sets are also open - for example, in a compact space, the whole space is open, and also compact. This interplay can be interesting to study, and, for "nice" spaces, works out quite well.
Remember - "open" and "closed" are properties of subsets of spaces, while "compact" is a property of entire spaces.
Answer: A possible way to look at this particular example (the difference between compact spaces and closed sets) is trying to codify the "extrinsicness" by saying that it is preserved under continuous maps. This applies in this case because continuous maps preserve compactness, but obviously continuous maps don't need to preserve closedness since it depends in the ambient space.
This is related to topological invariants, meaning properties which are preserved under homeomorphisms. We can take this approach further by working in a category and asking for properties which are preserved under isomorphisms.
EDIT: I didn't see that my answer is redundant given the answer by martini. I apologize.
Comment: It is neat to mention the redundancy, but your answer is useful as well. Especially the mentioned link with categories.
Answer: In some sense, a compact space is universally closed:

A Tychonoff space $X$ is compact iff for every Hausdorff space $Y$ and every continuous map $f : X \to Y$ then $f(X)$ is closed in $Y$.

The implication is clear since a continuous map sends compact sets on compact sets. Conversely, taking $Y=\beta X$ we deduce that $X$ is closed in its Stone-Čech compactification so $X= \beta X$ is compact.


Override Plugin Globally

Question: I'm making a custom jquery plugin that simply manipulates the css on a page, after it loads.
Basically, as I loop through a few elements, I search for things like emails, Dates, etc...
Example:

I'm sure most of you can clearly see what I'm doing.
My option: pluginActive, is either true or false.
If I specify false then my plugin simply ignores the instance, which is working great.
Now I've found moments that I want every pluginActive automatically to FALSE.
Is there a way I can globally set Every pluginActive to be false for all of my instances, without having to change each individually?
At the moment I'm manually putting conditions (in PHP).  But I'm curious if there's a more all-encompassing method, without omitting the

This is the easiest globalized way I could imagine.
Honestly, I was thinking of a more abstracted way to affect a plugin, and made it harder on myself.

Override Plugin Globally


Parsing JSON list of dictionaries

Question: I'm trying to retrieve the area value and the first pair of coordinates value for every area from a JSON list of dictionaries after an API call
[{'area': 'abcd', 'geojson': '{"type":"MultiPolygon","coordinates":[[[[103.8593,1.43905,...[103.6391,1.3527]]]]}'},
 {'area': 'efgh', 'geojson': '{"type":"MultiPolygon","coordinates":[[[[100.000,1.4000,...[103.6391,1.3527]]]]}'}
.
.

This is my code
# calling the API
results = requests.get(url).json()

area= []
coordinates = []

for i in results:
    a = i['pln_area_n']
    area.append(a)

for x in results:
    c = x['geojson']['coordinates'][0]
    coordinates.append(c)

TypeError: string indices must be integers

My code is definitely wrong, how do I access the first pair of coordinates value of the geojson key for every area?
Comment: `x['geojson']` is a **string**, you need to `json.load` it into a dictionary to be able to access the `'coordinates'`. The format of the API you're hitting seems a bit weird, I might be inclined to look at fixing this upstream.
Comment: @jonrsharpe You should post an answer showing how to deal with it. It seems like it's intentional, they did call that property `geojson`, indicating that it contains JSON, not an object.
Comment: @jonrsharpe it is weird, am looking into the api call. json.load and .json() works the same too as discussed in this thread? https://stackoverflow.com/questions/39719689/what-is-the-difference-between-json-load-and-json-loads-functions
Comment: What do you mean *"works the same too"*? The point is that you need to parse parts of it *twice*; once to get what you show in your question, then again for the content of the `geojson` values. As @Barmar has pointed out, the name suggests that a JSON string is expected for that value.
Answer: I'd guess your response is something like:
[{"area": "abcd", "geojson": "{\"type\": \"MultiPolygon\", ...}"}]

The values of the geojson property in the JSON are themselves JSON strings, and requests will only parse the first "level" of this. Hence you end up with the Python list:
[{'area': "abcd', 'geojson': '{"type": "MultiPolygon", ...}'}]

where the results[0]['geojson'] value is still a JSON object string, not parsed to a dictionary. This explains the error; '{"type": "MultiPolygon", ...}'['coordinates'] is trying to index into a string using another string, not accessing a dictionary's value by key:
>>> '{"type": "MultiPolygon", ...}'['coordinates']
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: string indices must be integers

You therefore need to import json and parse the JSON string values again, e.g. using a list comprehension:
coordinates = [
    json.loads(result['geojson'])['coordinates'][0]
    for result in results
]

Comment: `json.load` should be `json.loads`

Parsing JSON list of dictionaries


Jenkins headless linux slave connection error

Question: I get java.net.SocketException: Connection reset when trying to connect a headless debian slave to my main Jenkins master. It's been running good for a couple of weeks without error and suddenly I can't get it to connect.
I can telnet into the master on port 6256.
Slave output:
<code>#> java -jar ~/slave.jar -jnlpUrl https://test.tv/jenkins/computer/debian_slave_node_1/slave-agent.jnlp
Aug 12, 2013 10:10:46 AM hudson.remoting.jnlp.Main$CuiListener <init>
INFO: Hudson agent is running in headless mode.
Aug 12, 2013 10:10:46 AM hudson.remoting.jnlp.Main$CuiListener status
INFO: Locating server among [https://test.tv/jenkins/, http://test.tv/jenkins/]
Aug 12, 2013 10:10:46 AM hudson.remoting.jnlp.Main$CuiListener status
INFO: Connecting to test.tv:6256
Aug 12, 2013 10:10:46 AM hudson.remoting.jnlp.Main$CuiListener status
INFO: Handshaking
Aug 12, 2013 10:10:46 AM hudson.remoting.jnlp.Main$CuiListener error
SEVERE: Connection reset
java.net.SocketException: Connection reset
    at java.net.SocketInputStream.read(SocketInputStream.java:189)
    at java.net.SocketInputStream.read(SocketInputStream.java:121)
    at java.io.BufferedInputStream.fill(BufferedInputStream.java:235)
    at java.io.BufferedInputStream.read(BufferedInputStream.java:254)
    at hudson.remoting.ClassicCommandTransport.create(ClassicCommandTransport.java:98)
    at hudson.remoting.Channel.<init>(Channel.java:391)
    at hudson.remoting.Channel.<init>(Channel.java:387)
    at hudson.remoting.Channel.<init>(Channel.java:348)
    at hudson.remoting.Channel.<init>(Channel.java:344)
    at hudson.remoting.Channel.<init>(Channel.java:332)
    at hudson.remoting.Engine.run(Engine.java:238)
</code>
Jenkins Master output:
<code>java.io.IOException: Unexpected termination of the channel
at hudson.remoting.SynchronousCommandTransport$ReaderThread.run(SynchronousCommandTransport.java:50)
Caused by: java.io.EOFException
at java.io.ObjectInputStream$BlockDataInputStream.peekByte(ObjectInputStream.java:2596)
at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1316)
at java.io.ObjectInputStream.readObject(ObjectInputStream.java:370)
at hudson.remoting.Command.readFrom(Command.java:92)
at hudson.remoting.ClassicCommandTransport.read(ClassicCommandTransport.java:72)
at hudson.remoting.SynchronousCommandTransport$ReaderThread.run(SynchronousCommandTransport.java:48)
</code>
Answer: Hard to say what happens before knowing more. In particular:

does it fail at every connection request ? If so please check your auth.log on your server as it seems the failure happens after "status INFO: Handshaking" and before "Connected"
are your clock properly synchronized ?
what OSes are you using ? Which java version on your slaves ? check your PATH and JAVA_HOME
have you updated jenkins lately ? If so, have you updated the slave(s) ? Also have you tried reverting the update ? Which version are you using ? 1.520 took out support for JDK 1.5.
how do you run your java command ? From a terminal in an SSH session ? Is this scripted from the master ?

See also Jenkins slave jobs failing on "Unexpected termination of channel"
Comment: Thanks @coffeebreaks The Jenkins node started to respond after two days. I've a script that checks on Jenkins master if a node is connected or not and try to restart it. So it solved itself.
Answer: I've run into the same issue, which seemed to be worked-around by running jenkins-slave as root. Now, the thing periodically disconnects with that very same error, which I'm wondering is due to a LB keepalive. I'll update this answer as soon as I get more info.
Comment: Hi Will - just a heads up that for things like this people would typically leave a comment on the question, answers should really be used for providing solutions when they are ready :)
Comment: Whoops. I had a feeling this response was better as a comment, but I didn't want to create an account just to add this input. Will do next time though.
Comment: No worries - its a standard thing on here when people join that others try to help them out. And you should definitely create an account and get involved, it's a great community to get involved with!
Comment: Hi Will, our slave is running as root, (not the best solution). The Jenkins node started to respond after two days. I've a script that checks on Jenkins master if a node is connected or not and try to restart it. So it solved itself.
Answer: In my case everything was working under root account. But under user account, node client failed to connect to server with message "failed Unexpected termination of the channel".
The problem was with access-or-write to working folder. As soon as I've reassigned owner throug "chown -R", node starts successfully.


Page Refresh Javascript

Question: I am working on a music streaming website and i have this code and i want to know how to prevent page from changing song after i click on the href link
$.post("includes/handlers/ajax/getAlbumJson", {albumId: track.album}, function(data){
                var album = JSON.parse(data);

                $(".albumLink img").attr("src", album.artworkPath);
                $(".albumLink img").attr("onclick", "openPage('album.php?id=" + album.id + "')");
                $(".trackName span").attr("onclick", "openPage('album.php?id=" + album.id + "')");
                 $(".trackName a").attr("href", "album.php?id=" + album.id + "");

            });

Comment: write "javascript:void(0)" in href.
Comment: I have a music player underneath the page and it refreshes the songs after i click the href link
Answer: You should be able to just do:
$(".trackName a").on('click', function(){
return false;
});

Here's a working example:

$(".trackName a").on('click', function(){
    return false;
});

Click Me

Page Refresh Javascript


SQL Server Management Studio can not connect

Question: I have installed SQL Server Management Studio 2014. In "connect to server" window, I selected server type as "Database engine", server name as "(local)" but when I try to connect, n error is shown-

TITLE: Connect to Server
Cannot connect to ..
ADDITIONAL INFORMATION:
A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server) (Microsoft SQL Server, Error: 2)

Please help what to do...
Answer:
A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server) (Microsoft SQL Server, Error: 2)

This is a common error which arises when connecting to SQL Server with Management Studio.
This includes different type of error scenarios like (Service--Not Available),(Service-Not Running),(Network Library- Not Enabled),(Fire Wall-Blocking) Etc.
Please troubleshoot in systematic manner.

Click On start button and type Services.MSC
Check whether the SQL Server service has been installed and is running fine.

Please check the service whether started or not.
If Yes:

Next Scenario is Network Libraries Tune.

If No

Install the SQL Server Engine from the software package and start the service.
Answer: Please ensure these configurations status are active
Right Click on the Instance and Start it
Comment: Did you install SQL Server with management studio or is it just a SQL Management Studio?
Comment: When I click SQL Server Services, nothing shows in the right side window, "There are no items to show in this view." this message is shown. Please help---
Comment: I probably havent installed SQL Server on the system.
Comment: yes, chances are,, if you install when you continue the installation you would be asked SQL Instance name,Password blah blah..
Comment: Now don't run back and download whole SQL Studio with SQL Server. there is a Small Package (SQL only) just about 200MB so just select & download. do the proper installations then it will show in the Instance List
Comment: Why negative vote? please explain before put negatives. will be helpful to understand if there is fault
Answer: All Programs >> Microsoft SQL Server >> Configuration Tools >> SQL Server Configuration Manager >> SQL Server Services, and check if SQL Server service status is "Running".
Comment: When I click SQL Server Services, the message shows- "There are no items to show in this view."
Comment: Try to reinstall it or to install a new instance of SQL Server.
Answer:
All Programs
Microsoft SQL Server 2008 R2
Configuration Tool
SQL Server Configuration Manager
A pop up will open click on yes
Select Sql Server Services (At left side) and Make sure
    Status is running for all services (At right Side)

reference
Answer: in the login screen
Server name: Browse for more -- expand database Engine and choose your database then login again.


Anonymous users unable to download purchase

Question: I've set up a Drupal Commerce store (on localhost) for a book shop. One of the requirements is that people can buy ebooks without creating an account.
It all works fine if I buy a book as the administrator; at the end of the checkout process I can download the book. However, when I buy a book as an anonymous user I'm shown the 'Download now' link in plain text.
I'm using a content type named 'Books' with a field named 'Ebooks'. The latter uses the 'File' field type. The rest of my set-up is as follows:
Commerce File 7.x-2.0-beta2:

Product types: Books
Download limits: 5

Commerce License 7.x-1.2

Product types: Books
Line item types: Product

Permissions for anonymous users:

Checkout, Access checkout
Commerce licenses, View own licenses
Order, View own orders of any type

Rules:

Create a new account for an anonymous order: inactive
Assign an anonymous order to a pre-existing user: inactive
Activates licenses of an order: Completing the checkout process >
Activates all licenses of the provided order
Update the order status on checkout completion: Completing the
checkout process > Update the order state (to 'Pending')

At first I though the issue was that the order status is changed to 'Pending' once the checkout process has completed. However, changing this made no difference.
I then found that giving anonymous users permission to 'bypass license control' does instantly resolve the issue. However, that permission setting comes with a "give to trusted roles only; this permission has security implications".
So... something is not quite right in my set-up. It seems that anonymous users aren't given a license allowing them to download their purchase. I've run out of ideas though. What have I done wrong?
Answer: You have disabled the rules for creating an account for the anonymous user.
Therefore, the license never gets assigned to an actual user, stays assigned to user 0.
Commerce License and Commerce File were designed to license the file to an actual customer. I suggest either re-enabling the rules and creating the user accounts or developing a custom solution for the file downloads (you don't need most of commerce file if there's no actual user... just a temporary file link).
Comment: Thanks, that explains. Using a temporary file link would be the preferred solution - is there any documentation on how to set this up?


Estimating the error of a Taylor polynomial

Question: The information I'm given is that we are approximating $f(8)$ with a second degree Taylor polynomial for f centered around $a = 10$. Assume that the $abs(f'''(x)) \lt 3$ for $x$ on the interval $[6, 11]$.
This is all the information I have. The only way I know how to approximate the error of a Taylor polynomial is using the formula $f(x) - pn(x) =( \frac{(f^{(n+1)})(c)}{(n+1)!})(x - a)^{(n+1)}$ where $c$ is on the interval $[a, x]$, and $pn(x)$ is the n-th degree Taylor polynomial approximation of $f$ and the weird looking $f^{(n+1)}(c)$ is suppose to be the n+1th derivative of$f$ of c.
So I tried filling in the formula like this : $f(8) - p2(8)$ = (blank / 3!)(8-10)^3 and I'm trying to figure out what blank is suppose to be. So the interval should be $[10, 8]$ which is empty and besides that I have no idea of what to put where blank is.
Comment: $c$ should be between $8$ and $10$.
Answer: You can use the bound on the magnitude of the 3rd derivative, $3$, for the worst case for the bound. See this wikipedia article for details.
If $a$ is the center of the taylor series, then on the interval $(a-r,a+r)$, you can bound the remainder $R_k(x)$ for the $k$-th order polynomial as $M \frac{|x-a|^{k+1}}{(k+1)!} \leq M \frac{r^{k+1}}{(k+1)!}$ where $|f^{(k+1)}(x)| \leq M$ on the interval.
Comment: How do I pick r and do you know why I get the interval [10, 8]?
Comment: You only need the third derivative between $a$ and $x$, since the point $c$ of the remainter formula will be inside this segement. That is why consideration of $[8,10]$ is sufficient, and the bound for $[6,11]$ is of course also valid on the smaller interval.


Proof of Stickelberger's Theorem

Question: I am having some trouble in understanding the proof of Stickelberger's  Theorem,
$\textbf{Theorem :}$ If $K$ is an algebraic number field then $\Delta_K$, the discriminant of $K$, satisfies $$\Delta_K\equiv 0,1\pmod{4}$$
$\textbf{Proof :}$ Let $\lbrace a_1,\ldots ,a_n\rbrace\subseteq\mathfrak{O}_K$ be an integral basis for $K$ and $\sigma_1,\ldots\sigma_n :K\to \mathbb{C}$ be all the embeddings of $K$. Then we have by definition, $$\sqrt {\Delta_K}=\det([\sigma_i(a_j)])$$ and this can be written as $$\sqrt{\Delta_K}=\sum_{\pi\in A_n}\prod_{i=1}^n\sigma_i\left(a_{\pi (i)}\right)-\sum_{\pi\not\in A_n}\prod_{i=1}^n\sigma_i\left(a_{\pi (i)}\right):=P-N$$
Now for each embedding $\sigma_i$ we have, $$\sigma_i(P+N)=P+N,\hspace{5mm}  \sigma_i(PN)=PN$$ and hence $P+N, PN\in\mathbb{Q}$.
Hence we have $P+N,PN\in\mathbb{Z}$, because $P$ and $N$ are both algebraic integers. Now using the identity $$(P-N)^2=(P+N)^2-4PN$$ it follows that $\Delta_K\equiv0,1\pmod{4}.$
$\underline{\textbf{My questions}}:$
$(1)$ How can we apply $\sigma_i$ to $P+N$ and $PN$, I mean how does it follow that $P+N, PN\in K$ ?
$(2)$ Why is $\sigma_i(P+N)=P+N$ and $\sigma_i(PN)=PN$ ?
$(3)$ How does it follow that $P+N, PN\in\mathbb{Q}$ ?
Comment: Also asked in http://mathoverflow.net/questions/131057/doubt-in-the-proof-of-stickelbergers-theorem
Answer: First of all a short remark: I cannot really answer any of the three questions you asked at the end of your post. (For example, I have also the impression that it is not immediately clear why $P+N,PN \in K$.)
Nevertheless, here is my reconstruction of the proof you asked for. In some details, it is different from the proof you outlined. Instead, my proof will be in accordance with the answer to your question on mathoverflow (In fact, my proof hopefully answers the questions you asked in the comments to the mathoverflow-answer.)
Similar as in the proof you outlined, we can also write
$$\Delta_K=(\sum_{\pi \in X} \prod_{i=1}^n \sigma_{\pi(i)}a_i-\sum_{\pi \in Y} \prod_{i=1}^n \sigma_{\pi(i)}a_i)^2=(P-N)^2$$
where $X$ is the set of even permutations and $Y$ is the set of odd permuations in $S_n$. Note that we can assume $K \subset \mathbb{C}$. Let $L$ be a field with $K \subseteq L \subseteq \mathbb{C}$ and such that $L/ \mathbb{Q}$ is finite and Galois. (It is a well known fact in Galois Theory that a suitable $L$ exists). I will only explain the "critical step" of the proof, namely that $P+N, PN \in \mathbb{Q}$. (The rest should then be clear.) First of all I show the following statement:
($\star$)$\phantom{aaaaaaa}$$\phi(P+N)=P+N$ and $\phi(PN)=PN$ for all $\phi \in \text{Gal}(L/\mathbb{Q})$
Let $\phi \in \text{Gal}(L/\mathbb{Q})$. It follows from the normality of $L$ that $\sigma_iK \subseteq L$ for all the embeddings $\sigma_i$. Therefore, all the $\sigma_i a_j$ are in $L$ and we can apply $\phi$ to those elements (and thereby to $P$ and $N$). Moreover, for every $\sigma_i$, we can build the composition $\phi \circ \sigma_i$ and this is an embedding $K \to \mathbb{C}$. Now, it is not hard to see that the association $\sigma_i \mapsto \phi \circ \sigma_i$ gives us a bijection
$$\{\sigma_1,...,\sigma_n\} \to \{\sigma_1,...,\sigma_n\}$$
But this means that we can find a permutation $\tau \in S_n$ such that for every $i \in \{1,...,n\}$
$$\phi\circ \sigma_i=\sigma_{\tau(i)}$$
Distinguish two cases concerning $\tau$.
Case 1: $\tau$ is even. Then, $\tau X=X$ and we have
$$\begin{align}
\phi(\sum_{\pi \in X} \prod_{i=1}^n \sigma_{\pi(i)}a_i)
& = \sum_{\pi \in X} \prod_{i=1}^n \phi\circ\sigma_{\pi(i)}a_i \\
& = \sum_{\pi \in X} \prod_{i=1}^n \sigma_{\tau\pi(i)}a_i \\
& = \sum_{\pi \in \tau X} \prod_{i=1}^n \sigma_{\pi(i)}a_i \\
& =\sum_{\pi \in X} \prod_{i=1}^n \sigma_{\pi(i)}a_i
\end{align}$$
This shows $\phi(P)=P$. In a similar fashion, you can show that $\phi(N)=N$ (the key point is here that $Y=\tau Y$.)
Case 2: $\tau$ is odd. Here we have $\tau X=Y$ and $\tau Y=X$. It follows that $\phi(P)=N$ and $\phi(N)=P$ (the proof is similar to the one in case 1: simply write down the formulas for $\phi(P)$ and $\phi(N)$ and during the calculations, make use of $\tau X=Y$ and $\tau Y=X$).
In every case, $\phi(P+N)=P+N$ and $\phi(PN)=PN$ and this shows ($\star$).
Now, $(\star)$ says exactly that $P+N$ and $PN$ are in the fixed field of the Galois group. But this means $P+N, PN \in \mathbb{Q}$.
Answer: Maybe it's a bit late but you can also give a proof by only looking at ramification of $2$ in $K$. The theorem follows by proving that $\Delta_K\equiv 0\bmod 2$ implies $\Delta_K\equiv 0\bmod 4$, and that $\Delta_K\equiv 1\bmod 2$ implies $\Delta_K\equiv 1\bmod 4$.
Assume that $2|\Delta_K$. Then there exists a prime $\mathfrak{p}$ of $K$ lying over $2$ with $e=e(\mathfrak{p}/2)\geq 2$. If $e=2$ then we have wild ramification and hence $\mathfrak{p}^2|\mathfrak{D}_K$. Taking norms we conclude that $4|\Delta_K$. If $e\geq 3$ then we get $\mathfrak{p}^2|\mathfrak{p}^{e-1}|\mathfrak{D}_K$ so that similarly we obtain $4|\Delta_K$.
If $\Delta_K$ is odd, write $\Delta_K=u^2d$ for $d$ square-free. If $d=1$ then $\overline{\Delta}_K$ is square in $(\mathbb{Z}/4\mathbb{Z})^{*}$ so that $\Delta_K\equiv 1\bmod 4$. If $d\neq 1$ then $\mathbb{Q}(\sqrt{\Delta_K})=\mathbb{Q}(\sqrt{d})\neq \mathbb{Q}$ and if $N$ is the normal closure of $K/\mathbb{Q}$ then $\mathbb{Q}(\sqrt{\Delta_K})\subset N$. As $\Delta_K$ is odd we have that $2$ is unramified in $K$, hence also in $N$, hence also in $\mathbb{Q}(\sqrt{d})$, which implies $d\equiv 1\bmod 4$. As $u$ is odd we conclude that $\Delta_K\equiv 1\bmod 4$ as well.
Comment: This is a very nice argument!  I just used in in my algebraic number theory course.  Do you have an attribution for it, by any chance?
Comment: Thanks! I didn't see it anywhere else, I came up with the proof myself. Of course it still might be somewhere, I haven't looked extensively.
The way I stumbled upon it is I was once was playing around with what kind of ramification patterns can occur in an S3-extension of Q based on the value of the discriminant, and I noticed that using Stickelberger never gave me more information compared to the type of arguments in the above proof. This made me try to prove it using such arguments, and luckily, it worked :)

Proof of Stickelberger’s Theorem


JSON to Java Object UTF_8

Question: I`m using Jackson library to parse my java objects to/from json.
I have a problem, to parse text with "~".
Like: Questão.
I received:
Quest\u00c3\u00a3o

And after I use
objectMapper.readValue(json, targetClass);

I have this String on my Object Java: Questão .
How can I convert this "Quest\u00c3\u00a3o" for this "Questão"?
Thanks!
Answer: import java.net.URLDecoder;
String decodeStr = URLDecoder.decode("Quest\u00c3\u00a3o", "utf-8");

Comment: I try this:

String decodeStr = URLDecoder.decode("Quest\u00c3\u00a3o", "utf-8");
System.out.println("Decode: " + decodeStr);

this code print: Questão
Comment: @leonvian You can use `java.net.URLEncoder`. `URLEncoder.encode("Questão", "utf-8");`
Comment: The result for URLEncoder.encode("Questão", "utf-8"); was: Quest%C3%83%C2%A3o
Comment: Is this your expected?`org.apache.commons.lang.StringEscapeUtils.escapeJava("Questão")`

JSON to Java Object UTF_8


sqlite db which created by db browser does not work in android studio

Question: I have created an SQLite database using DB Browser, when I move it to the assets folder and open it in the android studio it looks so bad and it doesn`t work. what is the solution ? :(
here is a screenshot
Comment: why you want to open it? to see data?
Comment: No, just because the application stopped when I tried to query the database. so I found that the problem is in the database (look at the screen shot)
Answer: Actually the screen shot pretty much confirms that the file in the asset folder is a valid SQLite database.
That is the first 16 bytes match those of the database header The header string: "SQLite format 3\000" Database File Format.
Android Studio itself does not include the requirements to actaully open the file as an SQLite Database (there are tools, such as DB Browser that do this).
What you need to do, with your App, is open the file as an SQLiteDatabase. This is normally accomplished by copying the file from the asset folder to a suitable location (as the asset folder is part of the package it is read only) and then opening it from that location often via a subclass of the SQLiteOpenHelper.
There is a class available, namely SQLiteAssetHelper, that can make opening the database relatively easy. Note that SQLiteAssetHelper expects the database (name same as the file name including extension) to be in the databases folder of the assets folder (you would likely have to create this folder, although the screenshot shows that you have aleady placed the database into the databases folder).
Example
The following is a quick example of using the SQliteAssethelper to open the database and in this case list the items (tables, views, indexes, trigger etc) as per sqlite_master (SQlite's master table).
Build.gradle (App) (part thereof) :-
dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'com.android.support:appcompat-v7:28.0.0'
    implementation 'com.android.support.constraint:constraint-layout:1.1.3'
    implementation 'com.readystatesoftware.sqliteasset:sqliteassethelper:+' //<<<<<<<<<< ADDED JUST THIS LINE
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.2'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
}

See comment re added line

The DatabaseHelper (subclass of SQLiteAssethelper) DBHelper.java
public class DBHelper extends SQLiteAssetHelper {

    public static final String DBNAME = "DaycareCenters.db";
    public static final int DBVERSION = 1;

    SQLiteDatabase mDB;

    public DBHelper(Context context) {
        super(context, DBNAME, null, DBVERSION);
        mDB = this.getWritableDatabase();
    }
}

An invoking Activity (as an example) MainActivity.java
public class MainActivity extends AppCompatActivity {

    DBHelper mDBHlpr;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mDBHlpr = new DBHelper(this);
        Cursor csr = mDBHlpr.mDB.rawQuery("SELECT * FROM sqlite_master",null);
        while (csr.moveToNext()) {
            Log.d("SQLITEMASTER","Name = " + csr.getString(csr.getColumnIndex("name")) + " Type = " + csr.getString(csr.getColumnIndex("type")));
        }
        csr.close();
    }
}

Result (written to the Log)

Note I just copied a database that was convenient to copy, the tables etc list will not be the same as yours.

.
12-09 09:55:19.760 1473-1473/? I/SQLiteAssetHelper: successfully opened database DaycareCenters.db
12-09 09:55:19.764 1473-1473/? D/SQLITEMASTER: Name = android_metadata Type = table
12-09 09:55:19.764 1473-1473/? D/SQLITEMASTER: Name = player_card Type = table
12-09 09:55:19.764 1473-1473/? D/SQLITEMASTER: Name = sqlite_autoindex_player_card_1 Type = index
12-09 09:55:19.764 1473-1473/? D/SQLITEMASTER: Name = email Type = table
12-09 09:55:19.764 1473-1473/? D/SQLITEMASTER: Name = region Type = table
12-09 09:55:19.764 1473-1473/? D/SQLITEMASTER: Name = card Type = table
12-09 09:55:19.764 1473-1473/? D/SQLITEMASTER: Name = pc Type = table
12-09 09:55:19.764 1473-1473/? D/SQLITEMASTER: Name = sqlite_autoindex_pc_1 Type = index

First line is from the SQliteAssetHelper - it confirms that the database was copied from the assets folder.
The 2nd line shows table android_metadata, this is an android specific table that will be added, it contains the locale.
A few other tables.
A few indexes that are automatically created because of constraints or implied constraints
In short all is as expected.
Comment: where Log? to see the result
Comment: why the application stopped when I tried to query the database :(
Comment: In Android Studio click on **Logcat** near the bottom.There are numerous reason why a query may not work (again the logcat should say why). You should really ask another question (especially if you used the above and the tables etc were listed in the logcat, as this answers you initial question, in which case you should tick the question as answered).


Erro ao usar o System.Windows.Forms.SendKeys.Send("%{DOWN}")

Question: Em um aplicação windows form tenho um DateTimePicker e eu não quero que ele exiba a data então fiz o seguinte:
public CadNovoPagamento()
{
    InitializeComponent();

    dtpEmissao.Value = DateTime.Now;
    dtpEmissao.Format = DateTimePickerFormat.Custom;
    dtpEmissao.CustomFormat = " ";
}

private void dtpEmissao_ValueChanged(object sender, EventArgs e)
{
    dtpEmissao.CustomFormat = "dd/MM/yyyy";
}

private void dtpEmissao_KeyPress(object sender, KeyPressEventArgs e)
{
    String teste = e.KeyChar.ToString();
    if (e.KeyChar == (char)Keys.Enter || teste == "\t")
    {
        dtpEmissao.Text = dtpEmissao.Value.ToString();
        System.Windows.Forms.SendKeys.Send("{TAB}");
    }
}
private void dtpEmissao_Enter(object sender, EventArgs e)
{
    System.Windows.Forms.SendKeys.Send("%{DOWN}");
}

private void dtpEmissao_Leave(object sender, EventArgs e)
{
    if (dtpVencimento.Text != "" && txtDias.Text != "")
    {
        DateTime datavencimento = Convert.ToDateTime(dtpVencimento.Text);
        DateTime dataemissao = Convert.ToDateTime(dtpEmissao.Text);
        //Instância do TimeSpan recebendo a subtração entre as datas
        TimeSpan ts = datavencimento.Subtract(dataemissao);

        txtDias.Text = ts.TotalDays.ToString();
    }
}

Porem, quando ele entra no método dtpEmissao_Enter o computador trava e fica travado até abrir o gerenciador de tarefas.
Alguém sabe o que pode estar acontecendo?
Um observação em uma maquina o erro não acontece.
Comment: um datetimepicker, e vc nao quer que exiba a data ?! explique melhor por favor
Comment: seu código está bem estranho. Porque ao instanciar o `form`, coloca o custom format como `" "` e depois no evento `ValueChanged` você defime o custom format ?! Depois no `keypress`, você define o `Text` do controle sendo igual ao seu `value`...  e por fim, você pega o `Text` do datetimepicker, converte pra `DateTime` (oi?!) pra calcular um TimeStamp
Comment: sim preciso que ao abrir a tela o datetimepicker venha assim  __/__/____ porque esse não é um campo obrigatório, logo se eu trago com a data de hoje ao gravar ele grava com a data de hoje e necessariamente não é data de hoje.
Comment: Como eu poderia fazer esse "Show CheckBox" e/ou a MaskedTextBox  para não usar mais essa gambiarra?
Comment: @RovannLinhalis você sabe qual a Properties devo marcar?
Comment: veja a resposta
Answer: Sem entrar na questão do SendKeys, acho que a resolução pro seu problema pode ser mais simples:
Altere as properties do seu DateTimePicker:

Erro ao usar o System.Windows.Forms.SendKeys.Send(“%{DOWN}”)


How to solve system of equations depending on parameter

Question: \begin{cases} y=x^4 \\ y+8=a(x+5/4) \end{cases}
How many solutions does this sytem have depending on parameter a?
I need to solve it using derivatives somehow.
Thank you.
I solved using hint which bubba gave me.
Basically, we have this equation: $ x^4 + 8 = a(x + \frac54) $
Let's suppose that we have two functions: $ f(x) = x^4 + 8  $ and $g(x)=a(x+\frac54)$
$f(x)$ is a parabola looking thing while $g(x)$ is a line. So, we would have one solution when tangent line to $f(x)$ in some point $(x_0,f(x_0))$ derivative to $f(x)$ would be the same line as $g(x)$
So the derivative of $f(x)$ is $f'(x) = 4x^3$. So the tangent line would be $y = 4x_0^3(x-x_0) + f(x_0) = 4x_0^3x - 3x_0^4 + 8$. But we have that $y = g(x)$.
So \begin{cases} a=4x_0^3 \\ \frac54a=8-3x_0^4 \end{cases}.
Then we need to solve this equation:
$5x_0^3=8-3x_0^4$
The solutions are $x_0 = -2$ and $x_0=1$
So, we would have one solution when $a = 4$ and $a=-32$
And we would have no solutions if $0<=a<4$ or $0>=a>-32$.
And we would have two solutions if $a>4$ or $a<-32$
Comment: substracting this system gives you $-8 = x^4 - ax - \frac{5a}{4}$. Now you're down to one equation, can you take it from here?
Comment: Welcome to MSE, Yevs. We ask that people show us what they've tried already. That said, here's a tiny hint: what can derivatives tell you about how a function behaves?
Comment: You can write up your solution as an answer (it's Ok to answer your own questions). You might get some up-votes, and gain some points.
Answer: Think about the graphs of the two curves. The curve $y=x^4$ is a parabola-like thing. It's not really a parabola, but it has a similar shape. The other curve is a straight line through the point $(-\tfrac54, -8)$, whose slope depends on the value of $a$. For some values of $a$, the line will intersect the first curve twice, and for other values, there will be no intersection. The crucial state is when the two intersections coincide, which means that the line is tangent to the first curve. So, the key is to find a line that's tangent to the curve $y=x^4$ and passes through the point $(-\tfrac54, -8)$. As you said, you can use derivatives to do this.


Why isn't there any output?

Question: $results = db_query("select nid from {taxonomy_index} where tid = :tid", array(':tid' => arg(2)));
foreach ($results as $result) {
  $node = node_load($result->nid);
  echo $node->title;
}

I put the code in page--taxonomy.tpl.php, but there is no result. Why?
The output of print_r($results) is the following one.
DatabaseStatementBase Object
(
    [dbh] => DatabaseConnection_mysql Object
        (
            [shutdownRegistered:protected] =>
            [target:protected] => default
            [key:protected] => default
            [logger:protected] =>
            [transactionLayers:protected] => Array
                (
                )

            [driverClasses:protected] => Array
                (
                    [SelectQuery] => SelectQuery
                )

            [statementClass:protected] => DatabaseStatementBase
            [transactionSupport:protected] => 1
            [transactionalDDLSupport:protected] =>
            [temporaryNameIndex:protected] => 0
            [connectionOptions:protected] => Array
                (
                    [database] =>
                    [username] =>
                    [password] =>
                    [host] =>
                    [port] =>
                    [driver] =>
                    [prefix] => Array
                        (
                            [default] =>
                        )

                )

            [schema:protected] =>
            [prefixes:protected] => Array
                (
                    [default] =>
                )

            [prefixSearch:protected] => Array
                (
                    [0] => {
                    [1] => }
                )

            [prefixReplace:protected] => Array
                (
                    [0] =>
                    [1] =>
                )

        )

    [queryString] => select nid from taxonomy_index where tid = :tid

Comment: Whats the output for `$results->rowCount()` ?
Comment: i put print_r($results) to the question. there is no output.werid thing
Comment: what's use of the table taxonomy_index?
Comment: Duplicate of http://stackoverflow.com/questions/13737839/how-to-change-the-sql-command-into-drupal-7/13744389#13744389  Don't post across sites
Comment: Please don't put queries in your templates, it may cause mental harm yourself and other developers. :)
Answer: Please confirm you got any value from arg(2) which is equivalent to term id(tid) .
Try this code
$result = db_select('taxonomy_index', 't')
  ->fields('t')
  ->condition('tid', arg(2), '=')
  ->execute()
  ->fetchAssoc();

$node = node_load($result->nid);

print_r($node);

Answer: The taxonomy_index database table just contains a list of the nodes using a taxonomy term, not that taxonomy term, and any of its child terms (or its parent terms). If there isn't any node that is using a taxonomy term, the code you wrote doesn't print anything.
If you want to get a list of node using a taxonomy term, or its child terms, you could use code similar to the following one.
$tid = arg(2);
$query = db_select('taxonomy_term_data', 't');
$query->join('taxonomy_term_hierarchy', 'h', 'h.tid = t.tid');
$query->addField('t', 'tid');
$query->condition(
  db_or()
    ->condition('h.parent', $tid)
    ->condition('t.tid', $tid)
);
$query->addTag('term_access');
$query->orderBy('t.weight');
$query->orderBy('t.name');
$tids = $query->execute()->fetchCol();

$nids = db_query("select nid from {taxonomy_index} where tid IN :tids", array(':tids' => $tids))->fetchCol();

$nodes = node_load_multiple($nids);

The other reasons that could cause the code not to print anything are:

The taxonomy_index table is empty for some reasons, including the fact the Drupal variable taxonomy_maintain_index_table is not set to TRUE. Check what variable_get('taxonomy_maintain_index_table') returns; if it returns FALSE (or an equivalent value), that would explain why the table is not populated.
The value you are using as taxonomy term ID is not a taxonomy term ID.
There isn't any node using the taxonomy term for which you have the ID.

Why isn't there any output?


Adding a pause in JS while file downloads

Question: I have a function as follows:
 var audit ={
    init: function(){
      var dte = new Date();
      // hook into the get Accruals Link
      var accruals = $("#accruals");
      for (var i = 0, ii = accruals.length; i < ii; i++){
        $(accruals).bind("click", audit.accrualsClicked);
      }

      // hook into the get closed routes button
      var glbtn = $(".glBtn");
      for (var i = 0, ii = glbtn.length; i < ii; i++){
        $(glbtn).bind("click", audit.clickListener);
      }

      // hook into the GL Date1 element
      var glDate1 = $("#glDate1");
      for(var i = 0, ii = glDate1.length; i < ii; i++){
        var myDate = null;
        if ($("#glDate1").attr('rel') != null) {
          myDate = $.datepicker.parseDate("yy-mm-dd", $("#glDate1").attr('rel'));
        }
        else {
          myDate = dte.getFullYear() + '-' + dte.getMonth()+ '-' + dte.getDate();
        }
        $('#glDate1').datepicker({
          dateFormat: 'yy-mm-dd',
          minDate: -120,
          maxDate: '+1D',//'+1M +10D',
          showAnim: 'fadeIn',
          altField: '#actualDate',
          altFormat: 'yy-mm-dd',
          changeMonth: true,
          numberOfMonths: 2,
          showButtonPanel: true,
          defaultDate: myDate
          //onSelect: audit.doInvDate
        });
        $(glDate1).val(myDate);
      }
      // hook into the GL Date2 element
      var glDate2 = $("#glDate2");
      for(var i = 0, ii = glDate2.length; i < ii; i++){
        var myDate2 = null;
        if ($("#glDate2").attr('rel') != null) {
          myDate2 = $.datepicker.parseDate("yy-mm-dd", $("#glDate2").attr('rel'));
        }
        else {
          myDate2 = dte.getFullYear() + '-' + (dte.getMonth() +1) + '-' + dte.getDate();
        }
        $('#glDate2').datepicker({
          dateFormat: 'yy-mm-dd',
          minDate: -120,
          maxDate: '+1D',//'+1M +10D',
          showAnim: 'fadeIn',
          altField: '#actualDate',
          altFormat: 'yy-mm-dd',
          changeMonth: true,
          numberOfMonths: 2,
          showButtonPanel: true,
          defaultDate: myDate2
        });
        $(glDate2).val(myDate2);
      }
  },
  clickListener: function(event){
    audit.download(7);
  },

  accrualsClicked: function(Event){
    audit.download(6);
  },
  removeFile: function(fileName){
    var url     =  'http://'+window.location.hostname+'/truck/admin/export/service/removeFile.svc.php';
    var args    = "filename="+fileName;
    var res     =  audit.doAjax(url,args);
    //document.getElementById("Msg1").style.display = "none";
    if(res == '0'){
      alert('Failed to purge document: '+ fileName +' from file system')
    }
  },
  download: function(process){
    var gl1 = $('#glDate1').val();
    var gl2 = $('#glDate2').val();
    var url   =  'http://'+window.location.hostname+'/truck/admin/export/service/getFile.svc.php';
    var args  = "process="+process+"&gl1="+gl1+"&gl2="+gl2;
    var fileName =  audit.doAjax(url,args);
    if(fileName.length>3){
      var fileurl = "http://"+window.location.hostname+"/truck/admin/export/service/" + fileName;
      window.location = fileurl;
      audit.removeFile(fileName);
    }
  },
  doAjax: function(url, args){
    var retVal;
    retVal =   $.ajax({
                    type: "GET",
                    url: url,
                    data: args,
                    async: false
                }).responseText;
    if(retVal==null || retVal=="")retval=99;
    return retVal;
  }
}
audit.init();

This works fine in creating the file and creating the download box. One requirement I have is to remove the file after it is created and the user downloads it. Is there a way to put some type of pause, or listener, so that the audit.removeFile(fileName) does not run until the user either downloads or cancels the request (reference the download: function(process) sub function)?
Comment: Bumped for a second look
Comment: Rather than adding junk at the bottom of your question, improve your question. Your function is incomplete, and contains several undefined variables, such as `audit`.
Answer: Unfortunately, the answer is (currently) no on the client-side. The download happens in a different scope than where your page and client-side JavaScript exists. There are no related events you can monitor from within the page.
A couple server-side options that come to mind:

If your server maintains a lock on the file while it's being downloaded, which many (most?) do, you can safely use an automated process to clear out that temp directory periodically. Just be sure that process skips over files held open by the server and doesn't get hung on them.
If you serve the download through your own code instead of pointing users at a static file (even if your code ultimately just acts as a middleman to stream that static file down), then you'll know when the download has completed and can delete the file immediately afterward.
Comment: Interesting. Is there a better way to do this other than what I have defined?
Comment: @radi8: Added a couple server-side options to my answer.
Answer: As Dave Ward points out, the approach you're describing won't work. I'd simply run a job on a given interval on the server removing all files older than, say 10 minutes.
However, if you need to find a client side solution, you could try to use a popup.
In the global scope, you could add a function:
var popup = window.open(fileUrl);
popup.addEventListener('unload', function(){
  audit.removeFile();
});

Keep in mind that you should never use the unload event for anything important as a number of things can prevent it from running.
Comment: The problem there is that the page and download aren't related once the download begins. The user could close that page while the download was still in progress, and you wouldn't want to delete the file yet.
Comment: I know, but a popup solution could work most of the time if the files are quickly downloaded (i.e. images, texts, etc) and you could live with a popup window (which would have to be accepted in the popup blocker). If it's a good or bad idea depends on the system requirements, but I recommend the server side solution any day :)


Restricting a module to the irreducible components of an affine curve is injective

Question: The question is originally coming from a non-affine case, but I will only consider the affine one here.
Let $R$ be a ring which is reduced and has only a finite number of minimal prime ideals $P_1,\ldots,P_r$. Let $M$ be a finitely generated and torsion-free $R$-module (where the latter means that no regular element in $R$ can annihilate a non-zero element of $M$). There is a canonical map
$$R \to \prod_{i=1}^r R/P_i$$
which is injective since its kernel is given by $\bigcap_{i=1}^r P_i = \operatorname{Rad}(R) = 0$.

If we tensor this morphism with $M$, is it still injective? That is, is the morphism
  $$\varphi:M \to \prod_{i=1}^r M/P_iM$$
  injective?

It certainly is (by definition) if $M$ is flat.

But does the torsion-freeness suffice?
If not, can you give a counter example?
What are far less restrictive assumption on $M$ such that $\varphi$ is injective?

Of course, the reduceness of $R$ would help here again if $\bigcap_{i=1}^r P_iM \stackrel{??}{=} (\bigcap_{i=1}^r P_i)M = 0$. But I don't see why this should be true.

Edit: I forgot to mention that I work with curves and thus we also have $\dim R = 1$.
Answer: $\newcommand{\ass}{\operatorname{Ass}} \newcommand{\p}{\mathfrak{p}} \newcommand{tm}{\subseteq}$

Proposition: Let $R$ be a reduced ring and let $M$ be a torsion-free $R$-module. Then the map $M \to \prod_{P \in \ass(R)} M/PM$ is injective.

Proof: By Tag 0AVL it suffices to show that the induced local homomorphism for all associated primes of $M$ is injective. The torsion-free assumption on $M$ provides $\ass(M) \tm \ass(R)$ (see Torsionfree and associated primes) and thus it suffices to show the injectivity at minimal primes of $R$. Let $\p \in \ass(R)$ be a minimal prime of $R$. Then the localized homomorphism is $M_{\p} \to \prod_{P \in \ass(R)} (M/PM)_\p$. But for every minimal $\p \neq P$ we have $(M/PM)_\p = 0$ and thus the morphism is simply given by $M_\p \to (M/\p M)_\p \cong M_\p$ where the last isomorphism holds for minimal primes.
Remark: As the proof shows, we see that the above injection factors through $\prod_{P \in \ass(M)} M/PM$.
Answer: $M\to S^{-1}M$ is injective, where $S$ is the set of regular elements. But $S^{-1}R$ is just a product of fields and the rest should be clear.
Comment: I am not sure what I miss, but what you're saying is that the morphism $M \to \prod_i M_{P_i}$ is injective. So far I can follow, but where is the connection to the morphism $M \to \prod_i M/P_iM$?
Comment: $M_{P_i}=(M/P_iM)_{P_i}$.
Comment: Okay, I think I got it. From https://stacks.math.columbia.edu/tag/0AVL we know that we only need to check the injectivity at the associated primes of $M$ and those are a subset of the minimal primes of $R$ by the torsion-free assumption on $M$. Is this correct?


how to add a content creation in a view

Question: I've created a view where it displays all created articles by the current login user. named as "my Articles".
Now, I need to add a node/add/articles (which let me add a new article) together with the "my Articles"(view). where the "node/add/articles" is above of "my articles".
I don't have any idea how could I add an node/add/articles inside a view.
I need two solutions.
One is by not using a module and the other is using a module.
Comment: What do you mean by *content creation*? Be more specific please.
Comment: Please explain more. Your question is not clear.
Comment: adding a new node
Comment: What is your View ? a page or a block? Where of this View you need to display the node add link and block? your question is too vague
Answer: this could be done two ways that come to mind:
1) Create the view as a block, then under the block configuration set it to show at the top of the content region and only on node/add/article page
2) Create the view as a page, and then using Advanced Form Block create a block for the node/add/article form to show in the content region above the View, only on the page url for the view

Welcome to Advanced Form Block Module. With this module you can do the
  following:
1) Create any number of blocks with a particular node edit form.
2) create any number of blocks with a particular node add form of a
  content type.
3) Create as many blocks as you like of each kind.
4) From the content type choose which fields to display on a per block
  basis.However required fields will be automatically displayed.
5) All forms will be saved through ajax. So multiple node forms can be
  independently placed on a single page and worked with simultaneously.

how to add a content creation in a view


error calling ReportingService2005.FindItems(); specifically concerning the BooleanOperatorEnum parameter

Question: Having issues calling the ReportingService2005.FindItems() method from within powershell v2.
<code>$rs = New-WebServiceProxy -Uri $ReportServerUri -Namespace SSRS.ReportingService2005 -UseDefaultCredential;

$searchCondition = New-Object SSRS.ReportingService2005.SearchCondition
$searchCondition.ConditionSpecified  = $true
$searchCondition.Name = "Name";
$searchCondition.Value = "Sales";
[SSRS.ReportingService2005.SearchCondition[]] $searchConditions = @($searchCondition)

$boolOp = [SSRS.ReportingService2005.BooleanOperatorEnum]::And

#Also tried bellow initialization of enum.
#[SSRS.ReportingService2005.BooleanOperatorEnum] $boolOp = 0

$rs.FindItems("/", $boolOp ,$searchConditions)
</code>
Executing the above gives the following error:
Cannot convert argument "1", with value: "And", for "FindItems" to type "SSRS.ReportingService2005.BooleanOperatorEnum": "Cannot convert value "And" to type "SSRS.ReportingService2005.BooleanOperatorEnum". Error: "Invalid cast from 'SSRS.ReportingService2005.BooleanOperatorEnum' to 'SSRS.ReportingService2005.BooleanOperatorEnum'.""
Any help would be greatly appreciated,
Zach
Answer: Determined error to be related to the namespace paramater used in my webproxy. As it turns out, my script as posted runs successfully the first time it is excecuted in a session; it fails on successive executions in the same powershell session.
Found this article which explains the situation fairly well: http://www.vistax64.com/powershell/273120-bug-when-using-namespace-parameter-new-webserviceproxy.html
<code>$rs = New-WebServiceProxy -Uri $ReportServerUri -UseDefaultCredential;

$searchCondition = New-Object Microsoft.PowerShell.Commands.NewWebserviceProxy.AutogeneratedTypes.WebServiceProxy1er_ReportService2005_asmx_WSDL.SearchCondition;
$boolop = New-Object Microsoft.PowerShell.Commands.NewWebserviceProxy.AutogeneratedTypes.WebServiceProxy1er_ReportService2005_asmx_WSDL.BooleanOperatorEnum;
</code>


Jump to a heading in a view from outside the view on the same page

Question: I have a page with an introductory area and then a view that contains a large number of items grouped by a series of known headings. Kind of like this:
<code>_________________________________
Welcome Message and list of headings:
  - Heading 1
  - Heading 2
  - Heading 3
_________________________________
View:
Heading 1:
   - item 1
   - item 2
   ...
Heading 2:
   - item 3
Heading 3:
   - item 4
   - item 5
   - ....
</code>
and etc.
The page is put together using Panels; there is a custom content pane with the welcome message and list of links and the lower content is a view inside a pane.
I want the user to be able to click on a link in the top panel and be taken to a particular heading in the view below. I can't seem to think of a sensible way to do this without reworking how I do the entire view/page.
Any suggestions?
Answer: You should be able to do this using standard HTML anchors, just rewrite the output of the Headings to include a simple anchor tag and in your top panel (aka table of contents) make the links go to their corresponding anchor tags.


What causes stated console output in Tensorflow?

Question: Tensorflow puts out a lot of output in console, could you tell me what code in my program causes this output? Also, how do I suppress it?

....
Variable/Initializer/initial_value/7859, Variable/Initializer/initial_value/7860, Variable/Initializer/initial_value/7861, Variable/Initializer/initial_value/7862, Variable/Initializer/initial_value/7863, Variable/Initializer/initial_value/7864, Variable/Initializer/initial_value/7865, Variable/Initializer/initial_value/7866, Variable/Initializer/initial_value/7867, Variable/Initializer/initial_value/7868, Variable/Initializer/initial_value/7869, Variable/Initializer/initial_value/7870, Variable/Initializer/initial_value/7871, Variable/Initializer/initial_value/7872, Variable/Initializer/initial_value/7873, Variable/Initializer/initial_value/7874, Variable/Initializer/initial_value/7875, Variable/Initializer/initial_value/7876, Variable/Initializer/initial_value/7877, Variable/Initializer/initial_value/7878, Variable/Initializer/initial_value/7879, Variable/Initializer/initial_value/7880, Variable/Initializer/initial_value/7881, Variable/Initializer/initial_value/7882, Variable/Initializer/initial_value/7883, Variable/Initializer/initial_value/7884, Variable/Initializer/initial_value/7885, Variable/Initializer/initial_value/7886, Variable/Initializer/initial_value/7887, Variable/Initializer/initial_value/7888, Variable/Initializer/initial_value/7889, Variable/Initializer/initial_value/7890, Variable/Initializer/initial_value/7891, Variable/Initializer/initial_value/7892, Variable/Initializer/initial_value/7893, Variable/Initializer/initial_value/7894, Variable/Initializer/initial_value/7895, Variable/Initializer/initial_value/7896, Variable/Initializer/initial_value/7897, Variable/Initializer/initial_value/7898, Variable/Initializer/initial_value/7899, Variable/Initializer/initial_value/7900, Variable/Initializer/initial_value/7901, Variable/Initializer/initial_value/7902, Variable/Initializer/initial_value/7903, Variable/Initializer/initial_value/7904)' with input shapes: [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [6], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7],
[7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7],
[7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7],
[7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7], [7],.....

Here is my code
class LSTMmodel(tf.Module):
    def __init__(self, arg_name=None):
        super().__init__(name=arg_name)
        self.__input = tf.Variable(initial_value=[0.0 for x in range(7)], dtype=tf.float32)
        self.__input_reshaped = tf.reshape(self.__input, [1, 7, 1])
        self.__network = tf.keras.layers.LSTM(units=7, input_shape=(7,1))
        self.__output = tf.Variable(initial_value=[0.0 for x in range(7)], dtype=tf.float32)
        self.__output = tf.reshape(self.__output, [1, 7, 1])
    @tf.function
    def networkTraining(self, arg_data_train, arg_labels, arg_learning_rate):
        with tf.GradientTape() as t:
            print('loc 1')
            self.__input = tf.Variable(arg_data_train)
            print('loc 2')
            self.__input_reshaped = tf.reshape(self.__input, [1, 7, 1])
            self.__output = self.__network(self.__input_reshaped)
            print('loc 3')
            loss = tf.nn.sigmoid_cross_entropy_with_logits(labels=arg_labels, logits=self.__output)
            print('loc 4')
            dw, db = t.gradient(loss, [self.w, self.b])
            print('loc 5')
        self.w.assign_sub(arg_learning_rate * dw)
        self.b.assign_sub(arg_learning_rate * db)

    @tf.function
    def __call__(self, arg_input=[0 for x in range(7)]):
        self.__input = tf.Variable(arg_input)
        self.__output = self.__network(self.__input)
        return self.__output

# some other code
#
#
#
modela.networkTraining(cgm ,labels, 0.4)

EDIT:
The 'Variable/Ini..../<a_number>' happens right before the print('loc 4')
# ###########################FULL-CODE
import pandas
import scipy.io as loader
import tensorflow as tf
import keras
import numpy

tf.get_logger().setLevel('INFO')
class LSTMmodel(tf.Module):
    def __init__(self, arg_name=None):
        super().__init__(name=arg_name)
        self.__input = tf.Variable(initial_value=[0.0 for x in range(7)], dtype=tf.float32)
        self.__input_reshaped = tf.reshape(self.__input, [1, 7, 1])
        self.__network = tf.keras.layers.LSTM(units=7, input_shape=(7,1))
        self.__output = tf.Variable(initial_value=[0.0 for x in range(7)], dtype=tf.float32)
        self.__output = tf.reshape(self.__output, [1, 7, 1])
    @tf.function
    def networkTraining(self, arg_data_train, arg_labels, arg_learning_rate):
        with tf.GradientTape() as t:
            print('loc 1')
            self.__input = tf.Variable(arg_data_train)
            print('loc 2')
            self.__input_reshaped = tf.reshape(self.__input, [1, 7, 1])
            self.__output = self.__network(self.__input_reshaped)
            print('loc 3')
            loss = tf.nn.sigmoid_cross_entropy_with_logits(labels=arg_labels, logits=self.__output)
            print('loc 4')
            dw, db = t.gradient(loss, [self.w, self.b])
            print('loc 5')
        self.w.assign_sub(arg_learning_rate * dw)
        self.b.assign_sub(arg_learning_rate * db)

    @tf.function
    def __call__(self, arg_input=[0 for x in range(7)]):
        self.__input = tf.Variable(arg_input)
        self.__output = self.__network(self.__input)
        return self.__output
    # tf.nn.sigmoid_cross_entropy_with_logits(labels=None, logits=None)

correct = numpy.load('save.npy')
# link for the .mat file for your convenience
# https://drive.google.com/file/d/1NOZOeRm1oLOU12p3J4-zw3RrPnJZvw4-/view?usp=sharing
insulin = loader.loadmat('InsulinGlucoseData2.mat')
also = pandas.read_csv('dates222.csv')

# print(type(insulin['numCGM'][0:5]))
# quit()
cgm = []
temp = []
labels = []
# print(insulin['numCGM'])
# print(insulin['actBolusDelivered'])
counter = also.shape[0] - 1
counta = 0
# print(len(insulin['numCGM']))
while counter >= 0:
    if also['classification2'][counter] == 1:
        cgm.append(insulin['numCGM'][0][counter:counter + 6])
        labels.append([0, 0, 0, 0, 0, 0, 1])
        counter = counter - 7
    elif also['classification2'][counter] == 0:
        counter = counter - 1
        counta = counta + 1
        temp.append(insulin['numCGM'][0][counter])
        if counta == 7:
            counta = 0
            cgm.append(temp)
            temp = []
            labels.append([0, 0, 0, 0, 0, 0, 0])
    if counter - 7 < 0: break
    # print(counter)
# print(len(cgm[0]))
# quit()
modela = LSTMmodel(arg_name='ghajini_disease')
# print('------------------------------------------------')
# cgm = numpy.array(cgm, numpy.float32)
for each in labels:
    for each_one in each:
        each_one = float(each_one)
# print(len(labels))
# print('------------------------------------------------')
modela.networkTraining(cgm ,labels, 0.4)

out = modela(cgm)
print(out)

for each in out:
    su = su + each[-1]

train_accuracy = su/sum(labels) * 100

test = modela(new)

EDIT:
I suspect that this problem is being caused in the line self.__input = tf.Variable(arg_data_train). arg_data_train is actually a python list of python lists. I still don't understand the console output though.
Comment: can you provide the full code to reproduce please?
Answer: These logs might be due to looping in your code.
You can just turn off these logs using
import os
os.environ["TF_CPP_MIN_LOG_LEVEL"] = "2"
import tensorflow as tf


Posting data from webpage using JavaScript PHP jQuery to Google Sheet

Question: Before you say this is a duplicate, hear me out. I followed this answer (jQuery Ajax POST example with PHP), but I am trying to send the data to a Google Sheet. I have already got the code working on the Google Sheet, as I can add data to it by running my code directly from the sheet.
However, getting it to work with my webpage is apparently the problem. Even though I have followed the answer to the question I posted above, I think there is something more at play here that has to do with my lack of experience working in this area.
The code below is to a floating footer and is contained within the code of the whole webpage (where jquery-1.11.0.min.js and jquery-migrate-1.2.1.min.js have already been called). When I click on the submit button, the page looks like it processes the request, but nothing ever appears on the Google Sheet, Sheet1 (https://docs.google.com/spreadsheets/d/19l2kSHdBKEWtIFX44FxLBdvCoKjy7VqPF4IW6C1xAZc/edit?usp=sharing).
#document

Newsletter

      <form id="floater_footer" class="validate subscribe_form">

          <input type="text" class="form-control subscribe_mail" id="bar" name="bar" value="" placeholder="email address" required />

          <input type="submit" value="Subscribe" class="subscr_btn subscribe_btn" />

      </form>

Any suggestions on what could be going wrong? I am quite inexperienced when it comes to web development, as compared to most on this site. So I'm sure it's something simple I am missing!
Comment: If it makes the AJAX request you're losing that when the page reloads. If it is reloading the page you are having a problem with `event.preventDefault();`
Comment: You can do it , glad you got it solved.
Comment: Have you watched the AJAX request / response in the browser's developer tools? Have you included the jQuery library in the project? Are there an errors reported? Are you running this on a web-server?
Comment: I have not watched for that in the developer tools. I don't know how to do that, as the elements, console, and network tabs in Chrome are the only ones I use.
I included jquery-1.11.0.min.js and jquery-migrate-1.2.1.min.js.
The only errors reported are unrelated to this problem, and they aren't really errors that I'm concerned with right now.
It is actually running on a live site. There isn't much traffic on it, so I'm testing with it directly.
Comment: Those are a part of the developer tools.
Comment: Right, but I'm saying I don't know where I would see the request/response there.
Comment: It would be in the network tab.
Comment: The only thing I see that isn't normal page data is `?bar=testtext`. I used `bar` as the name for the text field I'm trying to send. It's appearing in the URL for some reason, though, it shouldn't. Perhaps what is actually happening is that the form isn't being submitted properly. It may just be reloading the page with the form data serialized and showing in the URL, but never doing the AJAX request. Does that makes sense?
Comment: I don't know why it worked, but I left the footer encapsulated in HTML as shown, but moved the script out to the head of the main page HTML. You gave me the idea that my script wasn't triggering at all with your last comment :) Do you want to make that an answer that I can then mark correct to give you rep, or should I do it? Thanks for all the help!
Answer: I don't completely understand why it worked, but taking out the script and putting it in the head of the page HTML seemed to work! Perhaps this was because having the script come after the elements was an issue, or perhaps having a $(document).ready() inside of an HTML that was inside the page's main HTML caused issue, or perhaps it was something else! No matter which one it is, the following solved the problem.
Up at the top of the code in the head of the page's HTML (but after the jQuery.js files were declared), I placed the script you saw already, but with some cosmetic changes. I'll put it here in the event I did indeed change something important that I didn't realize. I will also show the two jQuery files I included before the script:

Further down into the body of the HTML was this code where my footer was to be placed:
    #document

Newsletter

      <form id="floater_footer" class="validate subscribe_form">

          <input type="text" class="form-control subscribe_mail" id="email1" name="emailSignup" value="" placeholder="email address" required />

          <input type="submit" value="Subscribe" class="subscr_btn subscribe_btn" />

      </form>

Hopefully that will help somebody that has this problem in the future. You may see a reason this worked that I do not.
Big thanks to Jay Blanchard for making me question if my script was even triggering at all, which inspired me to pull the script out and put it somewhere else! The script almost certainly wasn't firing at all, and was the root of the problem. But WHY that was, I don't know. But I hope this helps someone else!


Adding workflow to files

Question: I'm working on a site that should let users to publish files (images), but I would to add a kind of workflow for these files.
Is there a way? I was thinking to use private/public files, in this way:

by default files are stored in "private" mode (so only certain users can see them)
create a module that simulates a workflow that "publish" a file, moving it to the "public" mode

Could be a solution?
Answer: The easiest way would be to create a content type called images, remove all the clutter and just add an image field. Since your images are now nodes, you can use any workflow module that you generally use. (Note you will have a overhead of one node for every image you upload)
If you don't want to follow the above approach then you can consider using rules and VBO module along with the the private folder options in image field settings.
Comment: This is a good way, but even if the node is not published, the file upload on sites/default/files is always available, so the best way could be to move files from private to public
Answer: Im not sure how you will tie this into like user roles or what your business logic is.
Here are some ideas / resources:

MediaMover module -- can add abitrary workflows to files. The examples are transcoding files, but its likely it could attach remove files to a public/privately made node for content viewing or sharing.
File Entity for D7, files are entities in D7.... woo!
Relation ACL, Relation is a module to add "relations" to entities. Relation ACL creates access logic to the given entity.
Encrypted Stream Wrapper or Encrypted Local Stream Wrapper, setups up a private filesystem URI and uploads files to that location. Allowed users can stream a de-crypted copy of the file to the enduser, files are stored encrypted on the filesystem.
Private Dynamic File Stream, store file entities of a certain type in a private filesytem and stream them as neccesary.

From your brief question I think you want to look at file_entity and either media mover or relation_acl.

Adding workflow to files


How do I use Excel.RangeAreas in Office JS?

Question: So I'm trying to use the RangeAreas class inside of Scriptlab to retrieve some information from multiple ranges at once, but I can't get it to work.
Here's my code:
$("#run").click(() => tryCatch(run));

async function run() {

  await Excel.run(async (context) => {
    var sheet = context.workbook.worksheets.getActiveWorksheet();
    var rangeAreas = sheet.getRanges("F3:F5, H3:H5");

    rangeAreas.load("address");

    await context.sync();

    console.log(rangeAreas.address);
  });
}

/** Default helper for invoking an action and handling errors. */
async function tryCatch(callback) {
  try {
    await callback();
  } catch (error) {
    // Note: In a production add-in, you'd want to notify the user through your add-in's UI.
    console.error(error);
  }
}

And this is the error I get in Scriptlab's console:
c {name: "RichApi.Error", code: "InvalidArgument", traceMessages: Array[0], innerError: null, debugInfo: Object…}
 name: "RichApi.Error"
 code: "InvalidArgument"
 traceMessages: Array[0]
 innerError: null
▶debugInfo: Object
 code: "InvalidArgument"
 message: "L'argument est manquant ou non valide, ou a un format incorrect."
 toString: function ()
 errorLocation: "Worksheet.getRanges"
 statement: "var ranges=activeWorksheet.getRanges(...);"
▶surroundingStatements: Array[8]
 0: "var workbook=context.workbook;"
 1: "var worksheets=workbook.worksheets;"
 2: "var activeWorksheet=worksheets.getActiveWorksheet();"
 3: "// >>>>>"
 4: "var ranges=activeWorksheet.getRanges(...);"
 5: "// <<<<<"
 6: "// Instantiate {ranges}"
 7: "ranges.load(["address"]);"
▶fullStatements: Array[6]
 line: 24
 column: 243520
 sourceURL: "https://appsforoffice.microsoft.com/lib/1/hosted/excel-mac-16.00.js"

I'm sure I've made a silly mistake somewhere, but I just can't find where, and it's driving me mad. Any help is greatly appreciated.
Answer: Your code runs perfectly on my side. Is your system locale is in French? there is a known issue for the separator for the ranges, the separator changes based on system local.
So I guess in French it maybe uses ";", can you try the following code below?
var rangeAreas = sheet.getRanges("F3:F5; H3:H5");

Comment: My system is indeed in french and that snippet worked like a charm! Thanks!


How do I update a site after its installation profile is updated?

Question: Say I decide to add a new module to an installation profile I've created and used to build a bunch of sites with.  Can I easily use Drush to update all of those sites to the latest version of the Installation Profile?
I've just recently started to grok installation profiles, but I'm not sure if they are useful after a site has been set up.  I manage 40+ sites at work, so this would be amazing if possible.
TIA.
Aaron
Answer: I don't know if you have any problem using Drush to update the installation profile, but I use git and everything is fine.
If you have code (in the installation profile) that writes on the db and push this to production nothing will happen. So all your changes must done manually.
Finally, the installation profiles aren't the best way to maintain a site, after Drupal install nothing will happen.
About the 40sites take a look at Aegir. It's a hosting platform for Drupals.


How does the Android platform detect ANR problems?

Question: When an Android application is not responding, an ANR dialog would pop up. My question is: how does the Android platform detect ANR and make the decision to initiate such a pop-up dialog.
Comment: From http://developer.android.com/training/articles/perf-anr.html, under the sub-heading **"What Triggers ANR?"**: *"Generally, the system displays an ANR if an application cannot respond to user input. For example, if an application blocks on some I/O operation (frequently a network access) on the UI thread so the system can't process incoming user input events.*"
Answer: Its based on the UI thread and how much time it takes the UI thread to return to the message loop (the message loop is hidden from you as the app developer, but there's a giant loop on your UI thread that receives messages for user input, draw requests, AsyncTask completion, etc).  Basically you have a fixed amount of time per message before it declares an ANR.  Time spent sleeping waiting for a message will never cause an ANR.  There's a separate watchdog process in Android that checks how long its been since the thread last got to the top of that loop, and if its too long it kills it and show the ANR dialog.
Comment: To add to this, I believe Android operates a 5 second input event timeout after which the ANR is displayed


What is the best way to draw a glossy circle in iPhone OpenGL or Coregraphics?

Question: I want to draw a circle on the iPhone screen with Shadow and glossy effect.I am new to coreGraphics and OpenGL and dont really know the difference between the two.And which library is to be used when.
How can I draw following image in iPhone? any reference point to learn the appropriate library would be great.

have 3 of those images [1]   [2]    [3]
and a slider to control the glow.when you slide to change the glow it should go across all these, and furthermore some levels could have upto 50 circles.
Comment: Any specific reason why a UIImage will not work?
Answer: OpenGL is not a library, it's an API that gives you a "no-frills" access to the graphics system. All it provides are graphics primitives (points, lines, triangles) that it places on the screen and rasterizes them applying colour, textures through mathematical formula and/or a program called shader.
Sure, what you want to draw can be drawn using OpenGL, but it will require several intermediate steps and an artistic understanding of how that image is created from drawing operations.
So to answer your question: The most simple approach is to store this kind of, well whatever it is, as a vector graphics (SVG), and draw it using a library that provides drawing from a file.
The choice between CoreGraphics and OpenGL should be based on what your application does primiarily: Is it rendering some 3D graphics, a custom written 3D engine maybe: Use OpenGL. If you're aiming to draw some kind of UI then CoreGraphics probably is the better choice.
Comment: Just a nitpick but doesn't OpenGL stand for Open Graphics Library?
Comment: It used to be called like this in the 1990-ies, but as soon as the first GPUs did show up, calling it a library no longer makes sense: A library usually implements something. On modern systems OpenGL is rather a interface to the graphics driver (and usually also some software rasterizer, that kicks in if there's no 3D capable hardware present). The name is a artifact from the days where the graphics hardware was programmed to the metal and abstracting that through a library made sense: Those days the SGI OpenGL directly accessed the hardware, at that time it was indeed a library.


Cannot login to ssh - stdin: is not a tty

Question: FIXED
If you have seen this in the login screen of your server...
stdin: is not a tty

...you know the trouble. Well. I've had the exact same problem on my root server. I tried several things to remount /dev/pts or /dev/tty but nothing worked and I wasn't able to open a second connection.
Then a friend of mine had the most basic idea to just restart the service "screen", which allows to create multiple virtual console sessions.
Guess what. The command...
service screen restart

...fixed the console sessions to work again. At the time the error occured, we had appox. 20 screens running.
Answer: This worked for me:
service screen restart

I believe our server just had too many tty sessions running (which screen sessions actually are) and couln't create a new one. We've had this problem only once before and we had about the same size of screens running.
After finding the bug, we also reinstalled "screen" by typing:
apt-get purge screen
apt-get autoclean
apt-get autoremove
apt-get install screen

just to make sure it's a setup error. We haven't had any problems since then.
EDIT: I contacted the server hoster to increase the maximum allowed tty sessions (which you should do too). The admin then set the maximum allowed tty sessions from 16 to 2048 (almost unlimited).


How can I use the spread operator with 'this'?

Question: I am defining a class in TypeScript.
So with the spread operator I can issue something like this:
class Foo {
  constructor(data: IDataStructure){
      const { ...k } = data; // and then k has taken over all the properties of data. Great!
  }

  public render () {

    return(

   );
  }
}

Now, I would love to do the same but not to put the properties in k but in the current object that is being created. I.e. I would like to do something like const { ...this } = data; Is there any smart way to do this in Typescript?
Comment: `...` isn't (and cannot be) an operator. It's just primary syntax.
Answer: You can't use spread to add properties to an existing object. There's no current syntax way of doing it; instead, use Object.assign:
Object.assign(this, data);

Example (in JavaScript):

class Example {
    constructor(data) {
        Object.assign(this, data);
    }
}
const e = new Example({answer: 42});
console.log(e.answer); // 42

Note that Object.assign does a shallow copy of the properties. So if one of data's properties refers to an object, that reference is copied over, and both data and this will refer to the same object:
const data = {
    answer: 67,
    obj: {
        prop: "value"
    }
};
Object.assign(this, data);
console.log(this.obj === data.obj); // true, it's a shallow copy, they both refer
                                    // to the same object

If you need a deep copy, where copying data also makes a copy of data.obj, see this question's answers.
Comment: I just found out it is not really working. What it does actually is to screw up your class. From that point on, whenever you wanna access the variables of the class thourough 'this' it is screwed as 'this' is now pointing to data.
Comment: @Jose - No, it isn't. `this` has a shallow copy of what's on `data`. I've added a note about deep cloning to the answer, but nothing in your question suggested that you wanted a deep copy.


How can i search with typing in selected category only?

Question: I am working on a website where i can select a category, in this case water earth or fire, and i want to search only in that selected category by the name of the picture. for example, i select the water category and the water pictures show up with their names (which works) but when i search, my search bar searches in all the categories and if 2 pictures have similar names from different categories they both show up. How can i make it search only within the selected category?
the code

(function() {

  const buttons = document.querySelectorAll('.btn')
  const storeImages = document.querySelectorAll('.store-items')

  buttons.forEach((button) => {
    button.addEventListener('click', (e) => {
      e.preventDefault()
      const filter = e.target.dataset.filter

      storeImages.forEach((item) => {
        if (filter === 'all') {
          item.style.display = 'block'
        } else {
          if (item.classList.contains(filter)) {
            item.style.display = 'block'
          } else {
            item.style.display = 'none'
          }
        }
      })
    })
  })

})();

const search = () => {
  const searchbox = document.getElementById("search-item").value.toUpperCase();

  const nature = document.querySelectorAll('.store-items');

  for (var i = 0; i < nature.length; i++) {
    let match = nature[i].getElementsByTagName('p')[0];

    if (match) {
      let textvalue = match.textContent || match.innerHTML

      if (textvalue.toUpperCase().indexOf(searchbox) > -1) {
        nature[i].style.display = "";
      } else {
        nature[i].style.display = "none";
      }
    }
  }

}

  All
  Water
  Earth
  Fire

<form>

  <input type="text" name="" id="search-item" placeholder="Search gallery" onkeyup="search()">
</form>

Ocean

Bridge

Flower Art

The first function is to filter them and the second one is the search one
Comment: Please send the code correctly
Answer: Use this (I edited script):

    var filter = "all";
(function () {

        const buttons = document.querySelectorAll('.btn')
        const storeImages = document.querySelectorAll('.store-items')
        buttons.forEach((button) => {
            button.addEventListener('click', (e) => {
                e.preventDefault()
                filter = e.target.dataset.filter

                search();
            })
        })
    })();

    const search = () => {
        const searchbox = document.getElementById("search-item").value.toUpperCase();

        const nature = document.querySelectorAll('.store-items');

        for (var i = 0; i < nature.length; i++) {
            let match = nature[i].getElementsByTagName('p')[0];

            if (match) {
                let textvalue = match.innerText;

                if (textvalue.toUpperCase().indexOf(searchbox) > -1 && (nature[i].classList.contains(filter) || filter === 'all')) {
                    nature[i].style.display = "block";
                } else {
                    nature[i].style.display = "none";
                }
            }
        }
    }

    All
    Water
    Earth
    Fire

<form>

    <input type="text" name="" id="search-item" placeholder="Search gallery" onkeyup="search()">
</form>

Ocean

Bridge

Flower Art

Shortly make the filter global (Becouse you need it when searching), and check the filter too in search. I called search  function from onclick listener becouse otherwise when you selected a filter, the search text would be skipped.
Comment: Thanks for the answer, ive been trying for hours now but i dont know how to do it @0x01010


Show: $L^1(\mathbb{R})$ with certain involution is not a $C^*$-algebra, since it does not hold the $C^*$ property

Question: I want to show that $L^1(\mathbb{R})$ with the convolution and the involution $f^*(z) = \overline{f(z)}$ is not a $C^*$-algebra, so it does not have the $C^*$ property, that is
$$
\|f*f^*\|_{L^1(\mathbb{R})} = \| f\|_{L^1(\mathbb{R})}^2.
$$
Does anyone know a simple counter example?
Answer: I found one, for
$$
f(x) = i \Big(\mathbf{1}_{(0,1)}(x) - \mathbf{1}_{(-1,0)}(x)\Big)
$$
we get
$$\|f\|_{L^1(\mathbb{R})}^2 = 4,$$
but
$$
\| f f^*\|_{L^1(\mathbb{R})} = \frac{8}{3}.
$$