How to add elements stored in a file to an array?

Question: I have a file which contains data elements as follows:
1749 12426 19597 38042 43350 52873 67704 75875 81829 96307

11615 16454 20015 27021 52762 66631 70625 83951 96527 96893

3370 5530 28692 39087 50591 59442 61906 69337 70643 91162

1947 4604 9657 16455 21149 22739 32809 66089 73871 97304

3429 5325 7888 24101 28851 31637 32424 57991 62470 65017

I am facing problem to add each element of the file on different index of array. While searching from internet i was only able to store all of the first row on index array[0].
(All line was stored on the index[0])
I want to store all the column elements array
array[0] = 1749
array[1] = 11615
array[2] = 3370
array[3] = 1947
array[4] = 3429

In second pass:
array[0] = 12426
array[1] = 16454
array[2] = 5530
array[3] = 4604
array[4] = 5325

And so on up to 10th pass.....
PLEASE make necessary changes in the code given below:
File            file = new File("SortedLines.txt");
FileInputStream fis  = null;

try {
    fis = new FileInputStream(file);

    int content;

    while ((content = fis.read()) != -1) {
        // convert to char and display it
        System.out.print((char)content);
    }
} catch (IOException e) {
    e.printStackTrace();
}

Comment: `PLEASE make necessary changes in the code given below` your code beside reading each characters in your file has nothing to do with problem you are describing. Maybe try something yourself first (Scanner class can be helpful here) and come back when you will get different results than expected, or some errors. Try to maybe read each line, split it on space and read n-th element you ware interested in.
Comment: So you'll overwrite the elements in each pass, right?
Comment: Simply store all the lines in String `ArrayList` and the separate each nos using `String.split()` method you'll get each no as separate no then add them
Comment: yes i want to over write elements in each pass
Answer: You should read the file lne by line, and for each line, split by spaces add the number to the array:
ArrayList<String> myArray = new ArrayList<String>(0);

//Read File Line By Line
  while ((strLine = br.readLine()) != null)   {

    // split by space
    String[] numbers= strLine.split(" ");

    for(String num numbers){
        myArray.add(strLine);
    }

  }

Comment: i am not able to implement it. can u please write the exact code. i m getting a lot of errors if i m pasting your code


There is a natrual connection on the tangent bundle?

Question: I come up with a (maybe stupid) question: let $M$ be a smooth manifold, then the exterior differential $d$ is a natural connection on $\Omega^k(M)$, hence by dualizing we get a natural connection on $TM$? How can it be true (without a metric)?
Answer: Since you say "dualizing", I assume you're talking about the case $k=1$. If we view differential forms as alternating tensors, the exterior derivative $\Omega^1(M) \to \Omega^2(M)$ can be viewed as a map $\Gamma(T^*M) \to \Gamma(T^*M \otimes T^*M),$ which has the right "type signature" to be a connection; but it does not satisfy the (correct kind of) Leibniz rule: for a smooth function $f$ and a one-form $\theta$ we have $$d(f \theta) = f d \theta + df \wedge \theta \ne f d \theta + df \otimes \theta.$$


Remove commas present inside a string in csv

Question: A csv file whose format is
name age comments

John 12  Hello World,Example

Jack 14  Hello,World

How to replace commas present in comment section with |(pipeline) symbol.
Commas can be present in name, age, and comments too. How to handle it dynamically within a text??
Comment: What is the delimiter character?
Comment: You want to remove the commas from a comma-separated value file?
Comment: Are you looking for a Java solution, or a sed one? They tend to be quite different.
Answer: Since you don't appear to be using commas as the field separator, it's as simple as
sed 's/,/|/g' file

To replace only in comments field:
while read name age comments; do echo "$name $age ${comments//,/|}"; done < file

Comment: This will replace all occurence of ','.I think he needs ',' to be removed only from "comments" section.
Answer: # any separator char but `/\.&[]` (or need to change the sed action), here `;`
Separator=";"

sed -e ":a
s/\(${Separator}[^${Separator}]*\),\([^${Separator}]*\)$/\1|\2/
ta" YourFile

Posix version so --posix on GNU sed


How to fix XPTY0004 error 2 items in one element in XSLT from XML to XML

Question: I need to make 2 groups for 2 persons if there are 2 persons in the base code.
At value-of the code mess up. If there are only one person its fine but when there are 2 elements with the same name the error XPTY0004 show.
<reqpers>
    <person man="a"/>
    <esttime>8 minutes</esttime>
    <person man="b"/>
    <esttime>5 minutes</esttime>
</reqpers>

   <xsl:template match="reqpers">
        <xsl:element name="reqPersons">
            <xsl:for-each-group select="*" group-starting-with="person">
                <xsl:element name="person">
                    <xsl:element name="estimatedTime">
                    <xsl:attribute name="unitOfMeasure">
                    <xsl:text>min</xsl:text>
                    </xsl:attribute>
                    <xsl:value-of select="substring-before(../esttime, ' ')" />
                    </xsl:element>
                </xsl:element>
            </xsl:for-each-group>
        </xsl:element>
    </xsl:template>

    <person man="a">
        <estimatedTime unitOfMeasure="min">8</estimatedTime>
    </person>
    <person man="b">
        <estimatedTime unitOfMeasure="min">5</estimatedTime>
    </person>

I figured out that I could use the a and b to tell which to use. but I can not figure out how.
Answer: The relevant element is part of the current-group() sequence so you can select it from there with current-group()[2] if there are only the two different elements you have in your sample or with current-group()[self::esttime] to select by its name:
  <xsl:template match="reqpers">
      <xsl:copy>
          <xsl:for-each-group select="*" group-starting-with="person" expand-text="yes">
              <person man="{@man}">
                  <estimatedTime unitOfMeasure="min">{substring-before(current-group()[self::esttime], ' ')}</estimatedTime>
              </person>
          </xsl:for-each-group>
      </xsl:copy>
  </xsl:template>

https://xsltfiddle.liberty-development.net/pPzifpK
Comment: hi i got a new problem. i need to  get "Operator" over in the atribut of  i used
Comment: @AlexanderLykkePedersen, consider to ask a new, separate question with the necessary details.
Comment: to answer my question i used this code


what is the kind of code that's written inside a dead lock scenario below?

Question: While looking up pieces of code that can cause deadlocks using threads, I came across this piece of code :
Thread t1 = new Thread(){
        public void run(){
            while(true){
                synchronized(str1){
                    try {
                        Thread.sleep(10);
                        } catch (InterruptedException e) {
                    }
                    synchronized(str2){
                        System.out.println(str1 + "::"+str2);
                    }
                }
            }

        }

    };

After declaring and instantiating a Thread object, it seems inside that thread the run method is written with accompanying logic and the Thread definition ends by closing the brace with semi colon .
What is the name of such a block of code? Is this what is called as an anonymous block?
Comment: Yes its anonymous class.
Comment: It's an "anonymous class". https://docs.oracle.com/javase/tutorial/java/javaOO/anonymousclasses.html
Comment: possible duplicate of [Creating the instance of abstract class or anonymous class](http://stackoverflow.com/questions/16785922/creating-the-instance-of-abstract-class-or-anonymous-class)
Answer: This is an anonymous class isntance. This code creates an instance of an anonymous class (i.e. it has no name) that extends Thread class and overrides its run method.


What happens to foreign key constraints in create...select statement?

Question: Just wondering what happens to the foreign key constrains of a source table, when it is replicated using CREATE...SELECT statement. Will the referential constraints be copied or ignored?
Here is an example:
CREATE TABLE foo(a int, b int, PRIMARY KEY(a));
CREATE TABLE source(id int, a int, PRIMARY KEY(id), FOREIGN KEY(a) REFERENCES foo(a));

CREATE TABLE target SELECT * FROM source;

So, my question is if attribute a on target also points to foo(a)? If the answer is vendor specific, I'm looking the answer for MySQL.
Answer: No, it won't create the FK constraint in target.  CREATE TABLE...SELECT just looks at the columns and data types of the SELECT result set, and that determines the definition of the new table.
I thought that using CREATE TABLE...LIKE could be a workaround for you, but I tested it on MySQL 5.5, and it also does not create the foreign keys.
CREATE TABLE target LIKE source;

I'm guessing because foreign keys are implemented in the InnoDB storage engine, not recognized by the storage-independent layer of MySQL, they probably don't show up in the storage-independent .FRM file.
This bug seems to confirm that CREATE TABLE...LIKE is implemented by simply copying the .FRM file:  http://bugs.mysql.com/bug.php?id=35526
But the fix mentioned was put into the MySQL 6.1 branch, and that branch was killed long ago.
So for now, you'll have to declare the foreign keys as a separate step.  I understand that in the future, the .FRM file is going away, so they'll have to change how CREATE TABLE...LIKE works.  Anyway, that doesn't help you today.


How to delete a file with a space at end of the name and hidden attributes?

Question: We have a hidden file with a space at the end of the file name.  Usually, I take ownership of the file, then use a command line rename with the 8.3 (dir/x) file name.  However, rename doesn't acknowledge hidden or system files.
Any ideas on how to remove it?  The original creator cannot access the file.  The system is a Windows 2003 server with NTFS and SMB file sharing (normal windows file sharing).
Answer: It's a while since this questions was asked, but I had the same problem and a simple delete on the command line did not work for.
I had to use the shortened DOS file name to get rid of such an undeletable file. With dir /X you will get the shortened file names. Then use this name for the delete command: del failfi~1.txt.
Comment: this is the only solution that worked for me.
Answer: write
\\?\
Before Absolute Path of file with the space at end.
del "\\?\D:\MyPath\MyFile " /S

Read more here:
Click here for: Very good information page about Windows command DEL
Comment: https://ss64.com/nt/syntax-filenames.html:
The "\\?\" Literal device prefix to a path string tells the Windows APIs to disable all string normalisation and to send the string that follows it straight to the file system. This is useful for accessing very long filenames. Starting in Windows 10, version 1607, MAX_PATH limitations have been removed from common Win32 file and directory functions. However, you must [opt-in](https://learn.microsoft.com/en-us/windows/win32/fileio/naming-a-file) to the new behavior.
Answer: In the command prompt, you can put the name of the file in quotes (including the space).  For example:
del "failfile.txt "
In Windows Explorer, you can go to Tools | Folder Options, click the View tab, and select "Show hidden files and folders." Then click OK and you'll see the file, and will be able to select and delete or rename it.
Comment: It shows the file in the list, although the icon is ghosted white.  If you right click the file, it doesn't show a security tab at all.  If you right click to rename it, it gives some odd error about the file needing a name.  However, I ended up doing a del /s /a to the folder above it with success, which is pretty much what you listed.  Apparently delete allows you to do this where rename and attrib won't work with that file name.  Crazy
Comment: You might test the Del "Failfile.txt ".
Answer: Try del filename? or remove the hidden attribute first with attrib -h filename? followed by a del filename.


Why does EC2 instance have problems upgrading my Ubuntu server to 12.04?

Question: I just tried upgrading our Ubuntu EC2 server to 12.04 from 11.10, and it halts on several package upgrades, starting with memtest86+. CTRL+C is the only way out, and in the end there is the following error:
Errors were encountered while processing:
 memtest86+
 ubuntu-standard
 grub-legacy-ec2
 grub-pc
 friendly-recovery
 linux-image-3.2.0-24-virtual
 python-apport
 linux-image-virtual
 linux-virtual
 apport

Any advice on what went wrong and how to fix it?
UPDATE: Turns out to be a problem with GRUB, though I still don't understand what is going wrong.  Why is GRUB used with EC2 at all?
Comment: Can you provide more details about the error message?
Comment: there is no other error message, it just freezes at "Setting up memtest86+ (4.20-1.1ubuntu1) ..."
Comment: What release are you starting with?  What AMI id are you using as a base?
Comment: 11.10 to 12.04 LTS worked for me, via SSH connection.
Answer: Try the upgrade again, but this time open a second ssh session to the server, and monitor some metrics:

vmstat 5 will alert you to memory problems
iostat 5 will show you if there is any I/O happening
top will show you any problems with CPU spikes or load average
using the sysstat package, you can log many of these metrics and view them later

Find out if anything is happening. View the list of running processes in top or ps auxfw for clues. Check active network connections with netstat -utnp. Once you have this info post back anything unusual or anything you don't understand.


how can i use methods of that class such as getFormView(), processFormSubmission(... , ... , ... , ...) when rewriting my controllers?

Question: can any one suggest any documentations on how to re-write SimpleFormController sub-classes to use annotated controllers instead, like how can i use methods of that class such as getFormView(), processFormSubmission(HttpServletRequest request, HttpServletResponse response, Object object,
            BindException errors) when rewriting my controllers?
The need to rewrite these classes come as a result of the need to upgrade to the recent versions of Spring like 4.1.4
Answer: Like I have already stated, am upgrading my spring to 4.1.4-RELEASE and it looks like the SimpleFormController class was totally removed preceeding it's deprecation in 3


Active Directory or Mac configuration. Where to look?

Question: I m a student at a university.
There is a computer lab which has Mac computers.
There is citrix account which is kinda VPN to school network. There is putty in citrix applications.
When i use putty and try to ssh into a Mac, my access is denied. However an sysadmin of the school is able to login to mac using putty and school credentials.
Well, where to look to fix this problem ?
Is this the Active Directory configuration for students or this is due to Mac configuration?
and how to fix this?
Thanks.
Comment: Can you clean this question up? Maybe have the sysadmin look at your question and ask them to clean it up?
Answer: If I understand the question, I think the answer is "ask the school sysadmin."
Comment: School admin said that He doesnt know about and i was asked to research this.
Answer: 1) It could be the computer or location you're trying to connect from. Test your account at the SysAdmin's computer (or have him test from yours).
2) If the sysadmin can use his school credentials to connect, but yours don't work (assuming they are also 'school credentials') then perhaps you could temporarily give yourself (or get him to give you) the same access as the admin and attempt the connection.  This should help determine if it's a permissions issue.


