问:
Cython calling MKL crashing on elementwise multiplication via vdMul
I can't figure out why this crashes when called from Python.  It is just a simple Cython code to call Intel MKL's vdMul function https://software.intel.com/en-us/mkl-developer-reference-c-v-mul.  I've tried copying every DLL from MKL into the directory and rewriting different parts but it keeps crashing although compiles fine.  Posting here as I probably made an obvious error to someone more experienced working in C++.  Here's the PYX code:

```<code>import numpy as np
cimport numpy as np
cimport cython
from cython cimport view

cdef extern from "mkl.h" nogil:
    double* vect_mult "vdMul"(int n,
                          double *a,
                          double *b,
                          double *y)

@cython.boundscheck(False)
@cython.wraparound(False)
@cython.cdivision(True)
cpdef mult(double[::1] A, double[::1] B, double[:,::1] output):
    cdef int Ashape0=A.shape[0], Bshape0=B.shape[0]
    cdef int N = Ashape0*Bshape0
    with nogil:
        vect_mult(N, &A[0], &B[0], &output[0,0])

#test script
from cyblas import mult
import numpy as np
a=np.random.randn(1000)
b=np.random.randn(1000)
output = np.zeros((a.shape[0],b.shape[0]))
mult(a,b,output)
</code>```

答:
I'm not sure, what do you want to do. As I understand the meaning of vdMult: its result is a n-dimensional vector with out[i]=a[i]*b[i]. So

output should be a flat array of size 1000.

by passing Ashape0*Bshape0 instead of min(Ashape0,Bshape0) you get a segmentation fault as the program tries to access arrays out of bounds.

You code should look something like this:

```<code>cpdef mult(double[::1] A, double[::1] B, double[::1] output):
    cdef int N = A.shape[0]#assuming all vectors have the same size
    with nogil:
        vect_mult(N, &A[0], &B[0], &output[0,0])
</code>```

Edit: vdMult performs a point-wise multiplication. I assume what you want to do, is to calculate out=a*b^t, that is out[i][j]=a[i]*b[j].

So it is an usual matrix multiplication and you could use cblas_dgemm. In your case the call would be (n - the number of elements in vector a, m - the number of elements in b):

```<code>cblas_dgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans,
                n, m, 1, 1.0, A, 1, B, m, 0.0, C, m);
</code>```

Body:
I can't figure out why this crashes when called from Python.  It is just a simple Cython code to call Intel MKL's vdMul function https://software.intel.com/en-us/mkl-developer-reference-c-v-mul.  I've tried copying every DLL from MKL into the directory and rewriting different parts but it keeps crashing although compiles fine.  Posting here as I probably made an obvious error to someone more experienced working in C++.  Here's the PYX code:

import numpy as np
cimport numpy as np
cimport cython
from cython cimport view

cdef extern from "mkl.h" nogil:
    double* vect_mult "vdMul"(int n,
                          double *a,
                          double *b,
                          double *y)

@cython.boundscheck(False)
@cython.wraparound(False)
@cython.cdivision(True)
cpdef mult(double[::1] A, double[::1] B, double[:,::1] output):
    cdef int Ashape0=A.shape[0], Bshape0=B.shape[0]
    cdef int N = Ashape0*Bshape0
    with nogil:
        vect_mult(N, &A[0], &B[0], &output[0,0])

#test script
from cyblas import mult
import numpy as np
a=np.random.randn(1000)
b=np.random.randn(1000)
output = np.zeros((a.shape[0],b.shape[0]))
mult(a,b,output)

Body:
I'm not sure, what do you want to do. As I understand the meaning of vdMult: its result is a n-dimensional vector with out[i]=a[i]*b[i]. So

output should be a flat array of size 1000.

by passing Ashape0*Bshape0 instead of min(Ashape0,Bshape0) you get a segmentation fault as the program tries to access arrays out of bounds.

You code should look something like this:

cpdef mult(double[::1] A, double[::1] B, double[::1] output):
    cdef int N = A.shape[0]#assuming all vectors have the same size
    with nogil:
        vect_mult(N, &A[0], &B[0], &output[0,0])

Edit: vdMult performs a point-wise multiplication. I assume what you want to do, is to calculate out=a*b^t, that is out[i][j]=a[i]*b[j].

So it is an usual matrix multiplication and you could use cblas_dgemm. In your case the call would be (n - the number of elements in vector a, m - the number of elements in b):

cblas_dgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans,
                n, m, 1, 1.0, A, 1, B, m, 0.0, C, m);


来源: stackexchange

问:
python datetime incorrect sorted
I'm getting some database dates and they can get mixed up.
I use the sorted () method to print these dates on a regular basis

```<code>datelist = ["1 2017", "2 2017", "6 2017",  "7 2017", "8 2017", "3 2017", "4 2017", "5 2017", "9 2017", "10 2017", "11 2017", "12 2017"]

for i in sorted(datelist):
        print(i)
</code>```

But the result is terrible ..!

```<code>1 2017
10 2017
11 2017
12 2017
2 2017
3 2017
4 2017
5 2017
6 2017
7 2017
8 2017
9 2017
</code>```

How can I get these values regularly?
Thanks in advance for help

ContentLicense: CC BY-SA 3.0

Title: python datetime incorrect sorted

Body:
I'm getting some database dates and they can get mixed up.
I use the sorted () method to print these dates on a regular basis

datelist = ["1 2017", "2 2017", "6 2017",  "7 2017", "8 2017", "3 2017", "4 2017", "5 2017", "9 2017", "10 2017", "11 2017", "12 2017"]

for i in sorted(datelist):
        print(i)

But the result is terrible ..!

1 2017
10 2017
11 2017
12 2017
2 2017
3 2017
4 2017
5 2017
6 2017
7 2017
8 2017
9 2017

How can I get these values regularly?
Thanks in advance for help

Body:
Use the key parameter of sorted to parse the string and sort by a datetime:

from datetime import datetime
datelist = ["1 2017", "2 2017", "6 2017",  "7 2017", "8 2017", "3 2017", "4 2017", "5 2017", "9 2017", "10 2017", "11 2017", "12 2017"]
for i in sorted(datelist,key=lambda s: datetime.strptime(s,'%m %Y')):
    print(i)

Output:

1 2017
2 2017
3 2017
4 2017
5 2017
6 2017
7 2017
8 2017
9 2017
10 2017
11 2017
12 2017


问:
How to tell if a user clicked on a confirmation email sent with user.sendEmailVerification() in jsx
I have this code for send a email,
but I do not know how to wait for the answer (if confirm or not)
because no matter if it confirms or not, it registers it

```<code>  handleSubmit = (e) => {
e.preventDefault()
firebaseAuth().createUserWithEmailAndPassword(this.email.value, this.pw.value)
.then(function(user) {
    user.sendEmailVerification()
}).then(function () {
    alert("User signup success");
}).catch(function (error) {
  var errorCode = error.code;
  var errorMessage = error.message;
  if (errorCode === 'auth/wrong-password') {

          alert('Wrong password.');
      }
  else if(errorCode=='auth/email-already-in-use'){
    alert("esa cuenta de correo ya esta en uso");
  }
  else {
          alert(errorMessage);
        }
        console.log(error);
      });
</code>```

}

答:
I don't know much about reactjs or fire base. But what you need to do is before you send the email create a unique id for every user when the submit the sign up form. In the email you genarate you need to add a button(link) to click if user need to get registered to the site. that link should redirect to your site with the id you have saved
ex
https://yoursite.com/signup-action?id=QSE$#@$WDVVDsfdsfew543

now when user click this you can get the id from the url and check if it is in the database and who is the user and can update the table to activate the user. That is how you know that the user has clicked the email.. then ask the user to log in

Body:
I have this code for send a email,
but I do not know how to wait for the answer (if confirm or not)
because no matter if it confirms or not, it registers it

  handleSubmit = (e) => {
e.preventDefault()
firebaseAuth().createUserWithEmailAndPassword(this.email.value, this.pw.value)
.then(function(user) {
    user.sendEmailVerification()
}).then(function () {
    alert("User signup success");
}).catch(function (error) {
  var errorCode = error.code;
  var errorMessage = error.message;
  if (errorCode === 'auth/wrong-password') {

          alert('Wrong password.');
      }
  else if(errorCode=='auth/email-already-in-use'){
    alert("esa cuenta de correo ya esta en uso");
  }
  else {
          alert(errorMessage);
        }
        console.log(error);
      });

}


问:
Use Flash Event System or build own Observer Design Pattern?
In this cookbook someone advocates to build own Observer Design Pattern:
http://cookbooks.adobe.com/post_Using_Observer_Pattern_instead_of_Events-18232.html

Is it really faster as for performance ?

答: Yes dispatching Event are slow, if performance are you goal you can go for your own event system or if you don't want to reinvent the wheel take a look at the as3 signals library from Robert Penner.

ContentLicense: CC BY-SA 2.5


问:
Getting specific fields' values of a text using awk, sed, and grep
I would like to get the values of the name fields of the following text, using sed, awk, grep or similar.

```<code>{
    "cast": [
        {
            "character": "",
            "credit_id": "52532e3119c29579400012b5",
            "gender": null,
            "id": 23629,
            "name": "Brian O'Halloran",
            "order": 0,
            "profile_path": "/eJsLxovTdcm6QK9PDB2pCe5FMqK.jpg"
        },
        {
            "character": "",
            "credit_id": "52532e3119c2957940001315",
            "gender": null,
            "id": 19302,
            "name": "Jason Mewes",
            "order": 1,
            "profile_path": "/so3nT2vgSCZMO2QXDVHF3ubxaFX.jpg"
        },
        {
            "character": "",
            "credit_id": "52532e3119c295794000133d",
            "gender": null,
            "id": 23630,
            "name": "Jeff Anderson",
            "order": 2,
            "profile_path": "/vjt5WhpJAx0jxvmiGc5PAOBzzb7.jpg"
        },
        {
            "character": "Silent Bob",
            "credit_id": "52532e3219c2957940001359",
            "gender": null,
            "id": 19303,
            "name": "Kevin Smith",
            "order": 4,
            "profile_path": "/3XXThSMqHQgQFjM4bMJ25U1EJTj.jpg"
        }
    ],
    "crew": [
        {
            "credit_id": "55425dbe9251410efa000094",
            "department": "Visual Effects",
            "gender": null,
            "id": 1419667,
            "job": "Animation Manager",
            "name": "Richard J. Gasparian",
            "profile_path": null
        },
        {
            "credit_id": "5544521dc3a3680ce60037e8",
            "department": "Art",
            "gender": null,
            "id": 1450356,
            "job": "Background Designer",
            "name": "Tristin Cole",
            "profile_path": null
        },
        {
            "credit_id": "554a142dc3a3683c84001851",
            "department": "Art",
            "gender": null,
            "id": 1447432,
            "job": "Background Designer",
            "name": "Nadia Vurbenova",
            "profile_path": null
        },
        {
            "credit_id": "554bcd2b9251414692002c9b",
            "department": "Production",
            "gender": null,
            "id": 1447493,
            "job": "Location Manager",
            "name": "Simon Rodgers",
            "profile_path": null
        },
        {
            "credit_id": "52532e3219c29579400013cd",
            "department": "Production",
            "gender": null,
            "id": 19303,
            "job": "Executive Producer",
            "name": "Kevin Smith",
            "profile_path": "/3XXThSMqHQgQFjM4bMJ25U1EJTj.jpg"
        },
        {
            "credit_id": "52532e3319c2957940001405",
            "department": "Production",
            "gender": null,
            "id": 59839,
            "job": "Producer",
            "name": "Harvey Weinstein",
            "profile_path": "/k4UCnh7n0r5CEjq30gAl6QCfF9g.jpg"
        },
        {
            "credit_id": "52532e3319c29579400014a7",
            "department": "Production",
            "gender": null,
            "id": 1307,
            "job": "Producer",
            "name": "Bob Weinstein",
            "profile_path": "/oe5Oxp034UOubnvZqqhurp6a1EP.jpg"
        }
    ],
    "id": 2
}
</code>```

