问:
Camera Pose Estimation With OpenCV and Python

I'm trying to use OpenCV with python to track camera pose in a video stream.  I have a sample of code that determines the pose between two images as a test environment.

The overall flow here is this:

Read in the images and convert to gray/resize.

Extract features with cv2 goodfeaturestotrack from both images.

Use cv2 calcOpticalFlowPyrLK to find matching points.

Convert the p1 points (starting image) to (x,y,z) with z for all points set as 0.

Resolve cv2 PnPRansac to get the rotation and translation vectors.

Convert angles from radians to degrees.

```<code>    def function(mtx,dist):

            #feature dictionary
            feature_params = dict( maxCorners = 1000,
                               qualityLevel = 0.3,
                               minDistance = 7,
                               blockSize = 7 )
            lk_params = dict( winSize  = (15,15),
                          maxLevel = 2,
                          criteria = (cv2.TERM_CRITERIA_EPS | cv2.TERM_CRITERIA_COUNT, 10, 0.03))

            #image 1
            image_1=cv2.imread("/Users/user/Desktop/Test_images/Test_image.jpg")
            image_1=cv2.resize(image_1,(640,480))
            gray_1=cv2.cvtColor(image_1,cv2.COLOR_BGR2GRAY)
            p1=cv2.goodFeaturesToTrack(gray, mask = None, **feature_params)

            #image read in
            image_2=cv2.imread("/Users/user/Desktop/Test_images/Test_image.jpg")
            image_2=cv2.resize(image_2,(640,480))
            gray_2 = cv2.cvtColor(image_2,cv2.COLOR_BGR2GRAY)
            p2, st, err = cv2.calcOpticalFlowPyrLK(gray_1, gray_2, p1, None, **lk_params)

            #convert the old points to 3d
            zeros=np.zeros([len(p1),1],dtype=np.float)
            old_3d=np.dstack((p1, zeros))

            #get rotational and translation vector
            blank,rvecs, tvecs, inliers = cv2.solvePnPRansac(old_3d, p2, mtx, dist)

            rad=180/math.pi

            roll=rvecs[0]*rad
            pitch=rvecs[1]*rad
            yaw=rvecs[2]*rad

            print(roll)
            print(pitch)
            print(yaw)
            print(tvecs)

        function(mtx,dist)

   rvec (roll, pitch and yaw)
    [ 0.35305807]
    [ 2.95965708]
    [ 0.10954427]

    tvec (x,y,x ???)
    [[ -668.42397254]
     [ -387.32180857]
     [ 1180.94652875]]
</code>```

Given the fact that I am using exactly the same image to run this sample calculation I was expecting rotation and translation vectors to be very close to zero. However they are quite high, take a look at the sample output below.  Additionally with different images with a known translation the vectors are very wrong.

The question at hand is my method sound?  Have I approached this problem right?  Have I matched the points correctly?  Is this level of noise normal or is there something I can do about it?

答:
You cannot use PnP if you don't know the 3D structure, that is, the 3D coordinates of the points that you have matched.

If you know the camera intrinsics, you can, however, estimate the homography (for a planar scene) or the essential matrix (for a general scene), and then decompose it to obtain the rotation and a translation up to scale. You can then do a bundle adjustment to refine the poses thus found.

If this is a one-shot project, it may be faster to do use a graphics environment like Blender, rather than code your own solution. See a matchmove tutorial here or here

Body:
I'm trying to use OpenCV with python to track camera pose in a video stream.  I have a sample of code that determines the pose between two images as a test environment.

The overall flow here is this:

Read in the images and convert to gray/resize.

Extract features with cv2 goodfeaturestotrack from both images.

Use cv2 calcOpticalFlowPyrLK to find matching points.

Convert the p1 points (starting image) to (x,y,z) with z for all points set as 0.

Resolve cv2 PnPRansac to get the rotation and translation vectors.

Convert angles from radians to degrees.

    def function(mtx,dist):

            #feature dictionary
            feature_params = dict( maxCorners = 1000,
                               qualityLevel = 0.3,
                               minDistance = 7,
                               blockSize = 7 )
            lk_params = dict( winSize  = (15,15),
                          maxLevel = 2,
                          criteria = (cv2.TERM_CRITERIA_EPS | cv2.TERM_CRITERIA_COUNT, 10, 0.03))

            #image 1
            image_1=cv2.imread("/Users/user/Desktop/Test_images/Test_image.jpg")
            image_1=cv2.resize(image_1,(640,480))
            gray_1=cv2.cvtColor(image_1,cv2.COLOR_BGR2GRAY)
            p1=cv2.goodFeaturesToTrack(gray, mask = None, **feature_params)

            #image read in
            image_2=cv2.imread("/Users/user/Desktop/Test_images/Test_image.jpg")
            image_2=cv2.resize(image_2,(640,480))
            gray_2 = cv2.cvtColor(image_2,cv2.COLOR_BGR2GRAY)
            p2, st, err = cv2.calcOpticalFlowPyrLK(gray_1, gray_2, p1, None, **lk_params)

            #convert the old points to 3d
            zeros=np.zeros([len(p1),1],dtype=np.float)
            old_3d=np.dstack((p1, zeros))

            #get rotational and translation vector
            blank,rvecs, tvecs, inliers = cv2.solvePnPRansac(old_3d, p2, mtx, dist)

            rad=180/math.pi

            roll=rvecs[0]*rad
            pitch=rvecs[1]*rad
            yaw=rvecs[2]*rad

            print(roll)
            print(pitch)
            print(yaw)
            print(tvecs)

        function(mtx,dist)

   rvec (roll, pitch and yaw)
    [ 0.35305807]
    [ 2.95965708]
    [ 0.10954427]

    tvec (x,y,x ???)
    [[ -668.42397254]
     [ -387.32180857]
     [ 1180.94652875]]

Given the fact that I am using exactly the same image to run this sample calculation I was expecting rotation and translation vectors to be very close to zero. However they are quite high, take a look at the sample output below.  Additionally with different images with a known translation the vectors are very wrong.

The question at hand is my method sound?  Have I approached this problem right?  Have I matched the points correctly?  Is this level of noise normal or is there something I can do about it?


来源: stackexchange

问:
MySQL date format convert "Fri, 06 Nov 2015 04:06:05 -0500"
I have "Fri, 06 Nov 2015 04:06:05 -0500" date format in MySQL.

I want to convert it to Y-m-d H:i:s format within MySQL query. Can anyone please help?

I tried this DATE_FORMAT("Fri, 06 Nov 2015 04:06:05 -0500", '%Y-%m-%d H:i:s') but didn't work.

答:
You can try this

```<code><?php
     echo  date('Y-m-d H:i:s', strtotime("Fri, 06 Nov 2015 04:06:05 -0500"));
?>
</code>```

Note- In strtotime() funtion you can pass your date value, which you wnats to convert.

Hope this will help!

ContentLicense: CC BY-SA 3.0

Body:
You can try this

<?php
     echo  date('Y-m-d H:i:s', strtotime("Fri, 06 Nov 2015 04:06:05 -0500"));
?>

Note- In strtotime() funtion you can pass your date value, which you wnats to convert.

Hope this will help!


问:
How to eliminate if-else with same condition but different actions inside another if-else?
Suppose I have the code like following:

```<code>int age=(from user input);
int weight=(from user input);

if(age>60){
    if(weight>100){
        function1();
    }else if(weight<40){
        function2();
    }else{
        function3();
    }
}else if(age<20){
    if(weight>100){
        function4();
    }else if(weight<40){
        function5();
    }else{
        function6();
    }
}else{
    if(weight>100){
        function7();
    }else if(weight<40){
        function8();
    }else{
        function9();
    }
}
</code>```

the problem is that the code pattern:

```<code>if(weight>100){
    //do something different
}else if(weight<40){
    //do something different
}else{
    //do something different
}
</code>```

repeats as there are different ranges of age. And I can't enclose the inner if-else into a single function, because the things to do is different even through the condition is the same. Is there any way to modify this code so that the code pattern:

```<code>if(age>60){
    //do something different
}else if(age<20){
    //do something different
}else{
    //do something different
}
</code>```

and

```<code>if(weight>100){
    //do something different
}else if(weight<40){
    //do something different
}else{
    //do something different
}
</code>```

would appear once only?

答:
Without seeing what all your function1-9 do (which would probably be too much code for Stack Overflow anyway), it's hard to give a definitive answer.  If function1, function2, and function3 all do some common thing when age > 60, and function1, function4, and function7 all do some common thing when weight > 100, then you might be able to split those functions apart, then put the common parts back together into new methods.

If you really have 9 different functions that have nothing in common, then there's no really good solution.  You could try setting up a map that maps all 9 combinations to functions:

```<code>Map<String, Runnable> functions = new HashMap<>();
functions.put("senior_heavy") = this::function1;
functions.put("senior_medium") = this::function2;
functions.put("senior_light") = this::function3;
functions.put("middleaged_heavy") = this::function4;
...
functions.put("child_light") = this::function9;
</code>```

[You'd have to think of better names, since a 20-year-old isn't exactly middleaged.]

Then:

```<code>String ageString;
// set this to "senior", "middleaged", or "child"
String weightString;
// set this to "heavy", "medium", or "light"

functions.get(ageString + "_" + weightString).run();
</code>```

Runnable is the interface for methods that take no parameters and don't return a result.  (For functions that take parameters and/or return results, there are other functional interface types that you'd use.  Or you could define your own as in smac89's answer, which would let you give a more descriptive name to the functional interface type.)  this::function1 is a reference to function1 belonging to the current object, this; if function1 is static, however, you'd need to say ThisClass::function1.

This would eliminate the duplicated if pattern, but it's not a pretty solution.  If I were reviewing your code, I wouldn't complain much about your original code, since the alternatives aren't great either.  (A 2-D array of Runnable is another alternative.)

Body:
Suppose I have the code like following:

int age=(from user input);
int weight=(from user input);

if(age>60){
    if(weight>100){
        function1();
    }else if(weight<40){
        function2();
    }else{
        function3();
    }
}else if(age<20){
    if(weight>100){
        function4();
    }else if(weight<40){
        function5();
    }else{
        function6();
    }
}else{
    if(weight>100){
        function7();
    }else if(weight<40){
        function8();
    }else{
        function9();
    }
}

the problem is that the code pattern:

if(weight>100){
    //do something different
}else if(weight<40){
    //do something different
}else{
    //do something different
}

repeats as there are different ranges of age. And I can't enclose the inner if-else into a single function, because the things to do is different even through the condition is the same. Is there any way to modify this code so that the code pattern:

if(age>60){
    //do something different
}else if(age<20){
    //do something different
}else{
    //do something different
}

and

if(weight>100){
    //do something different
}else if(weight<40){
    //do something different
}else{
    //do something different
}