How to open android app in PC browser with http protocol?

Question: First, I don't know how to call this in android development. I am trying to search on the internet but found nothing.
Scenario:

I develop an android app that could do database functions e.g. create, update, delete some data. Say simple list of animal names. I could do everything database functions but only on android device (I mean my app).

My question:

Could I do all the database functions on PC browser that connected to my android app with a url link?

For example -- http://192.168.1.1:7575/
Link above will open a user interface that connected to my app and I could do database functions on it. If I change the data then it will change the data on android app as well.
Btw, I'm not native english speaker. Thanks.
[EDIT]
See this image below: The right side is an android app that running on android device. The left side is web version that connected to the android device with a url. If I close the app on android, the web version also unavailable. It's only one app, an android app. I don't know how to achieve this ability.
link here
Comment: Yes this is possible. From your pc you could receive data from and post data to your Android app. All with a webpage. But its to your Android app what it does with the data. Your app could put it in a database or file or whatever. Your pc can only post/send data. It cannot execute database functions for your app.
Comment: There is not much to see. But you said you wanted to use `For example -- http://192.168.1.1:7575/` well that implies you have to instal a webserver on your Android device to begin with. And then added code to the webserver to handle GET and POST.
Comment: Do you mean an embedded webserver, like XAMPP that runs on Android app, right?
Is this hard to achieve it? I'm interested in this kind of feature that I can implement in my app.
Comment: For Android you could start with NanoHttpd webserver and add your logic. You could also install from play store a php webserver on your Android device and then write php scripts which do all. No need for an Android app then.
Answer: In Android Studio 4.1+ you can use the Database Inspector feature.
This feature lets you to see live update of the database, or manipulate the data.
You can read more about it here:
https://developer.android.com/studio/inspect/database
Comment: Could you see my edited question. Thanks.


Django Swagger and JSON API render issues

Question: Using django-rest-framework-json-api I am able to create API end points that work as described within the documentation. Attempted to provide API documentation using django-rest-swagger is not so easy.
1: Swagger uses media_type = 'application/json' which is not supported in the JSON API. To get around this I created a second render class (renderer_classes)  that sub classes the JSON API JSONRenderer and forces the media type.
Now the end point supports application/json and application/vnd.api+json and swagger is happy to render in JSON API document structure. Aware that the generated curl requests have none a standard JSON API header.
2: Swagger has the same issue with the parser.  While the work out from issue 1 does work there is a secondary challenge. Swagger renders a flat dictionary of field names which is not JSON API and ultimately is requested by DRF.
Is it possible to get swagger to parse in JSON API? At the moment Swagger is not working for PUT or POST.
djangorestframework-jsonapi==2.2.0
djangorestframework==3.5.4
Django==1.11.2
coreapi==2.3.1
python 3.6

Comment: This sounds like a bug with one of the two projects. Either `django-rest-swagger` looks at the models schema and ignores specifics of the views, or `django-rest-framework-json-api` does not present its views' schemas properly to documentation generators. Or maybe `django-rest-framework` does not even have a way for views to present their schemas to documentation generators. Either way I do not suspect there is a way to work around it without modifying the libraries.
Comment: @ZeusttheUnoobian I feel the issue was within `django-rest-swagger` but agree with your comments.
Answer: Answering my own question here so that others can gain value from what was learnt. We never found a solution to this issue and we did not have the time available to contribute to this project. In general the project also appears to be struggling, maybe due to people like us not contributing...
An alternative project drf-yasg has now emerged, which did not exist at the time of this original posting. drf-yasg was relatively easy to deploy and solved all of our issues so we have now migrated to this project instead.
So if you a looking for swagger api documentation for JSON API endpoints created within DRF, then I would suggest drf-yasg.
At the time of writing JSON API is not supported out of the box, but there is sample code to get it up and running relatively easily. With this change in place, all of the endpoints will be auto documented.
This Github Gist that contains the code from our app, hope that this helps you out until this feature is fully developed.
Comment: My experience is that `drf-yasg` is definitely an improvement and solves the mimetype problem, but still renders flat request and response body dictionaries. The only way I found around this was by defining separate (and nested) serializers for each call to replicate the schema of a JSON API call, and telling `drf-yasg` to use those instead of the one the application uses. I am kinda hoping you achieved the same result with less handwork, in which case I am curious how :)
Comment: @ZeusttheUnoobian The developer who dis this work is no longer with us, hence I am not across all of the details. Have added in some more details to the answer, included our sample code. Let me know how you go with it.
Comment: At least on first glance, this looks like more code but less hacky than what I did. I think I like it! This looks like something that could be a project-independent glue library between `djangorestframework-jsonapi` and `drf-yasg` with no to little modification. Kudos!
Answer: As you pointed out in your own answer there is an alternative: drf-yasg. This is great package but does not support JSON API schema out of the box.
That's way you'd even better use drf-yasg-json-api that adds JSON API support to drf-yasg by providing all necessary field inspectors, you just need to slightly extend your SWAGGER_SETTINGS.
Check drf-yasg-json-api Github repo for details.
Disclaimer: I am the author of this package.
Comment: That sounds like a great solution. Well done making this library!


Converter response data de HTML para PDF

Question: O meu response.data está retornado um boleto no formato HTML, quero convertê-lo para PDF. Como faço?
Abaixo uma parte do código:
imprimirboleto: function () {
    axios({
        method: 'get',
        url: '/server/boleto',
        params: {
            banco : this.banco,
            valor : this.valor,
        }
    }).then(function (response)
    {
        var myWindow = window.open("", "MsgWindow", "width=800,height=600, resizable, scrollbars,status")
        myWindow.document.write(response.data) // aqui quero abrir em pdf

    }).catch(function (error) {
        console.log(error)
    })
}

Comment: Talvez https://www.npmjs.com/package/vue-pdf possa ajudar.
Answer: Recomendo a biblioteca PDFKit, ela faz a "conversão" de HTML para PDF, já utilizei e é muito boa


Prove that $\gcd(a,b) = \gcd (a+b, \gcd(a,b))$