答:
Helo buddy, with awk just do it:

```<code>awk '/name/{gsub("[\",]*", "");print $2}' yourFile.txt
</code>```

Best regards!! ;)

Body:
I would like to get the values of the name fields of the following text, using sed, awk, grep or similar.

{
    "cast": [
        {
            "character": "",
            "credit_id": "52532e3119c29579400012b5",
            "gender": null,
            "id": 23629,
            "name": "Brian O'Halloran",
            "order": 0,
            "profile_path": "/eJsLxovTdcm6QK9PDB2pCe5FMqK.jpg"
        },
        {
            "character": "",
            "credit_id": "52532e3119c2957940001315",
            "gender": null,
            "id": 19302,
            "name": "Jason Mewes",
            "order": 1,
            "profile_path": "/so3nT2vgSCZMO2QXDVHF3ubxaFX.jpg"
        },
        {
            "character": "",
            "credit_id": "52532e3119c295794000133d",
            "gender": null,
            "id": 23630,
            "name": "Jeff Anderson",
            "order": 2,
            "profile_path": "/vjt5WhpJAx0jxvmiGc5PAOBzzb7.jpg"
        },
        {
            "character": "Silent Bob",
            "credit_id": "52532e3219c2957940001359",
            "gender": null,
            "id": 19303,
            "name": "Kevin Smith",
            "order": 4,
            "profile_path": "/3XXThSMqHQgQFjM4bMJ25U1EJTj.jpg"
        }
    ],
    "crew": [
        {
            "credit_id": "55425dbe9251410efa000094",
            "department": "Visual Effects",
            "gender": null,
            "id": 1419667,
            "job": "Animation Manager",
            "name": "Richard J. Gasparian",
            "profile_path": null
        },
        {
            "credit_id": "5544521dc3a3680ce60037e8",
            "department": "Art",
            "gender": null,
            "id": 1450356,
            "job": "Background Designer",
            "name": "Tristin Cole",
            "profile_path": null
        },
        {
            "credit_id": "554a142dc3a3683c84001851",
            "department": "Art",
            "gender": null,
            "id": 1447432,
            "job": "Background Designer",
            "name": "Nadia Vurbenova",
            "profile_path": null
        },
        {
            "credit_id": "554bcd2b9251414692002c9b",
            "department": "Production",
            "gender": null,
            "id": 1447493,
            "job": "Location Manager",
            "name": "Simon Rodgers",
            "profile_path": null
        },
        {
            "credit_id": "52532e3219c29579400013cd",
            "department": "Production",
            "gender": null,
            "id": 19303,
            "job": "Executive Producer",
            "name": "Kevin Smith",
            "profile_path": "/3XXThSMqHQgQFjM4bMJ25U1EJTj.jpg"
        },
        {
            "credit_id": "52532e3319c2957940001405",
            "department": "Production",
            "gender": null,
            "id": 59839,
            "job": "Producer",
            "name": "Harvey Weinstein",
            "profile_path": "/k4UCnh7n0r5CEjq30gAl6QCfF9g.jpg"
        },
        {
            "credit_id": "52532e3319c29579400014a7",
            "department": "Production",
            "gender": null,
            "id": 1307,
            "job": "Producer",
            "name": "Bob Weinstein",
            "profile_path": "/oe5Oxp034UOubnvZqqhurp6a1EP.jpg"
        }
    ],
    "id": 2
}

Body:
Helo buddy, with awk just do it:

awk '/name/{gsub("[\",]*", "");print $2}' yourFile.txt

Best regards!! ;)


问:
Anaconda Runtime Error: Python is not installed as a framework?
I've installed Anaconda with the pkg installer:

```<code>Python 2.7.10 |Continuum Analytics, Inc.| (default, May 28 2015, 17:04:42)
[GCC 4.2.1 (Apple Inc. build 5577)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
Anaconda is brought to you by Continuum Analytics.
Please check out: http://continuum.io/thanks and https://binstar.org
</code>```

but when I attempt to use anything from matplotlib, i.e.:

```<code> from matplotlib import pyplot as plt
</code>```

I get

```<code>RuntimeError: Python is not installed as a framework.
The Mac OS X backend will not be able to function correctly if Python is not installed
as a framework. See the Python documentation for more information on installing Python
as a framework on Mac OS X. Please either reinstall Python as a framework,
or try one of the other backends.
</code>```

I'm really not sure what this means, or how to go about fixing it.

答:
Posting since I just had this issue and this was a quick fix:

If you used pip to install:

Create ~/.matplotlib/matplotlibrc

Add "backend: TkAgg" (without the quotations) to the file.

Body:
I've installed Anaconda with the pkg installer:

Python 2.7.10 |Continuum Analytics, Inc.| (default, May 28 2015, 17:04:42)
[GCC 4.2.1 (Apple Inc. build 5577)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
Anaconda is brought to you by Continuum Analytics.
Please check out: http://continuum.io/thanks and https://binstar.org

but when I attempt to use anything from matplotlib, i.e.:

 from matplotlib import pyplot as plt

I get

RuntimeError: Python is not installed as a framework.
The Mac OS X backend will not be able to function correctly if Python is not installed
as a framework. See the Python documentation for more information on installing Python
as a framework on Mac OS X. Please either reinstall Python as a framework,
or try one of the other backends.

I'm really not sure what this means, or how to go about fixing it.

ContentLicense: CC BY-SA 4.0


问:
Logging without loss of time
Greetz fellows!

I'm looking for a way to log actions of a CLI script without losing time. I did some benchmarks and I figured out that by echoing someting after each action, the script will be nearly 2x slower and by appending actions to a log file it'll be 17x times slower.

So, anyone has a solution?

答: Log into a TCP resource/socket. And add a listener in the network on it. So there is no I/O.</p>

Title: Logging without loss of time


问:
C++ much faster than Bash script writing to text file
I wanted to test the performance of writing to a file in a bash script vs a C++ program.

Here is the bash script:

```<code>#!/bin/bash

while true; do
        echo "something" >> bash.txt
done
</code>```

This added about 2-3 KB to the text file per second.

Here is the C++ code:

```<code>#include <iostream>
#include <fstream>

using namespace std;

int main() {
    ofstream myfile;
    myfile.open("cpp.txt");

    while (true) {
        myfile << "Writing this to a file Writing this to a file \n";
    }

    myfile.close();
}
</code>```

This created a ~6 GB text file in less than 10 seconds.

What makes this C++ code so much faster, and/or this bash script so much slower?

答:
Compiled vs. Interpreted Languages

Bash is interpreted while C++ is compiled. Just that makes it a lot faster

Body:
I wanted to test the performance of writing to a file in a bash script vs a C++ program.

Here is the bash script:

#!/bin/bash

while true; do
        echo "something" >> bash.txt
done

This added about 2-3 KB to the text file per second.

Here is the C++ code:

#include <iostream>
#include <fstream>

using namespace std;

int main() {
    ofstream myfile;
    myfile.open("cpp.txt");

    while (true) {
        myfile << "Writing this to a file Writing this to a file \n";
    }

    myfile.close();
}

This created a ~6 GB text file in less than 10 seconds.

What makes this C++ code so much faster, and/or this bash script so much slower?


答:
There are several reasons to it.

First off, interpreted execution environments (like bash, perl alongside with non-JITed lua and python etc.) are generally much slower than even poorly written compiled programs (C, C++, etc.).

Secondly, note how fragmented your bash code is - it just writes a line to a file, then it writes one more, and so on. Your C++ program, on the other side, performs buffered write - even without your direct efforts to it. You might see how slower will it run if you substitute

```<code>myfile << "Writing this to a file Writing this to a file \n";
</code>```

with

```<code>myfile << "Writing this to a file Writing this to a file" << endl;
</code>```

for more information about how streams are implemented in C++, and why \n is different from endl, see any reference documentation on C++.

Thirdly, as comments prove, your bash script performs open/close of the target file for each line. This implies a significant performance overhead in itself - imagine myfile.open and myfile.close moved inside your loop body!

Title: C++ much faster than Bash script writing to text file

Body:
There are several reasons to it.

First off, interpreted execution environments (like bash, perl alongside with non-JITed lua and python etc.) are generally much slower than even poorly written compiled programs (C, C++, etc.).

Secondly, note how fragmented your bash code is - it just writes a line to a file, then it writes one more, and so on. Your C++ program, on the other side, performs buffered write - even without your direct efforts to it. You might see how slower will it run if you substitute

myfile << "Writing this to a file Writing this to a file \n";

with

myfile << "Writing this to a file Writing this to a file" << endl;

for more information about how streams are implemented in C++, and why \n is different from endl, see any reference documentation on C++.

Thirdly, as comments prove, your bash script performs open/close of the target file for each line. This implies a significant performance overhead in itself - imagine myfile.open and myfile.close moved inside your loop body!


问:
How to return the getText() values in array using protractor
I'm trying to return the options present in the list using the below function.

HTML

```<code><select>
  <option>one</option>
  <option>two</option>
  <option>three</option>
<select>
</code>```

Function

```<code>getValues(){
  var ele = element(by.xpath("......../select"));
  return ele.all(by.tagName('option')).getAttribute('value').getText().then(function (text){
  for (var i = 0; i < text.length; i++) {
    text[i] = text[i].trim();
  }
  return text;
 });
</code>```

}

When I print the values in console using console.log(getValues()), the console displays theManagedPromise{.....} function instead of options.

But I'm expecting the options as ["one","two","three"] array. Can anyone help me?

答:
Why create a complex method for it if you can also do it like this

getValues() {
  return element.all(by.css('select option')).getText();
}```
</div>
</div>
</p>

<p>The <code>getText()</code> can also be executed on a ElementFinderArray and it will return a promise that contains <code>['one', 'two', 'three']</code></p>

<p><strong>Update: with trim function</strong></p>

<p>First of all your code will not work because of 2 reasons:</p>

<ol>
<li>protractor uses promises, you first needs to resolve the promises before you can use the value. See also 1 of your previous questions you asked</li>
<li>You are using <code>.getAttribute('value').getText()</code>. This will never work.</li>
</ol>

<p>Below you will find a working example in 3 different styles.</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>// with your code
getValues() {
  var ele = element(by.xpath("......../select"));
  return ele.all(by.tagName('option'))
    .map(function(option) {
      return option.getText()
        .then(function(optionText) {
          return optionText.trim();
        });
    });
}

// with protractor shorthand notation
getValues() {
  return $$('select option').map((option) => {
    return option.getText()
      .then((optionText) => {
        return optionText.trim();
      });
  });
}

// 1 line
getValues() {
  return $$('select option').map((option) => option.getText().then((optionText) => optionText.trim()));
}</code>```