would appear once only?

Body:
Without seeing what all your function1-9 do (which would probably be too much code for Stack Overflow anyway), it's hard to give a definitive answer.  If function1, function2, and function3 all do some common thing when age > 60, and function1, function4, and function7 all do some common thing when weight > 100, then you might be able to split those functions apart, then put the common parts back together into new methods.

If you really have 9 different functions that have nothing in common, then there's no really good solution.  You could try setting up a map that maps all 9 combinations to functions:

Map<String, Runnable> functions = new HashMap<>();
functions.put("senior_heavy") = this::function1;
functions.put("senior_medium") = this::function2;
functions.put("senior_light") = this::function3;
functions.put("middleaged_heavy") = this::function4;
...
functions.put("child_light") = this::function9;

[You'd have to think of better names, since a 20-year-old isn't exactly middleaged.]

Then:

String ageString;
// set this to "senior", "middleaged", or "child"
String weightString;
// set this to "heavy", "medium", or "light"

functions.get(ageString + "_" + weightString).run();

Runnable is the interface for methods that take no parameters and don't return a result.  (For functions that take parameters and/or return results, there are other functional interface types that you'd use.  Or you could define your own as in smac89's answer, which would let you give a more descriptive name to the functional interface type.)  this::function1 is a reference to function1 belonging to the current object, this; if function1 is static, however, you'd need to say ThisClass::function1.

This would eliminate the duplicated if pattern, but it's not a pretty solution.  If I were reviewing your code, I wouldn't complain much about your original code, since the alternatives aren't great either.  (A 2-D array of Runnable is another alternative.)


问:
How can i execute two asynctask on same file?
I want to use two Asynctask on same file.
1 -> doing the compression to output filepath.
2 -> want a updated file size while 1st Asynctask is running.

How can i get this two things?

class VideoCompressor extends AsyncTask{

```<code>    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        progressBar.setVisibility(View.VISIBLE);
        Log.d(TAG,"Start video compression");
    }
    @Override
    protected Boolean doInBackground(String... params) {
        Log.d("doInBackground: ", "0 = " + params[0] + " 1 = " + params[1]);
        return MediaController.getInstance().convertVideo(params[0],params[1]);
    }
    @Override
    protected void onProgressUpdate(Integer... values) {
        super.onProgressUpdate(values);
        progressBar.setIndeterminate(false);
        progressBar.setMax(100);
        progressBar.setProgress(values[0]);
    }
    @Override
    protected void onPostExecute(Boolean compressed) {
        super.onPostExecute(compressed);
        progressBar.setVisibility(View.GONE);
        if(compressed){
            Log.d(TAG,"Compression successfully!");
        }
    }
}
</code>```

答: How about using onProgressUpdate method of AsyncTask, through which you can get the current progress of file compression.

Body:
I want to use two Asynctask on same file.
1 -> doing the compression to output filepath.
2 -> want a updated file size while 1st Asynctask is running.

How can i get this two things?

class VideoCompressor extends AsyncTask{

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        progressBar.setVisibility(View.VISIBLE);
        Log.d(TAG,"Start video compression");
    }
    @Override
    protected Boolean doInBackground(String... params) {
        Log.d("doInBackground: ", "0 = " + params[0] + " 1 = " + params[1]);
        return MediaController.getInstance().convertVideo(params[0],params[1]);
    }
    @Override
    protected void onProgressUpdate(Integer... values) {
        super.onProgressUpdate(values);
        progressBar.setIndeterminate(false);
        progressBar.setMax(100);
        progressBar.setProgress(values[0]);
    }
    @Override
    protected void onPostExecute(Boolean compressed) {
        super.onPostExecute(compressed);
        progressBar.setVisibility(View.GONE);
        if(compressed){
            Log.d(TAG,"Compression successfully!");
        }
    }
}


问:
Using Docker for Image training in Python (New to this)
All of my steps have worked very well up to this point. I am on a windows machine currently. I am in the root directory after using the command:

docker run -it gcr.io/tensorflow/tensorflow:latest-devel

then followed by a cd /tensorflow, I am now in the directory and it is time to train the images so i jused:

/tensorflow# python tensorflow/examples/image_retraining/retrain.py \

--bottleneck_dir=/tf_files/bottlenets \
  --how_many_training_steps 500 \
  --model_dir=/tf_files/retrained_graph.pb \
  --output_labels=/tf_files/retrained_labels.txt \
  --image_dir /tf_files/

And i get this error:
  File "tensorflow/examples/image_retraining/retrain.py", line 77, in
    import numpy as np
ImportError: No module named 'numpy'

I DO already have numpy installed in my python35 folder and it is up to date. Thanks a lot for any help, I am really stuck on this!

答:
Remove python 2.7 from Environment  variables and uninstall it . After That install python 3 and run following code to check if numPy is installed properly (It would be as it is included in python 3 package but just to recheck) :-

```<code>import numpy as np
a = 'hello world'
print a
</code>```

and numPy Should Work . Link The Folder again by

```<code>docker run -it -v (folder path)  gcr.io/tensorflow/tensorflow:latest-devel
</code>```

after that run

```<code>docker run -it gcr.io/tensorflow/tensorflow:latest-devel
</code>```

Body:
Remove python 2.7 from Environment  variables and uninstall it . After That install python 3 and run following code to check if numPy is installed properly (It would be as it is included in python 3 package but just to recheck) :-

import numpy as np
a = 'hello world'
print a

and numPy Should Work . Link The Folder again by

docker run -it -v (folder path)  gcr.io/tensorflow/tensorflow:latest-devel

after that run

docker run -it gcr.io/tensorflow/tensorflow:latest-devel


问:
Integer Value Right Padding in SQL
Step1: I have a table called XYZ which contains following integer columns:

```<code> ID      A          B          C
 1    201507    20150810   20150311
 2    20150812  201509     201510
</code>```

I need to write a SQL query where if any values of A, B, and C is smaller than 8 digits then I need to consider it as 8 digits by adding zeros to the right of the value for step2 (I am not allowed to update the table.). For example:

```<code> ID      A            B          C
 1    20150700    20150810   20150311
 2    20150812    20150900   20151000
</code>```

How to add zeros to the right of the integer values through SQL query?

Step 2: I need to find for each record A<B, B<C or not. Please let me know how to write the query. I am using PostgreSQL. Thank you.

答:
just try this</p>

```<code>select
ID,
A = LEFT(cast(a as varchar(100)+'00000000',8),
b = LEFT(cast(b as varchar(100)+'00000000',8),
C = LEFT(cast(c as varchar(100)+'00000000',8)
from xyz
</code>```

Title: Integer Value Right Padding in SQL

Body:
Step1: I have a table called XYZ which contains following integer columns:

 ID      A          B          C
 1    201507    20150810   20150311
 2    20150812  201509     201510

I need to write a SQL query where if any values of A, B, and C is smaller than 8 digits then I need to consider it as 8 digits by adding zeros to the right of the value for step2 (I am not allowed to update the table.). For example:

 ID      A            B          C
 1    20150700    20150810   20150311
 2    20150812    20150900   20151000

How to add zeros to the right of the integer values through SQL query?

Step 2: I need to find for each record A<B, B<C or not. Please let me know how to write the query. I am using PostgreSQL. Thank you.

Body:
just try this