Question: I started by saying that $\gcd(a,b) = d_1$ and $\gcd(a+b,\gcd(a,b)) = d_2$
Then I tried to show that $\ d_1 \ge d_2, d_1 \le d_2$.
I know that $\ d_2 | \gcd(a+b, d_1)$ hence $\ d_2 \le d_1 $.
How do I prove that $\ d_2 \ge d_1$ ?
Comment: What is $\gcd(a+b)$?
Comment: What Lord means is, how can you have a gcd of one single number, here being $a+b$?
Comment: @LordSharktheUnknown What do you mean by what is $\gcd(a+b)$ ?
Comment: Do you mean $\gcd(a+b, \gcd(a,b))$?
Comment: @imranfat My apologies its a typo.
Comment: On the right-hand side is  also $gcd(a+b)$
Comment: @Dannz I mean "what is $\gcd(a+b)$?". What is it, by the way?
Comment: @LordSharktheUnknown I thought I fixed the type, check again, isn't it?
Comment: @Dannz Still there, still baffling me.
Comment: @LordSharktheUnknown found it!
Answer: If $\gcd(a,b)=d_1$ then $a = d_1 x$ and $b= d_1 y$, where $x,y$ are integers. Consequently,
$$\gcd(a+b,\gcd(a,b))=\gcd(d_1(x+y),d_1) = d_1\gcd(x+y,1)=d_1.$$
Answer: $d_1$ divides $a$ and $b$, thus it divides $a+b$, and it divides $\gcd (a,b) $ (i.e. itself), thus $d_1$ divides $d_2$.
Answer: We have that $\exists x,y \in \mathbb{Z}$ s.t. $(a+b)x + d_1y = d_2$ by Euclid's Algorithm. Note that $d_1$ divides the LHS, so we must have $d_1 \mid d_2$ and hence the proof.
Answer: Don't worry about size so much as what they divide.
1) $\gcd(a,b)=d_1$ by definition divides $a$ and $b$ and thus $a+b$.  And everything divides itself.  So $\gcd(a,b)$ is a common divisor of $a+b$ and $\gcd(a,b)$ (and thus by definition is less or equal to the greatest common divisor of $a+b$ and $\gcd(a,b)$.  $d_1 \le d_2$).
2) Likewise $\gcd(a+b, \gcd(a,b))= d_2$ divides $\gcd(a,b)$.  So $d_2$ divides everything that $\gcd(a,b)$ divides so $d_2|a$ and $d_2|b$.  So $d_2$ is a common divisor of $a$ and $b$ (and thus by definition is less than or equal to the greatest common divisor of $a$ and $b$. $d_2 \le d_1$.)
Obligatory fleablood essay:  It's best not the think of the "greatest" in greatest common divisor as size as in "Five is bigger than four" but more in the sense of "completeness".  The size of the GCD is of little interest or importance.  What really matters is that can't find a more "comprehensive" factor but adding an additional component factor to GCD or by replacing a component factor of the GCD with another.
As a direct consequence the GCD is the largest possible factor but that is mostly and usually irrelevant.
Many text do not define the "greatest common factor" as "the common factor that is greatest" but as "the common factor so that all other common factors will divide into it".  I, personally, find this a troubling definition because i) it sounds much more obscure and obtuse than it actually is and ii) we must prove that there is such a number and that it is unique.
But I do like that it relates directly wot what does and does not divide the two terms and how.
By that definition:  1) above says $d_1|d_2$ and 2) says $d_2|d_1$ so (assuming we are dealing with positive integers) $d_1 = d_2$.


Analyticity of real parts to function

Question: Show that $xu_x+yu_y$ is the real part to an analytic function if $u(x,y)$ is the real part to an analytic function. To what analytic function is the real part to if $u = Re(f(z))$?
My attempted at a solution:
Write $u_1 = x\frac{\partial u}{\partial x}+y\frac{\partial u}{\partial y}$ and evaluate if $$\frac{\partial^2 u_1}{\partial x^2} + \frac{\partial^2 u_1}{\partial y^2}$$
is 0. However, I get third order derivatives that I can't handle. Is there a not-so-dirty way to solve this?
Comment: I think you use cauchy riemann
Answer: Hint: If $f=u+iv$ is analytic, then $f' = u_x + iv_x.$ Thefore $f'= u_x-iu_y$ by the Cauchy-Riemann equations.
Comment: Yes but here I have an $x$ in front of the $u_x$ and an $y$ in front of the $u_y$. I don't see how this helps me get around that problem.
Comment: Believe me, when you see the solution, you may have a palm print on your forehead.

Analyticity of real parts to function


MVC Api Action & System.Web.Http.AuthorizeAttribute - How to get post parameters?

Question: I have the following API Controller:
public class TestController : ApiController
{
    [HttpPost]
    [APIAuthorizeAttribute]
    public IQueryable<Computers> ListOfComputersInFolder(Guid folderId)
    {
        return GetListOfComputersForFolder(folderId);
    } // End of ListOfComputersInFolder
} // End of TestController