Body:
I'm trying to return the options present in the list using the below function.

HTML

<select>
  <option>one</option>
  <option>two</option>
  <option>three</option>
<select>

Function

getValues(){
  var ele = element(by.xpath("......../select"));
  return ele.all(by.tagName('option')).getAttribute('value').getText().then(function (text){
  for (var i = 0; i < text.length; i++) {
    text[i] = text[i].trim();
  }
  return text;
 });

}

When I print the values in console using console.log(getValues()), the console displays theManagedPromise{.....} function instead of options.

But I'm expecting the options as ["one","two","three"] array. Can anyone help me?

Body:
Why create a complex method for it if you can also do it like this

getValues() {
  return element.all(by.css('select option')).getText();
}

The getText() can also be executed on a ElementFinderArray and it will return a promise that contains ['one', 'two', 'three']

Update: with trim function

First of all your code will not work because of 2 reasons:

protractor uses promises, you first needs to resolve the promises before you can use the value. See also 1 of your previous questions you asked

You are using .getAttribute('value').getText(). This will never work.

Below you will find a working example in 3 different styles.

// with your code
getValues() {
  var ele = element(by.xpath("......../select"));
  return ele.all(by.tagName('option'))
    .map(function(option) {
      return option.getText()
        .then(function(optionText) {
          return optionText.trim();
        });
    });
}

// with protractor shorthand notation
getValues() {
  return $$('select option').map((option) => {
    return option.getText()
      .then((optionText) => {
        return optionText.trim();
      });
  });
}

// 1 line
getValues() {
  return $$('select option').map((option) => option.getText().then((optionText) => optionText.trim()));
}


问:
WordPress the_date skipping at intervals inside a loop
I have made a custom loop in WordPress and for some reason, the date is being skipped on random intervals, even though the other post content is getting pulled in successfully every time.

Any ideas, because it is completely baffling me!

For example, a list of posts and when the date is missing:

Date

Date

No date

Date

Date

No date

Date

No date

No date

No date

Here is the code, including all the loops:

```<code>    <?php query_posts('category_name=News&posts_per_page=10'); ?>
    <?php while (have_posts()) : the_post(); ?>

    <article>
        <div>
            <p>PUBLISHED: <?php the_date(); ?></p>
            <h4><a class="news_title_link" href="<?php the_permalink();?>"><?php the_title();?></a></h4>
            <?php the_excerpt(); ?>
            <br />
            <a href="<?php the_permalink();?>">Read more</a>
        </div>
        <div>
        <?php if ( function_exists( 'get_the_image' ) ) { get_the_image(array('default_size' => 'thumbnail','default_image' => '/wp-content/uploads/2010/06/default-thumb.jpg'));} ?>
        </div>
    </article>

    <?php endwhile; ?>
    <?php endif;?>
</code>```

答:
As of 2017, there is another simpler solution. You can simply use:

```<code>echo get_the_date();
</code>```

instead of the_date();. For me, it was the exact same problem with dates only displaying if they are different from the date before.

Body:
I have made a custom loop in WordPress and for some reason, the date is being skipped on random intervals, even though the other post content is getting pulled in successfully every time.

Any ideas, because it is completely baffling me!

For example, a list of posts and when the date is missing:

Date

Date

No date

Date

Date

No date

Date

No date

No date

No date

Here is the code, including all the loops:

    <?php query_posts('category_name=News&posts_per_page=10'); ?>
    <?php while (have_posts()) : the_post(); ?>

PUBLISHED: <?php the_date(); ?>

<a class="news_title_link" href="<?php the_permalink();?>"><?php the_title();?>

            <?php the_excerpt(); ?>

            <a href="<?php the_permalink();?>">Read more

        <?php if ( function_exists( 'get_the_image' ) ) { get_the_image(array('default_size' => 'thumbnail','default_image' => '/wp-content/uploads/2010/06/default-thumb.jpg'));} ?>

    <?php endwhile; ?>
    <?php endif;?>

Body:
As of 2017, there is another simpler solution. You can simply use:

echo get_the_date();

instead of the_date();. For me, it was the exact same problem with dates only displaying if they are different from the date before.


问:
Caffe didn't see hdf5.h when compiling
I am having trouble when installing Caffe Deep Learning Framework on Python:

When I run make command at caffe directory, it says

hdf5.h:no such directory

The steps I have done:

Update and upgrade my Ubuntu Server

Install Python 2.7

Having all of the dependencies base on http://caffe.berkeleyvision.org/install_apt.html

Run cp cp Makefile.config.example Makefile.config

Uncomment cpu_only = 1 in Makefile.config

I will be grateful if someone can help me.

Error message:

```<code>CXX src/caffe/util/hdf5.cpp
in file include from src/caffe/util/hdf5.cpp:1:0:
./include/caffe/util/hdf5.hpp:6:18: fatal error: hdf5.h: No such file or directory
compilation terminated

Makefile:572 recipe for target '.build_release/src/caffe/util/hdf5.o'
failed Make:*** [.build_release/src/caffe/util/hdf5.o] Error 1
</code>```

答:
This solution worked for me on the Ubuntu16.04LTS

```<code>sudo apt-get install libhdf5-10
sudo apt-get install libhdf5-serial-dev
sudo apt-get install libhdf5-dev
sudo apt-get install libhdf5-cpp-11
find /usr -iname "*hdf5.h*"
/usr/include/hdf5/serial/hdf5.h
export CPATH="/usr/include/hdf5/serial/"
</code>```

Title: Caffe didn't see hdf5.h when compiling

Body:
I am having trouble when installing Caffe Deep Learning Framework on Python:

When I run make command at caffe directory, it says

hdf5.h:no such directory

The steps I have done:

Update and upgrade my Ubuntu Server

Install Python 2.7

Having all of the dependencies base on http://caffe.berkeleyvision.org/install_apt.html

Run cp cp Makefile.config.example Makefile.config

Uncomment cpu_only = 1 in Makefile.config

I will be grateful if someone can help me.

Error message:

CXX src/caffe/util/hdf5.cpp
in file include from src/caffe/util/hdf5.cpp:1:0:
./include/caffe/util/hdf5.hpp:6:18: fatal error: hdf5.h: No such file or directory
compilation terminated

Makefile:572 recipe for target '.build_release/src/caffe/util/hdf5.o'
failed Make:*** [.build_release/src/caffe/util/hdf5.o] Error 1

Body:
This solution worked for me on the Ubuntu16.04LTS

sudo apt-get install libhdf5-10
sudo apt-get install libhdf5-serial-dev
sudo apt-get install libhdf5-dev
sudo apt-get install libhdf5-cpp-11
find /usr -iname "*hdf5.h*"
/usr/include/hdf5/serial/hdf5.h
export CPATH="/usr/include/hdf5/serial/"


问:
How to read from to end-points with redux-auto
I am using redux-auto but in the "init" (point 5) I want to hit two Api end-points. The documentation does not cover this case.

There is an example

```<code>export default function (user, payload, stage, result) {

  switch(stage){
    case 'FULFILLED':
    return ?? result.config + result.userData ??
      break;
    case 'REJECTED':
    console.error("problem loading user from server",result)
      break;
    case 'PENDING':
    default :
      break;
  }
  return user;
}

export function action (payload){
  var endpoints = ['//localhost:3000/api/users/507f191e810c19729de860ea',
         'https://api.mysite.com/users/settings/8B76YUTBI']

  return fetch( ? )
}
</code>```

How can I call two end-point when it only takes 1 promise?

I am working from the example where they load a user from an API
https://github.com/codemeasandwich/redux-auto/tree/master/example

Thanks for any help

答:
You need to handly each fetch within your action function. If you have an array of urls, you can use map to transform each to fetch calls.

```<code>export function action (payload){
  var endpoints = ['//localhost:3000/api/users/507f191e810c19729de860ea',
     'https://api.mysite.com/users/settings/8B76YUTBI']

 return  Promise.all(endpoints.map(url => fetch(url).then(resp => resp.json())))
            .then(([userData,config])=>({userData,config}))

}
</code>```

The above code is

Map over endpoints string to create your Ajax calls

Call json on the result of each fetch

Then  combine all responses using Promise.all

Destructor the array into 2 variables

Return a new Object with 2 properties

result in you reduct function will now have userData, config

Body:
I am using redux-auto but in the "init" (point 5) I want to hit two Api end-points. The documentation does not cover this case.

There is an example

export default function (user, payload, stage, result) {

  switch(stage){
    case 'FULFILLED':
    return ?? result.config + result.userData ??
      break;
    case 'REJECTED':
    console.error("problem loading user from server",result)
      break;
    case 'PENDING':
    default :
      break;
  }
  return user;
}

export function action (payload){
  var endpoints = ['//localhost:3000/api/users/507f191e810c19729de860ea',
         'https://api.mysite.com/users/settings/8B76YUTBI']

  return fetch( ? )
}

How can I call two end-point when it only takes 1 promise?

I am working from the example where they load a user from an API
https://github.com/codemeasandwich/redux-auto/tree/master/example

Thanks for any help

Body:
You need to handly each fetch within your action function. If you have an array of urls, you can use map to transform each to fetch calls.

export function action (payload){
  var endpoints = ['//localhost:3000/api/users/507f191e810c19729de860ea',
     'https://api.mysite.com/users/settings/8B76YUTBI']

 return  Promise.all(endpoints.map(url => fetch(url).then(resp => resp.json())))
            .then(([userData,config])=>({userData,config}))

}

The above code is

Map over endpoints string to create your Ajax calls

Call json on the result of each fetch

Then  combine all responses using Promise.all

Destructor the array into 2 variables

Return a new Object with 2 properties

result in you reduct function will now have userData, config


问:
According to the TLD or the tag file, attribute name is mandatory for tag text
I am new to Struts2. I got stuck with an issue:

```<code>According to the TLD or the tag file, attribute name is mandatory for tag text
</code>```

Hi my JSP file is

```<code><%@ taglib uri="/struts-tags" prefix="html"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Login</title>
</head>
<body>
<h2 style="color:red;"><% if(request.getParameter("msg")!=null) {
    out.println(request.getParameter("msg"));
}%></h2>
    <h1 class="welcome">Login To Your Account</h1>
    <div style="align-items: center;margin-left:200px;font-size:20px;white-space:pre;">
    <html:form action="/loginsuccess">
    UserName <html:text style="height:30px;width:300px;padding:10px;" property="username" /><br><br>
    PassWord  <html:password style="height:30px;width:300px;padding:10px;" property="password"/><br><br>
    <input type ="submit" value="Log in" /><br><br>
    New User ? <a href="signup.jsp">Signup</a>
    </html:form>
    </div>
</body>
</html>
</code>```

so this is giving me an error