select
ID,
A = LEFT(cast(a as varchar(100)+'00000000',8),
b = LEFT(cast(b as varchar(100)+'00000000',8),
C = LEFT(cast(c as varchar(100)+'00000000',8)
from xyz


问:
What's the different between HttpClient.post() and new HttpRequest('POST') in angular?
I am learning angular recently, and I find there are two way to make a POST request:

constructor(private httpClient: HttpClient) {
  httpClient.post(url, data, options);
}

constructor(private httpClient: HttpClient) {
  const req = new HttpRequest('POST', url, init);
  httpClient.request(req);
}```

So I want to know what is the different between them. Or they just two way to perform HTTP requests

答:
The post() function is really just a helper function, and is equivalent to request('POST', ...).

Checking the source at https://github.com/angular/angular/blob/master/packages/common/http/src/client.ts, post() calls request('POST'), which creates a HttpRequest object when the string 'POST' is passed in.  It isn't just as simple as that, as it wires up observables depending on options, etc, but that's what it is in essence.

Body:
I am learning angular recently, and I find there are two way to make a POST request:

constructor(private httpClient: HttpClient) {
  httpClient.post(url, data, options);
}

constructor(private httpClient: HttpClient) {
  const req = new HttpRequest('POST', url, init);
  httpClient.request(req);
}

So I want to know what is the different between them. Or they just two way to perform HTTP requests


问:
Default package source for NuGet defaulting to newly added source and not All or nuget.org
I added a NuGet 'Package source' to Visual Studio since we have an internal server at work.

Visual Studio now always defaults to my internal server and cannot find most of our NuGet packages until I switch the package source to All or nuget.org.

This is a minor inconvenience, but for the past few weeks, I have been doing many more clicks every time I need to work with the NuGet package manager.  Can anyone tell me how to default to All instead of having it always default to Internal nuget?

答:
Can anyone tell me how to default to All instead of having it always default to Internal nuget?

To my knowledge, the default package source of NuGet Package Manager depends on the order of package source and the property of activePackageSource in nuget.config.

The order of package source:

When you open NuGet Package Manager setting, Tools->Options->NuGet Packager Manager->Package Source, you will notice that there are up and down arrows for package source:

NuGet Package Manager will give priority for default NuGet package source in the top of the package source list. For example, if I set NuGet package source LocalServer at the top of that list, when I create a new project, the default NuGet source will be changed to LocalServer:

However, this priority of default NuGet source can easily be broken by the property of activePackageSource in nuget.config.

Open the nuget.config file from %appdata%\NuGet\NuGet.config, add the following code:

  <activePackageSource>
    <add key="LocalServer2" value="D:\LocalServerTest" />
  </activePackageSource>
```
<p><strong>Restart Visual Studio</strong>, then create a new project, you will find the default NuGet source change to the <code>LocalServer2</code>:</p>
<p><img src="https://i.stack.imgur.com/2yOSh.gif" alt="enter image description here" /></p>
<p><strong>So</strong>, if you want to default <code>nuget.org</code> instead of having it always default to <code>Internal nuget</code>, you can set the NuGet source <code>nuget.org</code> at top of NuGet source list or set the <code>nuget.org</code> as <code>activePackageSource</code> in the nuget.config:</p>
<pre class="lang-xml prettyprint-override"><code>  <activePackageSource>
    <add key="nuget.org" value="https://api.nuget.org/v3/index.json" protocolVersion="3" />
  </activePackageSource>
</code>```

Update for comment:

Is there no way to default to All? Maybe you can suggest defaulting to All (looks like you work for MS)

if you want to set the default NuGet source to All, you can use the setting below in nuget.config:

  <activePackageSource>
    <add key="All" value="(Aggregate source)" />
  </activePackageSource>
```

ContentLicense: CC BY-SA 4.0

Body:
Can anyone tell me how to default to All instead of having it always default to Internal nuget?

To my knowledge, the default package source of NuGet Package Manager depends on the order of package source and the property of activePackageSource in nuget.config.

The order of package source:

When you open NuGet Package Manager setting, Tools->Options->NuGet Packager Manager->Package Source, you will notice that there are up and down arrows for package source:

NuGet Package Manager will give priority for default NuGet package source in the top of the package source list. For example, if I set NuGet package source LocalServer at the top of that list, when I create a new project, the default NuGet source will be changed to LocalServer:

However, this priority of default NuGet source can easily be broken by the property of activePackageSource in nuget.config.

Open the nuget.config file from %appdata%\NuGet\NuGet.config, add the following code:

  <activePackageSource>
    <add key="LocalServer2" value="D:\LocalServerTest" />
  </activePackageSource>

Restart Visual Studio, then create a new project, you will find the default NuGet source change to the LocalServer2:

So, if you want to default nuget.org instead of having it always default to Internal nuget, you can set the NuGet source nuget.org at top of NuGet source list or set the nuget.org as activePackageSource in the nuget.config:

  <activePackageSource>
    <add key="nuget.org" value="https://api.nuget.org/v3/index.json" protocolVersion="3" />
  </activePackageSource>

Update for comment:

Is there no way to default to All? Maybe you can suggest defaulting to All (looks like you work for MS)

if you want to set the default NuGet source to All, you can use the setting below in nuget.config:

  <activePackageSource>
    <add key="All" value="(Aggregate source)" />
  </activePackageSource>


问:
Java Futures & Fast Dot Product
I'm trying to implement a dot product that leverages concurrency to run faster. I'm going for a divide and conquer approach where I split the vector into smaller and smaller bits then finally sum all the components together. But, instead of returning the values right away, I return Futures that will eventually contain the results.

Here's my attempt so far:

```<code>Future<Double> dotProduct(double[] x, double[] d, int start, int end) {
    if ((end-start) == 1) {
      return executor.submit(() -> {
        return x[start] * d[start];
      });
    } else if ((end-start) == 0) {
      return executor.submit(() -> {
        return 0.0;
      });
    }

    int middle = (start+end)/2;
    Future<Double> leftDotProduct = dotProduct(x, d, start, middle);
    Future<Double> rightDotProduct = dotProduct(x, d, middle, end);

    return executor.submit(() -> {
      double l = leftDotProduct.get();
      double r = rightDotProduct.get();
      return l + r;
    });
  }

  // Usage:
  Future<Double> v = dotProduct(x, d, 0, x.length);
  v.get()
</code>```

It produces correct results but it still runs slower than the equivalent sequential implementation. I've tested on small (4 entries) and large (20,000) entries.

I was thinking the slow down might be due to the recursive calls and setting up new stacks. But I'm not even sure how to redesign the algo if that was the case.

Any thoughts on what could be causing the delay and how to improve it would be really appreciated!

Edit:

For more context, I want to return futures because ultimately I aim to use this method to multiply a matrix by a vector:

```<code>  double[] parMult(double[] x) {
    if (this.getWidth() != x.length)
      throw new ArithmeticException("The matrix and vector are of incompatible sizes");

    // Create an array of futures that will store all the results from dot poduct
    Future<Double>[] f = new Future[this.getHeight()];
    for (int i=0; i<this.getHeight(); i++) {
      f[i] = dotProduct(x, this.data[i]);
    }

    // Get the values of all futures
    double[] b = new double[this.getHeight()];
    try {
      for (int i = 0; i < this.getHeight(); i++) {
        b[i] = f[i].get();
      }
    } catch (Exception e) {
      e.printStackTrace();
    }

    return b;
  }
</code>```

答:
You could try Java Fork/Join framework - it is designed exactly for this kind of computations.

The fork/join framework is an implementation of the ExecutorService interface that helps you take advantage of multiple processors. It is designed for work that can be broken into smaller pieces recursively. The goal is to use all the available processing power to enhance the performance of your application.

For your particular case it could be something like this:

```<code>class Product extends RecursiveTask<Double> {

    private final double[] x;
    private final double[] d;
    private final int start;
    private final int end;

    Product(double[] x, double[] d, int start, int end) {
        this.x = x;
        this.d = d;
        this.start = start;
        this.end = end;
    }

    @Override
    protected Double compute() {
        if ((end-start) == 1) {
            return x[start] * d[start];
        } else if ((end-start) == 0) {
            return 0.0;
        }
        int middle = (start+end)/2;
        Product leftDotProduct = new Product(x, d, start, middle);
        Product rightDotProduct = new Product(x, d, middle, end);
        return leftDotProduct.fork().join() + rightDotProduct.fork().join();
    }
}
</code>```

Then you can create it and fork(), or just call compute()

```<code>Product p = new Product(x, d, 0, 999999);
</code>```

After some tests it seems to be about 3 times faster than your approach, but still much slower than simple recursive solution.

Another option is to use CompletableFuture. Let's say you have a recursive method:

```<code>double dotProduct(double[] x, double[] d, int start, int end) {
    if ((end-start) == 1) {
        return x[start] * d[start];
    } else if ((end-start) == 0) {
        return 0.0;
    }

    int middle = (start+end)/2;
    double leftDotProduct = dotProduct(x, d, start, middle);
    double rightDotProduct = dotProduct(x, d, middle, end);

    return leftDotProduct + rightDotProduct;
}
</code>```

You can create CompletableFuture like this:

```<code>CompletableFuture<Double> f = CompletableFuture.supplyAsync(() -> dotProductSingleThread(x, d, 0, 999999));
</code>```

Then, if you have many futures, you can use

```<code>CompletableFuture.allOf(futures)
</code>```

to wait until al of them are completed.

Title: Java Futures & Fast Dot Product

Body:
I'm trying to implement a dot product that leverages concurrency to run faster. I'm going for a divide and conquer approach where I split the vector into smaller and smaller bits then finally sum all the components together. But, instead of returning the values right away, I return Futures that will eventually contain the results.

Here's my attempt so far:

Future<Double> dotProduct(double[] x, double[] d, int start, int end) {
    if ((end-start) == 1) {
      return executor.submit(() -> {
        return x[start] * d[start];
      });
    } else if ((end-start) == 0) {
      return executor.submit(() -> {
        return 0.0;
      });
    }

    int middle = (start+end)/2;
    Future<Double> leftDotProduct = dotProduct(x, d, start, middle);
    Future<Double> rightDotProduct = dotProduct(x, d, middle, end);

    return executor.submit(() -> {
      double l = leftDotProduct.get();
      double r = rightDotProduct.get();
      return l + r;
    });
  }

  // Usage:
  Future<Double> v = dotProduct(x, d, 0, x.length);
  v.get()

It produces correct results but it still runs slower than the equivalent sequential implementation. I've tested on small (4 entries) and large (20,000) entries.

I was thinking the slow down might be due to the recursive calls and setting up new stacks. But I'm not even sure how to redesign the algo if that was the case.

Any thoughts on what could be causing the delay and how to improve it would be really appreciated!

Edit:

For more context, I want to return futures because ultimately I aim to use this method to multiply a matrix by a vector:

  double[] parMult(double[] x) {
    if (this.getWidth() != x.length)
      throw new ArithmeticException("The matrix and vector are of incompatible sizes");

    // Create an array of futures that will store all the results from dot poduct
    Future<Double>[] f = new Future[this.getHeight()];
    for (int i=0; i<this.getHeight(); i++) {
      f[i] = dotProduct(x, this.data[i]);
    }

    // Get the values of all futures
    double[] b = new double[this.getHeight()];
    try {
      for (int i = 0; i < this.getHeight(); i++) {
        b[i] = f[i].get();
      }
    } catch (Exception e) {
      e.printStackTrace();
    }

    return b;
  }

Body:
You could try Java Fork/Join framework - it is designed exactly for this kind of computations.

The fork/join framework is an implementation of the ExecutorService interface that helps you take advantage of multiple processors. It is designed for work that can be broken into smaller pieces recursively. The goal is to use all the available processing power to enhance the performance of your application.

For your particular case it could be something like this:

class Product extends RecursiveTask<Double> {

    private final double[] x;
    private final double[] d;
    private final int start;
    private final int end;

    Product(double[] x, double[] d, int start, int end) {
        this.x = x;
        this.d = d;
        this.start = start;
        this.end = end;
    }

    @Override
    protected Double compute() {
        if ((end-start) == 1) {
            return x[start] * d[start];
        } else if ((end-start) == 0) {
            return 0.0;
        }
        int middle = (start+end)/2;
        Product leftDotProduct = new Product(x, d, start, middle);
        Product rightDotProduct = new Product(x, d, middle, end);
        return leftDotProduct.fork().join() + rightDotProduct.fork().join();
    }
}

Then you can create it and fork(), or just call compute()

Product p = new Product(x, d, 0, 999999);

After some tests it seems to be about 3 times faster than your approach, but still much slower than simple recursive solution.

Another option is to use CompletableFuture. Let's say you have a recursive method:

double dotProduct(double[] x, double[] d, int start, int end) {
    if ((end-start) == 1) {
        return x[start] * d[start];
    } else if ((end-start) == 0) {
        return 0.0;
    }

    int middle = (start+end)/2;
    double leftDotProduct = dotProduct(x, d, start, middle);
    double rightDotProduct = dotProduct(x, d, middle, end);

    return leftDotProduct + rightDotProduct;
}

You can create CompletableFuture like this:

CompletableFuture<Double> f = CompletableFuture.supplyAsync(() -> dotProductSingleThread(x, d, 0, 999999));

Then, if you have many futures, you can use

CompletableFuture.allOf(futures)

to wait until al of them are completed.


问:
Is there any way to update zone in specific views using dnspython?
Just like the title. I was struggling to work with that, but I couldn't find any way to make that work.
Is there anyone know how to do that. Please help, thanks!</p>

答: Finally, this problem has been solved by changing the match-clients dynamically through ssh and then rndc reload. This make the remote server only access to the specific view in which you want to update the zone using dnspython.


问:
MySQL/PHPMyAdmin - Importing 15,000 rows with 512MB of RAM
I'm trying to import 15,000 rows of data into my MySQL database. I know exactly how I would do this normally, but I have a constraint. 512MB of RAM... What's the most efficient way of doing this? Is there any way for MySQL to automatically import at a slower rate that way it doesn't crash due to not enough memory? Also, note that I'm using PHPMyAdmin. Thanks!</p>

答:
My guess is you are using a VPS on something like Digital Ocean? If so then you can create a swap file:
https://www.digitalocean.com/community/tutorials/how-to-add-swap-space-on-ubuntu-16-04

or look around for how to create a swap file for your os / vps.

Hope that helps. Cheers


问:
Where is the main() method In a JSP/Servlet application?
The reason I'm asking this is that I want to write code that initializes the application once it starts and cleans up later on.

I dont want to use a servlet init() method since it is per servlet.

答:
There is no main() method in Servlet.

If

The reason I'm asking this is that I want to write code that initializes the application once it starts and cleans up later on.

You can use ServletContextListener implemented

```<code>public class MyServletContext implements ServletContextListener{
    ServletContext context;
    public void contextInitialized(ServletContextEvent contextEvent) {
        System.out.println("Context Created");

    }
    public void contextDestroyed(ServletContextEvent contextEvent) {

        System.out.println("Context Destroyed");
    }
}
</code>```

web.xml

```<code><listener>
    <listener-class>
        com.yourpackage.MyServletContext
    </listener-class>
  </listener>
</code>```

ContentLicense: CC BY-SA 2.5

Body:
There is no main() method in Servlet.

If

The reason I'm asking this is that I want to write code that initializes the application once it starts and cleans up later on.

You can use ServletContextListener implemented

public class MyServletContext implements ServletContextListener{
    ServletContext context;
    public void contextInitialized(ServletContextEvent contextEvent) {
        System.out.println("Context Created");

    }
    public void contextDestroyed(ServletContextEvent contextEvent) {

        System.out.println("Context Destroyed");
    }
}

web.xml

<listener>
    <listener-class>
        com.yourpackage.MyServletContext
    </listener-class>
  </listener>


问:
Extract columns in nested Spark DataFrame as scala Arrays
I have a DataFrame myDf which contains an array of pairs of points (i.e. x and y coordinates), it has the following schema:

```<code>myDf.printSchema

root
 |-- pts: array (nullable = true)
 |    |-- element: struct (containsNull = true)
 |    |    |-- x: float (nullable = true)
 |    |    |-- y: float (nullable = true)
</code>```

I want to get x and y as individual plain Scala Array's. I think I need to apply the explode-function, but I cannot figure out how. I tried to apply this solution but I cant get it to work.

I'm using Spark 1.6.1 with Scala 2.10

EDIT: I realize that I had a misunderstanding how Spark works, getting the actual arrays is only possible if the data is collected (or using UDFs)

答:
There are two ways to get the points as plan scala Arrays:

collecting to the driver:

```<code>val localRows = myDf.take(10)
val xs: Array[Float] = localRows.map(_.getAs[Float]("x"))
val ys: Array[Float] = localRows.map(_.getAs[Float]("y"))
</code>```

or inside an UDF:

```<code>val processArr = udf((pts:WrappedArray[Row]) => {

  val xs: Array[Float] = pts.map(_.getAs[Float]("x")).array
  val ys: Array[Float] = pts.map(_.getAs[Float]("y")).array
  //...do something with it
})
</code>```

}

Body:
I have a DataFrame myDf which contains an array of pairs of points (i.e. x and y coordinates), it has the following schema:

myDf.printSchema

root
 |-- pts: array (nullable = true)
 |    |-- element: struct (containsNull = true)
 |    |    |-- x: float (nullable = true)
 |    |    |-- y: float (nullable = true)

I want to get x and y as individual plain Scala Array's. I think I need to apply the explode-function, but I cannot figure out how. I tried to apply this solution but I cant get it to work.

I'm using Spark 1.6.1 with Scala 2.10

EDIT: I realize that I had a misunderstanding how Spark works, getting the actual arrays is only possible if the data is collected (or using UDFs)

Body:
There are two ways to get the points as plan scala Arrays:

collecting to the driver:

val localRows = myDf.take(10)
val xs: Array[Float] = localRows.map(_.getAs[Float]("x"))
val ys: Array[Float] = localRows.map(_.getAs[Float]("y"))

or inside an UDF:

val processArr = udf((pts:WrappedArray[Row]) => {

  val xs: Array[Float] = pts.map(_.getAs[Float]("x")).array
  val ys: Array[Float] = pts.map(_.getAs[Float]("y")).array
  //...do something with it
})

}


问:
Keep Secret Keys Out
One of the causes of the local_settings.py anti-pattern is that putting SECRET_KEY, AWS
keys, etc.. values into settings files has problem:

Secrets often should be just that: secret! Keeping them in version control means
that everyone with repository access has access to them.

My question is how to keep all keys as secret?

答:
I wrote a getcreds() function which gets the secret key from a file. I keep the file in a place accessible to www-data so wherever I need credentials in settings.py I just make the call to getcreds() passing in the filename as an argument. It returns a list of all lines in the file and bingo I have the hidden secrets. Here is the code ...</p>

```<code>from __future__ import unicode_literals, absolute_import
import os

def getcreds(fname, project, credsroot='/var/www/creds', credsdir=None):
    """ return a list of userid and password and perhaps other data """
    if credsdir is None:
        credsdir = os.path.join(credsroot, project)
    creds = list()
    fname = os.path.join(credsdir, fname).replace("\\", "/")
    with open(fname, 'r') as f:
        for line in f:
            # remove leading/trailing whitespace and append to list
            creds.append(line.strip())
    assert creds, "The list of credentials is empty"
    return creds
</code>```

Title: Keep Secret Keys Out

Body:
I wrote a getcreds() function which gets the secret key from a file. I keep the file in a place accessible to www-data so wherever I need credentials in settings.py I just make the call to getcreds() passing in the filename as an argument. It returns a list of all lines in the file and bingo I have the hidden secrets. Here is the code ...

from __future__ import unicode_literals, absolute_import
import os

def getcreds(fname, project, credsroot='/var/www/creds', credsdir=None):
    """ return a list of userid and password and perhaps other data """
    if credsdir is None:
        credsdir = os.path.join(credsroot, project)
    creds = list()
    fname = os.path.join(credsdir, fname).replace("\\", "/")
    with open(fname, 'r') as f:
        for line in f:
            # remove leading/trailing whitespace and append to list
            creds.append(line.strip())
    assert creds, "The list of credentials is empty"
    return creds


问:
Can I watch Multiple directories for changes using ReadDirectoryChangesW() in c++?
I am trying to monitor different directories for changes using ReadDirectoryChangesW and I succeed in monitoring a single directory with it. But when it comes to monitoring multiple directories, I am having problems that the first directory is assigned to the handle and it looks for changes only in that directory and then only goes to watch the next directory if the first directory condition is satisfied. But I want to watch multiple directories simultaneously. Can I help me with this problem?

I am attaching the code below for the reference.

```<code>#include <iostream>
#include <windows.h>
#include <stdio.h>
#include <vector>
#include <fstream>
#include <mutex>
#include "sys/stat.h"
#include <dirent.h>

using namespace std;

mutex m1;

int main()
{
    HANDLE hDir[20];
    vector <string> directory_list;
    string f_path;
    string temp1;
    ifstream pfile;

    pfile.open("C:\\Users\\sathish-pt1608\\Desktop\\path_file.txt");

    if (!pfile.is_open())
        cout << "Unable to open the Requested File...";

    while(pfile.good())
    {
        getline(pfile,f_path);
        struct stat path_stat;
        stat(f_path.c_str(),&path_stat);

        if (S_ISREG(path_stat.st_mode))
        {
            int a = f_path.find_last_of('\\');
            directory_list.push_back(f_path.substr(0, a - 1));
        }
        else if(S_ISDIR(path_stat.st_mode))
        {
            DIR *dir;
            struct dirent *ent;

            dir = opendir(f_path.c_str());

            if (dir != NULL)
            {
                directory_list.push_back(f_path);
                while ( (ent = readdir(dir)) != NULL)
                {
                    temp1 = ent->d_name;
                }
                closedir(dir);
            }
            else
            {
                perror("Please Check the Directory Path...");
                EXIT_FAILURE;
            }
        }
    }

    for (int i = 0; i < directory_list.size();)
    {
        LPCTSTR DirName = directory_list[i].c_str();

        hDir[i] = CreateFile(DirName, FILE_LIST_DIRECTORY, FILE_SHARE_READ | FILE_SHARE_DELETE, NULL, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);

        FILE_NOTIFY_INFORMATION Buffer[1024];
        DWORD BytesReturned;

        if (!ReadDirectoryChangesW(hDir[i], &Buffer, sizeof(Buffer), TRUE, FILE_NOTIFY_CHANGE_LAST_WRITE,  &BytesReturned, NULL, NULL))
        {
            cout << DirName << endl;
        }
        else
            cout << "THE DIRECTORY HAS BEEN MODIFIED..." << endl;

        if (i == directory_list.size() - 1)
            i = 0;
        else
            i++;
    }
}
</code>```

答: You can but you will need to perform it as an asynchronous operation, either with only the LPOVERLAPPED parameter or with both it and the completion routine.  And as the docs say if you go the latter route you will need to be in an alertable wait.</p>

Body:
I am trying to monitor different directories for changes using ReadDirectoryChangesW and I succeed in monitoring a single directory with it. But when it comes to monitoring multiple directories, I am having problems that the first directory is assigned to the handle and it looks for changes only in that directory and then only goes to watch the next directory if the first directory condition is satisfied. But I want to watch multiple directories simultaneously. Can I help me with this problem?

I am attaching the code below for the reference.

#include <iostream>
#include <windows.h>
#include <stdio.h>
#include <vector>
#include <fstream>
#include <mutex>
#include "sys/stat.h"
#include <dirent.h>

using namespace std;

mutex m1;

int main()
{
    HANDLE hDir[20];
    vector <string> directory_list;
    string f_path;
    string temp1;
    ifstream pfile;

    pfile.open("C:\\Users\\sathish-pt1608\\Desktop\\path_file.txt");

    if (!pfile.is_open())
        cout << "Unable to open the Requested File...";

    while(pfile.good())
    {
        getline(pfile,f_path);
        struct stat path_stat;
        stat(f_path.c_str(),&path_stat);

        if (S_ISREG(path_stat.st_mode))
        {
            int a = f_path.find_last_of('\\');
            directory_list.push_back(f_path.substr(0, a - 1));
        }
        else if(S_ISDIR(path_stat.st_mode))
        {
            DIR *dir;
            struct dirent *ent;

            dir = opendir(f_path.c_str());

            if (dir != NULL)
            {
                directory_list.push_back(f_path);
                while ( (ent = readdir(dir)) != NULL)
                {
                    temp1 = ent->d_name;
                }
                closedir(dir);
            }
            else
            {
                perror("Please Check the Directory Path...");
                EXIT_FAILURE;
            }
        }
    }

    for (int i = 0; i < directory_list.size();)
    {
        LPCTSTR DirName = directory_list[i].c_str();

        hDir[i] = CreateFile(DirName, FILE_LIST_DIRECTORY, FILE_SHARE_READ | FILE_SHARE_DELETE, NULL, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);

        FILE_NOTIFY_INFORMATION Buffer[1024];
        DWORD BytesReturned;

        if (!ReadDirectoryChangesW(hDir[i], &Buffer, sizeof(Buffer), TRUE, FILE_NOTIFY_CHANGE_LAST_WRITE,  &BytesReturned, NULL, NULL))
        {
            cout << DirName << endl;
        }
        else
            cout << "THE DIRECTORY HAS BEEN MODIFIED..." << endl;

        if (i == directory_list.size() - 1)
            i = 0;
        else
            i++;
    }
}


问:
Extend an axis limit to -1 when that axis is logarithmic in R
I am doing the following:

```<code>x = c(0, 1, 2, 3, 4, 5)
y = x ^ 2
plot(x, y, log="y")
</code>```

What I want is that the graph also show me the scatter point at (x, y)=(0, 0).

I know that log(0) = -Inf. This will be the case when I am doing log(x) but here I am not doing log(x). Rather, I am just changing the scale of y-axis to be logarithmic. Therefore, I need to know if there is some way for me to display the scatter point (x, y) = (0, 0) as well.

答:
If your aim is to have a non-linear y-axis, and not necessarily a log-scale, then you can follow something like what's below.

```<code># transfrom y-values
ny <- sqrt(y)
# plot the transformed values
plot(x, ny, yaxt='n', ylab = "y")
# label the y-axis
axis(side = 2, at = ny, labels = y)
</code>```

Also, if you know what you want to replace log(0) with, then you can do that via ny, but I don't advise using log-scale when there is a zero.

Body:
I am doing the following:

x = c(0, 1, 2, 3, 4, 5)
y = x ^ 2
plot(x, y, log="y")

What I want is that the graph also show me the scatter point at (x, y)=(0, 0).

I know that log(0) = -Inf. This will be the case when I am doing log(x) but here I am not doing log(x). Rather, I am just changing the scale of y-axis to be logarithmic. Therefore, I need to know if there is some way for me to display the scatter point (x, y) = (0, 0) as well.

Body:
If your aim is to have a non-linear y-axis, and not necessarily a log-scale, then you can follow something like what's below.

# transfrom y-values
ny <- sqrt(y)
# plot the transformed values
plot(x, ny, yaxt='n', ylab = "y")
# label the y-axis
axis(side = 2, at = ny, labels = y)

Also, if you know what you want to replace log(0) with, then you can do that via ny, but I don't advise using log-scale when there is a zero.


答:
You can use strtotime() in php..it looks likes.</p>

```<code>date('Y-m-d H:i:s', strtotime($row['col_name']));
</code>```

Title: MySQL date format convert "Fri, 06 Nov 2015 04:06:05 -0500"

Body:
I have "Fri, 06 Nov 2015 04:06:05 -0500" date format in MySQL.

I want to convert it to Y-m-d H:i:s format within MySQL query. Can anyone please help?

I tried this DATE_FORMAT("Fri, 06 Nov 2015 04:06:05 -0500", '%Y-%m-%d H:i:s') but didn't work.

Body:
You can use strtotime() in php..it looks likes.

date('Y-m-d H:i:s', strtotime($row['col_name']));


问:
What's the difference between "aspnet_regiis -ir" and "aspnet_regiis -iru"?
The help text of aspnet_regiis utility says the following for "-ir" option:

```<code>Install this version of ASP.NET, register only. Do not change any web applications to use this version.
</code>```

And the following for "-iru" option:

```<code>Install this version of ASP.NET. If there are any existing applications that uses ASP.NET, it will not change IIS configuration to use this version.
</code>```

It must be my English, but I do not understand what the difference is - both won't change any apps to use this version. And I'm afraid that trying this out myself won't be precise, since I hardly know where to look into...

Does anyone know the difference?

答:
ASP.NET IIS Registration Options Summary

```<code>-i
</code>```

Install ASP.NET and updates existing applications to use the specified version of the application pool.

```<code>-ir
</code>```

Installs and registers ASP.NET.  This option is the same as the -i option except that it does not change the CLR version associated with any existing application pools.

```<code>-iru
</code>```

If ASP.NET is not currently registered with IIS, performs the tasks of -i.
If a previous version of ASP.NET is already registered with IIS, performs the tasks of -ir.

Essentially, depending on your previous setup, -iru may or may not update existing application pools to the version of ASP.NET you are installing.

Hope this clears things up.

Body:
The help text of aspnet_regiis utility says the following for "-ir" option:

Install this version of ASP.NET, register only. Do not change any web applications to use this version.

And the following for "-iru" option:

Install this version of ASP.NET. If there are any existing applications that uses ASP.NET, it will not change IIS configuration to use this version.

It must be my English, but I do not understand what the difference is - both won't change any apps to use this version. And I'm afraid that trying this out myself won't be precise, since I hardly know where to look into...

Does anyone know the difference?

Body:
ASP.NET IIS Registration Options Summary

-i

Install ASP.NET and updates existing applications to use the specified version of the application pool.

-ir

Installs and registers ASP.NET.  This option is the same as the -i option except that it does not change the CLR version associated with any existing application pools.

-iru

If ASP.NET is not currently registered with IIS, performs the tasks of -i.
If a previous version of ASP.NET is already registered with IIS, performs the tasks of -ir.

Essentially, depending on your previous setup, -iru may or may not update existing application pools to the version of ASP.NET you are installing.

Hope this clears things up.


问:
Reportlab - Unicode characters appear as boxes in unicode-supported font
Trying to use reportlab through python 3 to write a document that includes macrons (ā ē ī ō ū), but the macrons are showing up as boxes (■). The document is written in Arial font -- but if I open up the file in a word processor to check the font, the boxes are in 'Segoe UI Symbol' font.

For importing in Arial as a font that supports a broad range of unicode characters (which seems to have worked):

```<code>import reportlab.rl_config
reportlab.rl_config.warnOnMissingFontGlyphs = 0
from reportlab.pdfbase import pdfmetrics
from reportlab.pdfbase.ttfonts import TTFont
pdfmetrics.registerFont(TTFont('Arial', 'Arial.ttf'))
</code>```

I also import a dictionary through json, looking something like this when I open the json file in notepad:

```<code>{"example1":"b\u0101s"}
</code>```

The program reads and writes this dictionary:

```<code>from reportlab.platypus import SimpleDocTemplate, Paragraph, Spacer
from reportlab.lib.styles import getSampleStyleSheet
doc = SimpleDocTemplate("hello.pdf")
Story = [Spacer(1,2*inch)]
style = styles["Normal"]
with open('CompDict.json','r') as f:
        m_dic=json.load(f)
for key,value in m_dic:
     p=Paragraph(key+":"+value,style)
     Story.append(p)
doc.build(Story)
</code>```

The outcome should be a pdf with example1:bās but instead comes out as example1:b■s

答:
```<code>#Here I am writing chunks of code, hope you will understand

from reportlab.platypus import Paragraph, SimpleDocTemplate, Spacer
from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle
from reportlab.lib.enums import TA_CENTER,TA_JUSTIFY
from reportlab.pdfbase import pdfmetrics
from reportlab.pdfbase.ttfonts import TTFont
from reportlab.lib.fonts import addMapping

pdfmetrics.registerFont(TTFont('devaNagri', 'NotoSerifDevanagari.ttf')) # devaNagri is a folder located in **/usr/share/fonts/truetype** and 'NotoSerifDevanagari.ttf' file you just download it from https://www.google.com/get/noto/#sans-deva and move to devaNagri folder.

addMapping('devaNagri', 0, 0, 'NotoSerifDevanagari') #devnagri is a folder name and NotoSerifDevanagari is file name

style = getSampleStyleSheet()
style.add(ParagraphStyle(name="ParagraphTitle", alignment=TA_JUSTIFY, fontName="devaNagri")) # after mapping fontName define your folder name.
paragraph = Paragraph('your unicode string', style["ParagraphTitle"])
</code>```

Body:
Trying to use reportlab through python 3 to write a document that includes macrons (ā ē ī ō ū), but the macrons are showing up as boxes (■). The document is written in Arial font -- but if I open up the file in a word processor to check the font, the boxes are in 'Segoe UI Symbol' font.

For importing in Arial as a font that supports a broad range of unicode characters (which seems to have worked):

import reportlab.rl_config
reportlab.rl_config.warnOnMissingFontGlyphs = 0
from reportlab.pdfbase import pdfmetrics
from reportlab.pdfbase.ttfonts import TTFont
pdfmetrics.registerFont(TTFont('Arial', 'Arial.ttf'))

I also import a dictionary through json, looking something like this when I open the json file in notepad:

{"example1":"b\u0101s"}

The program reads and writes this dictionary:

from reportlab.platypus import SimpleDocTemplate, Paragraph, Spacer
from reportlab.lib.styles import getSampleStyleSheet
doc = SimpleDocTemplate("hello.pdf")
Story = [Spacer(1,2*inch)]
style = styles["Normal"]
with open('CompDict.json','r') as f:
        m_dic=json.load(f)
for key,value in m_dic:
     p=Paragraph(key+":"+value,style)
     Story.append(p)
doc.build(Story)

The outcome should be a pdf with example1:bās but instead comes out as example1:b■s


问:
How to find total and free size of mounted and unmounted partition at runtime
I am using tune2fs -l /dev/mmcblk0p1 but when i use this command and change the free space of partition by copying some files into it , tune2fs does not gives updated values.

Tune2fs gives correct value if i restart the system but does not updates values at runtime.

Please suggest some other command that provides coreect data at runtime for unmounted/mounted partitions both.

TIA.

答:
You can not get the exact value of free space available on a random unmounted block device/partition, because the actual free space will depend on actions kernel will perform when mounting the device. So the only proper way to get the amount of free space is to mount the partition first, then use the usual df utility, which will show the up to date space utilization.

However, if system crashes abruptly, the free space reported after remounting may actually be different from the value last reported by df prior to the crash.

For non-mounted devices/partitions, you can always obtain the total (but not free) space available using lsblk or similar utilities.


问:
cmucl: run-program output process exited only
I'm on debian stretch and install CMUCL from the stable repository. When trying the following

```<code>(run-program "sh" '("ls") :output T)
</code>```

I get

#<process 2845 :EXITED>

without the expected output. Any help please?

答:
Read ls(1) and dash(1) & bash(1). Notice that POSIX /bin/sh is often a symlink to one of them (often dash, sometimes bash). Be aware of the role of the PATH variable (e.g. in shells and for execvp(3)). And system(3) is using /bin/sh with -c, and your sh (assuming it is a POSIX shell) needs -c to interpret a string as a command.

You could try

```<code>  (run-program "/bin/ls" nil :output t)
</code>```

or

```<code>  (run-program "/bin/sh" '("-c" "ls") :output t)
</code>```

You probably don't have ls in your working directory (but somewhere else in your PATH; on POSIX it should be /bin/ls) and /bin/ls is not a shell script, but some ELF executable (on Linux; on most Unixes it is some executable and is not a script). So /bin/sh ls (or sh ls) can't work as you want it to.

To run ls there is no need to start a shell! And you might not need to fork a ls process for that purpose (of listing files), because you could call opendir(3) readdir(3) stat(2) closedir(3) as FFI (or find some package doing that).

PS. I have used SBCL to test these.

Body:
I'm on debian stretch and install CMUCL from the stable repository. When trying the following

(run-program "sh" '("ls") :output T)

I get

#<process 2845 :EXITED>

without the expected output. Any help please?

Body:
Read ls(1) and dash(1) & bash(1). Notice that POSIX /bin/sh is often a symlink to one of them (often dash, sometimes bash). Be aware of the role of the PATH variable (e.g. in shells and for execvp(3)). And system(3) is using /bin/sh with -c, and your sh (assuming it is a POSIX shell) needs -c to interpret a string as a command.

You could try

  (run-program "/bin/ls" nil :output t)

or

  (run-program "/bin/sh" '("-c" "ls") :output t)

You probably don't have ls in your working directory (but somewhere else in your PATH; on POSIX it should be /bin/ls) and /bin/ls is not a shell script, but some ELF executable (on Linux; on most Unixes it is some executable and is not a script). So /bin/sh ls (or sh ls) can't work as you want it to.

To run ls there is no need to start a shell! And you might not need to fork a ls process for that purpose (of listing files), because you could call opendir(3) readdir(3) stat(2) closedir(3) as FFI (or find some package doing that).

PS. I have used SBCL to test these.


问:
DomPDF table fixed column width and break long text
I have a table with very long texts that has no spaces (users like to post a full website URL complete with all the parameters)

Then I set on word-break:break-all; and word-wrap:break-word; on each  hoping that the text could fit on the table.

I also set all the  / column widths to some specified amount.

I use Laravel's DomPDF wrapper here: https://github.com/barryvdh/laravel-dompdf

Case 1: No table-layout: fixed

```<code><table class="bordered">
    <tr class="font-12">
        <th style="width: 25px">No</th>
        <th style="width: 100px">Nama Alat</th>
        <th style="width: 25px">Jml</th>
        <th style="width: 300px">Spesifikasi</th>
        <th style="width: 300px">Supplier</th>
        <th style="width: 150px">Gambar</th>
    </tr>
    @foreach ($items as $index => $item)
    <tr>
        <td style="width: 25px">{{ ($index+1) }}</td>
        <td style="width: 100px">{{ $item['name'] }}</td>
        <td style="width: 25px">{{ $item['jumlah_disetujui'] }}</td>
        <td class="font-12" style="width: 300px; word-break:break-all; word-wrap:break-word;">
            {!! nl2br( $item['spesifikasi'] ) !!}
        </td>
        <td class="font-12" style="width: 300px; word-break:break-all; word-wrap:break-word;">
            {!! nl2br( $item['supplier'] ) !!}
        </td>
        <td style="width: 150px">
            @if ($item['image'])
                <img style="max-height: 125px;" src="{{ $item['image'] }}" />
            @else
                -
            @endif
        </td>
    </tr>
    @endforeach
</table>
</code>```

Case 1 PDF Result:  Word-wrap does not work, column width works on cells with few texts, but does not work either on cells that has long texts (needs word-wrap).

Case 2: Adding table-layout: fixed

```<code><table class="bordered" style="table-layout: fixed"> <!-- only added this -->
    <tr class="font-12">
        <th style="width: 25px">No</th>
        <th style="width: 100px">Nama Alat</th>
        <th style="width: 25px">Jml</th>
        <th style="width: 300px">Spesifikasi</th>
        <th style="width: 300px">Supplier</th>
        <th style="width: 150px">Gambar</th>
    </tr>
    @foreach ($items as $index => $item)
    <tr>
        <td style="width: 25px">{{ ($index+1) }}</td>
        <td style="width: 100px">{{ $item['name'] }}</td>
        <td style="width: 25px">{{ $item['jumlah_disetujui'] }}</td>
        <td class="font-12" style="width: 300px; word-break:break-all; word-wrap:break-word;">
            {!! nl2br( $item['spesifikasi'] ) !!}
        </td>
        <td class="font-12" style="width: 300px; word-break:break-all; word-wrap:break-word;">
            {!! nl2br( $item['supplier'] ) !!}
        </td>
        <td style="width: 150px">
            @if ($item['image'])
                <img style="max-height: 125px;" src="{{ $item['image'] }}" />
            @else
                -
            @endif
        </td>
    </tr>
    @endforeach
</table>
</code>```

Case 2 PDF Result: Word-wrap works, but column width has no effect

What I want is: a table with fixed width columns that has a working word-wrap

Is this impossible to do on DomPDF?

Any workaround or 'hacks' that can help achieve this?

Or maybe I should start looking for other / better PDF generators?

EDIT:

I also found a lot of Github Issues on this, with no sign of the bug being fixed

Table cell width is not honored if content exceeds the specified dimensions #1017

Table widths do not conform to css width attribute. #1253

Fixed table layout ignored column widths #1432

答:
Not really an "answer", but my solution is switching to Snappy PDF (used the Laravel Package).

Worked like a charm, I did not even change the HTML markups.

Body:
I have a table with very long texts that has no spaces (users like to post a full website URL complete with all the parameters)

Then I set on word-break:break-all; and word-wrap:break-word; on each  hoping that the text could fit on the table.

I also set all the  / column widths to some specified amount.

I use Laravel's DomPDF wrapper here: https://github.com/barryvdh/laravel-dompdf

Case 1: No table-layout: fixed

        No
        Nama Alat
        Jml
        Spesifikasi
        Supplier
        Gambar

    @foreach ($items as $index => $item)

        {{ ($index+1) }}
        {{ $item['name'] }}
        {{ $item['jumlah_disetujui'] }}

            {!! nl2br( $item['spesifikasi'] ) !!}

            {!! nl2br( $item['supplier'] ) !!}

            @if ($item['image'])

            @else
                -
            @endif

    @endforeach

Case 1 PDF Result:  Word-wrap does not work, column width works on cells with few texts, but does not work either on cells that has long texts (needs word-wrap).

Case 2: Adding table-layout: fixed

        No
        Nama Alat
        Jml
        Spesifikasi
        Supplier
        Gambar

    @foreach ($items as $index => $item)

        {{ ($index+1) }}
        {{ $item['name'] }}
        {{ $item['jumlah_disetujui'] }}

            {!! nl2br( $item['spesifikasi'] ) !!}

            {!! nl2br( $item['supplier'] ) !!}

            @if ($item['image'])

            @else
                -
            @endif

    @endforeach

Case 2 PDF Result: Word-wrap works, but column width has no effect

What I want is: a table with fixed width columns that has a working word-wrap

Is this impossible to do on DomPDF?

Any workaround or 'hacks' that can help achieve this?

Or maybe I should start looking for other / better PDF generators?

EDIT:

I also found a lot of Github Issues on this, with no sign of the bug being fixed

Table cell width is not honored if content exceeds the specified dimensions #1017

Table widths do not conform to css width attribute. #1253

Fixed table layout ignored column widths #1432


问:
The TensorFlow library wasn't compiled to use AVX - AVX2
I'm new to Tensorflow.
I am using a 64 bit version of Windows 10 and I would like to install Tensorflow for the CPU.
I don't remember the exact steps that I followed to install it, however when I checked for the installation using:

```<code>import tensorflow as tf
hello = tf.constant('Hello, TensorFlow!')
sess = tf.Session()
print(sess.run(hello))
</code>```

I have the following output:

```<code>2017-10-18 09:56:21.656601: W C:\tf_jenkins\home\workspace\rel-win\M\windows\PY\36\tensorflow\core\platform\cpu_feature_guard.cc:45] The TensorFlow library wasn't compiled to use AVX instructions, but these are available on your machine and could speed up CPU computations.
2017-10-18 09:56:21.656984: W C:\tf_jenkins\home\workspace\rel-win\M\windows\PY\36\tensorflow\core\platform\cpu_feature_guard.cc:45] The TensorFlow library wasn't compiled to use AVX2 instructions, but these are available on your machine and could speed up CPU computations.
b'Hello, TensorFlow!'
</code>```

I am running python in Sublime Text 3 using the package SublimeREPL.
I tried to search these errors and found out that it means that the tensorflow is built without these instructions which could improve performances for the CPU. I also found the code to hide these warnings, but I actually I want to use these instructions.

The code that I found that enables this is:

```<code>bazel build -c opt --copt=-mavx --copt=-mavx2 --copt=-msse4.2 --copt=-msse4.1 --copt=-msse3 --copt=-mfma -k //tensorflow/tools/pip_package:build_pip_package
</code>```

but I got this output:

```<code>ERROR: Skipping '//tensorflow/tools/pip_package:build_pip_package': no such package 'tensorflow/tools/pip_package': BUILD file not found on package path.
WARNING: Target pattern parsing failed. Continuing anyway.
INFO: Found 0 targets...
ERROR: command succeeded, but there were errors parsing the target pattern.
INFO: Elapsed time: 8,147s, Critical Path: 0,02s
</code>```

How can I solve this problem?
Lastly, I don't understand what pip, wheel and bazel are so I need a step by step instructions.

Thank you a lot!

答:
if you want to download TensorFlow source, compile+install, use this link.
If you want to download binaries, then use this link.

Body:
I'm new to Tensorflow.
I am using a 64 bit version of Windows 10 and I would like to install Tensorflow for the CPU.
I don't remember the exact steps that I followed to install it, however when I checked for the installation using:

import tensorflow as tf
hello = tf.constant('Hello, TensorFlow!')
sess = tf.Session()
print(sess.run(hello))

I have the following output:

2017-10-18 09:56:21.656601: W C:\tf_jenkins\home\workspace\rel-win\M\windows\PY\36\tensorflow\core\platform\cpu_feature_guard.cc:45] The TensorFlow library wasn't compiled to use AVX instructions, but these are available on your machine and could speed up CPU computations.
2017-10-18 09:56:21.656984: W C:\tf_jenkins\home\workspace\rel-win\M\windows\PY\36\tensorflow\core\platform\cpu_feature_guard.cc:45] The TensorFlow library wasn't compiled to use AVX2 instructions, but these are available on your machine and could speed up CPU computations.
b'Hello, TensorFlow!'

I am running python in Sublime Text 3 using the package SublimeREPL.
I tried to search these errors and found out that it means that the tensorflow is built without these instructions which could improve performances for the CPU. I also found the code to hide these warnings, but I actually I want to use these instructions.

The code that I found that enables this is:

bazel build -c opt --copt=-mavx --copt=-mavx2 --copt=-msse4.2 --copt=-msse4.1 --copt=-msse3 --copt=-mfma -k //tensorflow/tools/pip_package:build_pip_package

but I got this output:

ERROR: Skipping '//tensorflow/tools/pip_package:build_pip_package': no such package 'tensorflow/tools/pip_package': BUILD file not found on package path.
WARNING: Target pattern parsing failed. Continuing anyway.
INFO: Found 0 targets...
ERROR: command succeeded, but there were errors parsing the target pattern.
INFO: Elapsed time: 8,147s, Critical Path: 0,02s

How can I solve this problem?
Lastly, I don't understand what pip, wheel and bazel are so I need a step by step instructions.

Thank you a lot!


问:
Can docker containers be made FULLY visible over the host network?
In our office, we have a small cluster of 10 computers. Some of the computers also host virtual machines (using VirtualBox). We use bridged networking for the virtual machines so that the virtual machines are fully accessible over the host network. Virtual machines get their ip addresses from the same pool (192.168.0.xxx) as the actual computers.

Is it possible to accomplish the same thing using docker containers? Please note that all our computers and virtual machines are running Ubuntu 17.10 (artful aardvark).

I know that it is possible to do port forwarding between docker containers and host computer. But we want more than that! We want docker containers to receive ip addresses directly from the host network (i.e. 192.168.0.xxx). Can you please tell whether this is possible? If yes, how can this be accomplished? Thank you!

答:
yes, it can be done by 'macVlan' network driver.

First, you need to create a macvlan network:

```<code>docker network create -d macvlan --subnet=192.168.1.0/24 --gateway=192.168.1.1 -o parent=eth0 mynet
</code>```

This command will create a macVlan network which it's subnet and gateway is the same as host's config

And, you can run docker container with specific network:

```<code>docker run --net=mynet -it --rm alpine:latest /bin/sh
</code>```

Thit's all. You can fetch container's IP and try to ping it in other hosts.

PS:  The container can't be accessed by mother host.

ref doc: https://docs.docker.com/engine/userguide/networking/get-started-macvlan/

Body:
yes, it can be done by 'macVlan' network driver.

First, you need to create a macvlan network:

docker network create -d macvlan --subnet=192.168.1.0/24 --gateway=192.168.1.1 -o parent=eth0 mynet

This command will create a macVlan network which it's subnet and gateway is the same as host's config

And, you can run docker container with specific network:

docker run --net=mynet -it --rm alpine:latest /bin/sh

Thit's all. You can fetch container's IP and try to ping it in other hosts.

PS:  The container can't be accessed by mother host.

ref doc: https://docs.docker.com/engine/userguide/networking/get-started-macvlan/


问:
Directly assigning to a std::vector after reserving does not throw error but does not increase vector size
Let's create a helper class to assist visualizing the issue:

```<code>class C
{
int ID = 0;

public:
C(const int newID)
{
    ID = newID;
}

int getID()
{
    return ID;
}
};
</code>```

Suppose you create an empty std::vector<C> and then reserve it to hold 10 elements:

```<code>std::vector<C> pack;
pack.reserve(10);
printf("pack has  %i\n", pack.size()); //will print '0'
</code>```

Now, you assign a new instance of C into index 4 of the vector:

```<code>pack[4] = C(57);
printf("%i\n", pack[4].getID()); //will print '57'
printf("pack has  %i\n", pack.size()); //will still print '0'
</code>```

I found two things to be weird here:

1) shouldn't the assignment make the compiler (Visual Studio 2015, Release Mode) throw an error even in Release mode?