And the following is my basic APIAuthorizeAttribute.
public class APIAuthorizeAttribute : System.Web.Http.AuthorizeAttribute
{
    public override void OnAuthorization(System.Web.Http.Controllers.HttpActionContext actionContext)
    {
        var Request = System.Web.HttpContext.Current.Request;
        var folderId = Request.RequestContext.RouteData.Values["folderId"] ?? Request.Params["folderId] as string;
        if(null == folderId)
        {
            folderId = actionContext.ControllerContext.RouteData.Values["folderId"];
        }

        base.OnAuthorization(actionContext);
    }
}

The problem that I'm having is that folderId is coming out null in the onAuthorize method. (I based the fetcher on this code).
It seems to me that this should be working, but I cannot seem to get it to. Any ideas on what I am doing wrong and how I should go about getting the posted parameter?
Edit: I tried reading the post data directly with the following:
using (StreamReader inputStream = new StreamReader(request.InputStream))
{
    output = inputStream.ReadToEnd();
}
request.InputStream.Position = 0;

Which gets me the post data in JSON format which I could then parse, but then my call never makes it though. I get the following exception in the Response:

500 - Internal server error.

There is a problem with the resource you are looking for, and it cannot be displayed.

at System.Json.JXmlToJsonValueConverter.JXMLToJsonValue(Stream jsonStream, Byte[] jsonBytes)\u000d\u000a   at System.Net.Http.Formatting.JsonMediaTypeFormatter.<>c__DisplayClass7.<OnReadFromStreamAsync>b__6()\u000d\u000a   at System.Net.Http.Internal.TaskHelpers.RunSynchronously[TResult](Func`1 func, CancellationToken cancellationToken)"}

EDIT:
In the end, it seems like this could possibly be a bug with the combination of ApiController, System.Web.Http.AuthorizeAttribute and HttpPost (it does work when using HttpGet). A bug report has been submitted.
Answer: The AuthorizeAttribute should have an AuthorizationContext parameter rather than a HttpActionContext one, from that you should be able to access the RouteData e.g.
public override void OnAuthorization(AuthorizationContext filterContext)
{
    var folderId = filterContext.RouteData.Values["folderId"];
    ...
}

Update
Noticed you are using ApiController and as such using Http.AuthorizeAttribute (explains why you don't have an AuthorizationContext). In that case, you can get the RouteData via the action context e.g.
var folderId = actionContext.Request.GetRouteData().Values["folderId"];

Comment: Note that because this is an [APIController](http://msdn.microsoft.com/en-us/library/system.web.http.apicontroller(v=vs.108).aspx) and not a [Controller](http://msdn.microsoft.com/en-us/library/system.web.mvc.controller(v=vs.108).aspx), I use the `System.Web.Http.AuthorizeAttribute` and not the `System.Web.Mvc.AuthorizeAttribute`. I tried accessing its `ControllerContext.RouteData.Values["folderId"] and it still returned null.
Comment: are you using `HttpPost`? Just to test, I switch to `HttpGet` and now I am able to get the data via `System.Web.HttpContext.Current.Request["folderId"]`.
Comment: thanks I took a look at this as well, but still no luck. The `actionContext.Request` class is a [HttpRequestMessage](http://msdn.microsoft.com/en-us/library/system.net.http.httprequestmessage_methods) and does not contain a `GetRouteData` method. Also if I look at: actionContext.ControllerContext.RouteData.Values it only contains two keys: controller and action. I think my best choice of action would be to read the post data from the inputStream. I gave this a try and confirmed that I can see my post data, but the seems a bit hacky, so I'm going to keep looking for now.
Comment: @Zenox the [GetRouteData](http://msdn.microsoft.com/en-us/library/system.net.http.httprequestmessageextensions.getroutedata(v=vs.108).aspx) is an extension method of `HttpRequestMessage`, make sure you are including a reference to the `System.Web.Http` namespace.
Comment: ah, thanks. Adding the namespace did add the extension method, but the `keys` property only contains 'controller' and 'action'. From what I am seeing, I think that the `OnAuthorization` method must be called before the framework has populated the rest of the values.
Comment: @Zenox The data should be in there somewhere, I can't remember off the top of my head. Possibly the `DataTokens` collection?
Comment: I checked the `actionContext.ControllerContext.RouteData.Route.DataTokens` collection and its empty. I'm fairly confident i've walked the entire path of the `actionContext` instance now and cannot find the folderId anywhere. I may start looking for an alternative method to accomplish what I am looking for. Thanks for the help though.
Comment: @Zenox I have a custom `AuthorizeAttribute` which in the `OnAuthorization` method access route data via `actionContext.ControllerContext.RouteData.Values` therefore I can't understand why yours doesn't work. MVC4 is still in Beta so there is potential for it to be a bug, but doesn't make sense that it works for me and not you.
Comment: @Zenox ah that's what it must be, I am using `HttpGet`. Weird why you can't get post parameters though.
Answer: I have also encountered this problem.
To work around it I wrote the following method which I call from within the OnAuthorization method:
private static object GetValueFromActionContext(HttpActionContext actionContext, string key)
{
    var queryNameValuePairs = actionContext.Request.GetQueryNameValuePairs();

    var value = queryNameValuePairs
        .Where(pair => pair.Key.Equals(key, StringComparison.OrdinalIgnoreCase))
        .Select(pair => pair.Value)
        .FirstOrDefault();

    var methodInfo = ((ReflectedHttpActionDescriptor) (actionContext.ActionDescriptor)).MethodInfo;
    var parameters = methodInfo.GetParameters();
    var parameterType =
        parameters.Single(p => p.Name.Equals(key, StringComparison.OrdinalIgnoreCase)).ParameterType;

    var converter = TypeDescriptor.GetConverter(parameterType);

    return converter.ConvertFromString(value);
}

This code makes the following assumptions:

The key you are extracting matches an argument name on the action method.
The parameter type you are obtaining will have a converter valid for the type.
You are not using any custom binding or formatting on the parameter.

In the scenario that I am using the code I am only expecting simple types such as Guid, Boolean, String etc and could be customised as per your requirements.
The extension method GetQueryNameValuePairs is part of the System.Net.Http.HttpRequestMessageExtensions class and will read querystring / form data.
Example use:
object folderId = GetValueFromActionContext(actionContext, "folderId");

Answer: If the request's contenttype is application/json;charset=utf-8
The API action can retrieve the Post Data as follow:
Stream stream = actionContext.Request.Content.ReadAsStreamAsync().Result;
Encoding encoding = Encoding.UTF8;
stream.Position = 0;
string responseData = "";

using (StreamReader reader = new StreamReader(stream, encoding))
{
    responseData = reader.ReadToEnd().ToString();
}

var dic = JsonConvert.DeserializeObject<IDictionary<string, string>>(responseData);

Answer: You can give this extension method a try: (this is an excerpt of working code)
public static string GetParameter(this RequestContext requestContext, string key)
{
    if (key == null) throw new ArgumentNullException("key");

    var lowKey = key.ToLower();

    return requestContext.RouteData.Values.ContainsKey(lowKey) &&
           requestContext.RouteData.Values[lowKey] != null
               ? requestContext.RouteData.Values[lowKey].ToString()
               : requestContext.HttpContext.Request.Params[lowKey];
}

I agree with James' answer, you have to access the request context via the actionContext in this scenario.


How to get a PHP array field value from a PHP file using jquery/Ajax?

Question: I would like to know how to get a PHP array field value from a PHP file using jquery/Ajax. In fact, I have three files: mapage.html , moslem.php and moslem1.php . You find below the code of each file.
The code of mapage.html:


Combine overlapping Gaussian distributions

Question: Given the mean and covariance matrix of the pair-wise (multivariate normal) distributions
\begin{align}
P(X_1,X_2) &\sim \mathcal{N}(\mu_{12},\Sigma_{12}),\\
P(X_2,X_3) &\sim \mathcal{N}(\mu_{23},\Sigma_{23}) \quad \text{and}\\
P(X_1,X_3) &\sim \mathcal{N}(\mu_{13},\Sigma_{13})
\end{align}
What is the best estimate for $\mu^\star,\Sigma^\star$ in
\begin{align}
P(X_1,X_2,X_3) &\sim \mathcal{N}(\mu^\star,\Sigma^\star),
\end{align}
the joint distribution of $X_1,X_2,X_3$?

Edit:
Note, that $\mu_{12},\mu_{13},\mu_{23} \in \mathbb{R}^2$ and $\mu^\star \in \mathbb{R}^3$ (similar for the covariance matrices).
If I would have only two one dimensional distributions, $P(X_1) \sim \mathcal{N}(\mu_{1},\Sigma_{1})$ and $P(X_2) \sim \mathcal{N}(\mu_{2},\Sigma_{2})$ I would combine them by concatenating the mean vectors and using $diag(\Sigma_{1}, \Sigma_{2})$ as a diagonal covariance matrix.
Comment: Is it guaranteed that $X_1, X_2, X_3$ have a trivariate normal distribution? The reason for asking is that the three random variables do possess a mean vector and a covariance matrix without necessarily being jointly normal as well.
Comment: Not guaranteed, but the goal is to approximate it with a normal distribution as good as possible given the 3 mean vectors and covariance matrices.
Comment: Why do you mention "estimation" when you know the parameters of the pairwise marginals? There is no data involved at this stage.
Answer: This question can have multiple answers depending on who is doing the answering, or, depending on the interpretation placed on it,
it might be unanswerable.
As I understand the question, we are given that $X_1, X_2$, and $X_3$ are pairwise jointly normal random variables with specified mean vectors
and covariance matrices. We are asked for a trivariate joint normal
distribution that is "most consistent" with this information.
As an engineer (and wannabe probabilist), the first thing I would do
is to check the given information for consistency.

It must be the case that $\mu_{ij} = (\mu_i, \mu_j)$
where $\mu_i = E[X_i]$, $i = 1,2,3$. So, if the problem claims that $\mu_{12} = (4,10)$ while $\mu_{23} = (5,-3)$, the given information
is inconsistent.
Similarly, the covariance matrices must be consistent: in
$\Sigma_{ij}$, the diagonal terms are
$\sigma_i^2 = \operatorname{var}(X_i)$ and
$\sigma_j^2 = \operatorname{var}(X_j)$. Each variance occurs
in two of the three covariance matrices and it must have the same
value in both occurencse. It must also be true that the
off-diagonal terms in $\Sigma_{ij}$ must be equal, and that
$\Sigma_{ij}$ must have determinant $\geq 0$.

If the above consistency checks are satisfied, then, regardless
  of whether the $X_i$ are pairwise jointly normal or not, the
  mean vector of $(X_1,X_2,X_3)$ is
  $$\mu = (\mu_1,\mu_2,\mu_3)\tag{1}$$ and
  the covariance matrix is
  $$\Sigma = \left[\begin{matrix}
\sigma_1^2& \sigma_{12}& \sigma_{13}\\
\sigma_{21} & \sigma_2^2 & \sigma_{23}\\
\sigma_{31} & \sigma_{32} & \sigma_3^2\end{matrix}\right]\tag{2}$$
  in which the upper left $2\times 2$ submatrix is the given
  $\Sigma_{12}$, the lower right $2\times 2$ submatrix is the given
  $\Sigma_{23}$, and the "four-corners" submatrix is the given $\Sigma_{13}$.

At this point, the probabilist's answer to the question

Which trivariate joint normal distribution is most consistent
  with the given information?

would be that $\mathcal N(\mu,\Sigma)$ is the only
trivariate normal distribution that is exactly
consistent with the
given information (that the marginal bivariate distributions
are the specified bivariate joint normal distributions). No other trivariate
normal distribution can be as good a match with the given
information.
On the other hand, the question might be interpreted as

Which trivariate joint normal distribution is the "best
  approximation" to the actual unspecified joint distribution
  of $(X_1,X_2,X_3)$?

and to my lowly engineering mindset, this question is unanswerable
since neither the meaning of "best" nor the target to be
matched is known;
dyed-in-the-wool probabilists might choose to give a different
response.  Other readers who disagree with my
interpretation might want to try their hand at
finding the trivariate joint normal distribution that best approximates
$$f(x_1,x_2,x_3) = \begin{cases}
2\phi(x_1)\phi(x_2)\phi(x_3),
& \text{for}~ x_1 \geq 0, x_2 \geq 0, x_3 \geq 0,\\
&\text{ or}~ x_1<0, x_2< 0, x_3 \geq 0,\\
&\text{ or}~ x_1<0, x_2\geq 0, x_3 < 0,\\
&\text{ or}~ x_1\geq 0, x_2< 0, x_3 < 0,\\
0, &\text{otherwise},\end{cases}$$
where $\phi(\cdot)$ is the standard normal density function.
Note that the $X_i$ are pairwise independent standard normal
random variables.

On the other hand, a good statistician might take it that the OP
has masses of data (maybe even "Big Data") from which
the OP has drawn the inference that it is reasonable to
assume that the $X_i$ are pairwise jointly normal
random variables, and that $\mu_{12}$, $\mu_{23}$, $\mu_{13}$, $\Sigma_{12}$
$\Sigma_{23}$, $\Sigma_{13}$ are sample means, variances, and covariances
 gleaned from three different data sets
of the form $\{(x_{1,i}, x_{2,i})\colon i = 1,2,\ldots n_1\}$,
$\{(x_{2,j},x_{3,j})\colon j = 1,2,\ldots, n_2\}$ and
$\{(x_{1,k},x_{3,k})\colon k = 1,2,\ldots n_3\}$. Then it
is almost certain that the first entry in $\mu_{12}$
(which is $\frac{1}{n_1}\sum_i x_{1,i}$) is not the same
as the first entry in $\mu_{13}$ (which is $\frac{1}{n_3}\sum_k x_{1,k}$).
Similarly for the other means, variances and covariances.  So,
should the data be merged to get better estimates of what the
means, variances, etc are?  Is there data available of the
form $\{(x_{1,m}, x_{2,m}, x_{3,m})\colon m = 1,2,\ldots N\}$
that might allow some form of estimation as to what the
 actual joint distribution of $(X_1,X_2,X_3)$ is?
Considerations of this type
lead to the kinds of answers given by Tim and Karel Macek.
Answer: The problem can be solved as an optimization one. Given $\mu$ and $\Sigma$ for $X_1,X_2,X_3$, you have corresponding marginalizations $\tilde{\mu}_{1,2}$, $\tilde{\Sigma}_{1,2}\dots$. The marginalization of multivariate Gaussian is simple.
To quantify how those match to $\tilde{\mu}_{1,2}$, $\tilde{\Sigma}_{1,2}\dots$, you can use Kulback-Leibler divergence for Gaussians for each of those marginalizations.
Then you have to solve
$$[\mu^*,\Sigma^*]=\arg\min_{\mu,\Sigma}(KLD_{1,2}+KLD_{2,3}+KLD_{1,3})$$.
Answer: You are referring to multivariate normal distribution parametrized by a vector of means $\boldsymbol{\mu}$ and covariance matrix $\boldsymbol{\Sigma}$. The MLE estimators for those parameters are sample means for $\mu_i$'s and sample covariance for $\boldsymbol{\Sigma}$.


Remove inline-block space between two wordpress loop elements?

Question: How do i remove the inline-block space between two divs that are a part of the wordpress loop? They are supposed to sit side-by-side, each being 50% width. I realize I could change the width to 49% or use floats, but I would like to leave it this way if possible.
I know you normally can do it by eliminating the white space in the coding with comments as below:

Frick TDSH 355XL
Slide Valve and Rotor Housing

Frick NGC300 Gear Plate

This is my wordpress loop, and no matter where I put the comment, and still adds white space in the actual returned html.
<?php
  $my_query = new WP_Query(
    array(
      'cat' => '2',
    )
  );

  while ( $my_query->have_posts() ) : $my_query->the_post();
?>

  <?php
    if ( has_post_thumbnail() ) {
      the_post_thumbnail();
    }
  ?>

<?php the_title(); ?>
<?php the_content(); ?>

<?php endwhile;?><?php wp_reset_postdata();?>

And this is what is showing up in Developer Tools:

...

...

I'm sure I'm just overlooking something easy, but any help would be appreciated. Thanks!
@Prusprus here it is straight from the source code:

Frick NGC300 Gear Plate

Frick TDSH 355XL

Slide Valve and Rotor Housing

Comment: You have a line break between your closing PHP tag and your  tag (lines 9 and 10 in your example code). Have you tried close this up?
Comment: That was it! I was so worried about the end of the loop I didn't even think of that. Not sure I would have put two-and-two together anyways. Thanks for pointing it out!
Comment: Can you paste what's returned directly from the source code? I think the developer tools might reformat the code liens for better reading.
Answer: There may be a different way to mark this as answered, not sure, but @Prusprus gave me the solution in a comment above.
I simply had to remove a line break at the start of my code between the closing php tag and the start of my div.
Comment: I was about to recommend putting all the php in question on one line, then systematically break the code for readability, checking each time to isolate the issue.
Comment: That's exactly where I'll start next time. Thanks!
Comment: Users  should probably upvote the comment as well, to give the real answer more weight. Also, the answer could be deleted and reposted by @Prusprus.
Answer: The traditional way of floating inline-block elements could correct this, but since its unfavored there is another way.
You can also set the letter spacing of the parent element to -0.31em to solve this and set the letter-spacing back to normal in the divs themselves. I'll set up a jsfiddle in a sec.
CODE
.row {
     letter-spacing:-0.31em;
}
.col {
     letter-spacing:normal;
     display:inline-block;
     width:50%;
}

Good luck!
Comment: A suggestion above fixed it, but I appreciate the help! Your way works, but I had to add a container div around my divs to change the letter-spacing, and in this case I just don't want the extra markup. Thanks though!
Answer: Two methods here

Set the parent's font-size to 0 and then restore it on the inline-block elements.
Apply a suitable margin to the last div.

DEMO x 2
HTML

CSS
.opt1, .opt2 {
    margin:10px;
    border:1px solid green;
}

.before-after {
    display:inline-block;
    background:lightgrey;
    width:50%;
    height:100px;
    font-size:16px
    font-size:1rem;
}

.opt1 {
     font-size:0;
}

.opt2 .before-after{
    vertical-align:top;
}

.opt2 .before-after:last-child {
    margin-left:-.25em;

}

Comment: Thanks a lot for the assistance! Both of these methods work great, but in this specific instance I wanted to do it without adding any extra container divs. I will definitely keep this solutions for the future though. Thanks again!


Construct a pointer in C from an address

Question: I initially get an address of a pointer from another processor and I need a pointer that points to the items at that address.  Don't worry too much about the MPI_Recv, just know that I am getting information from another processor. So I have:
<code>MPI_Recv(&a, sizeof(int), MPI_INT, 0, 1, MPI_COMM_WORLD, &status);

c = a;
printf("%d",c[0]);
</code>
Why does this give me a segmentation fault?  I have tried allocating memory for c as well before setting c = a and it will still seg fault.
Comment: Search virtual memory address first.
Comment: Another very relevant detail: Which operating system?
Comment: OS: Linux. This is a parallel application and should be processor I believe
Comment: @hyde If I am running my application on a cluster, I would assume each node would have its own processor.  However each node may have several processes.  I think this is the correct distinction, but please correct me if I am wrong.
Comment: @thepristinedesign Ah clustering, `mpi` tag added now, even. There it might or might not be right terminology to say *processor*, I'm not familiar enough to say it one way or another... Deleting my comments above.
Answer: Each process has its own separate virtual address spaces. Pointers from one process are meaningless in the context of another process.
You have several options:

Use threads instead of processes.
Use shared memory.
Send the actual data rather than just a pointer.

Only the last option is viable if your processes can reside on different computers.
Comment: With shared memory one still has to provide relative addresses instead of direct pointers as the shared memory segment may be mapped at different virtual addresses in each process.
Comment: This answer is correct, but it misses *MPI shared memory*.


nginx Rewrite for CImage Cache

Question: I'm setting up a script (http://dbwebb.se/opensource/cimage) to do some image processing and I'd like to cache the resulting image output.  I have that part working fine.
The problem I'm running into is when someone goes to download the image from the cache.  The question mark on the query string is passed through on the proxy url, so the downloaded image has a default filename of "test.jpg&height=200" which doesn't open properly on windows without renaming it.
I need to set up some kind of rewrite rule so that the first "?" character gets changed to a "&".  It would also need to still work if the request is simply just for the filename without any additional parameters.
What do I need to add to make the url accessible with a "?", but send to the server as an "&"?
Origin
http://origin.example.com/img.php?src=folder1/test.jpg&height=200
Current Edge Cache (this is how it works now):
http://cdn.example.com/dynimg/folder1/test.jpg&height=200
Desired Edge Cache:
http://cdn.example.com/dynimg/folder1/test.jpg?height=200
http://cdn.example.com/dynimg/folder1/test.jpg
nginx config (the important area):
location /dynimg/ {

                expires                 14d;

                proxy_pass              http://origin.example.com/img.php?src=;
                proxy_cache_valid       200 302 2880m;
                proxy_cache_valid       404 1m;

        }

Answer: Your image processing application should send the Content-Disposition HTTP header, where the desired filename is sent. This way the user's browser will use that filename instead of the filename derived from the URL of the request.
Nginx proxy cache will save the Content-Disposition header, and then users will get the correct filenames.

nginx Rewrite for CImage Cache


A collection of 14 identical ping pong balls, 8 identical golf balls, and 27 identical marbles is to be chosen from. How many ways to choose ...

Question: For part a: 8 objects total
I tried 49 Choose 8 which is wrong
For part b: 14 objects total
For part c: 26 objects total
These two I did not know how to do because my process for part a is incorrect.
Comment: (a) is a basic [stars-and-bars problem](https://en.wikipedia.org/wiki/Stars_and_bars_%28probability%29); (b) and (c) will in addition require an [inclusion-exclusion argument](https://en.wikipedia.org/wiki/Inclusion%E2%80%93exclusion_principle). The first link gives you a formula for solving (a) together with a decent explanation of where it comes from.
Comment: How do you know when to use stars and bars? Why would I use stars and bars here and not $C_8^{49}$?
Comment: Why not $C_{49}^8$? Let choose 8 marbels of 27 identical. If they were pairwise different you really would have $C_{27}^8$ different combinations. But they are identical and obviously you have only one possible combination and it even doesn't matter how many of them there are (if there is enough number of them).
Answer: For the part a you can assume that you have infinite number of balls of each king and you need to find number of combinations with repetitions $\left(\!\!\binom{8}{3}\!\!\right) = \binom{8+3-1}{3-1} = \binom{10}{2} = 45$.
For the part b such assumption is incorrect, but if you choose $k$ golf balls then you should choose one of $\left(\!\!\binom{14-k}{2}\!\!\right) = \binom{14-k+2-1}{2-1} = 15-k$ combination of two other kinds. So the answer is $\sum_{k=0}^8 15-k = 9\cdot15 - \frac{8\cdot9}2 = 99$.
For the part c you can choose 0 to 8 golf balls and 0 to 14 ping pong balls and all the rest will be marbles. So we get $9 \cdot 15 = 135$ sets.
Comment: Why is n=8 and k=3?
Comment: $n = 8$ is number of objects to choose and $k = 3$ is number of kinds of objects available.
Answer:
How do you know when to use stars and bars? Why would I use stars and bars here and not $C_8^{49}$?

There actually are $\binom{49}8$ different sets of $8$ objects that you could pick from this collection of $14$ identical ping pong balls, $8$ identical golf balls, and $27$ identical marbles. If you quoted the question exactly, your answer is literally correct, and the person who wrote the question didn't ask what he or she intended to ask. Thanks to years of experience with the subject and the kinds of problems that are commonly used, I know that the intention was to ask in how many distinguishable ways $8$ of these objects can be chosen; the signal here is the word identical.
There are $\binom{14}3\binom82\binom{27}3$ ways to choose a set containing $3$ ping pong balls, $2$ golf balls, and $3$ marbles, but since we can't tell one ping pong ball, golf ball, or marble from another, these $29,811,600$ sets of objects are indistinguishable and are supposed to be counted as just one way. In other words, we're counting two sets as identical if they have the same number of objects of each type. In this sense a set of these objects is completely determined by the three numbers $n_p,n_g$, and $n_m$, the numbers of ping pong balls, golf balls, and marbles, respectively, in the set: two sets with the same values for those three numbers are considered identical and counted as just one way of choosing the objects.
We can therefore recast the problem: we want to count the number of solutions to the equation $$n_p+n_g+n_m=8\tag{1}$$ such that $n_p,n_g$, and $n_m$ are integers satisfying the inequalities $0\le n_p\le 14$, $0\le n_g\le 8$, and $0\le n_m\le 27$. In this case the upper limits of $14,8$, and $27$ are irrelevant: no solution of $(1)$ in non-negative integers violates any of those restrictions. Thus, for all practical purposes we're just counting the solutions to $(1)$ in non-negative integers. This is an example of a basic stars-and-bars problem; the formula given (and reasonably well explained) at the link gives us the answer
$$\binom{8+3-1}{3-1}=\binom{10}2=45\;.$$
Similarly, the second problem was intended to ask for the number of distinguishable sets of $14$ items, which is the number of solutions to the equation
$$n_p+n_g+n_m=14\tag{2}$$
such that $n_p,n_g$, and $n_m$ are integers satisfying the inequalities $0\le n_p\le 14$, $0\le n_g\le 8$, and $0\le n_m\le 27$. This time one of the upper limits matters: $(2)$ has solutions in non-negative integers that violate the upper limit of $8$ on $n_g$. The trick here is to forget that limit for a moment, pretending that we actually have at least $14$ golf balls available, and get a preliminary total of
$$\binom{14+3-1}{3-1}=\binom{16}2$$
solutions. Some of these solutions, however, are inadmissible, since they involve taking more than $8$ golf balls; we'd like to count the inadmissible solutions and subtract them from the total.
Let $n_p'=n_p$, $n_g'=n_g-9$, and $n_m'=n_m$; if $\langle n_p,n_g,n_m\rangle$ is a solution to $(2)$ such that $0\le n_p\le 14$, $n_g\ge 9$ (and is therefore inadmissible), and $0\le n_m\le 27$, then $\langle n_p',n_g',n_m'\rangle$ is a solution in non-negative integers to
$$n_p'+n_g'+n_m'=5\;,\tag{3}$$
since $14-9=4$. Conversely, any solution to $(3)$ in non-negative integers becomes an inadmissible solution to $(2)$ when you add $9$ to $n_g'$. Thus, $(2)$ has
$$\binom{5+3-1}{3-1}=\binom72$$
inadmissible solutions, and the answer to (b) is therefore only
$$\binom{16}2-\binom72=120-21=99\;.$$
For (c) you'll be counting integer solutions to
$$n_p+n_g+n_m=26\tag{3}$$
that satisfy the inequalities $0\le n_p\le 14$, $0\le n_g\le 8$, and $0\le n_m\le 27$, and you'll have to work a bit harder to count the inadmissible solutions. The problem is that there are solutions to $(3)$ that violate the bound $n_p\le 14$ but neither of the other upper bounds; solutions that violate the bound $n_g\le 8$ but neither of the other upper bounds; and solutions that violate both the bound $n_p\le 14$ and the bound $n_g\le 8$. (The third upper bound cannot be violated, since we're choosing only $26$ objects.) I've already illustrated most of the ideas that you need; the very first sentence of the Wikipedia article on the inclusion-exclusion principle is the one missing piece.


java.lang.ClassNotFoundException....once more

Question: I have updated my app today and after that I got 12 crash reports. As i can see all are tide to my main activity class. Here's couple of them:
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{rs.androidaplikacije.zastaveigradovi/rs.androidaplikacije.zastaveigradovi.MainActivity}: java.lang.ClassNotFoundException: rs.androidaplikacije.zastaveigradovi.MainActivity in loader dalvik.system.PathClassLoader[/data/app/rs.androidaplikacije.zastaveigradovi-1.apk]
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1573)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1667)
at android.app.ActivityThread.access$1500(ActivityThread.java:117)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:935)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:130)
at android.app.ActivityThread.main(ActivityThread.java:3687)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:507)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:867)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:625)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.ClassNotFoundException: rs.androidaplikacije.zastaveigradovi.MainActivity in loader dalvik.system.PathClassLoader[/data/app/rs.androidaplikacije.zastaveigradovi-1.apk]
at dalvik.system.PathClassLoader.findClass(PathClassLoader.java:240)
at java.lang.ClassLoader.loadClass(ClassLoader.java:551)
at java.lang.ClassLoader.loadClass(ClassLoader.java:511)
at android.app.Instrumentation.newActivity(Instrumentation.java:1021)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1565)
... 11 more

