How do I use IPTABLES to create a HTTPS (443) passthrough around Squid?

Question: I've got Ubuntu and Squid running on a machine acting as a transparent proxy and a default gateway for many pc's on my network, which means all internet bound activity comes through the interface to be filtered before leaving for the router (192.168.1.1). HTTPS/SSL (443) does not work because packets on port 443 will come in and hit a wall as I have no rules specified for it.
How do I use iptables to create a passthrough for 443 connections?
----------------- EDIT -----------------------
Managed to get https working after setting the proxy settings for SSL to point to the squid box. However, if I were making a linux router (which I sort of am), would it mean SSL would never work unless I have a proxy running? The IP address for the linux box is 192.168.1.235 and i've set a test computer running winXP to that as its default gateway. Surely there's a way to allow 443 SSL to "pass through" without even touching on the proxy?
I'm also a tad confused as to why https is working at all...I haven't got any sort of routes or anything in the iptables that deal with 443.
Any light shed on this would be greatly appreciated!
Answer: You can not transparently proxy HTTPS. When you transparent proxy, clients think they are talking to the remote server. With HTTPS, they will attempt to create an SSL connection, which will authenticate the remote host by comparing the remote certificate to the hostname. This won't work because your squid will not have the right certificate.
You can, however, proxy HTTPS connections, because clients that know how to proxy HTTPS will open a connection to your proxy and issue a CONNECT request, which basically tunnels the connection via the proxy.
The best thing for you to do is to block direct access to port 443 and tell your users that if they want to use HTTPS, they must configure their browser to use the proxy.
Comment: +1 for being completely correct.
Comment: How do you "block direct access to port 443"? And how do you unblock it then if the user configures their browser to use the proxy?
Answer: This assumes a bit about your configuration, but this should be close to what you need. Assuming the LAN side is eth1:
iptables -I INPUT -i eth1 -p tcp --dport 443 -j ACCEPT
This will jump all packets coming in from the LAN side with a destination port of 443 to the ACCEPT target and then out to the router, again I'm assuming you already have that set up.
Hope that helps.
EDIT: per your comment about having only one interface:
You will need a source-address based rule, then -- modify the addresses as needed:
iptables -I INPUT -p tcp -s 192.168.1.0/24 --dport 443 -j ACCEPT
Comment: nope! I only have eth0 set up as the box only has a single ethernet connection

how do i set up the accept chain?
Comment: See David's comment below. I completely forgot about what he mentions.


Specifying a MAC address of a new virtual machine instance on Google Cloud

Question: We are planning to move a Windows 2012 Server to Google Cloud, but we have one issue. We are going to reinstall on this server an application that uses the server's MAC address for its licensing so we have to maintain the MAC address of the old server. Can we specify the MAC address of the new server during the deploying of the preconfigured image on the Google cloud?
Thanks
Answer: Unfortunately, currently customizing MAC address is not supported in Google Cloud Platform VMs and thus it can not be specified during the deployment. However, there is an open feature request for it in the Google Cloud Public Issue Tracker.
I would recommend anyone who has similar request to star the feature request to ensure that they receive updates about it and post comments to attract more attention to it.


How to setup sublime text 3 to run on C++11, but it opens the cmd each run?

Question: How do I run C++11 in Sublime Text 3?
I found this and this works, but I want it to be able to open cmd each run.
(1)
<code>{
"shell_cmd": "g++ -std=c++11 \"${file}\" -o \"${file_path}/${file_base_name}\"",
"file_regex": "^(..[^:]*):([0-9]+):?([0-9]+)?:? (.*)$",
"working_dir": "${file_path}",
"selector": "source.c, source.c++",

"variants":
[
    {
        "name": "Run",
        "shell_cmd": "g++ -std=c++11 \"${file}\" -o \"${file_path}/${file_base_name}\" && \"${file_path}/${file_base_name}\""
    }
]
}
</code>
Like this one:
(2)
<code>{
    "cmd":
     [
         "g++", "-Wall", "-ansi", "-pedantic-errors", "$file_name", "-o",
         "${file_base_name}.exe", "&&", "start",
         "cmd", "/k" , "$file_base_name"
    ],
     "selector": "source.cpp",
     "working_dir": "${file_path}",
     "shell": true
}
</code>
The problem with (1) is it runs with the console inside Sublime Text 3, I don't want that, unfortunately.
The problem with (2) is it runs well and it opens CMD each time, which is what I need, but it's on C++98. When I need C++11.
So, is there a way to modify any one of these build systems so that I can run C++11 and make it open CMD every run (instead of running it on the console)? Thanks.
Comment: Have you tried modifying the version that runs in `cmd` like you want to use the correct compiler arguments to get the version you want?
Answer: I was able to figure it out with a little bit of tinkering involved.
<code>{
"shell_cmd": "g++ -std=c++11 \"${file}\" -o \"${file_path}/${file_base_name}\"",
"file_regex": "^(..[^:]*):([0-9]+):?([0-9]+)?:? (.*)$",
"working_dir": "${file_path}",
"selector": "source.c, source.c++",

"variants":
[
    {
        "name": "Run",
        "shell_cmd": "g++ -std=c++11 \"${file}\" -o \"${file_path}/${file_base_name}\" && start cmd /k \"${file_path}/${file_base_name}\""
    }
]
}
</code>


Distribution of areas of uniform random cuts in a sphere