2) since it does not and the element is in fact stored in position 4, shouldn't the vector then have size = 1 instead of zero?

答:
Undefined behavior is still undefined. If we make this a vector of objects, you would see the unexpected behavior more clearly.

```<code>#include <iostream>
#include <vector>

struct Foo {
  int data_ = 3;
};

int main() {
  std::vector<Foo> foos;
  foos.reserve(10);
  std::cout << foos[4].data_; // This probably doesn't output 3.
}
</code>```

Here, we can see that because we haven't actually allocated the object yet, the constructor hasn't run.

Another example, since you're using space that the vector hasn't actually started allocating to you, if the vector needed to reallocate it's backing memory, the value that you wrote wouldn't be copied.

```<code>#include <iostream>
#include <vector>

int main() {
  std::vector<int> foos;
  foos.reserve(10);
  foos[4] = 100;
  foos.reserve(10000000);
  std::cout << foos[4]; // Probably doesn't print 100.
}
</code>```

Body:
Let's create a helper class to assist visualizing the issue:

class C
{
int ID = 0;

public:
C(const int newID)
{
    ID = newID;
}

int getID()
{
    return ID;
}
};

Suppose you create an empty std::vector<C> and then reserve it to hold 10 elements:

std::vector<C> pack;
pack.reserve(10);
printf("pack has  %i\n", pack.size()); //will print '0'