```<code>org.apache.jasper.JasperException: /login.jsp (line: 44, column: 10) According to the TLD or the tag file, attribute name is mandatory for tag text
    org.apache.jasper.compiler.DefaultErrorHandler.jspError(DefaultErrorHandler.java:42)
    org.apache.jasper.compiler.ErrorDispatcher.dispatch(ErrorDispatcher.java:443)
    org.apache.jasper.compiler.ErrorDispatcher.jspError(ErrorDispatcher.java:237)
    org.apache.jasper.compiler.Validator$ValidateVisitor.visit(Validator.java:859)
    org.apache.jasper.compiler.Node$CustomTag.accept(Node.java:1538)
    org.apache.jasper.compiler.Node$Nodes.visit(Node.java:2375)
    org.apache.jasper.compiler.Node$Visitor.visitBody(Node.java:2427)
    org.apache.jasper.compiler.Validator$ValidateVisitor.visit(Validator.java:895)
    org.apache.jasper.compiler.Node$CustomTag.accept(Node.java:1538)
    org.apache.jasper.compiler.Node$Nodes.visit(Node.java:2375)
    org.apache.jasper.compiler.Node$Visitor.visitBody(Node.java:2427)
    org.apache.jasper.compiler.Node$Visitor.visit(Node.java:2433)
    org.apache.jasper.compiler.Node$Root.accept(Node.java:474)
    org.apache.jasper.compiler.Node$Nodes.visit(Node.java:2375)
    org.apache.jasper.compiler.Validator.validateExDirectives(Validator.java:1817)
    org.apache.jasper.compiler.Compiler.generateJava(Compiler.java:217)
    org.apache.jasper.compiler.Compiler.compile(Compiler.java:373)
    org.apache.jasper.compiler.Compiler.compile(Compiler.java:353)
    org.apache.jasper.compiler.Compiler.compile(Compiler.java:340)
    org.apache.jasper.JspCompilationContext.compile(JspCompilationContext.java:657)
    org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:357)
    org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:395)
    org.apache.jasper.servlet.JspServlet.service(JspServlet.java:339)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
    org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter.doFilter(StrutsPrepareAndExecuteFilter.java:96)
</code>```

Should i add anything more to the text tag?

答:
The taglib definition is for Struts2, but the JSP code is for Struts1. You can't substitute TLD from one framework to another, so the code won't work.

In Struts2 we usually name the prefix with s: to distinguish between frameworks, but you can use old preifix if you like it, nevertheless the code should be rewritten to use the new tag library.

```<code><%@ taglib uri="/struts-tags" prefix="html"%>
</code>```

If you need help migrating Struts1 application to Struts2 you should read Migration from Struts 1 to Struts 2.

Body:
I am new to Struts2. I got stuck with an issue:

According to the TLD or the tag file, attribute name is mandatory for tag text

Hi my JSP file is

<%@ taglib uri="/struts-tags" prefix="html"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Login</title>

<% if(request.getParameter("msg")!=null) {
    out.println(request.getParameter("msg"));
}%>

Login To Your Account

    UserName

    PassWord

    <input type ="submit" value="Log in" />

    New User ? Signup

so this is giving me an error

org.apache.jasper.JasperException: /login.jsp (line: 44, column: 10) According to the TLD or the tag file, attribute name is mandatory for tag text
    org.apache.jasper.compiler.DefaultErrorHandler.jspError(DefaultErrorHandler.java:42)
    org.apache.jasper.compiler.ErrorDispatcher.dispatch(ErrorDispatcher.java:443)
    org.apache.jasper.compiler.ErrorDispatcher.jspError(ErrorDispatcher.java:237)
    org.apache.jasper.compiler.Validator$ValidateVisitor.visit(Validator.java:859)
    org.apache.jasper.compiler.Node$CustomTag.accept(Node.java:1538)
    org.apache.jasper.compiler.Node$Nodes.visit(Node.java:2375)
    org.apache.jasper.compiler.Node$Visitor.visitBody(Node.java:2427)
    org.apache.jasper.compiler.Validator$ValidateVisitor.visit(Validator.java:895)
    org.apache.jasper.compiler.Node$CustomTag.accept(Node.java:1538)
    org.apache.jasper.compiler.Node$Nodes.visit(Node.java:2375)
    org.apache.jasper.compiler.Node$Visitor.visitBody(Node.java:2427)
    org.apache.jasper.compiler.Node$Visitor.visit(Node.java:2433)
    org.apache.jasper.compiler.Node$Root.accept(Node.java:474)
    org.apache.jasper.compiler.Node$Nodes.visit(Node.java:2375)
    org.apache.jasper.compiler.Validator.validateExDirectives(Validator.java:1817)
    org.apache.jasper.compiler.Compiler.generateJava(Compiler.java:217)
    org.apache.jasper.compiler.Compiler.compile(Compiler.java:373)
    org.apache.jasper.compiler.Compiler.compile(Compiler.java:353)
    org.apache.jasper.compiler.Compiler.compile(Compiler.java:340)
    org.apache.jasper.JspCompilationContext.compile(JspCompilationContext.java:657)
    org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:357)
    org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:395)
    org.apache.jasper.servlet.JspServlet.service(JspServlet.java:339)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
    org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter.doFilter(StrutsPrepareAndExecuteFilter.java:96)

Should i add anything more to the text tag?

Body:
The taglib definition is for Struts2, but the JSP code is for Struts1. You can't substitute TLD from one framework to another, so the code won't work.

In Struts2 we usually name the prefix with s: to distinguish between frameworks, but you can use old preifix if you like it, nevertheless the code should be rewritten to use the new tag library.

<%@ taglib uri="/struts-tags" prefix="html"%>

If you need help migrating Struts1 application to Struts2 you should read Migration from Struts 1 to Struts 2.


问:
How do you get the Ruby on Rails generated id of a form element for reference in JavaScript?
When using the form_for helper and a text_field call, Ruby on Rails will generate a unique id for the <input /> element that it outputs. How can I generate the same id for later inclusion into JavaScript generated later?

```<code><%= form_for @user do |f| %>
  <%= f.text_field :username %>
<% end %>
</code>```

Then later in the page:

```<code><%= javascript_tag do %>
  $('<%= id of the :username field %>').doSomethingReallyCool();
<% end %>
</code>```

答:
Since your Javascript code is placed in a ruby embedded file (.erb) that is being interpreted by the server before being sent to the client browser, you can generated the required JS variable with a ruby snippet like:

```<code>var id='#id_for_'+<%= @user.username %>
var id='#comment_info_'+<%= n %>
</code>```

and then use it simply as $(id).doSomethingReallyCool();.

If you need to control the value of the id generated by the form in first instance, you can do it passing the id in the html hash options:

```<code>f.text_field :username, id:"id_for_#{…}"
</code>```

If you're using a unobtrusive JS approach, you would like to place the JS code into a partial (.js.erb) and have the controller use it if the user client allows JS. E.g.:

```<code>class FooController < ApplicationController

def foo_doo
  … # some logic
  respond_to do |format|
    format.js # this will render javascript in file “foo_doo.js.erb” if allowed
    format.html { … } # html fallback for unobtrusive javascript
  end
end
</code>```

This is the recommended approach nowadays. The problem now is that you need to pass the variables to your JS code. If these variables came from a form, place them in opportune hidden form fields. And then use the render's locals option to have them available by your partial, as in:

```<code>format.js { render 'foo_doo', locals: {n:n} }
</code>```

If the JS code is updating a template that use some variables, use the same approach:

```<code>var id='#comment_info_'+<%= n %>
$(id).replaceWith("<%= j (render partial:…, locals: {…}) %>")
</code>```

Body:
When using the form_for helper and a text_field call, Ruby on Rails will generate a unique id for the <input /> element that it outputs. How can I generate the same id for later inclusion into JavaScript generated later?

<%= form_for @user do |f| %>
  <%= f.text_field :username %>
<% end %>

Then later in the page:

<%= javascript_tag do %>
  $('<%= id of the :username field %>').doSomethingReallyCool();
<% end %>

Body:
Since your Javascript code is placed in a ruby embedded file (.erb) that is being interpreted by the server before being sent to the client browser, you can generated the required JS variable with a ruby snippet like:

var id='#id_for_'+<%= @user.username %>
var id='#comment_info_'+<%= n %>

and then use it simply as $(id).doSomethingReallyCool();.

If you need to control the value of the id generated by the form in first instance, you can do it passing the id in the html hash options:

f.text_field :username, id:"id_for_#{…}"

If you're using a unobtrusive JS approach, you would like to place the JS code into a partial (.js.erb) and have the controller use it if the user client allows JS. E.g.:

class FooController < ApplicationController

def foo_doo
  … # some logic
  respond_to do |format|
    format.js # this will render javascript in file “foo_doo.js.erb” if allowed
    format.html { … } # html fallback for unobtrusive javascript
  end
end

This is the recommended approach nowadays. The problem now is that you need to pass the variables to your JS code. If these variables came from a form, place them in opportune hidden form fields. And then use the render's locals option to have them available by your partial, as in:

format.js { render 'foo_doo', locals: {n:n} }

If the JS code is updating a template that use some variables, use the same approach:

var id='#comment_info_'+<%= n %>
$(id).replaceWith("<%= j (render partial:…, locals: {…}) %>")


问:
Multiple paths in location element of web.config
How can I specify multiple paths in one location element in web.config?

```<code><location path="Images">
    <system.web>
        <authorization>
            <allow users="?" />
        </authorization>
    </system.web>
</location>
</code>```

We would like to add styles and images to location, e.g. <location path="images, styles">.

Is it possible to put multiple paths in location element (and how would I do that)?

答: You must use one location element for each location that you want to control access to. The path can be a directory, which will make the rules apply to everything in that directory.</p>

Body:
How can I specify multiple paths in one location element in web.config?

<location path="Images">
    <system.web>
        <authorization>
            <allow users="?" />
        </authorization>
    </system.web>
</location>

We would like to add styles and images to location, e.g. <location path="images, styles">.

Is it possible to put multiple paths in location element (and how would I do that)?


问:
More components or just html in one page angular 4
I am trying to understand which is the better approach for performance. I have a page where my header, body and footer sections are there. Header and footer sections are just plain htmls. There are 2 approaches for this like in app.component.html i can include 3 components, creating components helps me in modularizing and re-usability.

```<code><app-header></app-header>
<app-body></app-body>
<app-footer></app-footer>
</code>```

Other way is just write whole of the html in app-component.html.

Which is the better approach seeing that header and footer has just htmls. Does making those as components degrade the performance?

答: I think plain HTML is always going to be faster than any framework in terms of rendering ... just because Angular or React are cool doesn't mean you need to add useless stuff like nested components that do nothing (ex thumbnails for 2-3 fields )</p>

Body:
I am trying to understand which is the better approach for performance. I have a page where my header, body and footer sections are there. Header and footer sections are just plain htmls. There are 2 approaches for this like in app.component.html i can include 3 components, creating components helps me in modularizing and re-usability.

<app-header></app-header>
<app-body></app-body>
<app-footer></app-footer>

Other way is just write whole of the html in app-component.html.

Which is the better approach seeing that header and footer has just htmls. Does making those as components degrade the performance?


问:
How to enforce a formal protocol with C++ templates?
When using the compile-time duck typing inherent with the template style, is there any way to enforce the requirement that the template argument implements certain methods with certain signatures?

```<code>struct ProtocolT {
  void g() const;
  void h();
}

// I want the compiler to check that T conforms to ProtocolT
// that is, T must implement g() and h() rather than just g()
template <typename T>
void f(const T& x) {
  x.g();
}
</code>```