Question: TLDR;
What's the probability law of the area of a random cut on a sphere, with the random cut being perpendicular to a fixed segment connecting two antipodal points on the sphere, and sampled uniformly?
More precise description and my results
Suppose to have a sphere of radius 1, to choose a segment connecting two antipodal points and to randomly sample (with uniform distribution) a point on this segment. Now draw the 2d plane orthogonal to the segment and passing by the point.
This plan will cut the sphere in two, determining a circle. I would like to find the distribution of the areas of such circles.
Using the transfer operator, unless I did some trivial algebra  errors, I have showed that called $P(A)$ the random variable of the area of such circle, we have that (the support is $[0, \pi]$), $P(A)$ has a density, and it is
$$
\frac{1}{2\pi\sqrt{(1 - A/\pi)}}.
$$
Since I need this result for a computational problem I would be fine with this, but I wonder it this density is coming from a know probability law. Any help is appreciated :)
Comment: It is a stretched (by a factor of $\pi$) version of a $\text{Beta}\left(1,\frac12\right)$ distribution
Comment: Brillian! Thank you. If you make it as an answer I'll give you a deserved upvote :)
Answer: As requested in comments:
It is a stretched (by a factor of $\pi$) version of a $\text{Beta}\left(1,\frac12\right)$ distribution
See Wikipedia on the Beta distribution for some of the statistics, remembering to scale where necessary
Comment: Am I misunderstanding something? ... It seems to me that we have the area of the base of a spherical cap (like in [this](https://en.wikipedia.org/wiki/Spherical_cap) picture), so $A=\pi\sin^2\theta$, $\theta\sim\text{Uniform}(0,\pi)$. If so, I think @Nisba's density for $A$ is missing a factor that turns it into a (stretched) $\text{Beta}(1/2,1/2)$ distribution.
Comment: @r.e.s.  Traces of the Bertrand paradox. What seems to be uniformly distributed is the point on a diagonal of the sphere (I think *segment* is used here as line segment rather than circular or spherical segment). So the point halfway from the centre to the surface corresponds to a median area of $\pi\left(1-\frac1{2^2}\right)$.  This is consistent with $\text{Beta}(1,1/2)$ but not with  $\text{Beta}(1/2,1/2)$.


Return large file from JAX-WS service

Question: I'm trying to return large file from JAX-WS service method, but getting strange client error. Here is my code:
@WebService(targetNamespace = "http://java.CAEServer", portName = "CAEInstance")
public interface Instance  {
    @WebMethod(action = "http://java.CAEServer/getResultsArch")
    DataHandler getResultsArch(org.caebeans.caeserver.Instance instance);
}

Implementation:
MTOM(enabled = true, threshold = 2048)
@BindingType(SOAPBinding.SOAP11HTTP_MTOM_BINDING)
@StreamingAttachment(parseEagerly=true, memoryThreshold=4000L)
@WebService(endpointInterface = "org.caebeans.wsrf.Instance")
public class InstanceImpl implements Instance {
    @Override
    public DataHandler getResultsArch(org.caebeans.caeserver.Instance instance) {
        try {
            return workStorageManager.getWorkPackage(instance.getId());
        } catch (Exception e) {
            logger.fatal("Failed to zip work", e);
            throw new RuntimeException("Failed to zip results");
        }
    }
}

getWorkArch returns DataHandler with zipped data. Here is client code:
Instance instanceTransport = new InstanceImplService().getInstanceImplPort();
SOAPBinding binding = (SOAPBinding) ((BindingProvider) instanceTransport).getBinding();
binding.setMTOMEnabled(true);

byte[] resultArch = instanceTransport.getResultsArch(instance);

And when I'm trying to run it, I'm getting errors. Here is server stack trace:
java.io.IOException: Broken pipe
at sun.nio.ch.FileDispatcher.write0(Native Method)
at sun.nio.ch.SocketDispatcher.write(SocketDispatcher.java:29)
at sun.nio.ch.IOUtil.writeFromNativeBuffer(IOUtil.java:69)
at sun.nio.ch.IOUtil.write(IOUtil.java:40)
at sun.nio.ch.SocketChannelImpl.write(SocketChannelImpl.java:336)
at sun.net.httpserver.Request$WriteStream.write(Request.java:397)
at sun.net.httpserver.ChunkedOutputStream.writeChunk(ChunkedOutputStream.java:108)
at sun.net.httpserver.ChunkedOutputStream.write(ChunkedOutputStream.java:77)
at sun.net.httpserver.PlaceholderOutputStream.write(ExchangeImpl.java:390)
at com.sun.xml.internal.ws.transport.http.server.ServerConnectionImpl$2.write(ServerConnectionImpl.java:163)
at javax.activation.DataHandler.writeTo(DataHandler.java:294)
at com.sun.xml.internal.ws.encoding.MtomCodec$ByteArrayBuffer.write(MtomCodec.java:189)
at com.sun.xml.internal.ws.encoding.MtomCodec.encode(MtomCodec.java:156)
at com.sun.xml.internal.ws.encoding.SOAPBindingCodec.encode(SOAPBindingCodec.java:249)
at com.sun.xml.internal.ws.transport.http.HttpAdapter.encodePacket(HttpAdapter.java:328)
at com.sun.xml.internal.ws.transport.http.HttpAdapter.access$100(HttpAdapter.java:82)
at com.sun.xml.internal.ws.transport.http.HttpAdapter$HttpToolkit.handle(HttpAdapter.java:470)
at com.sun.xml.internal.ws.transport.http.HttpAdapter.handle(HttpAdapter.java:233)
at com.sun.xml.internal.ws.transport.http.server.WSHttpHandler.handleExchange(WSHttpHandler.java:95)
at com.sun.xml.internal.ws.transport.http.server.WSHttpHandler.handle(WSHttpHandler.java:80)
at com.sun.net.httpserver.Filter$Chain.doFilter(Filter.java:65)
at sun.net.httpserver.AuthFilter.doFilter(AuthFilter.java:65)
at com.sun.net.httpserver.Filter$Chain.doFilter(Filter.java:68)
at sun.net.httpserver.ServerImpl$Exchange$LinkHandler.handle(ServerImpl.java:557)
at com.sun.net.httpserver.Filter$Chain.doFilter(Filter.java:65)
at sun.net.httpserver.ServerImpl$Exchange.run(ServerImpl.java:529)
at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908)
at java.lang.Thread.run(Thread.java:680)

And here is client stack trace:
xception in thread "main" java.lang.OutOfMemoryError: Java heap space
at com.sun.xml.internal.org.jvnet.staxex.ByteArrayOutputStreamEx.readFrom(ByteArrayOutputStreamEx.java:60)
at com.sun.xml.internal.org.jvnet.staxex.Base64Data.get(Base64Data.java:225)
at com.sun.xml.internal.org.jvnet.staxex.Base64Data.length(Base64Data.java:266)
at com.sun.xml.internal.ws.encoding.MtomCodec$MtomXMLStreamReaderEx.getTextCharacters(MtomCodec.java:508)
at com.sun.xml.internal.bind.v2.runtime.unmarshaller.StAXStreamConnector.handleCharacters(StAXStreamConnector.java:312)
at com.sun.xml.internal.bind.v2.runtime.unmarshaller.StAXStreamConnector.bridge(StAXStreamConnector.java:176)
at com.sun.xml.internal.bind.v2.runtime.unmarshaller.UnmarshallerImpl.unmarshal0(UnmarshallerImpl.java:351)
at com.sun.xml.internal.bind.v2.runtime.BridgeImpl.unmarshal(BridgeImpl.java:109)
at com.sun.xml.internal.bind.api.Bridge.unmarshal(Bridge.java:222)
at com.sun.xml.internal.ws.client.sei.ResponseBuilder$DocLit.readResponse(ResponseBuilder.java:514)
at com.sun.xml.internal.ws.client.sei.SyncMethodHandler.invoke(SyncMethodHandler.java:110)
at com.sun.xml.internal.ws.client.sei.SyncMethodHandler.invoke(SyncMethodHandler.java:78)
at com.sun.xml.internal.ws.client.sei.SEIStub.invoke(SEIStub.java:107)
at $Proxy31.getResultsArch(Unknown Source)
at Main.main(Main.java:73)

What's wrong?
EDIT: Here is hosting code in my Main class:
Endpoint instanceEndpoint = Endpoint.publish(serverHost + INSTANCE_PATH, instance);

Client is runned with default MacOS java 6 settings. I'm trying to download 400Mb file, and without TOM enabled, the server fell with OutOfMemory error.
Comment: What is the JAX-WS runtime? What about the memory for your client? The byte array may constains the full file?
Comment: See edit, I've added some info
Comment: I always like to verify that it is using MTOM using Wireshark, due to client and server having to agree to use it.  As suggested below, you can also tell the client to use more heap space.
Answer: Here are some suggestions and observations:

Broken pipe exception is thrown when the server is responding to the client but client connection terminates midway.
This is quite obvious as your client crashed with out of  memory error and its not able to handle the amount of data received from the server with the given heap-size (I see you are trying to hold the data in byte array.).
One and quickest solution is to increase the heap-size of the client VM to appropriate value.
Other and more practical option (provided your use case entertains this) is to stream the data in a persistent location (e.g. a file). This way the entire data will not be loaded in the memory

EDIT:
If you check the documentation. There a StreamingDataHandler class which can be used to stream the data. This this particular link. There is a subtopic called Streaming SOAP Attachments. It gives and example of large file download, very close to your use case.
   I think you only need to change the client side code and use StreamingDataHandler instead of DataHandler
Comment: Can you provide some streaming examples? I've tryed to do this in these code samples. Also, file size can be various - even several gygabytes.
Comment: I've changed my code as written in the article, but still getting OutOfMemory on client :(
Comment: Can you please tell on which line OME occurs ?
Comment: It occurs on the line with remote call (in my case - `getResultArch`). Also, looks like it working on Linux, but not MacOS
Comment: The default heap size allocated to VM differs from platform to platform. You can [Check the heapsizes](http://stackoverflow.com/questions/2015463/how-to-view-the-current-heap-size-that-an-applicatin-is-using) allocated on different machine and find out the precise memory requirement.

Return large file from JAX-WS service


Can someone point out what I'm doing wrong here with my solids of revolution?

Question: This is very simple but I can't figure out what I'm doing wrong.
Let's say I'm rotating $f(x)=x^2$ around the y-axis.  I have limits on the x-axis of a=1 and b=2.  I want the volume under the curve, so I use the shells method, which gives me:
$2\pi \int_a^b f(x)x\delta x$ = $\frac{15}{2}\pi$
Now let's say I do it another way.  I'll find the volume of the hollow cylinder with outer radius $b$ and inner radius $a$ and height f(b).  This is $12\pi$. Now I want to subtract what's above the curve rotated around the y-axis.
I rotate function f around the y-axis, this time getting the volume above the curve.  I can do this by integrating $f^{-1}(y)$ with limits $f(a)$ and $f(b)$.  That gives me:
$\pi\int_{f(a)}^{f(b)}(f^{-1}(y))^2dy = \pi\int_1^4(\sqrt(y))^2dy = \pi\int_1^4y dy=\frac{15}{2}\pi$.
I'm sure at this point I've already made my mistake since the last answer gave me my final answer before I was expecting it.
Where's my mistake?
Answer: In calculating the volume generated above the curve, you forgot that you have washers with outer radius $\sqrt{y}$ and inner radius $1$, not disks of radius $\sqrt{y}$: you should have
$$\begin{align*}
\pi\int_1^4\left(\left(\sqrt{y}\right)^2-1^2\right)dy&=\pi\int_1^4(y-1)dy\\
&=\pi\left[\frac12y^2-y\right]_1^4\\
&=\pi\left(\frac{15}2-3\right)\\
&=\frac92\pi\;.
\end{align*}$$
Now when you subtract this from $12\pi$ youl'll get exactly what you expect.
Comment: @David: Eep! Yes.
Answer: There is a mild typo, you wrote $\pi\int_1^4x\, dy$ instead of $\pi\int_1^4y\, dy$, but that's not the problem, since you calculated as if it had been $y$.
In your second way, when you are trying to find out what to subtract, you are subtracting too much.  You are using slicing to find  the volume of the piece removed. So you need to find
$$\int_1^4 \pi(y-1)\,dy.$$
This is because your slice also has a hole in it. The cross-section of the slice has a hole of radius $1$. So the area of the slice is $\pi((\sqrt{y})^2-1^2)$.
Comment: Yeah thanks for pointing out the typo.  In my head, I mix it up a little:  I imagine 2 different $y$s, hence the confusion :)
Comment: Thanks, I see it now.  I need to be careful about that.  So I suppose it was just a coincidence that $2\pi \int_a^b f(x)x\delta x = \pi\int_{f(a)}^{f(b)}(f^{-1}(y))^2dy$.


Missing feeds plugin after Drupal core update

Question: I have inherited a Drupal site from another developer and since I updated Drupal (Commerce Kickstart) to the lates version I have a warning "Missing Feeds plugin FeedsEntityProcessor..". I am not familiar with wthe Feeds module before so have no idea what is actually missing and where to look for it. Any ideas?
Comment: Thanks for the tip! I reverted the feeds module to the version it was before I updated it and now it seems ok again.
Comment: Oké, can you accept my answer so users that stumble on this problem in the future know this was the correct answer, thanks.
Answer: Have a look at this issue, should fix your problem: https://www.drupal.org/node/2397763


Floyd Rose detuning after the first dive-bomb past dropD and can't recover E tuning on the adjustments without unlocking WHY

Question: I have a Jackson js32 roads special. I get it in E tuning Lock it down and after the first dive bomb it knocks out of tune so far I can't get it back without unlocking it WHY someone please help
Comment: Not sure if it's the case for you but I looked up the guitar and the first review I found says that the guitar the reviewer got was poorly aligned so that the tremolo block hits the body when divebombing, lifts the tremolo knife edge off its posts and puts guitar out of tune when it falls back in slightly different position.
Answer: divebombing unloads the strings so much tension can be release all along their length - even beyond the nut and bridge pieces. When you bring the bridge back up to pitch, there is nothing to increase the tension beyond the nut back to where it was, so your strings end up at a lower pitch.
The best solution is a locking nut, which is why many brands have this option combined with a fully floating bridge. It needs to be locked securely so the strings cannot slip even a little.
Another solution is to pre-divebomb when tuning to allow the strings to settle somewhere predictable.
Comment: Tuning with a whammy bar & non-locked nut… the eternal dilemma. Dive to keep in tune, but then every time you bend it goes flat. Bend to keep in tune, then every dive goes flat. My solution was to remove the whammy & tighten the bridge solid ;))
Comment: One of my guitars has the Zero-Point trem, which is an attempt to fix this, but it doesn't feel as nice as a proper trem I can divebomb all day long
Comment: I only have a variety of 'standard' Strats, with their very primitive system. I couldn't even tell you where any of the whammy bars are these days. I think this is a habit i started in the 80s & haven't used one since ;)) My Variax is a hard-tail anyway.
Comment: I do happily use all the different trems for their different sounds (Kahler, Floyd-Rose, Strat etc) along with fixed bridge for more solid sustain and tone as needed. But my fave is the Ibanez Floyd Rose or my Joe Satriani special