Now, you assign a new instance of C into index 4 of the vector:

pack[4] = C(57);
printf("%i\n", pack[4].getID()); //will print '57'
printf("pack has  %i\n", pack.size()); //will still print '0'

I found two things to be weird here:

1) shouldn't the assignment make the compiler (Visual Studio 2015, Release Mode) throw an error even in Release mode?

2) since it does not and the element is in fact stored in position 4, shouldn't the vector then have size = 1 instead of zero?

Body:
Undefined behavior is still undefined. If we make this a vector of objects, you would see the unexpected behavior more clearly.

#include <iostream>
#include <vector>

struct Foo {
  int data_ = 3;
};

int main() {
  std::vector<Foo> foos;
  foos.reserve(10);
  std::cout << foos[4].data_; // This probably doesn't output 3.
}

Here, we can see that because we haven't actually allocated the object yet, the constructor hasn't run.

Another example, since you're using space that the vector hasn't actually started allocating to you, if the vector needed to reallocate it's backing memory, the value that you wrote wouldn't be copied.

#include <iostream>
#include <vector>

int main() {
  std::vector<int> foos;
  foos.reserve(10);
  foos[4] = 100;
  foos.reserve(10000000);
  std::cout << foos[4]; // Probably doesn't print 100.
}


问:
What's the best way to write a command-line app in Java?
Okay, I know there are probably a dozen ways to solve this, but I am looking for either a skeleton app or some sort of tutorial that will explain the best way to write a framework for creating Java-based command-line tools.  If my program requires a lot of switches/options/etc., what's the best way to handle all of them?