Of course, even without this, there is perfect type safety: if the template argument  T does not have a method used in the template function implementation, the compiler will always complain.

But I find it appealing to state clearly that class T must have all the methods specified in some class ProtocolT. It would allow me to constrain the design earlier in the development process by requiring methods from T that I don't yet use in the template function implementation.

Even if I didn't include any unused methods in ProtocolT, I still think a verified protocol conformance would help when I need to write a class usable as T. (Of course, no one stops me from writing ProtocolT for documentation purposes, but then the compiler won't validate that ProtocolT includes at least all the required methods.)

答:
Maybe inserting corresponding static_assert:

```<code>static_assert
(
    ::std::is_same< void, decltype(::std::declval< T >().h()) >::value
,   "T must implement void h(void)"
);
</code>```

Also note that in your example when T follows ProtocolT requirements it still won't work because f accepts a const reference to T, while ProtocolT only says it should have non-const g().

Body:
When using the compile-time duck typing inherent with the template style, is there any way to enforce the requirement that the template argument implements certain methods with certain signatures?

struct ProtocolT {
  void g() const;
  void h();
}

// I want the compiler to check that T conforms to ProtocolT
// that is, T must implement g() and h() rather than just g()
template <typename T>
void f(const T& x) {
  x.g();
}

Of course, even without this, there is perfect type safety: if the template argument  T does not have a method used in the template function implementation, the compiler will always complain.

But I find it appealing to state clearly that class T must have all the methods specified in some class ProtocolT. It would allow me to constrain the design earlier in the development process by requiring methods from T that I don't yet use in the template function implementation.

Even if I didn't include any unused methods in ProtocolT, I still think a verified protocol conformance would help when I need to write a class usable as T. (Of course, no one stops me from writing ProtocolT for documentation purposes, but then the compiler won't validate that ProtocolT includes at least all the required methods.)

Body:
Maybe inserting corresponding static_assert:

static_assert
(
    ::std::is_same< void, decltype(::std::declval< T >().h()) >::value
,   "T must implement void h(void)"
);

Also note that in your example when T follows ProtocolT requirements it still won't work because f accepts a const reference to T, while ProtocolT only says it should have non-const g().


问:
R installed.packages() randomly stopped working on windows 7
installed.packages() command in R lists your installed packages.  Mine was working for almost a year and then this command randomly started throwing an error.  As this is a built-in command, I am not even sure how to "reinstall" it or address this.  Any ideas how to fix the error and get the command working again?

```<code>> installed.packages()
Error in gzfile(file, mode) : cannot open the connection
In addition: Warning message:
In gzfile(file, mode) :
  cannot open compressed file `'C:\Users\Mitch\AppData\Local\Temp\Rtmp6Dawpa/libloc_190_4464fd2b.rds', probable reason 'No such file or directory'`
</code>```

One suggestion on here involved this in combination:

.libPaths()

installed.packages(lib.loc = 'my path')

The results of this produced yet another error as shown here.  Looks like an issue with the installed file still but how to address is the question:

```<code>> installed.packages(lib.loc = 'C:/ProgramFilesCoders/R/R-3.3.2/library')
Error in gzfile(file, mode) : cannot open the connection
In addition: Warning message:
In gzfile(file, mode) :
  cannot open compressed file 'C:\Users\Mitch\AppData\Local\Temp\Rtmp6Dawpa/libloc_190_4464fd2b.rds', probable reason 'No such file or directory'
>
</code>```

答:
I think the issue lies in terms of the where the function is looking for the package information. installed.packages() needs an argument lib.loc.

From official documentation

```<code>lib.loc     character vector describing the location of R library trees to search through
</code>```

Looks like the function for some reason is looking in AppData\Local\Temp which is the download location and not the installed location.

Without looking at your R_Home and .libPaths() is difficult to nail down where the problem is, however running .libPaths() should give you one or more paths as shown in the below example. None of these should be temp locations.

```<code>>.libPaths()
[1] "C:/Users/UserName/Documents/R/win-library/3.4"
[2] "C:/Program Files/R/R-3.4.0/library"
</code>```

If not, you can set the path  within the .libPaths("your path") or pass the path of the library as part of installed.packages(lib.loc = 'your path') and try again.

Body:
installed.packages() command in R lists your installed packages.  Mine was working for almost a year and then this command randomly started throwing an error.  As this is a built-in command, I am not even sure how to "reinstall" it or address this.  Any ideas how to fix the error and get the command working again?

> installed.packages()
Error in gzfile(file, mode) : cannot open the connection
In addition: Warning message:
In gzfile(file, mode) :
  cannot open compressed file `'C:\Users\Mitch\AppData\Local\Temp\Rtmp6Dawpa/libloc_190_4464fd2b.rds', probable reason 'No such file or directory'`

One suggestion on here involved this in combination:

.libPaths()

installed.packages(lib.loc = 'my path')

The results of this produced yet another error as shown here.  Looks like an issue with the installed file still but how to address is the question:

> installed.packages(lib.loc = 'C:/ProgramFilesCoders/R/R-3.3.2/library')
Error in gzfile(file, mode) : cannot open the connection
In addition: Warning message:
In gzfile(file, mode) :
  cannot open compressed file 'C:\Users\Mitch\AppData\Local\Temp\Rtmp6Dawpa/libloc_190_4464fd2b.rds', probable reason 'No such file or directory'
>

Body:
I think the issue lies in terms of the where the function is looking for the package information. installed.packages() needs an argument lib.loc.

From official documentation

lib.loc     character vector describing the location of R library trees to search through

Looks like the function for some reason is looking in AppData\Local\Temp which is the download location and not the installed location.

Without looking at your R_Home and .libPaths() is difficult to nail down where the problem is, however running .libPaths() should give you one or more paths as shown in the below example. None of these should be temp locations.

>.libPaths()
[1] "C:/Users/UserName/Documents/R/win-library/3.4"
[2] "C:/Program Files/R/R-3.4.0/library"

If not, you can set the path  within the .libPaths("your path") or pass the path of the library as part of installed.packages(lib.loc = 'your path') and try again.


问:
NodeJS - Server responds with 404 and then loads the page
Does someone understand what's going on in my nodeJS application.
When I do an asynchronous call using ajax the server first responds with a 404 error then loads the page. The application works fine but I have a lot of boring logs saying "Can't set headers after they are sent."

Here is the route part

```<code>module.exports = function(passport) {
          var router = express.Router();
          ........
          router.get('/dashboard', isLogged, dashcontroller.showdashboard);
          router.get('/dashboard/general', isLogged, dashcontroller.general);
          ........
          return router;
    }
</code>```

here the controller

```<code>exports.showdashboard = function(req, res, next) {
  if (req.user.status == 'active')
    res.render('dashboard', { title: 'title' , user: req.user});
  else
    res.redirect('/user/logout');

  next();
}

exports.general = function(req, res, next) {
  if (req.user.status == 'active')
    res.render('general', { title: 'title' , user: req.user});
  else
    res.redirect('/user/logout');

  next();
}
</code>```

The asynchronous request, this code is reachable by the client from /dashboard and resides in public/javascripts/code.js. The client found it and executes it with no problems.

```<code>$(function() {
    $("li.infos").click(function() {
      $("li.basket").removeClass("active")
      $("li.infos").addClass("active")
        $('.main-container')
           .load('/user/dashboard/general');
    });
});
</code>```

All works fine but i still get those boring logs

```<code>GET /stylesheets/dashboard.css 304 0.555 ms - -
GET /javascripts/dashboard.js 304 0.280 ms - -
GET /javascripts/basket.js 304 0.323 ms - -
abc deserializeUser
Executing (default): SELECT `id`, `username`, `public_key`, `email`, `password`, `last_login`, `basketcount`, `status`, `activation_token`, `createdAt`, `updatedAt` FROM `users` AS `user` WHERE `user`.`id` = 6;

GET /user/dashboard/general 404 35.837 ms - 2290
Error: Can't set headers after they are sent.
    at ServerResponse.OutgoingMessage.setHeader (_http_outgoing.js:356:11)
    at ServerResponse.header (/home/me/Documents/app/node_modules/express/lib/response.js:730:10)
and the trace goes on
</code>```

Does anyone understand what is happening?
thank you in advice

答:
Can't set headers after they are sent." is not a boring log message.

You are calling next() after writing http response, that's why you are facing the issue.
e.g.

```<code>exports.showdashboard = function(req, res, next) {
   if (req.user.status == 'active')
     return res.render('dashboard', { title: 'title' , user: req.user});
   else
     return res.redirect('/user/logout');
}
</code>```

and, same with exports.general.

Body:
Does someone understand what's going on in my nodeJS application.
When I do an asynchronous call using ajax the server first responds with a 404 error then loads the page. The application works fine but I have a lot of boring logs saying "Can't set headers after they are sent."

Here is the route part

module.exports = function(passport) {
          var router = express.Router();
          ........
          router.get('/dashboard', isLogged, dashcontroller.showdashboard);
          router.get('/dashboard/general', isLogged, dashcontroller.general);
          ........
          return router;
    }

here the controller

exports.showdashboard = function(req, res, next) {
  if (req.user.status == 'active')
    res.render('dashboard', { title: 'title' , user: req.user});
  else
    res.redirect('/user/logout');

  next();
}

exports.general = function(req, res, next) {
  if (req.user.status == 'active')
    res.render('general', { title: 'title' , user: req.user});
  else
    res.redirect('/user/logout');

  next();
}

The asynchronous request, this code is reachable by the client from /dashboard and resides in public/javascripts/code.js. The client found it and executes it with no problems.

$(function() {
    $("li.infos").click(function() {
      $("li.basket").removeClass("active")
      $("li.infos").addClass("active")
        $('.main-container')
           .load('/user/dashboard/general');
    });
});

All works fine but i still get those boring logs

GET /stylesheets/dashboard.css 304 0.555 ms - -
GET /javascripts/dashboard.js 304 0.280 ms - -
GET /javascripts/basket.js 304 0.323 ms - -
abc deserializeUser
Executing (default): SELECT `id`, `username`, `public_key`, `email`, `password`, `last_login`, `basketcount`, `status`, `activation_token`, `createdAt`, `updatedAt` FROM `users` AS `user` WHERE `user`.`id` = 6;

GET /user/dashboard/general 404 35.837 ms - 2290
Error: Can't set headers after they are sent.
    at ServerResponse.OutgoingMessage.setHeader (_http_outgoing.js:356:11)
    at ServerResponse.header (/home/me/Documents/app/node_modules/express/lib/response.js:730:10)
and the trace goes on

Does anyone understand what is happening?
thank you in advice

Body:
Can't set headers after they are sent." is not a boring log message.

You are calling next() after writing http response, that's why you are facing the issue.
e.g.

exports.showdashboard = function(req, res, next) {
   if (req.user.status == 'active')
     return res.render('dashboard', { title: 'title' , user: req.user});
   else
     return res.redirect('/user/logout');
}

and, same with exports.general.


问:
How to copy a list from a cell to another
I have this function which copy a sheet to another workbook.