Equivalence of algebraic closures

Question: A couple of weeks ago, we were given the following theorem in class:
Let $\alpha \in \bar{\mathbb{Q}}$ and $K = \mathbb{Q}(\alpha)$. Then $\bar{K} = \bar{\mathbb{Q}}$.
I can see that $\bar{\mathbb{Q}} \subseteq \bar{K}$ since $\mathbb{Q}\subseteq K$. But I am having trouble proving $\bar{K} \subseteq \bar{\mathbb{Q}}$. So if $\beta \in \bar{K}$, then there is a $f \in K[t]$ such that $f(\beta) = 0$. Must $m(t)$ (the minimal polynomial of $\alpha$ in $\mathbb{Q}$) divide $f$? If so, can we say the quotient $\frac{f(t)}{m(t)}$ is the polynomial over $\mathbb{Q}$ that we are looking for? I.e. $\frac{f(\beta)}{m(\beta)} = 0$. (Must this quotient be in $\mathbb{Q}[t]$?)
Comment: Hint: $\alpha \in \overline{\mathbb{Q}}$, hence $K=   \mathbb{Q}[\alpha] \subseteq \overline{\mathbb{Q}}$
Comment: I think I see where you're going with this. Could you provide one more hint on why $\mathbb{Q}(\alpha) \subseteq \bar{\mathbb{Q}}$?
Comment: By definition of $\overline{\mathbb{Q}}$ is the field of all algebraic element over $\mathbb{Q}$, now  every element in the $\mathbb{Q}(\alpha)$ is algebraic over  $\mathbb{Q}$
Answer: Another characterisation of algebraic elements over field  $K$ is that $K(\beta)$ has finite dimension as a $K$-vector space. If $\dim_K K(\beta)=n$ and $\dim_{\mathbf Q}K=p$, then
$$\dim_{\mathbf Q}(K(\beta))=np$$
Now $\mathbf Q(\beta)$ is a $\mathbf Q$-subspace of $K(\beta)$, hence it has finite dimension, which proves $\beta $ is algebraic over $\mathbf Q$.

Equivalence of algebraic closures


Access logs show someone "GET"ing a random ip, why does this return 200?

Question: I have a small linux box set up with Apache as a way to teach myself Apache. I've set up port forwarding on my router so it's accessible from the outside world, and I've gotten a few strange requests for pages that don't exist from an IP address in China.
Looking at my access_log shows that most of these return 404 errors, which I'm guessing is a good thing. However, there is one request that looks like this:
<code>220.127.116.11 - - [25/Dec/2010:19:05:25 -600] "GET http://22.214.171.124/ HTTP/1.1" 200 3895
</code>
I'm curious what this request means... That IP address is unconnected to my server as far as I know, and visiting it simply tells me information about my uid.
So, my questions are: How is it that this request is showing up in my access_log, why is it returning 200, and is this a bad thing (do I need to set up more security)?
Answer: They are using it as a proxy.. or trying to use it as a proxy
Comment: Anyone who runs a service accessible to the public at large will run into this, people trying to take advantage of possible misconfigurations.  If you had your Apache badly configured as an open proxy, the request would have been fufilled.  Since you don't, all you get is a weird log entry.
Answer: The format of the GET request is a proxy request. If you have the proxy function of your web server enabled then it will fetch the remote page and return it to the requestor.
If you have the proxy function disabled then the request is altered internally and the default page is served exactly as if they had requested / instead.
Comment: http://httpd.apache.org/docs/2.2/mod/mod_proxy.html specifically http://httpd.apache.org/docs/2.2/mod/mod_proxy.html#proxyrequests
Comment: This was quite helpful, thanks. Is there something in the apache documentation that explains this/what directive configures how my server can be used as a proxy?
Answer: '200' is just a regular/successful return code.
What it means is that the person requesting the page has retrieved it properly and, in this case, was the root location of your web server [http://22.214.171.124/] - no other pages or addresses.
It's normal and you will see many of these once the website is up and running.. that's how analytics applications/reporting works.. and that's how they can plot on a user's visit or behaviour.
Hope this helps!
Cheers,
Alex
Comment: I'm aware that 200 is a successful return code. As I said, that ip is not the location of my server, which prompted the question. Why did apache return 200 if the request was for something that does not exist on my server. Also, how would one make that request in the first place?
Comment: You can do it to any webserver through `telnet` or `nc`, i.e. `telnet http://www.example.invalid 80` and then manually entering enter, then `GET HTTP://www.go-here.invalid/index.html HTTP/1.1`


C application error on run

Question: I've built a C application, and when I build it, it shows no errors, but when I run it, it gives me the error "Segmentation Fault: 11".
If it helps, here is the code I am using:
#include <stdio.h>
int main(char *argv[]) {
printf("The project path is: ./Projects/%c", argv[1]);
return 0;
}

Answer: The correct main prototyped syntax is
int main(int argc, char *argv[]) { ... }

Also %c conversion specification in printf prints a character, to print a string use %s.
Answer: You have a number of problems:

The signature for main is an argument count followed by an array of C strings.
You should always check the count before using the array.
The array is of strings so you need %s to print them.

This should work:
#include <stdio.h>
int main(int argc, char *argv[]) {
    if (argc < 2)
        fprintf (stderr, "Wrong number of arguments\n");
    else
        printf ("The project path is: ./Projects/%s\n", argv[1]);
    return 0;
}

Comment: I was going throught all the responses, and I made sure to try everyone, but I didn't find that I was meant to be using %s instead of %c on the printf, and from now on, I'll remember to check there is enough command line arguments. Thanks :)
Answer:
Change the signature to int main(int, char*[]);
What arguments are you passing to the process? If you're not passing any argv[1] is out of range
Comment: I am passing 1 argument to the program, which is the project name.   But it still doesn't print out the entered string when I use argv[1]
Answer: First, change your main to:
int main(int argc, char *argv[])

Second, you have a mismatch between what you're passing to printf, and what you've told it you're going to pass. argv[1] is a pointer to characters, not a character. You need/want to use the %s conversion to print it out:
printf("The project path is: ./Projects/%s", argv[1]);

In this specific case, it's not really mandatory to check for enough arguments, because  even if you don't pass any command line arguments, argv will contain at least argv[0] followed by a null pointer. As such, using argv[1] is safe, but if you haven't passed a command line argument, may print as something like (null).
Nonetheless, you generally want to check the value of argc before using argv. In this case, you can get away with it, but only more or less by accident. Trying to use argv[2] the same way could give undefined behavior.
Answer: In addition to the other suggestions, you may need to revisit your printf format. %c is used to print a single character, and argv[1] is char *. Either use argv[1][0] or some such, or use the string format specifier, %s.