How do you decide which stuff should be placed into an options/settings file, and which stuff gets put on the command line?  Any sort of sample code would be great, that way I can put my time more towards the central focus of my app rather than the command-line plumbing.

答:
How do you decide which stuff should be placed into an options/settings file, and which stuff gets put on the command line?

There's no such dilemma, many things are useful in both places. With the settings file you let the user define defaults and with the command line you let the user override them. Of course, there are cases when only one of the two makes sense, but I'd take providing both as the starting point.


问:
Scroll-able area select box as opposed to drop down, Rails
https://www.w3schools.com/html/tryit.asp?filename=tryhtml_elem_select_size

The select box I see is an area based select box as opposed to a drop down. However, In rails I can only get the drop down based select box. I have tried:

```<code><%= f.collection_select :role_cont, Role.where(company: current_user.company), :name, :name, include_blank: true, :multiple => true, class: 'form-control chosen-it', :size => 10 %>
</code>```

The above does not work. Note the :size attribute. From a gem I have:

```<code><%= select_tag 'recipients', recipients_options(@chosen_recipient), multiple: true, class: 'form-control chosen-it' %>
</code>```

This does work, it creates an area based select box that I want. How do I set my select boxes to be a scroll able area as opposed to a simple drop down? Also I want to be able to use scroll able select box even when I can only select a singular object