```<code>Public Function copierFeuilleDeA(fromWb As Workbook, fromFeuille As String, toWb As Workbook, toFeuille As String) As Boolean

    copierFeuilleDeA = True

    On Error GoTo errorHandler

    fromWb.Worksheets(fromFeuille).Cells.Copy

    toWb.Worksheets(toFeuille).Range("A1").PasteSpecial Paste:=xlPasteColumnWidths
    toWb.Worksheets(toFeuille).Range("A1").PasteSpecial Paste:=xlPasteValues
    toWb.Worksheets(toFeuille).Range("A1").PasteSpecial Paste:=xlPasteFormats
    toWb.Worksheets(toFeuille).Range("A1").PasteSpecial Paste:=xlPasteFormulas

    Application.CutCopyMode = False
    toWb.Worksheets(toFeuille).Activate
    toWb.Worksheets(toFeuille).Range("A1").Select

    Exit Function

errorHandler:
    copierFeuilleDeA = False
    MsgBox Err.Number & " : " & Err.Description
End Function
</code>```

The function works nice, it copies the values, the formats, the columns widths and the formulas, but doesn't copy the list which  is in the cell F26 (the items of the list are 0, 1, 2,3,4, 5).

So how to make this function copy the list?

Thanks

答:
You need to paste the data validation list as well.</p>

```<code>toWb.Worksheets(toFeuille).Range("A1").PasteSpecial Paste:=xlPasteValidation
</code>```

Body:
I have this function which copy a sheet to another workbook.

Public Function copierFeuilleDeA(fromWb As Workbook, fromFeuille As String, toWb As Workbook, toFeuille As String) As Boolean

    copierFeuilleDeA = True

    On Error GoTo errorHandler

    fromWb.Worksheets(fromFeuille).Cells.Copy

    toWb.Worksheets(toFeuille).Range("A1").PasteSpecial Paste:=xlPasteColumnWidths
    toWb.Worksheets(toFeuille).Range("A1").PasteSpecial Paste:=xlPasteValues
    toWb.Worksheets(toFeuille).Range("A1").PasteSpecial Paste:=xlPasteFormats
    toWb.Worksheets(toFeuille).Range("A1").PasteSpecial Paste:=xlPasteFormulas

    Application.CutCopyMode = False
    toWb.Worksheets(toFeuille).Activate
    toWb.Worksheets(toFeuille).Range("A1").Select

    Exit Function

errorHandler:
    copierFeuilleDeA = False
    MsgBox Err.Number & " : " & Err.Description
End Function

The function works nice, it copies the values, the formats, the columns widths and the formulas, but doesn't copy the list which  is in the cell F26 (the items of the list are 0, 1, 2,3,4, 5).

So how to make this function copy the list?

Thanks

Body:
You need to paste the data validation list as well.

toWb.Worksheets(toFeuille).Range("A1").PasteSpecial Paste:=xlPasteValidation


问:
C++ a class to be used only by another class
I'm building a class (class A) which needs to be able to create a number of instances of another class (class B) in the course of its operation, but class B is only used by a few member functions of class A, and never used outside of the class. How should class B best be defined? Is it practical / reasonable to make it a private member of Class A? Is this the intended purpose of nested classes, or am I parting with the spirit of the construct?

Thanks,
Wyatt

EDIT: On further consideration, I'm not really asking about best practice, as this is for a personal project. I want to include class B as a member of class A from an encapsulation standpoint - it just seems reasonable that a class which is wholly subordinate should in fact be a part of its owning class.

What I'm wondering is whether or not this is a reasonable use-case for nested classes? If not, what is the purpose of nested classes?

答: I would just make class B completely unrelated to class A -- if nothing else, it's going to make it easier to write tests if you can test class A and class B separately. If you don't want to go that route, prevent anyone from instantiating class B except class A by defining class B, making it have a private constructor, and then making class A a friend.


问:
Selenium Web Driver & Java. Element is not clickable at point (x, y). Other element would receive the click
I used explicit waits and I have the warning:

org.openqa.selenium.WebDriverException:
  Element is not clickable at point (36, 72). Other element would receive
  the click: ...
  Command duration or timeout: 393 milliseconds

If I use Thread.sleep(2000) I don't receive any warnings.

```<code>@Test(dataProvider = "menuData")
public void Main(String btnMenu, String TitleResultPage, String Text) throws InterruptedException {
    WebDriverWait wait = new WebDriverWait(driver, 10);
    driver.findElement(By.id("navigationPageButton")).click();

    try {
       wait.until(ExpectedConditions.elementToBeClickable(By.cssSelector(btnMenu)));
    } catch (Exception e) {
        System.out.println("Oh");
    }
    driver.findElement(By.cssSelector(btnMenu)).click();
    Assert.assertEquals(driver.findElement(By.cssSelector(TitleResultPage)).getText(), Text);
}
</code>```

答:
You can try </p>

```<code>WebElement navigationPageButton = (new WebDriverWait(driver, 10))
 .until(ExpectedConditions.presenceOfElementLocated(By.id("navigationPageButton")));
navigationPageButton.click();
</code>```

Body:
I used explicit waits and I have the warning:

org.openqa.selenium.WebDriverException:
  Element is not clickable at point (36, 72). Other element would receive
  the click: ...
  Command duration or timeout: 393 milliseconds

If I use Thread.sleep(2000) I don't receive any warnings.

@Test(dataProvider = "menuData")
public void Main(String btnMenu, String TitleResultPage, String Text) throws InterruptedException {
    WebDriverWait wait = new WebDriverWait(driver, 10);
    driver.findElement(By.id("navigationPageButton")).click();

    try {
       wait.until(ExpectedConditions.elementToBeClickable(By.cssSelector(btnMenu)));
    } catch (Exception e) {
        System.out.println("Oh");
    }
    driver.findElement(By.cssSelector(btnMenu)).click();
    Assert.assertEquals(driver.findElement(By.cssSelector(TitleResultPage)).getText(), Text);
}

Body:
You can try

WebElement navigationPageButton = (new WebDriverWait(driver, 10))
 .until(ExpectedConditions.presenceOfElementLocated(By.id("navigationPageButton")));
navigationPageButton.click();


问:
Query - min(Cost) and show Supplier for that cost
I've been stuck on a MySQL query. The table is:

```<code>CREATE TABLE items_costs (
  UPC varchar(15) NOT NULL,
  SupplierID int(11) NOT NULL,
  Current_as_of_Date datetime DEFAULT NULL,
  Cost1 float DEFAULT NULL,
  Cost2 float DEFAULT NULL,
  Cost3 float DEFAULT NULL,
  MSRP float DEFAULT NULL,
  MAP float DEFAULT NULL,
  Unique_Entry_Id datetime DEFAULT NULL,
  PRIMARY KEY (UPC,SupplierID),
  KEY SupplierID (SupplierID),
  CONSTRAINT items_costs_ibfk_1 FOREIGN KEY (UPC) REFERENCES items (UPC),
  CONSTRAINT items_costs_ibfk_2 FOREIGN KEY (SupplierID) REFERENCES suppliers (SupplierID)
) ENGINE=InnoDB DEFAULT CHARSET=utf8`
</code>```

I'm getting the lowest of Cost1, Cost2, Cost3 for each item:

```<code>MIN(LEAST(IFNULL(ic.Cost3, ic.Cost1), IFNULL(ic.Cost2, ic.Cost1), ic.Cost1)) AS Cost
</code>```

However, now I need to get the SupplierID associated with that particular Cost

I've tried:

```<code>SELECT
    ic.UPC,
    ic.SupplierID,
    ic.Current_as_of_Date,
    ic.Cost1 AS Cost,
    ic.MSRP,
    ic.MAP,
    s.SupplierName,
    s.Map_YN AS Supplier_MAP
FROM
    items_costs AS ic
        JOIN
    suppliers AS s ON s.supplierId = ic.SupplierID
WHERE
    (ic.upc , ic.Cost1) IN (SELECT
            ic_min.UPC,
                MIN(LEAST(IFNULL(ic_min.Cost3, ic_min.Cost1),
                        IFNULL(ic_min.Cost2, ic_min.Cost1),
                        ic_min.Cost1)) AS Cost
        FROM
            items_costs ic_min
        GROUP BY ic_min.UPC))
</code>```

...which gives the lowest Cost by UPC, as recommended in other threads. However, still getting duplicate UPC's, which should be unique.

What could I be doing wrong here?

Thanks a lot!

答:
You could use DISTINCT </p>

```<code>    SELECT DISTINCT
      ic.UPC,
      ic.SupplierID,
      ic.Current_as_of_Date,
      ic.Cost1 AS Cost,
      ic.MSRP,
      ic.MAP,
      s.SupplierName,
      s.Map_YN AS Supplier_MAP
  FROM items_costs AS ic
  JOIN suppliers AS s ON s.supplierId = ic.SupplierID
  WHERE  (ic.upc , ic.Cost1) IN (
      SELECT
              ic_min.UPC,
              MIN(LEAST(IFNULL(ic_min.Cost3, ic_min.Cost1),
                      IFNULL(ic_min.Cost2, ic_min.Cost1),
                        ic_min.Cost1)) AS Cost
          FROM items_costs ic_min
          GROUP BY ic_min.UPC))
</code>```

Body:
I've been stuck on a MySQL query. The table is:

CREATE TABLE items_costs (
  UPC varchar(15) NOT NULL,
  SupplierID int(11) NOT NULL,
  Current_as_of_Date datetime DEFAULT NULL,
  Cost1 float DEFAULT NULL,
  Cost2 float DEFAULT NULL,
  Cost3 float DEFAULT NULL,
  MSRP float DEFAULT NULL,
  MAP float DEFAULT NULL,
  Unique_Entry_Id datetime DEFAULT NULL,
  PRIMARY KEY (UPC,SupplierID),
  KEY SupplierID (SupplierID),
  CONSTRAINT items_costs_ibfk_1 FOREIGN KEY (UPC) REFERENCES items (UPC),
  CONSTRAINT items_costs_ibfk_2 FOREIGN KEY (SupplierID) REFERENCES suppliers (SupplierID)
) ENGINE=InnoDB DEFAULT CHARSET=utf8`

I'm getting the lowest of Cost1, Cost2, Cost3 for each item:

MIN(LEAST(IFNULL(ic.Cost3, ic.Cost1), IFNULL(ic.Cost2, ic.Cost1), ic.Cost1)) AS Cost

However, now I need to get the SupplierID associated with that particular Cost

I've tried:

SELECT
    ic.UPC,
    ic.SupplierID,
    ic.Current_as_of_Date,
    ic.Cost1 AS Cost,
    ic.MSRP,
    ic.MAP,
    s.SupplierName,
    s.Map_YN AS Supplier_MAP
FROM
    items_costs AS ic
        JOIN
    suppliers AS s ON s.supplierId = ic.SupplierID
WHERE
    (ic.upc , ic.Cost1) IN (SELECT
            ic_min.UPC,
                MIN(LEAST(IFNULL(ic_min.Cost3, ic_min.Cost1),
                        IFNULL(ic_min.Cost2, ic_min.Cost1),
                        ic_min.Cost1)) AS Cost
        FROM
            items_costs ic_min
        GROUP BY ic_min.UPC))

...which gives the lowest Cost by UPC, as recommended in other threads. However, still getting duplicate UPC's, which should be unique.

What could I be doing wrong here?

Thanks a lot!