java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{rs.androidaplikacije.zastaveigradovi/rs.androidaplikacije.zastaveigradovi.MainActivity}: java.lang.ClassNotFoundException: rs.androidaplikacije.zastaveigradovi.MainActivity in loader dalvik.system.PathClassLoader[/data/app/rs.androidaplikacije.zastaveigradovi-1.apk]
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1664)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1766)
at android.app.ActivityThread.access$1500(ActivityThread.java:156)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:994)
at android.os.Handler.dispatchMessage(Handler.java:130)
at android.os.Looper.loop(SourceFile:351)
at android.app.ActivityThread.main(ActivityThread.java:3833)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:538)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:901)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:659)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.ClassNotFoundException: rs.androidaplikacije.zastaveigradovi.MainActivity in loader dalvik.system.PathClassLoader[/data/app/rs.androidaplikacije.zastaveigradovi-1.apk]
at dalvik.system.PathClassLoader.findClass(PathClassLoader.java:271)
at java.lang.ClassLoader.loadClass(ClassLoader.java:582)
at java.lang.ClassLoader.loadClass(ClassLoader.java:542)
at android.app.Instrumentation.newActivity(Instrumentation.java:1056)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1656)
... 11 more

And here's my main activity. I did not change anything in it at all.
public class MainActivity extends SwarmActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        preload(this, 5259, "0d2ab20831857f730c1c362705970d1f");
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);

        super.onCreate(savedInstanceState);
        setContentView(R.layout.splash);

        Thread splashTimer = new Thread(){
            public void run(){
                try {
                    sleep(2000);
                    Intent menuIntent = new Intent("rs.androidaplikacije.zastaveigradovi.MENU");
                    startActivity(menuIntent);
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                finally{
                    finish();
                }
            }
        };
        splashTimer.start();
    }

    private void preload(MainActivity mainActivity, int i, String string) {
        // TODO Auto-generated method stub

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }

}