C application error on run


Object-oriented database puzzle?

Question: I'm currently taking an OOP class and here is my problem:
Assume database for a bike rental: class 'bike' => sub-classes 'borrowed bike' and 'returned bike'. Borrowed bike has the additional field 'due date' and returned bike the field 'location'
The task is to extend this database to treat all kinds of things you could borrow from the rental. However, the implementation needs to be as object-oriented as possible. I have been browsing through my Java book but I haven't been able to find a clever solution.
So, how can I add the functionality that every item (bike, roller skates, ...) is either 'borrowed' or 'returned' with the associated additional fields without having separate sub-classes for every type of item?
(I suggested my teacher that the state of every 'item' is either 'borrowed' or 'returned' but I was told that this is not object-oriented enough)
All help is appreciated!
Comment: Give all "items" (bike, roller skates, etc.) classes the same parent class with that field borrowed/returned.
Comment: Thank you all for your replies! I'm sure all these approaches would work in practise. Still I'm not sure what is the most object-oriented way to implement this? My original suggestion was to add the field 'isBorrowed' (or something similar) to class 'Item' but I was told that this is not an object-oriented approach. Using an interface is obliviously OO but in this case I still need to have the fields 'due' and 'location' in class 'Item' which is not optimal. I'm puzzled.
Answer: Create an interface with a getStatus() method and make all item classes implement it.
Answer: Create 2 interfaces for borrowed ones and returned ones.
public interface returnedItem(){
   public String getLocation();
   public void setLocation(String s);
}

public interface borrowedItem(){
   public Date getDue();
   public void setDue(Date date);
}

Comment: If I use this approach I need to have fields 'due' and 'location' in class 'item', right? This was my original suggestion which was redected by my teacher.
Answer: One simple way to give all objects (bike, roller skates, etc) a borrowed or returned is to make a super class.
Ex:
public class Borrowable {
    private boolean borrowed = false;

    public borrow() {
        borrowed = true;
    }

    public return() {
        borrowed = false;
    }

    public isBorrowed() {
        return borrowed;
    }

}

If you extend this class with bike then you can call the borrowable methods without having to write the code over again.
Comment: I also suggested this approach but apparently it's not OO enough?
Comment: Too bad I can't talk to your teacher. This is what OOP is all about.
Answer: Use an interface:
interface Item{
    boolean isBorrowed();
}

Then make abstract classes for all different items by implementing the interface.
abstract class Bike implements Item{
    //code
}

abstract class RollerSkates implements Item{
    //code
}

//etc.

Now extend these abstract classes:
public class BorrowedBike extends Bike{
    //code
    //add additional field 'due date'
    boolean isBorrowed(){
        return true;
    }
}

public class ReturnedBike extends Bike{
    //code
   //add additional field 'location'
    boolean isBorrowed(){
        return false;
    }
}

Comment: This is a very clear way to implement this but unfortunately the objective was to avoid having sub-classes for every type of item. I'm still puzzled.
Comment: @Kuririn Can you post the code you've written and the exact response from your teacher?  This is a relatively decent OO approach, but your teacher may have something else in mind (maybe generics, enums, Strings, etc.).  It is also possible your teacher isn't explaining to you what he/she wants in a well manner.
Answer: what you can do is to create a class type for each item ,
create Item class which is a generic class , and inherit from it 2 sub-classes borrowed item and returned one
class Bike
...
class Skates
...
class Roller

class Item<T>
...
class BorrowedItem<T> extends Item<T>
...
class ReturnedItem<T> extends Item<T>

Answer: Instead of making borrowed bike and returned bike for bike sub class
you can follow an approach to make a class
item with variable nameOfItem and type it can be either bike ,roller stakes or any other.
It will hold for an instance
Name            status
bike            returned
roller stakes   borrowed

Object-oriented database puzzle?


Multithreaded DbContext Operations

Question: The following code (on a single DbContext) results in "A second operation started on this context before a previous operation completed".
[HttpGet]
[Route("api/[controller]/circuit")]
public async Task<IEnumerable<object>> GetAllCircuits()
{
    var circuits = await Task.WhenAll((await _context.Circuits.ToListAsync()).Select(async x => new
    {
        x.Id,
        x.FastestLap,
        x.LengthInMiles,
        Country = await _context.Countries.FirstOrDefaultAsync(c => c.Id == x.CountryId),
        Map = await _context.Maps.FirstOrDefaultAsync(m => m.Id == x.MapId),
        Locations = await _context.Locations.Where(l => l.CircuitId == x.Id).ToListAsync()
    }));

    return circuits;
}

I was able to fix this by stripping out the async/await and Task.WhenAll parts, and replacing them with .Result, which seems to be a big no-no in .NET. Fixed example below:
[HttpGet]
[Route("api/[controller]/circuit")]
public async Task<IEnumerable<object>> GetAllCircuits()
{
    var circuits = (await _context.Circuits.ToListAsync()).Select(x => new
    {
        x.Id,
        x.FastestLap,
        x.LengthInMiles,
        Country = _context.Countries.FirstOrDefaultAsync(c => c.Id == x.CountryId).Result,
        Map = _context.Maps.FirstOrDefaultAsync(m => m.Id == x.MapId).Result,
        Locations = _context.Locations.Where(l => l.CircuitId == x.Id).ToListAsync().Result
    });

    return circuits;
}

My three questions are:

Why does this happen?
Is the "fixed" code clean? If not, please could you suggest a better approach?
Can I just use .ToList() rather than the async variant?

Thanks!
Comment: Why don't you write a "normal" LINQ to Entities query - no async things inside, `IQueryable`, with just awaited final `ToListAsync()`? And use navigation properties instead of these "manual: joins.
Comment: 1. The reason you get the exception is because EF can't guarantee that the data it returns is still valid because another thread might have updated/deleted data from the DB.  2. Calling `.Result` on an async function is worse than just calling the synchronous version of the function (i.e. `ToList` instead of `ToListAsync`). 3.  Yes, but doing that would defeat the entire purpose of async programming. If you set up your database tables with foreign keys you should prefer navigation properties over manually loading from context (as @IvanStoev says)
Answer:
Why does this happen?

DbContext doesn't allow multiple operations on the same db connection. In this case, you have one call (ToListAsync) followed by multiple concurrent calls (the Select).

Is the "fixed" code clean? If not, please could you suggest a better approach?

No. You shouldn't use .Result.
Your options are:

(Ideal) Change the LINQ query so that it includes all the necessary information in one query, e.g., using joins or includes. This is the ideal solution because there's only one query and the db server can handle it most efficiently.
Only do one operation at a time, since you only have one connection. This is why the .Result is working, but a better solution would be to use await, just do them one at a time instead of using Select with Task.WhenAll. The disadvantage to this approach is that the operations are only done one at a time.
Keep the multiple operations, and open up one db connection per operation. The disadvantage to this approach is that it requires multiple db connections.

Can I just use .ToList() rather than the async variant?

The ToListAsync isn't the problem. The problem is Select + WhenAll.
Comment: Great thanks! Sometimes I guess it just takes a step back to look at the wider problem, rather than the immediate error. I'll give the first option a go now :)

Multithreaded DbContext Operations


Could not bind proxy receiver to the RMI registry

Question: I am trying to connect to matlab from java file and do some operations. Some times it is working fine but sometimes while trying to connect to matlab from java I am getting an error.
The code which I use for connecting to matlab is
MatlabProxyFactoryOptions options = new MatlabProxyFactoryOptions.Builder()
        .setMatlabLocation("/usr/local/MATLAB/R2014a/bin/matlab")
            .build();

MatlabProxyFactory factory = new MatlabProxyFactory(options); //Create a proxy, which we will use to control MATLAB
MatlabProxy proxy = factory.getProxy();

proxy.eval("addpath SourceCode/Hipc/");
String executeThis = "run_BVD(" + upload2Bean.getUserImage2FileName() + ",1);";
proxy.eval(executeThis);
proxy.exit();

proxy.disconnect(); //Disconnect the proxy from MATLAB