Body:
You could use DISTINCT

    SELECT DISTINCT
      ic.UPC,
      ic.SupplierID,
      ic.Current_as_of_Date,
      ic.Cost1 AS Cost,
      ic.MSRP,
      ic.MAP,
      s.SupplierName,
      s.Map_YN AS Supplier_MAP
  FROM items_costs AS ic
  JOIN suppliers AS s ON s.supplierId = ic.SupplierID
  WHERE  (ic.upc , ic.Cost1) IN (
      SELECT
              ic_min.UPC,
              MIN(LEAST(IFNULL(ic_min.Cost3, ic_min.Cost1),
                      IFNULL(ic_min.Cost2, ic_min.Cost1),
                        ic_min.Cost1)) AS Cost
          FROM items_costs ic_min
          GROUP BY ic_min.UPC))


问:
javascript: get height of pseudo :before element
I need the height of a pseudo :before element. Sounds like a no-brainer, but I cannot get it to work. This is what I have tried:

```<code>$('.test:before').height() // --> null
</code>```

And a jsfiddle
Any suggestions what I do wrong ?

UPDATE: The height of .test depends on the content. What I need to do is, when the height gets bigger than the pseudo element, I need to add a padding to the right of the element. However, because the height of the pseudo element is set by css I don't know it in my program

答:
Super-late reply, but: you can use vanilla JavaScript to get pseudo-element dimensions using the getComputedStyle method:

```<code>var testBox = document.querySelector('.test');

// Or with jQuery: testBox = $('.test').get(0); - We want the JS element, without the jQuery wrapper

var pseudoBeforeHeight = window.getComputedStyle(testBox, ':before').height; // Returns (string) "70px"
</code>```

This will return a string of the pixel value, regardless of the CSS declaration (e.g. 4.375rem = 70px, 10vh = 70px, calc(8vh + 1rem) = 70px, so to get the number (in pixels) you can just do:

var pseudoHeightNum = parseInt(pseudoBeforeHeight);

With regards to compatibility: CanIUse suggests that, as of July 2017 it works pretty much across the in all modern browsers (apparently even with support for IE9 and above): reference.

Body:
I need the height of a pseudo :before element. Sounds like a no-brainer, but I cannot get it to work. This is what I have tried:

$('.test:before').height() // --> null

And a jsfiddle
Any suggestions what I do wrong ?

UPDATE: The height of .test depends on the content. What I need to do is, when the height gets bigger than the pseudo element, I need to add a padding to the right of the element. However, because the height of the pseudo element is set by css I don't know it in my program

Body:
Super-late reply, but: you can use vanilla JavaScript to get pseudo-element dimensions using the getComputedStyle method:

var testBox = document.querySelector('.test');

// Or with jQuery: testBox = $('.test').get(0); - We want the JS element, without the jQuery wrapper

var pseudoBeforeHeight = window.getComputedStyle(testBox, ':before').height; // Returns (string) "70px"

This will return a string of the pixel value, regardless of the CSS declaration (e.g. 4.375rem = 70px, 10vh = 70px, calc(8vh + 1rem) = 70px, so to get the number (in pixels) you can just do:

var pseudoHeightNum = parseInt(pseudoBeforeHeight);

With regards to compatibility: CanIUse suggests that, as of July 2017 it works pretty much across the in all modern browsers (apparently even with support for IE9 and above): reference.


问:
xlwings - can't find xlwings32.dll
I originally had an older version of Anaconda and Python2.7 on my machine, and xlwings worked great.  I recently uninstalled Anaconda / Python (via window's add remove programs...), and installed the newest version of Anaconda with Python 3.6 (which includes xlwings).

I went back to my excel sheets, and suddenly it can't find the xlwings dll.  I've checked:

The DLL is in the same folder as python.exe

My environment variables are correct, and have the python.exe
folder path in PATH.

I can, in Command Line, go to python $, and import xlwings, and
see its path is in the correct spot...

Thanks for any ideas!

答:
I managed to solve the issue by going into the "xlwings" module and replacing any mention of the xlwings dll with the full file location, as in the following image:

Disclaimer: I've only been using the xlwings package for 2 days so I'm not sure if this is the right method.

Title: xlwings - can't find xlwings32.dll


问:
error with PDFBox in servlets
**iam trying to generate a pdf of my page contents from doPost method. but my tomcat server fails to start each time

below is my code

@SuppressWarnings({ "deprecation", "resource" })
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        try{
            String filename="mypdf";
            PDDocument mydoc=new PDDocument();
            PDPage page=new PDPage();

            mydoc.addPage(page);

            PDPageContentStream content=new PDPageContentStream(mydoc, page);

            content.beginText();
            content.setFont(PDType1Font.COURIER_BOLD, 30);
            content.moveTextPositionByAmount(250, 750);
            content.drawString("syllabus");
            content.endText();

            content.close();
            mydoc.save(filename);
            mydoc.close();

            System.out.println("the pdf saved at"+System.getProperty("user.dir"));

        }catch(IOException ie)
        {
            System.out.println("IOexception"+ie);
        }
    }
```

**

答:
This worked for me. just try formatting like this. </p>

```<code>@SuppressWarnings("javadoc")
public class Billing extends javax.servlet.http.HttpServlet implements javax.servlet.Servlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    performTask(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException,
        IOException {
    performTask(request, response);
}
private void performTask(HttpServletRequest request, HttpServletResponse response) throws ServletException,
        IOException {

        //Create pdf
        PDDocument document = new PDDocument();

        //Create Page
        PDPage page = new PDPage();

        //Adding the page
        document.addPage(page);

       //Loading the page
       File file = new File("D:/akash/my_doc.pdf");
       //writing text
       contentStream.beginText();
       contentStream.newLineAtOffset(295, 757);
       contentStream.setFont(PDType1Font.HELVETICA_BOLD, 12);
       contentStream.showText("CHIMERA TRANSPLANT RESEARCH FOUNDATION");
       contentStream.endText();

       //Saving the document
       document.save("D:/akash/my_doc.pdf");

       //Closing the document
        document.close();
}
}
</code>```

Title: error with PDFBox in servlets

Body:
**iam trying to generate a pdf of my page contents from doPost method. but my tomcat server fails to start each time

below is my code

@SuppressWarnings({ "deprecation", "resource" })
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        try{
            String filename="mypdf";
            PDDocument mydoc=new PDDocument();
            PDPage page=new PDPage();

            mydoc.addPage(page);

            PDPageContentStream content=new PDPageContentStream(mydoc, page);

            content.beginText();
            content.setFont(PDType1Font.COURIER_BOLD, 30);
            content.moveTextPositionByAmount(250, 750);
            content.drawString("syllabus");
            content.endText();

            content.close();
            mydoc.save(filename);
            mydoc.close();

            System.out.println("the pdf saved at"+System.getProperty("user.dir"));

        }catch(IOException ie)
        {
            System.out.println("IOexception"+ie);
        }
    }

**

Body:
This worked for me. just try formatting like this.

@SuppressWarnings("javadoc")
public class Billing extends javax.servlet.http.HttpServlet implements javax.servlet.Servlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    performTask(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException,
        IOException {
    performTask(request, response);
}
private void performTask(HttpServletRequest request, HttpServletResponse response) throws ServletException,
        IOException {

        //Create pdf
        PDDocument document = new PDDocument();

        //Create Page
        PDPage page = new PDPage();

        //Adding the page
        document.addPage(page);

       //Loading the page
       File file = new File("D:/akash/my_doc.pdf");
       //writing text
       contentStream.beginText();
       contentStream.newLineAtOffset(295, 757);
       contentStream.setFont(PDType1Font.HELVETICA_BOLD, 12);
       contentStream.showText("CHIMERA TRANSPLANT RESEARCH FOUNDATION");
       contentStream.endText();

       //Saving the document
       document.save("D:/akash/my_doc.pdf");

       //Closing the document
        document.close();
}
}


问:
ScrollView Inside ScrollView
I Know people from Google have asked us not to put Scrollable view inside another Scrollable view but is there any official statement from them directing us not to do so?</p>

答:
[...] is there any official statement from them directing us not to do so?

I think there is though I can't seem to find it in my notes. I know I found such a statement when trying to have a scroll view in a list activity. I think there is actually a logical focus "bug" in the way the Android UI system deals with nested scrollables which probably should be better detected and communicated to the developer. But my advice is...

In the end it is better to consider a single scrollable view for the sake of the user anyway. It's like having scroll bars inside scroll bars on an HTML page; it may be legal but its a terrible user experience.

Title: ScrollView Inside ScrollView


问:
re-rendering issues when using HOC for loader
I am building an app where there is tons of pages and each page needs loader icon to show when the data is coming from server but has not arrived yet but no content is shown if there is no data at all. I could show this without using Higher Order Component(HOC) with no problem but doing so in every component is tedious. I want the loader code be reusable so that i can use this in every component wherever needed. But I am facing the problem.

If there is data, there is no issue. If there is no data at all, then
  the loader keeps loading and loading instead should show no content.

I had to use if (!this.props.size) inside componentDidMount to fetch the data because if i dont do this, the component will be re-rendering continuously and if i do this, the component will not re-render if there is data but if there is no data at all, the component gets re-rendered continuously with loading icon.

Here is the code

```<code>class Logs extends React.PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      show: false,
    };
  }
  componentDidMount() {
    // this.props.requestLogs();
    if (!this.props.logs.size) {
      this.props.requestLogs();
    }
  }

  //componentWillUnmount() {
    //document.body.removeEventListener("", this.props.requestLogs());
  //}

  renderLogs() {
    const { logs } = this.props;
    return logs.size > 0
      ? logs.valueSeq().map(log => {
          return (
            <div className="card" key={log.get("_id")}>
              <li className="row">
                <div className="col-md-6">
                  <a
                    onClick={() =>
                      this.handleDialog(log.get("_id"), log.get("error_stack"))}
                  >
                    {log.get("error_message")}
                  </a>
                </div>
                <div className="col-md-6 text-right">
                  <a
                    className="text-danger"
                    onClick={() => this.handleDelete(log.get("_id"))}
                  >
                    Delete
                  </a>
                </div>
              </li>
            </div>
          );
        })
      : <p>No Content</p>;
  }
  render() {
    const { logs, isRequesting } = this.props;
    return (
      <div className="container">
        <div className="row mg-btm-md">
          <div className="col-xs-6"> <h1>Logs</h1></div>
        </div>
        <ul className="list-group">
          {this.renderLogs()}
          {this.state.show ? this.props.dialog : null}
        </ul>
      </div>
    );
  }
}

export default connect(mapStateToProps, mapDispatchToProps)(
  Loader("isRequesting")(Logs)
);

const Loader = prop => WrappedComponent => {
  return class Loader extends React.PureComponent {
    render() {
      return this.props[prop]
        ? <div className="earth-spinning">
            <img
              src={EarthSpinning}
              alt="spinner"
              style={{ margin: "0 auto" }}
            />
          </div>
        : <WrappedComponent {...this.props} />;
    }
  };
};

export default Loader;
</code>```

complete code is here https://gist.github.com/SanskarSans/b30c085ffacf01c58b66f128096746cc

答:
I did something super simple, and there is surely places to improve.
But it solved the issues you wanted, if you have a flag of "loadedData" you show the data, if not you show a loader.

link to code:
https://codepen.io/tzookb/pen/VWdeyE

code:

```<code>class SomeComponent extends React.Component {
  render() {
    return <div>Im a basic component</div>;
  }
}