Everything works fine on my phone, but i got a lot of crash reports today. Can someone tell me what's the problem?
Comment: Could you post the manifest file?
Comment: What is the full inheritance of `SwarmActivity`? If any of the superclasses depend on a class that doesn't exist on someone's phone, then this error will be thrown. If they merely **REFER** to another class, the class can't load. (worst case: you may have to use dynamic class loading via reflection).
Comment: I just import com.swarmconnect.SwarmActivity;. It's online leaderboard service.
Answer: I think that the problem is in the way your application is "packaged".  The exception is saying that the class loader cannot find the rs.androidaplikacije.zastaveigradovi.MainActivity class when it tries to load it.  The fact that you didn't change your code is probably not relevant.
Why it works on your phone and not on other peoples' is less clear.  But it could be that:

The version you are running on your phone is not identical to the one that other people are getting from the app store (or wherever).
Your phone has other stuff on it, and that other stuff is what makes the difference.

(It is also possible that the root cause is earlier than the exception in the reports.  On a real Java platform, it is possible for class loading and initialization to fail, leaving some classes in an unintializable state.  This can then cause later things to fail to load.  In this case, the later exceptions don't tell you the real cause of the problems.  You have to look to the earlier exception stacktraces for the real cause.  HOWEVER, I don't think that is what is happening here.)
Comment: When I install it over Eclipse it works fine, when I install it over Play Store it crashes on start.
Comment: Well at least you can reproduce the problem now!


How to prefix all tables of a package in laravel?

Question: I'm creating some packages based on DDD. Each domain going into its own package.
I also want to prefix each package tables with certain prefix so that they are sorted in phpMyAdmin.
I know I can change config.php of my host app. But that's not what I want.
This is a sample of the result I'm searching to get in phpMyAdmin
auth_users
auth_roles
auth_tokens
auth_user_roles
sales_leads
sales_campaigns
sales_conversions
ticketing_tickets
ticketing_posts
ticketing_attachments
...

And I have auth, sales, ticketing and other packages.
How can I do that?
Comment: This might help: https://stackoverflow.com/a/7971098/177526
Answer: There is no way to directly do that in Laravel.
You can have several db_connection with diferrent prefix but not sure it helps your requirement.
To, as best, answer your need, I should create a "sql view" to each table with the desired name.
CREATE VIEW auth_users AS SELECT * FROM users;
...


Interromper loop na página

Question: Estou com um problema, que pesquisei e pensei como fazer, mas não consegui resolver. Tenho um select na página que precisa ser populado após uma condição ser satisfeita. E após isso, ele precisa consultar os dados relativos a opção escolhida no select. Suponha que esse select seja para preencher o nome de usuários, e após ele ser preenchido, deve ser feita uma consulta no banco com os dados relativos aquele usuário. E é aí que ficou o meu problema, embora consiga preencher o select e trazer os dados relativos ao usuário escolhido, toda vez que a página é iniciada, o script roda novamente e toda hora fica consultando. Fica meio que um loop de consultas que não consigo interromper. Como posso fazer com que seja feita apenas uma consulta e após isso, ele interrompa de modo que a consulta não seja feita novamente?

É mais um problema de lógica do que de sintaxe, razão pela qual reduzi
  o código em si.

    <form method="post">
    <select class='form-control' id='opcoes'>
    </select>
    </form>

Comment: O que retorna no ajax?
Comment: aquele ajax, retorna dados no formato json, com os quais preencho o select. Após isso, preciso submeter o form, e é esse o meu problema, não sei onde posso colocar esse form para consultar sem que ele fique dando loop com isso
Comment: tudo acontece do jeito que quero, exceto esse loop
Comment: A principio dá pra resolver criando uma flag (true/false) na sessão, onde quando é realizado a operação do ajax, no controller você altera a flag para false. No JS, você pode recuperar uma variável de sessão usando "${flag}".
Comment: bem pensado, uma variável de sessão no próprio javascript...
Answer: Bom, vamos lá. Pelo que entendi. Após preencher o select, você gostaria de enviar o form, mas ele continua num loop o Ajax, certo?!
O que você pode fazer pra resolver isso é criar uma variável de "trava" e preenchê-la no success do ajax. Vou tentar dar um exemplo:
    var stop = false;

<form method="post">
<select class='form-control' id='opcoes'>
</select>
</form>

Aqui tem uns exemplos de utilização de funções no final do ajax: http://api.jquery.com/jquery.ajax/#entry-examples
Espero que tenha ajudado. Abraços

Interromper loop na página


Boost not refreshing views page

Question: I am using Drupal 7.32 and the latest Boost, Boost Crawler and Cache Expiration modules. My 'normal pages' refresh fine with boost when i amend them ie. articles, Basic Page, Content Type node, but if I change a node which belongs to a Views page (e.g. a News item on a News Blog page contructed with a View), then it does not pull in the latest news item i have just created i.e. does not expire the News Blog page. Within the documentation at https://www.drupal.org/node/545908 it shows the option
<code>[x] Clear all cached views pages associated with a node on update/delete
</code>
But I cant see where to set this in the Boost module settings. I think that would fix my problem. Maybe that is referring to old documentation, perhaps the new module does it in a different way.
Can anyone help?
Answer: After a bit of digging around I found that this is resolved by adding the URL to the Cache Expiration setting as follows. Go to » Administration » Configuration » System >> Cache Expiration, the under Node Expiration tab, then in the section 'What URLs should be expired when node action is triggered?', tick Custom Pages, then add the URL of your pages that are created with Views, in my case its just the word News. There may be a way to add conditioning on this so it only expires the News page when nodes relating to it are amended. If anyone finds that out, can they let me know. You can also tick under Module Status in the Debug section at the bottom 'Watchdog + site message ', it will display a message show which urls have been expired (cleared).

Boost not refreshing views page


How to "project out" some dimensions of an n-d array?