答:
Here why you added ':multiple => true' if you want select only one option,
these option is used when you want to select multiple values from select box.

```<code><%= f.collection_select :role_cont, Role.where(company: current_user.company), :name, :name, include_blank: true, :multiple => true, class: 'form-control chosen-it', :size => 10 %>
</code>```

Remove :multiple => true and it work as you want without area based select box

Body:
https://www.w3schools.com/html/tryit.asp?filename=tryhtml_elem_select_size

The select box I see is an area based select box as opposed to a drop down. However, In rails I can only get the drop down based select box. I have tried:

<%= f.collection_select :role_cont, Role.where(company: current_user.company), :name, :name, include_blank: true, :multiple => true, class: 'form-control chosen-it', :size => 10 %>

The above does not work. Note the :size attribute. From a gem I have:

<%= select_tag 'recipients', recipients_options(@chosen_recipient), multiple: true, class: 'form-control chosen-it' %>

This does work, it creates an area based select box that I want. How do I set my select boxes to be a scroll able area as opposed to a simple drop down? Also I want to be able to use scroll able select box even when I can only select a singular object

Body:
Here why you added ':multiple => true' if you want select only one option,
these option is used when you want to select multiple values from select box.

<%= f.collection_select :role_cont, Role.where(company: current_user.company), :name, :name, include_blank: true, :multiple => true, class: 'form-control chosen-it', :size => 10 %>

Remove :multiple => true and it work as you want without area based select box


问:
Add a filter on a DbSet that is included on a related DbSet?
The following are some stuffs behind the scene.

```<code>public class User : BaseTransactionModel
{
    public Guid UserId { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

public class Transaction
{

    public int TransactionId { get; set; }
    public string TransactionName { get; set; }
    public int TransactionHistoryId { get; set; }

    public virtual TransactionHistory TransactionHistory { get; set; }
}

public class TransactionHistory
{
    public int TransactionHistoryId { get; set; }
    public DateTime CreatedDateTime { get; set; }
    public Guid UserId { get; set; }
    public int TransactionId { get; set; }

    public virtual ICollection<User> Users { get; set; }
    public virtual ICollection<Transaction> Transactions { get; set; }
}

public class BaseTransactionModel
{

    public int TransactionHistoryId { get; set; }
    public int TransactionId { get; set; }

    public virtual TransactionHistory TransactionHistory { get; set; }
    public virtual Transaction Transaction { get; set; }
}
</code>```

With the above entities, I am trying to get all the Transactions from a User on a specified Date.

So I tried including both User and TransactionHistory on the Transaction DbSet:

```<code>Context.Transaction
    .Include(t => t.User)
    .Include(t => t.TransactionHistory)
    ...
</code>```

I wanted to add a where clause that filter the transaction from the date in transaction history entities:

```<code>Context.Transaction
    .Include(t => t.User)
    .Include(t => t.TransactionHistory)
    .Where(t => t.TransactionHistory.CreatedDateTime <= StartDateFilter && t.TransactionHistory.CreatedDateTime >= EndDateFilter)
</code>```

but could not able to do so. Since TransactionHistory is also a list of entity (or whatever it is called).

What could be the possible solution to get what I am trying to achieve ?

PS: I am new to EF and the title could be misleading. If so, feel free to update it.

答:
Try this instead

```<code>Context.Transaction
    .Where(t => t.TransactionHistory.CreatedDateTime <= StartDateFilter && t.TransactionHistory.CreatedDateTime >= EndDateFilter)
.Select(x=> new {x.User,x.TransactionHistory});
</code>```

OR This

```<code>Context.Transaction
.Where(t => t.TransactionHistory.CreatedDateTime <= StartDateFilter && t.TransactionHistory.CreatedDateTime >= EndDateFilter)
.Include(t => t.User)
.Include(t => t.TransactionHistory)
</code>```

Body:
The following are some stuffs behind the scene.

public class User : BaseTransactionModel
{
    public Guid UserId { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

public class Transaction
{

    public int TransactionId { get; set; }
    public string TransactionName { get; set; }
    public int TransactionHistoryId { get; set; }

    public virtual TransactionHistory TransactionHistory { get; set; }
}

public class TransactionHistory
{
    public int TransactionHistoryId { get; set; }
    public DateTime CreatedDateTime { get; set; }
    public Guid UserId { get; set; }
    public int TransactionId { get; set; }

    public virtual ICollection<User> Users { get; set; }
    public virtual ICollection<Transaction> Transactions { get; set; }
}

public class BaseTransactionModel
{

    public int TransactionHistoryId { get; set; }
    public int TransactionId { get; set; }

    public virtual TransactionHistory TransactionHistory { get; set; }
    public virtual Transaction Transaction { get; set; }
}

With the above entities, I am trying to get all the Transactions from a User on a specified Date.

So I tried including both User and TransactionHistory on the Transaction DbSet:

Context.Transaction
    .Include(t => t.User)
    .Include(t => t.TransactionHistory)
    ...

I wanted to add a where clause that filter the transaction from the date in transaction history entities:

Context.Transaction
    .Include(t => t.User)
    .Include(t => t.TransactionHistory)
    .Where(t => t.TransactionHistory.CreatedDateTime <= StartDateFilter && t.TransactionHistory.CreatedDateTime >= EndDateFilter)

but could not able to do so. Since TransactionHistory is also a list of entity (or whatever it is called).

What could be the possible solution to get what I am trying to achieve ?

PS: I am new to EF and the title could be misleading. If so, feel free to update it.

Body:
Try this instead

Context.Transaction
    .Where(t => t.TransactionHistory.CreatedDateTime <= StartDateFilter && t.TransactionHistory.CreatedDateTime >= EndDateFilter)
.Select(x=> new {x.User,x.TransactionHistory});

OR This

Context.Transaction
.Where(t => t.TransactionHistory.CreatedDateTime <= StartDateFilter && t.TransactionHistory.CreatedDateTime >= EndDateFilter)
.Include(t => t.User)
.Include(t => t.TransactionHistory)


问:
How to use map function instead of for loop in javascript?
This is my array :

```<code>var filteredData = [{ id: 1, phoneno: '91888888888', sender: 'test' },{ id: 2, phoneno: '9199999999999', sender: 'hel' }]
</code>```

I use for loop

```<code>for (var i = 0; i < filteredData.length; i++) {
   if (filteredData[i].sender === test) {
       console.log('worked');
   }else{
       console.log('not worked');
   }
}
</code>```

How to exactly do this with map ? in javascript instead of for loop.

答:
```<code>var filteredData = [{ id: 1, phoneno: '77777777777', sender: 'test' },{ id: 2, phoneno: '917338966917', sender: 'hel' }]
filteredData.map(filterDetails);
function filterDetails(data) {
    if(data.sender == 'test'){
     console.log('worked');
     }
     else{
     console.log('not worked');
     }
}
</code>```

Body:
This is my array :

var filteredData = [{ id: 1, phoneno: '91888888888', sender: 'test' },{ id: 2, phoneno: '9199999999999', sender: 'hel' }]

I use for loop

for (var i = 0; i < filteredData.length; i++) {
   if (filteredData[i].sender === test) {
       console.log('worked');
   }else{
       console.log('not worked');
   }
}

How to exactly do this with map ? in javascript instead of for loop.


问:
network traffic of application
Is it possible to measure the network traffic of applications running in iphone ?
can anyone suggest me the road map or example kind of thing please ?

Using proxy is that possible ?

答: Yup, you can use the Paros proxy which was built for web application security assessments.  Tutorial can be found here: Sniff Your iPhone's Network Traffic.  </p>

Title: network traffic of application


问:
Swift: can properties be required based on another property being set?
I want to re-use a single viewcontroller but re-purposed slightly and I'm wondering if there is a structured way to require some properties to be set based on another property.

For example assume that the viewcontroller has the following properties
- var displayMode: DisplayMode // see below
- var id: Int
- var description: String
- var name: String

If we are in quickView mode then I expect a ID and Description values to be set.
Else if we are in defaultView mode I expect the Name property to be set.

```<code>enum DisplayMode {
    case quickView
    case defaultView
}
</code>```

Obviously I could just set those and expect them to be set but I'm wondering if there is a structured Swift-like way of forcing this, like having the properties nested in the DisplayMode type?

答:
I think something like this is what you want:

```<code>var displayMode: DisplayMode {
    didSet {
        if displayMode == quickview {
            // self.id = whatever
            // do whatever else you want
        }
        else if displayMode == default {
            // self.id = whatever
            // do whatever else you want
        }
    }
}

var id: Int
var description: String
var name: String
</code>```

(Edit: Of course, it'd be a little different because you're using an enum, but you get the gist of it.)

Another option might be to use KVO. https://developer.apple.com/library/content/documentation/Cocoa/Conceptual/KeyValueObserving/KeyValueObserving.html

Body:
I want to re-use a single viewcontroller but re-purposed slightly and I'm wondering if there is a structured way to require some properties to be set based on another property.

For example assume that the viewcontroller has the following properties
- var displayMode: DisplayMode // see below
- var id: Int
- var description: String
- var name: String

If we are in quickView mode then I expect a ID and Description values to be set.
Else if we are in defaultView mode I expect the Name property to be set.

enum DisplayMode {
    case quickView
    case defaultView
}

Obviously I could just set those and expect them to be set but I'm wondering if there is a structured Swift-like way of forcing this, like having the properties nested in the DisplayMode type?

Body:
I think something like this is what you want:

var displayMode: DisplayMode {
    didSet {
        if displayMode == quickview {
            // self.id = whatever
            // do whatever else you want
        }
        else if displayMode == default {
            // self.id = whatever
            // do whatever else you want
        }
    }
}

var id: Int
var description: String
var name: String

(Edit: Of course, it'd be a little different because you're using an enum, but you get the gist of it.)

Another option might be to use KVO. https://developer.apple.com/library/content/documentation/Cocoa/Conceptual/KeyValueObserving/KeyValueObserving.html


问:
Integer Value Right Padding in SQL
Step1: I have a table called XYZ which contains following integer columns:

```<code> ID      A          B          C
 1    201507    20150810   20150311
 2    20150812  201509     201510
</code>```

I need to write a SQL query where if any values of A, B, and C is smaller than 8 digits then I need to consider it as 8 digits by adding zeros to the right of the value for step2 (I am not allowed to update the table.). For example:

```<code> ID      A            B          C
 1    20150700    20150810   20150311
 2    20150812    20150900   20151000
</code>```

How to add zeros to the right of the integer values through SQL query?

Step 2: I need to find for each record A<B, B<C or not. Please let me know how to write the query. I am using PostgreSQL. Thank you.

答:
```<code>SELECT CAST(2015 AS VARCHAR(10))+REPLICATE('0',8-LEN(2015))

SELECT  2015 *(CAST('1'+REPLICATE('0',8-len(2015))  AS INT))
</code>```

Title: Integer Value Right Padding in SQL

Body:
Step1: I have a table called XYZ which contains following integer columns:

 ID      A          B          C
 1    201507    20150810   20150311
 2    20150812  201509     201510

I need to write a SQL query where if any values of A, B, and C is smaller than 8 digits then I need to consider it as 8 digits by adding zeros to the right of the value for step2 (I am not allowed to update the table.). For example:

 ID      A            B          C
 1    20150700    20150810   20150311
 2    20150812    20150900   20151000

How to add zeros to the right of the integer values through SQL query?

Step 2: I need to find for each record A<B, B<C or not. Please let me know how to write the query. I am using PostgreSQL. Thank you.


问:
<lambda>() takes 1 pos
I am practicing using the functools.reduce() function with a lambda function. The problem I am having is that I keep getting an error. Here is my code:

```<code>>>> from functools import reduce
>>> import math
>>> l = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> reduce( (lambda x: math.sqrt(x)), l )
</code>```

And here is the output:

```<code>TypeError: <lambda>() takes 1 positional argument but 2 were given
</code>```

I have moved parentheses around but nothing seems to work. For some reason, this code works just fine:

```<code>>>> from functools import reduce
>>> reduce( (lambda x, y: x * y), [1, 2, 3, 4] )
24
>>> reduce( (lambda x, y: x / y), [1, 2, 3, 4] )
0.041666666666666664
</code>```

but I can't see any difference other than that the second example has a second parameter y. Can anybody offer any advice on why I am getting this error?

答:
The correct syntax is:

```<code>reduce(lambda acc, x: math.sqrt(x), l)
</code>```

The lambda passed to reduce requires two arguments: the accumulated result and the current value.

Title: <lambda>() takes 1 pos

Body:
I am practicing using the functools.reduce() function with a lambda function. The problem I am having is that I keep getting an error. Here is my code:

>>> from functools import reduce
>>> import math
>>> l = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> reduce( (lambda x: math.sqrt(x)), l )

And here is the output:

TypeError: <lambda>() takes 1 positional argument but 2 were given

I have moved parentheses around but nothing seems to work. For some reason, this code works just fine:

>>> from functools import reduce
>>> reduce( (lambda x, y: x * y), [1, 2, 3, 4] )
24
>>> reduce( (lambda x, y: x / y), [1, 2, 3, 4] )
0.041666666666666664

but I can't see any difference other than that the second example has a second parameter y. Can anybody offer any advice on why I am getting this error?

Body:
The correct syntax is:

reduce(lambda acc, x: math.sqrt(x), l)

The lambda passed to reduce requires two arguments: the accumulated result and the current value.