function withLoader(WrappedComponent) {
  return class extends React.Component {
    render() {
      if (this.props.loadedData) {
        return <WrappedComponent {...this.props} />;
      } else {
        return <h1>Loading...</h1>;
      }
    }
  };
}

let SomeComponentWithLoader = withLoader(SomeComponent);

ReactDOM.render(<SomeComponentWithLoader loadedData={false} />, document.getElementById("app"));
</code>```

Body:
I am building an app where there is tons of pages and each page needs loader icon to show when the data is coming from server but has not arrived yet but no content is shown if there is no data at all. I could show this without using Higher Order Component(HOC) with no problem but doing so in every component is tedious. I want the loader code be reusable so that i can use this in every component wherever needed. But I am facing the problem.

If there is data, there is no issue. If there is no data at all, then
  the loader keeps loading and loading instead should show no content.

I had to use if (!this.props.size) inside componentDidMount to fetch the data because if i dont do this, the component will be re-rendering continuously and if i do this, the component will not re-render if there is data but if there is no data at all, the component gets re-rendered continuously with loading icon.

Here is the code

class Logs extends React.PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      show: false,
    };
  }
  componentDidMount() {
    // this.props.requestLogs();
    if (!this.props.logs.size) {
      this.props.requestLogs();
    }
  }

  //componentWillUnmount() {
    //document.body.removeEventListener("", this.props.requestLogs());
  //}

  renderLogs() {
    const { logs } = this.props;
    return logs.size > 0
      ? logs.valueSeq().map(log => {
          return (

                      this.handleDialog(log.get("_id"), log.get("error_stack"))}
                  >
                    {log.get("error_message")}

                   this.handleDelete(log.get("_id"))}
                  >
                    Delete

          );
        })
      :
No Content
;
  }
  render() {
    const { logs, isRequesting } = this.props;
    return (

Logs

          {this.renderLogs()}
          {this.state.show ? this.props.dialog : null}

    );
  }
}

export default connect(mapStateToProps, mapDispatchToProps)(
  Loader("isRequesting")(Logs)
);

const Loader = prop => WrappedComponent => {
  return class Loader extends React.PureComponent {
    render() {
      return this.props[prop]
        ?

        : <WrappedComponent {...this.props} />;
    }
  };
};

export default Loader;

complete code is here https://gist.github.com/SanskarSans/b30c085ffacf01c58b66f128096746cc

Body:
I did something super simple, and there is surely places to improve.
But it solved the issues you wanted, if you have a flag of "loadedData" you show the data, if not you show a loader.

link to code:
https://codepen.io/tzookb/pen/VWdeyE

code:

class SomeComponent extends React.Component {
  render() {
    return <div>Im a basic component</div>;
  }
}

function withLoader(WrappedComponent) {
  return class extends React.Component {
    render() {
      if (this.props.loadedData) {
        return <WrappedComponent {...this.props} />;
      } else {
        return <h1>Loading...</h1>;
      }
    }
  };
}

let SomeComponentWithLoader = withLoader(SomeComponent);

ReactDOM.render(<SomeComponentWithLoader loadedData={false} />, document.getElementById("app"));


问:
resize image respecting a min width / height and max width / height in javascript
I have this function that resizes an image (after that I have some other stuff to rotate and crop to a square.
The problem here is I want the user be able to post images that are at least 640x640. What happens with this function is that if a user posts a 1080X1920 image (iphone picture), it will resize it to 562 X 1000 and then (with not shown code) it will be cropped to 562 X 562 ... The server will so refuse the image because it's smaller then 640X640.
Can anyone help me improve this function so that it will return max width and height 1000 X 1000 but also respect a min width and height 640 X 640 ?
By experimenting I found that if I set the Max Width and Height to 1138 the same 1080X1920 px image will be cropped to 640X640 but that is not acceptable solution. Any clue?

```<code>img.onload = function () {
            var width = img.width,
                height = img.height,
                canvas = document.createElement('canvas'),
                ctx = canvas.getContext("2d"),
                start_Y,
                start_X;

            console.log( width, "  ", height);

            var MAX_WIDTH = 1000;
            var MAX_HEIGHT = 1000;

            // set proper canvas dimensions before transform & export
            if ([5, 6, 7, 8].indexOf(srcOrientation) > -1) {
                if (width > height) {
                    if (width > MAX_WIDTH) {
                        height *= MAX_WIDTH / width;
                        width = MAX_WIDTH;
                    }
                } else {
                    if (height > MAX_HEIGHT) {
                        width *= MAX_HEIGHT / height;
                        height = MAX_HEIGHT;
                    }
                }
                canvas.width = height;
                canvas.height = width;

                console.log(canvas.width, " ", canvas.height);

            } else {

                if (height > MAX_HEIGHT) {
                    width *= MAX_HEIGHT / height;
                    height = MAX_HEIGHT;
                }
                canvas.width = width;
                canvas.height = height;

                console.log(canvas.width, " ", canvas.height);
                }
}
</code>```

maybe I found a way, I modified the function like this:

```<code>        img.onload = function () {
            var width = img.width,
                height = img.height,
                canvas = document.createElement('canvas'),
                ctx = canvas.getContext("2d"),
                start_Y,
                start_X;

            var MAX_WIDTH = 1000;
            var MAX_HEIGHT = 1000;

            var MIN_WIDTH = 640;
            var MIN_HEIGHT = 640;

            var ratio;

            // set proper canvas dimensions before transform & export
            if ([5, 6, 7, 8].indexOf(srcOrientation) > -1) {
                if (width > height) {

                    console.log('w > h');

                    if (width > MAX_WIDTH) {
                        height *= MAX_WIDTH / width;

                        if(height < MIN_HEIGHT){

                            ratio = MIN_HEIGHT / height;

                            height = MIN_HEIGHT;

                            width = MAX_WIDTH * ratio;

                        }else{

                            width = MAX_WIDTH;

                        }

                    }
                } else {

                    console.log('h > w');

                    if (height > MAX_HEIGHT) {
                        width *= MAX_HEIGHT / height;

                        if(width < MIN_WIDTH){

                            ratio = MIN_WIDTH / width;

                            width = MIN_WIDTH;

                            height = MIN_HEIGHT * ratio;

                        }else{

                            height = MAX_HEIGHT;
                        }

                    }
                }
                canvas.width = height;
                canvas.height = width;

                console.log(canvas.width, " ", canvas.height);

            } else {

                console.log('other Orientations');

                if (height > MAX_HEIGHT) {
                    width *= MAX_HEIGHT / height;

                    if(width < MIN_WIDTH){

                        ratio = MIN_WIDTH / width;

                        width = MIN_WIDTH;

                        height = MAX_HEIGHT * ratio;

                    }else{

                        height = MAX_HEIGHT;

                    }

                }
                canvas.width = width;
                canvas.height = height;

                console.log(canvas.width, " ", canvas.height);
            }
}
</code>```

答:
You have to calculate a ratio like this when width is bigger than height

```<code>var ratio = 640 / height;
</code>```

Or

```<code>var ratio = 640 / width;
</code>```

Having this ratio you can calculate the other value

```<code>Height = ratio × height;
Width = ratio × width;
</code>```

After this you have a redized image / element.

Body:
I have this function that resizes an image (after that I have some other stuff to rotate and crop to a square.
The problem here is I want the user be able to post images that are at least 640x640. What happens with this function is that if a user posts a 1080X1920 image (iphone picture), it will resize it to 562 X 1000 and then (with not shown code) it will be cropped to 562 X 562 ... The server will so refuse the image because it's smaller then 640X640.
Can anyone help me improve this function so that it will return max width and height 1000 X 1000 but also respect a min width and height 640 X 640 ?
By experimenting I found that if I set the Max Width and Height to 1138 the same 1080X1920 px image will be cropped to 640X640 but that is not acceptable solution. Any clue?

img.onload = function () {
            var width = img.width,
                height = img.height,
                canvas = document.createElement('canvas'),
                ctx = canvas.getContext("2d"),
                start_Y,
                start_X;

            console.log( width, "  ", height);

            var MAX_WIDTH = 1000;
            var MAX_HEIGHT = 1000;

            // set proper canvas dimensions before transform & export
            if ([5, 6, 7, 8].indexOf(srcOrientation) > -1) {
                if (width > height) {
                    if (width > MAX_WIDTH) {
                        height *= MAX_WIDTH / width;
                        width = MAX_WIDTH;
                    }
                } else {
                    if (height > MAX_HEIGHT) {
                        width *= MAX_HEIGHT / height;
                        height = MAX_HEIGHT;
                    }
                }
                canvas.width = height;
                canvas.height = width;

                console.log(canvas.width, " ", canvas.height);

            } else {

                if (height > MAX_HEIGHT) {
                    width *= MAX_HEIGHT / height;
                    height = MAX_HEIGHT;
                }
                canvas.width = width;
                canvas.height = height;

                console.log(canvas.width, " ", canvas.height);
                }
}

maybe I found a way, I modified the function like this:

        img.onload = function () {
            var width = img.width,
                height = img.height,
                canvas = document.createElement('canvas'),
                ctx = canvas.getContext("2d"),
                start_Y,
                start_X;

            var MAX_WIDTH = 1000;
            var MAX_HEIGHT = 1000;

            var MIN_WIDTH = 640;
            var MIN_HEIGHT = 640;

            var ratio;

            // set proper canvas dimensions before transform & export
            if ([5, 6, 7, 8].indexOf(srcOrientation) > -1) {
                if (width > height) {

                    console.log('w > h');

                    if (width > MAX_WIDTH) {
                        height *= MAX_WIDTH / width;

                        if(height < MIN_HEIGHT){

                            ratio = MIN_HEIGHT / height;

                            height = MIN_HEIGHT;

                            width = MAX_WIDTH * ratio;

                        }else{

                            width = MAX_WIDTH;

                        }

                    }
                } else {

                    console.log('h > w');

                    if (height > MAX_HEIGHT) {
                        width *= MAX_HEIGHT / height;

                        if(width < MIN_WIDTH){

                            ratio = MIN_WIDTH / width;

                            width = MIN_WIDTH;

                            height = MIN_HEIGHT * ratio;

                        }else{

                            height = MAX_HEIGHT;
                        }

                    }
                }
                canvas.width = height;
                canvas.height = width;

                console.log(canvas.width, " ", canvas.height);

            } else {

                console.log('other Orientations');

                if (height > MAX_HEIGHT) {
                    width *= MAX_HEIGHT / height;

                    if(width < MIN_WIDTH){

                        ratio = MIN_WIDTH / width;

                        width = MIN_WIDTH;

                        height = MAX_HEIGHT * ratio;

                    }else{

                        height = MAX_HEIGHT;

                    }

                }
                canvas.width = width;
                canvas.height = height;

                console.log(canvas.width, " ", canvas.height);
            }
}

Body:
You have to calculate a ratio like this when width is bigger than height

var ratio = 640 / height;

Or

var ratio = 640 / width;

Having this ratio you can calculate the other value

Height = ratio × height;
Width = ratio × width;

After this you have a redized image / element.