Error is
matlabcontrol.MatlabConnectionException: Could not bind proxy receiver to the RMI registry
    at matlabcontrol.RemoteMatlabProxyFactory.requestProxy(RemoteMatlabProxyFactory.java:104)
    at matlabcontrol.RemoteMatlabProxyFactory.getProxy(RemoteMatlabProxyFactory.java:144)
    at matlabcontrol.MatlabProxyFactory.getProxy(MatlabProxyFactory.java:81)
    at com.Daos.Upload2Dao.upload(Upload2Dao.java:43)
    at com.ActionClasses.Upload2Action.execute(Upload2Action.java:94)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:483)
    at com.opensymphony.xwork2.DefaultActionInvocation.invokeAction(DefaultActionInvocation.java:440)
    at com.opensymphony.xwork2.DefaultActionInvocation.invokeActionOnly(DefaultActionInvocation.java:279)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:242)
    at com.opensymphony.xwork2.interceptor.DefaultWorkflowInterceptor.doIntercept(DefaultWorkflowInterceptor.java:163)
    at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:87)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236)
    at com.opensymphony.xwork2.validator.ValidationInterceptor.doIntercept(ValidationInterceptor.java:249)
    at org.apache.struts2.interceptor.validation.AnnotationValidationInterceptor.doIntercept(AnnotationValidationInterceptor.java:68)
    at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:87)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236)
    at com.opensymphony.xwork2.interceptor.ConversionErrorInterceptor.intercept(ConversionErrorInterceptor.java:122)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236)
    at com.opensymphony.xwork2.interceptor.ParametersInterceptor.doIntercept(ParametersInterceptor.java:195)
    at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:87)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236)
    at com.opensymphony.xwork2.interceptor.ParametersInterceptor.doIntercept(ParametersInterceptor.java:195)
    at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:87)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236)
    at com.opensymphony.xwork2.interceptor.StaticParametersInterceptor.intercept(StaticParametersInterceptor.java:148)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236)
    at org.apache.struts2.interceptor.CheckboxInterceptor.intercept(CheckboxInterceptor.java:93)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236)
    at org.apache.struts2.interceptor.FileUploadInterceptor.intercept(FileUploadInterceptor.java:306)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236)
    at com.opensymphony.xwork2.interceptor.ModelDrivenInterceptor.intercept(ModelDrivenInterceptor.java:89)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236)
    at com.opensymphony.xwork2.interceptor.ScopedModelDrivenInterceptor.intercept(ScopedModelDrivenInterceptor.java:128)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236)
    at org.apache.struts2.interceptor.ProfilingActivationInterceptor.intercept(ProfilingActivationInterceptor.java:104)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236)
    at org.apache.struts2.interceptor.debugging.DebuggingInterceptor.intercept(DebuggingInterceptor.java:267)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236)
    at com.opensymphony.xwork2.interceptor.ChainingInterceptor.intercept(ChainingInterceptor.java:126)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236)
    at com.opensymphony.xwork2.interceptor.PrepareInterceptor.doIntercept(PrepareInterceptor.java:138)
    at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:87)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236)
    at com.opensymphony.xwork2.interceptor.I18nInterceptor.intercept(I18nInterceptor.java:148)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236)
    at org.apache.struts2.interceptor.ServletConfigInterceptor.intercept(ServletConfigInterceptor.java:164)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236)
    at com.opensymphony.xwork2.interceptor.AliasInterceptor.intercept(AliasInterceptor.java:128)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236)
    at com.opensymphony.xwork2.interceptor.ExceptionMappingInterceptor.intercept(ExceptionMappingInterceptor.java:176)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236)
    at org.apache.struts2.interceptor.FileUploadInterceptor.intercept(FileUploadInterceptor.java:306)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236)
    at org.apache.struts2.impl.StrutsActionProxy.execute(StrutsActionProxy.java:52)
    at org.apache.struts2.dispatcher.Dispatcher.serviceAction(Dispatcher.java:468)
    at org.apache.struts2.dispatcher.FilterDispatcher.doFilter(FilterDispatcher.java:395)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:220)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:501)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
    at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:950)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1040)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:607)
    at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:314)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Thread.java:745)
Caused by: java.rmi.NoSuchObjectException: no such object in table
    at sun.rmi.transport.StreamRemoteCall.exceptionReceivedFromServer(StreamRemoteCall.java:276)
    at sun.rmi.transport.StreamRemoteCall.executeCall(StreamRemoteCall.java:253)
    at sun.rmi.server.UnicastRef.invoke(UnicastRef.java:379)
    at sun.rmi.registry.RegistryImpl_Stub.bind(Unknown Source)
    at matlabcontrol.RemoteMatlabProxyFactory.requestProxy(RemoteMatlabProxyFactory.java:99)
    ... 75 more