Question: Suppose that M is an n-dimensional array (of numbers).  one can also think of M as an (n - k)-dimensional array of k-dimensional arrays.  I want to generate the array corresponding to applying some function f to each one of those k-dimensional arrays.
More precisely, I want to generate a new (n - k)-dimensional array N where the value for each cell N(i1, i2, …, in-k-1, in-k) is obtained by applying a (scalar-valued) function f to the k-dimensional array at M(i1, i2, …, in-k-1, in-k).
(The function f is typically some "summarizing function", like the mean, the median, the max, or the min.)
I imagine that the way to do this would involve arrayfun in some way, but I have not been able to figure out how to get arrayfun to iterate only over the first (n - k) dimensions of M.
Answer: If you are only interested in applying simple functions like mean / median / max / min to the k-vectors, i.e. functions for which the k-dimensional structure of these vectors is irrelevant, then this is the way to go:
s = size(M);
N = reshape(fun(reshape(M, prod(s(1 : end - k)), []).'), s(1 : end - k));

This code assumes that fun operates on the first dimension of its argument, as is the case for mean, median, min, and max and many other Matlab standard functions.
It first reshapes M into a two-dimensional array, where the first dimension corresponds to the first n – k dimensions of M, and the second dimension corresponds to the last k dimensions of M. Through the transpose fun operates across the second set of dimensions. It returns a scalar for each column, such that the result can be reshaped back into an (n – k)-dimensional array N of a form corresponding to the first n – k dimensions of M.


How to prevent appending multiple times in the table, Once It forcing to double click multiple times the table row using Jquery?

Question: I have module appending the result of response to the other table. looking forward I found a solution in my module. however I found problem on that i will give to you guys the scenario what the problem it does.
First Scenario:
 User will choose what condiment he wanted to click, Looking forward Ex. User 1 choose the Second table row, the Condiments *LG FRIES.

Second Scenario:
 In the first scenario user choose the *LG FRIES, as you can see here modal will open and the result of response will append to the table B.

Third Scenario: Well First and Second scenario look works and good, but here I will show you, how does appending will multiply in the table once i force double click the table row of *LG FRIES.

So now i will let you show my codes.
This is my function for getting the result of clicking the of table row then the result will append to the table B.
$('table#noun_chaining_order').on('click','tr.editCondiments',function(e){

    var allow_to_open_condiments_conditional =  $(this).closest("tr").find(".allow_to_open_condiments_conditional").text();

    if(allow_to_open_condiments_conditional == 'Yes') {

        $('.conditional_table_hidden_noun').hide();

        $('.conditional_table_hidden_condiments').show();

        $('table#noun_chaining_order tr').removeClass('selected');

        $(this).addClass('selected');

        var find_each_id_condiments = $(this).find('td.condi_section_id').text();
         $("table#customer_table_update_chain_order tbody").html('');

        $('#customer_modal_update_chain_order').modal('show');

         $.ajax({
          url:'/get_each_id_section_condiments',
          type:'get',
          data:{find_each_id_condiments:find_each_id_condiments},
          success:function(response){

            var get_each_section = response[0].condiments_table;

            $.each(get_each_section, function (index, el) {

               var stringify = jQuery.parseJSON(JSON.stringify(el));

              var cat_condi_screen_name = stringify['cat_condi_screen_name'];
              var cat_condi_price = stringify['cat_condi_price'];
              var cat_condi_image = stringify['cat_condi_image'];
              var image = '';

              // $('#edit_chainingBuild').append("
" + Qty + "	" + Condiments + "	" + Price + "	"+menu_builder_details_id+"
");

              $('table#customer_table_update_chain_order tbody').append("
" + cat_condi_screen_name + "	" + cat_condi_price + "	"+image+"
");

            });

          },
          error:function(response){
            console.log(response);
          }
        });

    }
    else
    {

    }

});

So the question will be, How to stop appending multiple times once I force double click the table row?
Comment: From what I see here I can not see the problem. Could you show us the response from your ajax request (in Chrome [Right Click] -> Inspect  -> Network.
And try to put your "clean table code" in the success function
Comment: I already try to console my success function once i clicked multiple times, the response also give multiple, if i clicked once It workes find.
Comment: You want to clear earlier table data ?
Comment: yes.. my works find if i clicked once, but when  force to clicked multiple times, then it will append multiple times in the table
Comment: well yes sure because you probably add the data to a database when you click on the add button. So the same date is stored multiple times in you database. Thats why it would be helpful to see what the response to you ajax call is. Or a screenshoot of your database table would also be useful.
Comment: hi @marcramser i will update my post, I will screenshot the response result.
Comment: please see the new update
Comment: We need the "Network" tab not the "Console" one.  Or to me more specific click on the "Network" tab (reload the page with pressing the button "F5", then click on "XHR", then on the "/get_each_id_section_condiments" request and then on "Response" that is what we would need.
Comment: @marcramser sure i will, sorry for the delay message..
Comment: take a look my update
Comment: the thing on the right of your screenshoot (after you have selected the "Response" tab
Answer: I see simple solutions here.

When you appending cart item, you can add that item ID from database
to the element. And before appending check if an item from response
doesn't exist in BODY.
Another solution will be just after you click append - hide that CTA
    (button)to prevent it from another click.
Check your database for multiple records.

Anyways, please check when you do ajax request? after click?
Have you tried to debug your code with breakpoints? or console?
Comment: ok i will replace all the content, so it will better more understanable.
Comment: Hi Aivaras, I have no problem with my database, seems i have problem to my function, which when i force clicked manytimes the append duplicate many times also
Comment: Hey. Have you tried other solution from my list? How does it go? ;)
Comment: Then please add more JS code. I need to understand were you requesting AJAX.


Can't change attribute data-*** with jquery

Question: I don't understand why the request for button does not performed. I must to change the direction for mobile screens, but until it's now work.

$( "button.btn-tooltip" ).attr( "data-placement", "left" );
body {
  padding: 10px;
}

button {
  width: 100px;
  height: 30px;  margin: 10px;
}

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>

<button type="button" class="btn btn-tooltip" data-toggle="tooltip" data-placement="right" title="Tooltip"></button>
Comment: The code as posted works. Follow with `console.log (document.querySelector(".btn").dataset.placement);` to verify. Something else is wrong.
Answer: You're probably looking at the default tooltip, rather than Bootstrap's tooltip. The regular toolbar defaults to the bottom-right, which could be giving you confusion with the data-placement of right:

$("button.btn-tooltip").attr("data-placement", "left");
body {
  text-align: center;
}

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>

<button type="button"
        class="btn btn-tooltip"
        data-toggle="tooltip"
        data-placement="right"
        title="Tooltip">
        Text
</button>

To use Bootstrap tooltips, you need to remember to initialise them with:
$(document).ready(function(){
    $('[data-toggle="tooltip"]').tooltip();
});

Adding this code shows that your data-placement change does indeed work as expected:

$(document).ready(function(){
    $('[data-toggle="tooltip"]').tooltip();
});

$("button.btn-tooltip").attr("data-placement", "left");
body {
  text-align: center;
}

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>

<button type="button"
        class="btn btn-tooltip"
        data-toggle="tooltip"
        data-placement="right"
        title="Tooltip">
        Text
</button>

If your code is not giving you the same result, then your JavaScript may be running before the DOM has fully loaded (meaning that the button wouldn't exist for it to be manipulated).
In this case, ensure that your code is wrapped inside a $(document).ready(function(){}) to force the JavaScript to wait until the button has been created.
Hope this helps! :)
Comment: Thank you so much!
Answer: I think the attribute is added indeed, but because you add the attribute after the bootstrap have initialized, so it does not work.
Do you use the tooltip in bootstrap? you can try to set the attribute before call
$('button.btn-tooltip').tooltip()
Answer: you can just do
$("button.btn-tooltip").data( "placement", "left" );

Answer: Your code as written works properly, as seen here:
http://jsbin.com/xozuseyeyi/edit?html,js,output
My suspicion is that your javascript code is running before your button is available in the DOM.
Have you tried wrapping your code inside a document.ready() handler or similar?
$(document).ready(function() {
    $("button.btn-tooltip").data( "placement", "left" );
});


Memory leak from a docker container with a Flask application

Question: I am having a strange problem, when I start multiple docker containers with Flask applications. The containers with the apps are used for simulation purposes and are not deployed for production, I simply needed a way to allow the docker containers to communicate between each other and GET/POST API calls seemed to be a good solution. However, this is where my problem occurred, when I start the containers and the Flask application starts, the memory usage (which I am observing with htop) starts to increase. Just by starting the Flask server, the container size increases by 200 MB. I can honestly live with that, however, the problem is, that after every API call, the memory usage keeps increasing. Here is a small snippet of one of the functions:
@app.route('/execute/step=<int:step>', methods=['GET'])
def execute(step):
    url = f'http://my_url:5000/some/api/call/step={step}'
    response = requests.get(url)
    data = eval(response.text)

    if data:
        # unimportant calculations

        if demand <= supply:
            for b in people_b:
                buyer_id = b['id']
                post_data = {some_data}
                url = f'http://my_url:5000/set_data/id={buyer_id}'
                requests.post(url, data=post_data)

            for s in people_s[:-1]:

                seller_id = s['id']
                post_data = {some_data
                             }
                url = f'http://my_url:5000/set_data/id={seller_id}'
                requests.post(url, data=post_data)

            # unimportant steps

            seller_id = local_ids[-1]['id']
            post_data = {some_data}
            url = f'http://my_url:5000/set_data/id={seller_id}'
            requests.post(url, data=post_data)

            return 'Success\n'
        else:
            for s in people_s:
                seller_id = s['id']
                post_data = {some_data}
                url = f'http://my_url:5000/set_data/id={seller_id}'
                requests.post(url, data=post_data)

            for b in people_b[:-1]:
                #unimportant steps

                buyer_id = b['id']
                post_data = {some_data}
                url = f'http://my_url:5000/set_data/id={buyer_id}'
                requests.post(url, data=post_data)

            #unimportant steps

            buyer_id = people_b[-1]['id']
            post_data = {some_data}
            url = f'http://my_url:5000/set_data/id={buyer_id}'
            requests.post(url, data=post_data)

            return 'Success\n'
    else:
        return 'No success\n'

Above is one of the methods, I have deleted some unimportant computation steps, but what I wanted to show is, that there are nested API calls as well. I tried calling gc.collect() before every return in the functions, however, this resulted no success.
Is this behavior expected when performing so many API calls or is there a problem with the implementation or docker/Flask usage?
Comment: Looks like `response.text` might be the problem here: https://stackoverflow.com/questions/24656207/memory-leaks-in-requests-library
Comment: Try running with `response.content` (or some dummy content) and see if you get the same memory leaks?
Comment: `eval` is evil. Don't get used to it! Use JSON!
Comment: I am still not fully aware, what would the difference be if I use `response.json()` and `response.content`. Apparently using `response.text` and `eval()` is not optimal, but what about the other two?
Comment: Anyways, I removed `eval` and `response.text` and the memory leaks are gone. If someone posts an answer, I would happily accept it.
Answer: The problem with the memory leak was entirely due to using eval and response.text. After switching to using json output, the memory leaks were gone.


How to fit a Linear Regression model with linearly related predictor variables

Question: I have three predictor variables x,y and z and a outcome variable "grade". The three predictor variable are linearly related (x+y+z=1). When I fit a linear regression model using these variables, I get NA as the coefficient of one of the predictors.
How do I interpret the results shown below? Or is there any other way of handing such data?

lm(grade~x+y+z, df)
  Call:
  lm(formula = grade ~ x + y + z, data = df)
  Coefficients:
  (Intercept)            x            y            z
      0.6635      -0.6283       0.7285           NA
Comment: Welcome to CV. Can you include *why* you want to include `x`, `y` and `z` if they are colinear? What do they represent; what is the research question?
Comment: I did Latent Class Analysis on my data and found three clusters. As such, each data record will have three cluster memberships (probabilities which sum up to 1) instead of each data record falling into one cluster (like in hard clustering).
Using these cluster probabilities, I wanted to predict an outcome variable to see which the association of each cluster with the outcome variable
Comment: What did you perform the clustering on, if not the grades?
Comment: With counts of click stream (log trace) data for each student.
Answer: If x, y and z are predicted class probabilities as you've stated in the comments, then it might be a lot easier to simply include dummy variables for the predicted class. In that case, there is the effect of being predicted to be x, y, or neither (which means you're predicted to be z). The last (or first) class will then simply be the intercept and you can easily compare all three.
Apart from the problem of colinearity, I can't imagine there being a linear relationship between the grade someone scores and the probability of belonging to a class. How would you even interpret this? Should you consider the difference between $0.99$ and $0.95$ to be the same as the difference between $0.54$ and $0.50$? Because that is what a linear relationship implies. Moreover, not only the probabilities are probably skewed and certainly bounded, but so are the grades.
If you insist on using class probability, you should remove one of the three classes' probabilities, as it is already implicitly in the model by including the other two classes' probabilities. Saying that you cannot look at all three at the same time is a misunderstanding.
Answer: You shouldn't be using linearly dependent predictors (x+y+z=1) in your model, this issue is known as Multicollinearity.
What you need to do is to drop all the linear dependent columns and refit your model, e.g. using x & y only lm(grade~x+y, df), assuming that x & y are linearly independent.
The mathematical reason behind is that in Linear Regression, it tries to compute the psuedoinverse $(X^TX)^{-1}$ of your input data $X = \begin{pmatrix}
1 & x_{1} & y_{1} & z_{1}\\
\vdots &  \vdots  & \vdots & \vdots\\
1 & x_{n} & y_{n} & z_{n}
 \end{pmatrix} $ , but since the columns are linearly dependent,the matrix is not full rank and thus cannot be inverted. Once you removed the linear dependent column(s), the matrix will become full rank and can be inverted and solved.
Comment: Thanks for your comment. But if I fit the model with two variables, then is there a way to interpret how the third variable is going to affect the outcome variable?
Comment: Since the third variable can be completely determined by the other 2, it doesn't "add" any explanation power, but you can always pick any 2 independent variables that's helpful for explanation (pick `y & z` instead of `x & y`); you can also do a substitution by `x = 1 - y - z` into your trained model `y = ax + by + c` and get the new model `y = (b-a)y + (-a)z + (a + c)`
Comment: But, each time I can only compare (use) two variables and see its association with the outcome.
Is there any other technique other than regression that I can use to measure the affect on the outcome variable by all the three predictors?
Comment: that matrix has full rank. your answer makes sense only if you include a constant (for intercept) column
Comment: Thanks @carlo for pointint that out, corrected the matrix in the answer
Comment: @aranelladen: the pseudoinverse of $X$ is $X(X^TX)^{-1}$, not $(X^TX)^{-1}$.
Answer: It may not look like it at first glance, but this question is a sort of duplicate of another question the original poster asked. abhinava stated in comments here that he fit a latent class analysis (LCA). In LCA, you are trying to infer each observation's value of an unseen (i.e. latent) un-ordered categorical variable $K$. It's actually a bit more complex: what you actually get is the probability that each observation falls into each latent class. Thus, abhinava is trying to determine $\overline{grade} | K$.
Imagine you had actually observed the true value of $K$. Then this would be trivial. You'd just treat $K$ as a categorical variable in the regression.
However, again, we haven't got the true value of $K$. We inferred it, and we estimated the probability that each person has $K = 1, K = 2, K = 3...$ In my link, you'll see a brief description of latent class regression, which I believe is how you'd handle this situation.
A less technically correct way to handle it, which I neglected to mention in my other answer, is for abhinava to assign each observation to their modal class, i.e. the latent class they are most likely to belong to. This is wrong, because it ignores the uncertainty in the latent class. Also, what if your LCA model can't be very certain about each person's latent class, e.g. a lot of people have $P(K_i) = 0.4, 0.3, 0.3$? However, if the LCA model does separate people very well, e.g. most people look more like $P(K_i) = 0.9, 0.05, 0.05$, then modal class assignment isn't too far wrong. One can calculate Shannon's entropy after fitting an LCA model. I'm not sure if depmixS4, the package the OP used, does so, but many do, or this can be calculated manually. High values of entropy (one guideline I heard suggested 0.8 or higher; entropy in the LCA context is usually normalized to a 0 to 1 scale) mean modal class assignment shouldn't be too bad.


$\log\Gamma(z)$ formula to deduce an estimate

Question: I currently want to show
$$
\log\Gamma(z)=(z-1/2)\log z-z+\frac{1}{2}\log2\pi+\int_0^\infty \frac{[u]-u+1/2}{u+z}du.
$$
where $[u]$ denotes the floor function. Here, $z$ is a complex variable.
Could anyone provide a hint? This comes from Murty's Problems in Analytic Number Theory Exercise 6.3.13, but I do not want to look in the back of the book for the solution.
What I have tried thus far is to take the Hadamard factorization of $1/\Gamma(z)$, take the logarithm, and try to estimate the series that comes out of it. Unfortunately, what I get is
$$
\log\Gamma(z)=-\gamma z-\log z+\sum_{n=1}^\infty \frac{\log(1+\frac{z}{n})}{n}.
$$
Here, the series isn't easy to work with. I tried partial summation but it doesn't provide me with any reasonable approach for estimate.
I have a few more ideas on approaches, but am posting this question in case I come back empty handed.
Thanks!
Comment: This is Stirling formula with explicit  remainder, though one has to be careful of its domain of application (which is the plane minus  the negative real axis pointwise, but a wedge uniformly); usually one proves it by denoting by $f(z)$ the exponential of the right hand side and showing that it is well defined, analytic and satisfies the same functional equation as Gamma plus the required vertical boundness in the strip from $1$ to $2$ which  characterizes Gamma  uniquely  up to a multiplicative constant
Answer: The integral begs for $\int_0^\infty=\sum_{n=1}^\infty\int_{n-1}^n$ and summation by parts (even without the book at hand).
More conceptually though, it looks like a remainder of the Euler–Maclaurin summation formula: $$\sum_{n=0}^N f(n)=\int_0^N f(x)\,dx+\frac{f(0)+f(N)}{2}+\int_0^N f'(x)\left(x-\lfloor x\rfloor-\frac12\right)dx$$ for, say, $f\in C^1[0,N]$, applied to $f(x)=\log(x+z)$, assuming $z\in\mathbb{C}\setminus\mathbb{R}_{\leqslant 0}$ fixed. To make things easy, we let $z\in\mathbb{R}_{>0}$ and rely on analytic continuation elsewhere. Let $$I_N=\int_0^N\frac{\lfloor x\rfloor-x+1/2}{x+z}\,dx;$$ then, computing all the other pieces of the formula, we get $$I_N=\left(N+z+\frac12\right)\log(N+z)-\left(z-\frac12\right)\log z-N-\sum_{n=0}^N\log(z+n).$$
The connection to $\Gamma$ (basically the idea behind Euler's definition) is the formula $$\Gamma(z)=\lim_{N\to\infty}\frac{N^z N!}{z(z+1)\cdots(z+N)}$$ (a proof is obtained by computing $\int_0^1\big[N(1-x^{1/N})\big]^z\,dx$ and taking $N\to\infty$).
Thus $\lim\limits_{N\to\infty}I_N=\log\Gamma(z)-(z-1/2)\log z+\lim\limits_{N\to\infty}L_N$, where $$L_N=\left(N+z+\frac12\right)\log\frac{N+z}{N}+\log\frac{N^N e^{-N}\sqrt{N}}{N!}.$$ The first term tends to $z$ as $N\to\infty$, and the second tends to $-\frac12\log(2\pi)$ by Stirling's formula.
Not sure if this is elementary enough. Compared to the suggestion by @Conrad in his comment, this doesn't use any not-that-hard-to-prove characterizations of $\Gamma$, but I've decided to use the Euler-Maclaurin summation formula, which is nice to have at hand (including a proof).
Comment: This is indeed elementary enough. I never did manage to figure out. The observation with the remainder term of Euler-Maclaurin is very insightful! Thank you.


HP 1920 - VLAN 2 issue, no internet

Question: I have some issue setting up my HP 1920 Managed switch with layer 3, I do not have internet on VLAN 2 or 3
What I would like to is following:
One ISP with two separated networks.
I have following equipment:
1 x Router: Apple Time capsule
1 x Managed switch: HP 1920-8g-poe+ (65w) switch
My setup is now as shown on the picture, but I do not have internet on VLAN 2 or 3:
Network diagram
Router (Apple Timecapsule) - IP: 10.0.1.1, subnet 255.255.255.0)
VLAN 1 Mangement -> 10.0.1.7 (Gets IP from router, which have  DHCP and NAT)
VLAN 2 OFFICE    -> 10.0.2.7 (interface IP, subnet 255.255.255.0)
VLAN 3 PRIVATE   -> 10.0.3.7 (interface IP, subnet 255.255.255.0)
There is created IPv4 routing on VLAN 2 to from 10.0.2.0 to 10.0.1.1 (interface 1, VLAN 1)
I can ping VLAN interface, but not the router.
Can someone tell me what I doing wrong?
Thank you.
Comment: How is the switch configured? Provide the whole configuration in question.
Comment: After you solve the "ping the router" problem, you're going to run into another issue which is un-resolvable. As far as I know, Apple's Peter products will only NAT for their LAN subnet, and it's impossible to configure them otherwise. Since internet-bound traffic will be coming from a subnet the router doesn't know about, it will not perform NAT translation for that traffic. Solution: don't try and use consumer equipment for this. Get a real professional-grade router.
Answer: From your configuration :

My setup is now as shown on the picture, but I do not have internet on
VLAN 2 or 3:
...
Router (Apple Timecapsule) - IP: 10.0.1.1, subnet 255.255.255.0)

It's normal you can ping only from your VLAN1 because the interface of your router is in this vlan and it knows only this subnet.
You have two solutions :
Configure your router to know the three vlans and configure the interface between the router and your switch in trunk mode with the three vlans.
If you can't have your vlans in your router, you will must to create a subnet between your switch and your router and adding a route in your switch to access to internet and a route in your router to access on your VLAN subnets.

HP 1920 - VLAN 2 issue, no internet


For every complex $z$, $e^z \ne 0$

Question: In Real and Complex Analysis, 3rd Edition, Walter Rudin advances the following:

How does $e^z \cdot e^{-z} = 1$ entail $(a)$?
Comment: If $e^z=0$ then you will have $0 \cdot e^{-z}=0$ which is absurd
Answer: Hint: $\forall z\in\mathbb{C}:0\cdot z=0$
Answer: If there was a $z\in \mathbb{C}$ such that $e^z=0$ we would have
$e^z\cdot e^{-z}=0\cdot e^{-z} \Rightarrow\\1=0$
which simply is not true.
EDIT
Another way to look at it is by using the form $e^z=e^{x+iy}=e^x(\cos y+i\sin y)$
with $x,y \in \mathbb{R}$
Thus $0=e^{x+iy}=e^x(\cos y+i\sin y)\Rightarrow \cos y=-i\sin y$
which cannot hold.
Answer: if $e^z$ assumed to be $0$ then it can not be $$e^z\cdot e^{-z}=1$$ (it would be zero)
Answer: Another way to see is a proof by contradiction. Assume there exists a complex number z for which $e^z=0$.Then $|e^z|=0$. Which implies for this z, $e^{\Re{z}}=0$. Which is not true for any real number $\Re{z}$. Hence proved.

For every complex $z$, $e^z \ne 0$