Answer: I get this error when Matlab is closed (I'm using Windows).
To get it working again, kill the javaw.exe showed in Task Manager (to open it press Ctrl+Shift+Esc) or restart the webserver (for example in Glassfish it would be restart-domain mydomain4from command prompt).
You can try to avoid the above situation by setting these options when configuring the matlabcontrol object. On Windows you'll always get one single  Matlab windows open all the time, and on Linux Matlab will work seamlessly, without any window, and will terminate the program after use.
final Long MATLAB_PROXY_TIMEOUT = 200000L;

  options = new MatlabProxyFactoryOptions.Builder()
               .setHidden(true)
               .setUsePreviouslyControlledSession(true)
               .setProxyTimeout(MATLAB_PROXY_TIMEOUT)
               .build();
  factory = new MatlabProxyFactory(options);
  proxy = factory.getProxy(); // Create a proxy that controls MATLAB

Edit: I believe this error (Could not bind proxy receiver to the RMI registry)  happens mainly during development, i.e. many new compilations trying to access the same instance of RMI registry. Once the program is in final version, it should only bind once to RMI registry and stay in a stable connection.
Answer: I also got this error on Windows 10, and when I checked the Task Manager, Background Processes (Ctrl+Shift+Esc). Apparently there was 10 background Matlab processes running under the hood, and I did not use any parfor loop at the time, so after killing all those processes, everything worked fine again.


How can I properly update Cobbler's distro_signatures.json to support SecurityOnion?

Question: I am trying to install SecurityOnion (an xubuntu 12.04 based linux distrobution) using cobbler.
I have followed the instructions here to get cobbler installed from source on Ubuntu 12.04.
I have also followed the instructions here to configure cobbler but I am getting an error on the cobbler import step.
I am running
cobbler import --name=securityonion --path=/media/iso --breed=ubuntu but it fails
task started: 2014-03-08_110255_import
task started (id=Media import, time=Sat Mar  8 11:02:55 2014)
Found a candidate signature: breed=ubuntu, version=precise
Found a candidate signature: breed=ubuntu, version=saucy
Found a candidate signature: breed=ubuntu, version=oneiric
Found a candidate signature: breed=ubuntu, version=lucid
Found a candidate signature: breed=ubuntu, version=quantal
Found a candidate signature: breed=ubuntu, version=raring
No signature matched in /var/www/cobbler/ks_mirror/securityonion
!!! TASK FAILED !!!

I assume this is because I need to add a signature to /var/lib/cobbler/distro_signatures.json
I know I should be able to copy and paste the definition for precise and make it work since SecurityOnion uses 12.04 but I don't know how to change the definition so that it matches whatever string of text I assume cobbler is looking for under the installation files that make up securityonion.
I have read the documentation on cobbler site but it doesn't seem to give me what I need to be able to add an additional distribution.
Anyone know what I can do to modify the signatures file to accept this additional distribution?
Answer: Cobbler will download the latest 'update' distro_signatures.json using the command below:
# cobbler signature update

Comment: I am not looking to download the latest version but to author a new version by adding a new signature to the file.
Comment: Since it is Ubuntu based -- wouldn't you use Ubuntu as the signature?  For  instance both Fedora and RHEL fall under the Red Hat signature. http://cobbler.github.io/manuals/2.4.0/4/2/3_-_Distro_Signatures.html


Solution Verification: Prove or Disprove: If $L$ is an irregular language and $F$ is finite language, then $F\cap L^+$ is regular.

Question:
Prove or Disprove:
If $L$ is an irregular language and $F$ is finite language, then $F\cap L^+$ is regular.

Note: $L^+=\bigcup_{i=1}^{\infty}L^i$.
I will be attempting to prove this statement.
First, I know that if a language is finite then it's regular, so I know for sure that $F$ is finite and regular. Now I don't really need to care if $L^+$ is finite or not and if it's irregular or not, because the intersection between a finite language $F$ and $L^+$ will always be finite, using the fact that $F\cap L^+ \subseteq F$.
And since it's a finite language, it will be regular.
Would appreciate any approvals and feedback, thanks in advance.
Answer: Looks good to me! More generally, take any finite language F and any language
L (whether L is regular, irregular, context free, ....),
their intersection must be finite, and hence their intersection is regular.


Prime numbers stretch to infinity, but what about the distance between them?

Question: That is, let $p_n$ be the nth positive prime number. Does $$L = \lim\limits_{n \to \infty} \left( p_{n+1} - p_n \right)$$ equal infinity?
Comment: I doubt whether the behavior of that sequence is completely known, since it is still unsolved whether there are infinitely many twin primes.
Answer: No, the limit (probably) does not exist.
The sequence $p_{n+1} - p_n$ has a name: it is called the sequence of prime gaps. Define $g_n = p_{n+1} - p_n$, then you are interested in the sequence $g_1, g_2, \dots$. The following facts are known:

For any $k$, it is easy to see that the $(k-1)$ numbers $k!+2, k!+3, \dots, k!+k$ are all non-prime. Thus there exist arbitrarily long sequences of composite numbers; in other words, $g_n$ can get arbitrarily large: for any $k$ there exists $n$ such that $g_n \ge k$. Equivalently, $$ \limsup_{n \to \infty}  (p_{n+1} - p_n) = \infty.$$
There is the (believed) twin-prime conjecture which states that there exist infinitely many primes that differ by 2; this means that $g_n$ takes the value $2$ for infinitely many $n$, or $$\liminf_{n \to \infty} (p_{n+1} - p_n) = 2.$$ Even if it turns out to be false for 2, there is Polignac's conjecture that for any even integer $k$, there exist infinitely many primes that differ by $k$; this has not been proved or disproved for any $k$. Even better, it has been proved in 2005, assuming a certain conjecture (which I think is weaker than the Riemann hypothesis) that there are infinitely many $n$ for which $g_n$ is at most $16$, thus $$\liminf_{n \to \infty} (p_{n+1} - p_n) \le 16.$$
The "average" gap between the $n$th prime and the next increases logarithmically: $g_n \approx \ln p_n$. So you can say that the distance between primes does become infinite "on average"; though infinitely often it touches very small numbers.
Comment: @Luke: AFAICT, Zhang's result does not yet prove Polignac's conjecture. It says that there are infinitely many prime gaps less than $C \approx 7 \times 10^7$, so technically all we can say is that *at least one gap* less than $C$ occurs infinitely often (not all gaps). But, it's a step in the relevant direction.
Comment: But Zhang's result does prove the "probably" at the top: it proves that $\liminf_{n \to \infty} (p_{n+1} - p_n)$ is finite, and therefore the $\limsup$ and $\liminf$ are different, i.e. the limit definitely does not exist.
Comment: I accepted your answer essentially because of the last topic. I should have thought in terms of average too, quite interesting.
Comment: I just found this survey article that has a lot more details: http://www.ams.org/journals/bull/2007-44-01/S0273-0979-06-01142-6/S0273-0979-06-01142-6.pdf ("Small gaps between prime numbers: The work of Goldston-Pintz-Yildirim")
Comment: Polignac turned out to be right: http://golem.ph.utexas.edu/category/2013/05/bounded_gaps_between_primes.html.
Answer: Assuming some fairly reasonable conjectures, then $(p_{n+1}-p_n)$ is a divergent sequence (i.e. a limit does not exist).  For example:
Conjecture: There exists an infinite number of twin primes.  (where $p_{n+1}-p_n=2$ an infinite number of times)
Conjecture: There exists an infinite number of prime pairs that differ by 4.  (where $p_{n+1}-p_n=4$ an infinite number of times)
However, we can observe that $\lim\sup (p_{n+1}-p_n)=\infty$, since $n!+k$ is composite (properly divisible by k) for all $n \geq 2$ and $2 \leq k \leq n$.  Therefore there are arbitrarily large prime gaps.
Answer: If the limit is not infinity, then there can be found infinitely many primes differing by less than some bound M.  Answering whether that is the case seems to be an open problem still.
The closest (contingent) answer after some quick searching seems to be the one noted at the bottom of this page about the Elliott–Halberstam conjecture stating that there are infinitely many pairs of primes differing by at most 16 (they used the linked conjecture in their proof).
If that were true, then the answer to your question would be no.
Though, maybe it is of interest to you that there are arbitrarily large gaps between primes, which is a related question.  The proof is pretty simple: consider the numbers following $n!$...
Comment: The numbers from $n!+2$ through to $n!+n$ are clearly all composite, though these sized sequences of $n-1$ consecutive composite numbers in fact appear a lot earlier for $n>3$.
Answer: Whether the limit does exists is not known now,but the gap between two consective prime numbers can be arbitrarily large.


Formulário não cadastra, nenhum nome fica gravado

Question: Meu formulário não está salvando nenhum dado no banco, o que pode ser?

    <?php

      if(isset($_SERVER['REQUEST_METHOD']) AND $_SERVER['REQUEST_METHOD'] == 'POST'){

        extract($_POST);

    if(isset($nome))
        if($nome === '' OR strlen($nome)<4){
            echo 'Insira um nome existente';
        }elseif($sobrenome=='' OR strlen($sobrenome)<6){
            echo 'Insira um sobrenome existente';
        }elseif($email==''){
            echo 'Insira seu e-mail';
        }elseif(!preg_match("/^[az0-9_\.\-]+@[az0-9_\.\-}*{a-z0-9_\-]+\.[a-z]{2,4}$/i",$email)){
            echo 'E-mail invalido tente outro';
        }else{

            include('../../sllapsocial/classes/DB.class.php');

            $verificar = DB::getConn()->prepare("SELECT `id` FROM `usuarios` WHERE `email`=?");
            if($verificar->execute(array($email))){
                if($verificar->rowCount()>=1){
             echo 'Este e-mail ja existe';

         }elseif($senha=='' OR strlen($senha)<4){
            echo'Senha fraca Insira mais caracteres';
         }elseif(strtolower($capctha) <> strtolower($_SESSION['capcthaCadastro'])){
             echo 'Codigo errado';
         }else{
             $senhaInsert = sha1($senha);
             $nascimento = "$ano-$mes-$dia";
             $inserir = DB::getConn()->prepare("INSERT INTO `usuarios` SET `email`=?, `senha` =?, `nome`=? `sobrenome`=?, `sexo`=?, `nascimento`=?`cadastro`=NOW()");

             if($inserir->execute(array($nome,$sobrenome,$email,$senhaInsert,$nascimento,$sexo))){
            header('Location: ./');
               }

            }

           }

        }

        }

      ?>

Para ter acesso,É facil e gratis.

 <form name="cadastro" action="" method="post" >

Nome
         <input name="Nome" type="text" class="txtInput" value="<?php if(!empty($nome)) echo $nome; ?>" size="40"/>

             Sobrenome
             <input name="Sobrenome" type="text" class="txtInput" value="<?php if(!empty($sobrenome)) echo $sobrenome; ?>" size="40"/>

           Seu e-mail
             <input name="Seu e-mail" type="text" class="txtInput" value=" <?php  if(!empty($email)) echo $email; ?>" size="40"/>

             Insira o e-mail novamente
             <input name="Insira o e-mail novamente" type="text" class="txtInput" size="40" value=" <?php if(!empty($email)) echo $email; ?>" />

             Senha
             <input name="Senha" type="password" class="txtInput" size="40" value="<?php  if(!empty($senha)) echo $senha; ?>" />

           Data de nascimento
             <select name="Dia">
               <option value="">Dia</option>
               <?php
         for($d=1;$d<=31;$d++){
             $zero = ($d<10) ? 0 : '';
             if(!empty($dia)==$zero.$d){
             echo '<option selected="selected" value="',$zero,$d,'">',$zero,$d,'</option>';
             }else{
             echo '<option value="',$zero,$d,'">',$zero,$d,'</option>';
             }

         }

      ?>

             </select>

             <select name="Mes">
               <option value="">Mês</option>
               <?php
       $meses = array('','janeiro','fevereiro','março','abril','maio','junho','julho','agosto','setembro','outubro','novembro','dezembro');
       for($m=1;$m<=12;$m++){
       $zero = ($m<10) ? 0 : '';
       if($zero.$m == $meses){
        echo '<option selected="selected"value="',$zero,$m,'">',$meses[$m],'</option>';
       }else{
            echo '<option "value="',$zero,$m,'">',$meses[$m],'</option>';
       }
       }
      ?>

             </select>

             <select name="Ano">
               <option value="">Ano</option>
               <?php
      for($a=date('Y');$a>=(date('Y')-100);$a--){
          if(!empty($ano)){
              echo '<option selected"selected" value="',$a,'">',$a,'</option>';
          }else{
              echo '<option value="',$a,'">',$a,'</option>';
        }
      }
      ?>

             </select>

             Sou do sexo
             <select name="sexo">
               <option <?php if(!empty($sexo) == 'masculino') echo'selected"selected"'; ?> value="masculino" >Masculino</option>
               <option <?php if(!empty($sexo) == 'feminino') echo'selected"selected"'; ?>value="feminino" >Feminino</option>
             </select>

Digite o código acima:
             <input class="txtInput" type="text" name="captcha"  />
             <input type="submit" value="Continue" class="SubmitContinue" name="Continue" />
        </form>

Comment: Comece por colocar os campos dos forms todos em minúscula, pois você está misturando tudo na hora de usar as variáveis. Outra coisa, como já recomendado em outras ocasiões, suma com esse `extract` do seu código e use declaração direta `$nome = $_POST['nome'];` etc. Acho que este é um bom começo para avançar no código.
Comment: Cuidado com o atributo `name` dos input's, eles não são para colocar mensagem, são o nome dos parâmetros enviados no `POST`.
Comment: nao PAPA charlie eu coloquei o nome e sobrenome em letras maiusculas e funcionou :) agora o problema é oemail Notice: Undefined variable: Email in
Comment: Olá David, bem-vindo ao [pt.so]. Por favor tome mais cuidado na formatação das perguntas (você sempre pode [edit] para melhorar). Além disso, tente incluir mais informações para ajudar os outros a responder. Aparece alguma mensagem de erro? Você tentou algum tipo de debug? Tem alguma pista? Etc. Quanto mais você disser, mais chance você tem de conseguir uma resposta. Obrigado.
Comment: sim ja tentei depurar mais nao obteu nenhum resultado como se esse codigo nao existe no formulario
Comment: Bacco infelismente nao funcionou esse método esta aparecendo Notice: Undefined index: nome in C:\wamp\www\redesocial\estilos\index.php on line 68
Comment: Isso é bom sinal. Um aviso de que nao foi nenhum campo 'nome' no form.
Comment: Bacco alterei tudo mais continua com o mesmo erro
Comment: é continuação [dessa aqui?](http://pt.stackoverflow.com/questions/32652/notice-undefined-variable-nome-in-c-wamp-aonde-esta-por-favor)
Comment: sim mais essa é outra conta que perdi a senha
Comment: Se você der um insert com dados definidos (`$inserir->execute(array('nome' , 'sobrenome' ...) ) `) eles são gravados no DB ou não?
Comment: Siga a resposta do @perdeu, e se a questão foi resolvida, marque a resposta.
Comment: PESSOAL RESOLVI ESSE LADO agora esta dando o seguinte erro Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[HY000] [1049] Base 'redeocial' inconnue' in C:\wamp\www\redesocial\classes\DB.class.php on line 6
( ! )
PDOException: SQLSTATE[HY000] [1049] Base 'redesocial' inconnue in C:\wamp\www\redesocial\classes\DB.class.php on line 6
Call Stack
# Time Memory Function Location
1 0.0029 157776 {main}( ) ..\index.php:0
2 0.0049 163328 DB::getConn( ) ..\index.php:82
3 0.0049 163752 __construct ( ) ..\DB.class.php:6
Comment: Ou o nome da database está errado ou ela não existe, teste direto no banco o comando: `show databases`. Qualquer coisa crie uma nova perguntar descrevendo o problema e o que já tento fazer para resolve-lo.
Comment: @perdeu database esta funcionando direito , estou seguindo o conselho anterior do Bacco tirei o extract() e adicionei $nome = $_POST['nome'];
Answer: 1 - Tome cuidado ao digitar nomes de campos/variáveis no html/php Nome é diferente de nome, veja no seu form como está definição:
<input name="Nome" type="text"

No php depois do extract() ele vai virar $Nome e não $nome.
if(isset($nome))

2- sql
Parecer ser erro de sintaxe no insert:
INSERT INTO `usuarios` SET
 `email`=?,
 `senha` =?,
 `nome`=? <---- falta uma virgula
 `sobrenome`=?,
 `sexo`=?,
 `nascimento`=? <---- aqui também
 `cadastro`=NOW()

Sempre que o mysql retornar o código 1064 sempre é algum erro de sintaxe como nome de coluna/tabela escrito errado ou aspas em lugares errados.
A mesnagem de erro é parecida como:

Error Code: 1064. You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '' at line 1

Lista dos códigos  de erro mysql
Sintaxe ao alternativa do insert


Pearson correlation of data sets with possibly zero standard deviation?

Question: I am having a problem computing the pearson correlation coefficient of data sets with possibly zero standard deviation (i.e. all data has the same value).
Suppose that I have the following two data sets:
float x[] = {2, 2, 2, 3, 2};
float y[] = {2, 2, 2, 2, 2};

The correlation coefficient "r", would be computed using the following equation:
float r = covariance(x, y) / (std_dev(x) * std_dev(y));

However, because all data in data set "y" has the same value, the standard deviation std_dev(y) would be zero and "r" would be undefined.
Is there any solution for this problem? Or should I use other methods to measure data relationship in this case?
Comment: @whuber - it is true that the $r$ is undefined, but not necessarily that the "true" unknown correlation $\rho$ cannot be estimated.  Just have to use something different to estimate it.
Comment: @whuber - estimate is a bad choice of words for me (you may have noticed I'm not the best wordsmith), what I meant was that although $\rho$ may not be uniquely identified, this does not mean that the data are useless in telling us about $\rho$.  My answer gives an (ugly) demonstration of this from an algebraic point of view.
Comment: There is no "data relationship" in this example because y does not vary.  Assigning *any* numerical value to *r* would be a mistake.
Comment: @probability You presuppose this is a problem of estimation and not simply one of characterization.  But accepting that, what estimator would you propose in the example?  No answer can be universally correct because it depends on how the estimator will be used (a loss function, in effect).  In many applications, such as PCA, it seems likely that using *any* procedure that imputes a value to $\rho$ may be worse than other procedures that recognize $\rho$ cannot be identified.
Comment: @Probability It seems your analysis is contradictory: if indeed y is modeled with a normal distribution, then a sample of five 2's shows this model is inappropriate.  Ultimately, you don't get something for nothing: your results depend strongly on the assumptions made about the priors.  The original problems in identifying $\rho$ are still there but have been hidden by all these additional assumptions.  That seems IMHO just to obscure the issues rather than clarify them.
Comment: @whuber - I'd say it actually "brings out" all the assumptions that one actually makes when using pearson correlation (normality).  Its not that you get something for nothing, its that it highlights the "something" that was already there, left unspecified or thrown out with the passage to infinite limits in the parameter space and/or sample space (which is not a reflection of "reality" but a mathematical convenience which enables closed form solutions to many problems).
Comment: @whuber - the five 2's are highly implausible, but so is any five numbers with continuous distributions.  All the 5 two's mean is that the data do not rule out arbitrarily small variances, so the results do depend on what is known about small variances apart from the data.  the fact that @andree wants a correlation suggests that he has information other than data which indicates non-zero variation.  So why not use that information in the most conservative way, by specifying a lower bound?
Comment: @probability I agree your analysis makes some assumptions explicit, but I don't think they are ones that most people "usually" make.  For instance, one does not normally assume all correlations are equally likely (your uniform prior on $\rho$.)  There are similar unsupported assumptions in the other priors.  Some unstated assumptions are that it even makes sense to use priors and that "uninformative" priors are not appreciably influencing the results.  Only the OP can settle the former question, but the latter question bothers me.
Comment: @prob An alternative model for five 2's is that measurements are discrete.  That leads to a potentially fruitful investigation of measurement process and measurement error and possibly incorporating it in the model.  *Then*, if you use Bayesian techniques, that's fine, because *the priors can be justified.*  What bothers me is proposing priors without any such analysis.  One ill effect of that approach is that it can inhibit people from thinking constructively about the data.
Comment: @whuber - if the "true" standard deviation of these measurements was say $0.1$ with "true" mean $2$, this is consistent with the observed data. A discrete model would also be useful here.  I think we are debating over certain ambiguities in the question though.  I took pearson correlation to mean that normal distribution was implied - you feel that this is not justified, but do not give an alternative solution and declare this an "ill-posed" problem (implicitly).  And the uniform prior for $p(\rho)$ has nothing to do with the point of my answer.
Comment: (cont'd) this is why I left $p(\rho)$ arbitrary, with a possible recommendation for uniform.  the point of my answer was to indicate that even with the most non-informative priors for the other parameters can give some information about the true correlation.  The problem just needs to be specified in a little more detail, to extract what is actually known about the data $x$ and $y$.  The priors I use for the means and standard deviations can be justified on conservative grounds.  If more is known, then the analysis will be improved.
Answer: The "sampling theory" people will tell you that no such estimate exists.  But you can get one, you just need to be reasonable about your prior information, and do a lot harder mathematical work.
If you specified a Bayesian method of estimation, and the posterior is the same as the prior, then you can say the data say nothing about the parameter.  Because things may get "singular" on us, then we cannot use infinite parameter spaces.  I am assuming that because you use Pearson correlation, you have a bivariate normal likelihood:
$$p(D|\mu_x,\mu_y,\sigma_x,\sigma_y,\rho)=\left(\sigma_x\sigma_y\sqrt{2\pi(1-\rho^2)}\right)^{-N}exp\left(-\frac{\sum_{i}Q_i}{2(1-\rho^2)}\right)$$
where
$$Q_i=\frac{(x_i-\mu_x)^2}{\sigma_x^2}+\frac{(y_i-\mu_y)^2}{\sigma_y^2}-2\rho\frac{(x_i-\mu_x)(y_i-\mu_y)}{\sigma_x\sigma_y}$$
Now to indicate that one data set may be the same value, write $y_i=y$, and then we get:
$$\sum_{i}Q_i=N\left[\frac{(y-\mu_y)^2}{\sigma_y^2}+\frac{s_x^2 + (\overline{x}-\mu_x)^2}{\sigma_x^2}-2\rho\frac{(\overline{x}-\mu_x)(y-\mu_y)}{\sigma_x\sigma_y}\right]$$
where
$$s_x^2=\frac{1}{N}\sum_{i}(x_i-\overline{x})^2$$
And so your likelihood depends on four numbers, $s_x^2,y,\overline{x},N$.  So you want an estimate of $\rho$, so you need to multiply by a prior, and integrate out the nuisance parameters $\mu_x,\mu_y,\sigma_x,\sigma_y$.  Now to prepare for integration, we "complete the square"
$$\frac{\sum_{i}Q_i}{1-\rho^2}=N\left[\frac{\left(\mu_y-\left[y-(\overline{x}-\mu_x)\frac{\rho\sigma_y}{\sigma_x}\right]\right)^2}{\sigma_y^2(1-\rho^{2})}+\frac{s_x^2}{\sigma_{x}^{2}(1-\rho^{2})} + \frac{(\overline{x}-\mu_x)^2}{\sigma_x^2}\right]$$
Now we should err on the side of caution and ensure a properly normalised probability.  That way we can't get into trouble.  One such option is to use a weakly informative prior, which just places restriction on the range of each.  So we have $L_{\mu}<\mu_x,\mu_y<U_{\mu}$ for the means with flat prior and $L_{\sigma}<\sigma_x,\sigma_y<U_{\sigma}$ for the standard deviations with jeffreys prior.  These limits are easy to set with a bit of "common sense" thinking about the problem.  I will take an unspecified prior for $\rho$, and so we get (uniform should work ok, if not truncate the singularity at $\pm 1$):
$$p(\rho,\mu_x,\mu_y,\sigma_x,\sigma_y)=\frac{p(\rho)}{A\sigma_x\sigma_y}$$
Where $A=2(U_{\mu}-L_{\mu})^{2}[log(U_{\sigma})-log(L_{\sigma})]^{2}$.  This gives a posterior of:
$$p(\rho|D)=\int p(\rho,\mu_x,\mu_y,\sigma_x,\sigma_y)p(D|\mu_x,\mu_y,\sigma_x,\sigma_y,\rho)d\mu_y d\mu_x d\sigma_x d\sigma_y$$
$$=\frac{p(\rho)}{A[2\pi(1-\rho^2)]^{\frac{N}{2}}}\int_{L_{\sigma}}^{U_{\sigma}}\int_{L_{\sigma}}^{U_{\sigma}}\left(\sigma_x\sigma_y\right)^{-N-1}exp\left(-\frac{N s_x^2}{2\sigma_{x}^{2}(1-\rho^{2})}\right) \times$$
$$\int_{L_{\mu}}^{U_{\mu}}exp\left(-\frac{N(\overline{x}-\mu_x)^2}{2\sigma_x^2}\right)\int_{L_{\mu}}^{U_{\mu}}exp\left(-\frac{N\left(\mu_y-\left[y-(\overline{x}-\mu_x)\frac{\rho\sigma_y}{\sigma_x}\right]\right)^2}{2\sigma_y^2(1-\rho^{2})}\right)d\mu_y d\mu_x d\sigma_x d\sigma_y$$
Now the first integration over $\mu_y$ can be done by making a change of variables $z=\sqrt{N}\frac{\mu_y-\left[y-(\overline{x}-\mu_x)\frac{\rho\sigma_y}{\sigma_x}\right]}{\sigma_y\sqrt{1-\rho^{2}}}\implies dz=\frac{\sqrt{N}}{\sigma_y\sqrt{1-\rho^{2}}}d\mu_y$ and the first integral over $\mu_y$ becomes:
$$\frac{\sigma_y\sqrt{2\pi(1-\rho^{2})}}{\sqrt{N}}\left[\Phi\left(
\frac{U_{\mu}-\left[y-(\overline{x}-\mu_x)\frac{\rho\sigma_y}{\sigma_x}\right]}{\frac{\sigma_y}{\sqrt{N}}\sqrt{1-\rho^{2}}}
\right)-\Phi\left(
\frac{L_{\mu}-\left[y-(\overline{x}-\mu_x)\frac{\rho\sigma_y}{\sigma_x}\right]}{\frac{\sigma_y}{\sqrt{N}}\sqrt{1-\rho^{2}}}
\right)\right]$$
And you can see from here, no analytic solutions are possible.  However, it is also worthwhile to note that the value $\rho$ has not dropped out of the equations.  This means that the data and prior information still have something to say about the true correlation.  If the data said nothing about the correlation, then we would be simply left with $p(\rho)$ as the only function of $\rho$ in these equations.
It also shows how that passing to the limit of infinite bounds for $\mu_y$ "throws away" some of the information about $\rho$, which is contained in the complicated looking normal CDF function $\Phi(.)$.  Now if you have a lot of data, then passing to the limit is fine, you don't loose much, but if you have very scarce information, such as in your case - it is important keep every scrap you have.  It means ugly maths, but this example is not too hard to do numerically.  So we can evaluate the integrated likelihood for $\rho$ at values of say $-0.99,-0.98,\dots,0.98,0.99$ fairly easily.  Just replace the integrals by summations over a small enough intervals - so you have a triple summation
Comment: @steffen - lol.  Its not that difficult, you just need to practice.  And always always always remember that the product and sum rules of probability are *the only rules you will ever need*.  They will extract whatever information is there - whether you see it or not.  So you apply product and sum rules, then just do the maths.  That is all I have done here.
Comment: @probabilityislogic:  If you could humor a nonmathematical statistician/researcher...would it be possible to summarize or translate your answer to a group of dentists or high school principals or introductory statistics students?
Comment: @rolando2 - the first thing I wouldn't do is show them the above formulas - enough to scare most people away, or at least make their eyes glaze over and the "smile and nod" would happen.  This would be best done using a graph of the integrated likelihood for various prior ranges $U_{\mu},L_{\mu},U_{\sigma},L_{\sigma}$ - one because this is what matters and two because graphs are easy to understand and to explain.  This will answer exactly *how much* the data and prior information say about the correlation.  my point was that its not nothing.
Comment: @prob - I appreciate your giving it a shot.  I'm still unable to follow.
Comment: @probabilityislogic: Wow. Simply wow. After seen some of your answers I really wonder: what should a doofus like me do to reach such a flexible bayesian state of mind ?
Comment: @steffen - and the other rule - more a mathematical one than stats one - don't pass to an infinite limit too early in your calculations, your results may become arbitrary, or little details may get thrown out.  Measurement error models are a perfect example of this (as is this question).
Comment: @probabilityislogic: Thank you, I'll keep this in mind... as soon as I am done working through my "Bayesian Analysis"-copy ;).
Answer: I agree with sesqu that the correlation is undefined in this case. Depending on your type of application you could e.g. calculate the Gower Similarity between both vectors, which is:
$gower(v1,v2)=\frac{\sum_{i=1}^{n}\delta(v1_i,v2_i)}{n}$ where $\delta$ represents the kronecker-delta, applied as function on $v1,v2$.
So for instance if all values are equal, gower(.,.)=1. If on the other hand they differ only in one dimension, gower(.,.)=0.9. If they differ in every dimension, gower(.,.)=0 and so on.
Of course this is no measure for correlation, but it allows you to calculate how close the vector with s>0 is to the one with s=0. Of course you can apply other metrics,too, if they serve your purpose better.
Comment: +1 That's a creative idea.  It sounds like the "Gower Similarity" is a scaled [Hamming distance](http://en.wikipedia.org/wiki/Hamming_distance).
Comment: @whuber: Indeed it is !
Answer: The correlation is undefined in that case. If you must define it, I would define it as 0, but consider a simple mean absolute difference instead.
Answer: This question is coming from programmers, so I'd suggest plugging in zero. There's no evidence of a correlation, and the null hypothesis would be zero (no correlation).  There might be other context knowledge that would provide a "typical" correlation in one context, but the code might be re-used in another context.
Comment: There's no evidence of *lack* of correlation either, so why not plug in 1?  Or -1?  Or anything in between?  They all lead to re-usable code!
Comment: @prob I question why it makes sense *as a generic procedure* to average over all correlations.  In effect this procedure substitutes the definite and possibly quite wrong answer "zero!" for the correct answer "the data don't tell us."  That difference can be important for decision making.
Comment: @whuber - you plug in zero because the data is "less constrained" when it is independent - this is why maxent distributions are independent unless you explicitly specify correlations in the constraints.  Independence can be viewed as a conservative assumption when you know of no such correlations - effectively you are averaging over *all possible correlations*.
Comment: Just because the question might be from a programmer, does not mean you should convert an undefined value to zero.  Zero means something specific in a correlation calculation.  Throw an exception.  Let the caller decide what should happen.  Your function should calculate a correlation, not decide what to do if one cannot be computed.


The Zencoder API library is not installed ... zencoder in a library path such as sites/all/libraries

Question: I have installed Zencoder 2.1.1 for my Drupal 7.22 but it's not working as I see the following error:
<code>The Zencoder API library is not installed. Download the library and install it to a directory called zencoder in a library path such as sites/all/libraries.
</code>
I have already done what it required:
<code>[root@ip-10-128-146-179 libraries]# pwd
/var/www/html/drupal/sites/all/libraries
[root@ip-10-128-146-179 libraries]# ls -lrt zencoder/Services/
total 12
-rw-r--r-- 1 root root 7867 Jul 21 16:32 Zencoder.php
drwxr-xr-x 2 root root 4096 Jul 21 16:32 Zencoder
[root@ip-10-128-146-179 libraries]# ls -lrt
total 4
drwxr-xr-x 5 root root 4096 Jul 21 16:32 zencoder
</code>
What do I need to now?
Screehshot
Comment: This question appears to be off-topic because it is about configuring webserver and it's libraries, not about using them with Drupal.
Answer: I cleared all caches and ran cron and that solved the problem.
Thanks to this.