问:
Devise gem registration model issue
I have an age check for my users in which if they want to sign up for my app, they have to be a certain age.  I am using the devise gem, but created a method in my user model to check the age....I get an error stating that whatever I want to do they can't due to a nil class.  Basically i have a user, but the birth_date on the user is not saving.

Which tells me that where I am putting this logic is in the wrong place. However I'm not sure where.  I have a registration controller, and a user controller. I also have user model. I don't have a registration model, i'm wondering if either my method needs to be in a different model that I don't have? Or if i'm building it incorrectly.

My user model

```<code>class User < ActiveRecord::Base
  before_create :age_restriction

  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable

  def age_restriction
    if (self.birth_date&.to_date + 18.years) < Date.today # assuming dob format is mm/dd/yy
      errors.add :birth_date, 'must be older than 18'
    end
  end
end
</code>```

My registration model

```<code>Cass RegistrationsController < Devise::RegistrationsController
  before_action :configure_sign_up_params, only: :create
  before_action :configure_account_update_params, only: :update

  protected

  def configure_sign_up_params
    devise_parameter_sanitizer.permit(:sign_up, keys: [:bith_date, :first_name, :last_name])
    binding.pry
  end

  def configure_account_update_params
    devise_parameter_sanitizer.permit(:account_update, keys: [:birth_date, :first_name, :last_name])
  end
end
</code>```

The breakpoint I have in there, when I type in devise_parameter_sanitizer I get

```<code> @permitted=
  {:sign_in=>[:email, :password, :remember_me],
   :sign_up=>
    [:email, :password, :password_confirmation, :bith_date, :first_name, :last_name],
   :account_update=>[:email, :password, :password_confirmation, :current_password]},
 @resource_name=:user>
</code>```

答:
Typo. It's currently, :bith_date. Fix that to birth_date and the model should be able to read the proper attribute.

It was nil, since you're checking for self.birth_date, while the param you permitted is :bith_date

Allow :birth_date in the sign_up_params.

Title: Devise gem registration model issue

Body:
I have an age check for my users in which if they want to sign up for my app, they have to be a certain age.  I am using the devise gem, but created a method in my user model to check the age....I get an error stating that whatever I want to do they can't due to a nil class.  Basically i have a user, but the birth_date on the user is not saving.

Which tells me that where I am putting this logic is in the wrong place. However I'm not sure where.  I have a registration controller, and a user controller. I also have user model. I don't have a registration model, i'm wondering if either my method needs to be in a different model that I don't have? Or if i'm building it incorrectly.

My user model

class User < ActiveRecord::Base
  before_create :age_restriction

  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable

  def age_restriction
    if (self.birth_date&.to_date + 18.years) < Date.today # assuming dob format is mm/dd/yy
      errors.add :birth_date, 'must be older than 18'
    end
  end
end

My registration model

Cass RegistrationsController < Devise::RegistrationsController
  before_action :configure_sign_up_params, only: :create
  before_action :configure_account_update_params, only: :update

  protected

  def configure_sign_up_params
    devise_parameter_sanitizer.permit(:sign_up, keys: [:bith_date, :first_name, :last_name])
    binding.pry
  end

  def configure_account_update_params
    devise_parameter_sanitizer.permit(:account_update, keys: [:birth_date, :first_name, :last_name])
  end
end

The breakpoint I have in there, when I type in devise_parameter_sanitizer I get

 @permitted=
  {:sign_in=>[:email, :password, :remember_me],
   :sign_up=>
    [:email, :password, :password_confirmation, :bith_date, :first_name, :last_name],
   :account_update=>[:email, :password, :password_confirmation, :current_password]},
 @resource_name=:user>


来源: stackexchange

问:
ImageView image load logic from gallery
I am having 2 ImageView. I want to load image from gallery into ImageView. My requirement is, if I select the image 1st time, then image should be loaded into ImageView 1, and when I select image 2nd time, image should be loaded into ImageView 2.  </p>

```<code> -(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo :(NSDictionary *)info
        {
          int  count=0;

            iscamera=YES;
            _imageuser.image=[info objectForKey:UIImagePickerControllerOriginalImage];
            _imageuser1.image=[info objectForKey:UIImagePickerControllerOriginalImage];
            _imageuser2.image=[info objectForKey:UIImagePickerControllerOriginalImage];

            if (ipc.sourceType == UIImagePickerControllerSourceTypeSavedPhotosAlbum) {
                if (count==0) {
                    pngData = UIImagePNGRepresentation(_imageuser.image);
                    pngData = UIImagePNGRepresentation(_imageuser1.image);
                }

        else if (count== 1)
        {
            pngData = UIImagePNGRepresentation(_imageuser.image);
            pngData = UIImagePNGRepresentation(_imageuser2.image);
        }
                count ++;
            }

            else{
                pngData = UIImagePNGRepresentation([self rotateUIImage:_imageuser.image clockwise:YES]);

            }
            [picker dismissViewControllerAnimated:YES completion:nil];

        }
</code>```

答:
```<code>    //initialize count with 0
let count = 0
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
    imagePicker.dismiss(animated: true, completion: nil)
    // get image
  let capturedImage = info[UIImagePickerControllerOriginalImage] as? UIImage
    // you can set image to any imageview according to count value
   if(count == 0){
        firstImageView.image = capturedImage

    }else if (count == 1){

        secondImageView.image = capturedImage
    }else{

    }
    // increment count so that we can set image to appropriate image view
    count ++
}
</code>```

ContentLicense: CC BY-SA 3.0

Title: ImageView image load logic from gallery

Body:
I am having 2 ImageView. I want to load image from gallery into ImageView. My requirement is, if I select the image 1st time, then image should be loaded into ImageView 1, and when I select image 2nd time, image should be loaded into ImageView 2.

 -(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo :(NSDictionary *)info
        {
          int  count=0;

            iscamera=YES;
            _imageuser.image=[info objectForKey:UIImagePickerControllerOriginalImage];
            _imageuser1.image=[info objectForKey:UIImagePickerControllerOriginalImage];
            _imageuser2.image=[info objectForKey:UIImagePickerControllerOriginalImage];

            if (ipc.sourceType == UIImagePickerControllerSourceTypeSavedPhotosAlbum) {
                if (count==0) {
                    pngData = UIImagePNGRepresentation(_imageuser.image);
                    pngData = UIImagePNGRepresentation(_imageuser1.image);
                }

        else if (count== 1)
        {
            pngData = UIImagePNGRepresentation(_imageuser.image);
            pngData = UIImagePNGRepresentation(_imageuser2.image);
        }
                count ++;
            }

            else{
                pngData = UIImagePNGRepresentation([self rotateUIImage:_imageuser.image clockwise:YES]);

            }
            [picker dismissViewControllerAnimated:YES completion:nil];

        }


问:
List an entity from an Object via LINQ
I have the following Classes object.I want to list only PIds.

Classes.Select(x=>x.Entities) only returns me a list of Entities object. I need to query further to list only PId's.

```<code>Classes: [
{
  Id: "ea7c8653-0aa1xxxxxxx",
  Name: "Math",
  Entities: [
              {
               PId: "0552619b-5303-4ac5-a1d9-xxxxxx",
               Name: "Upper",
              },
              {
                PId: "0885214-5303-4ac5-a1d9-xxxxxx",
                Name: "Lower",
              },
              {
                PId: "6522145-5303-4ac5-a1d9-xxxxxx",
                Name: "Medium",
              }
          ]
     }
]
</code>```

答:
The problem.

I understand from your example that Classes is a list of class objects. Let's assume a simple class definition, for the sake of example:

```<code>public class MyClass
{
    public String Name { get; set; }
    public List<Entity> Entities { get; set; }
}
</code>```

Try and answer the following question: what is the type of names in the following snippet? Try to answer it, don't just read on.

```<code>var names = Classes.Select(x=>x.Name);
</code>```

 names is a List<String>, because MyClass.Name is of type String.

What is the type of entities in the following snippet? Try to answer it, don't just read on.

```<code>var entities = Classes.Select(x=>x.Entities);
</code>```

 entities is a List<List<Entity>>, because MyClass.Entities is of type List<Entity>.

This is important to understand: entities is not a list of entity objects, but rather a list of lists of entity objects. This makes a meaningful difference.

It is possible to turn a List<List<Entity>> into a List<Entity>.

SelectMany is used for exactly that reason. Essentially, it performs a normal Select, and then automatically merges the lists into one big list (usually called "flattening" the list).

```<code>var entities2 = Classes.SelectMany(x=>x.Entities);
</code>```

entities2 is a List<Entity>, because SelectMany() has flattened the List<List<Entity>> for you.

However, I'm not sure if this is what you want or not. It depends.

The solution.

It depends on what you want.

If you want a flat list of all pId values:

```<code>var pidList = Classes.SelectMany(c => c.Entities).Select(e => e.PId);
</code>```

In this case, pidList will be a List<string>.

If you want a separate list of pId values for every class object, i.e. without flattening the list:

```<code>var pidListPerClass = Classes.Select(c => c.Entities.Select(e => e.PId))
</code>```

In this case, pidList will be a List<List<string>>.

Footnote

  In case someone wishes to point it out, I'm not really focusing on whether the variable types are IEnumerable<T>, List<T> or any other collection type. The only meaningful distinction I'm trying to make is between a single object or a collection of objects. List is simply the easiest to understand and the shortest to type.

Title: List an entity from an Object via LINQ

Body:
I have the following Classes object.I want to list only PIds.

Classes.Select(x=>x.Entities) only returns me a list of Entities object. I need to query further to list only PId's.

Classes: [
{
  Id: "ea7c8653-0aa1xxxxxxx",
  Name: "Math",
  Entities: [
              {
               PId: "0552619b-5303-4ac5-a1d9-xxxxxx",
               Name: "Upper",
              },
              {
                PId: "0885214-5303-4ac5-a1d9-xxxxxx",
                Name: "Lower",
              },
              {
                PId: "6522145-5303-4ac5-a1d9-xxxxxx",
                Name: "Medium",
              }
          ]
     }
]

Body:
The problem.

I understand from your example that Classes is a list of class objects. Let's assume a simple class definition, for the sake of example:

public class MyClass
{
    public String Name { get; set; }
    public List<Entity> Entities { get; set; }
}

Try and answer the following question: what is the type of names in the following snippet? Try to answer it, don't just read on.

var names = Classes.Select(x=>x.Name);

 names is a List<String>, because MyClass.Name is of type String.

What is the type of entities in the following snippet? Try to answer it, don't just read on.

var entities = Classes.Select(x=>x.Entities);

 entities is a List<List<Entity>>, because MyClass.Entities is of type List<Entity>.

This is important to understand: entities is not a list of entity objects, but rather a list of lists of entity objects. This makes a meaningful difference.

It is possible to turn a List<List<Entity>> into a List<Entity>.

SelectMany is used for exactly that reason. Essentially, it performs a normal Select, and then automatically merges the lists into one big list (usually called "flattening" the list).

var entities2 = Classes.SelectMany(x=>x.Entities);

entities2 is a List<Entity>, because SelectMany() has flattened the List<List<Entity>> for you.

However, I'm not sure if this is what you want or not. It depends.

The solution.

It depends on what you want.

If you want a flat list of all pId values:

var pidList = Classes.SelectMany(c => c.Entities).Select(e => e.PId);

In this case, pidList will be a List<string>.

If you want a separate list of pId values for every class object, i.e. without flattening the list:

var pidListPerClass = Classes.Select(c => c.Entities.Select(e => e.PId))

In this case, pidList will be a List<List<string>>.

Footnote

  In case someone wishes to point it out, I'm not really focusing on whether the variable types are IEnumerable<T>, List<T> or any other collection type. The only meaningful distinction I'm trying to make is between a single object or a collection of objects. List is simply the easiest to understand and the shortest to type.


问:
Header guards in C++ and C
At LearnCpp.com | 1.10 — A first look at the preprocessor. Under Header guards, there are those code snippets:

add.h:

```<code>#include "mymath.h"
int add(int x, int y);
</code>```

subtract.h:

```<code>#include "mymath.h"
int subtract(int x, int y);
</code>```

main.cpp:

```<code>#include "add.h"
#include "subtract.h"
</code>```

In implementing the header guard, it is mentioned as follows:

```<code>#ifndef ADD_H
#define ADD_H

// your declarations here

#endif
</code>```

What could the declaration be here? And, should int main() come after #endif?

Is adding _H a convention or a must do thing?

Thanks.

答:
The FILENAME_H is a convention. If you really wanted, you could use #ifndef FLUFFY_KITTENS as a header guard (provided it was not defined anywhere else), but that would be a tricky bug if you defined it somewhere else, say as the number of kittens for something or other.

In the header file add.h the declarations are literally between #ifndef and #endif.

```<code>#ifndef ADD_H
#define ADD_H

#include "mymath.h"
int add(int x, int y);

#endif
</code>```

Finally, int main() shouldn't be in a header file. It should always be in a .cpp file.

To clear it up:

#ifndef ADD_H basically means "if ADD_H has not been #defined in the file or in an included file, then compile the code  between #ifndef and #endif directives". So if you try to #include "add.h" more than once in a .cpp file, the compiler will see what the ADD_H was already #defined and will ignore the code between #ifndef and #endif. Header guards only prevent a header file from being included multiple times in the same .cpp file. Header guards don't prevent other .cpp files from including the header file. But all .cpp files can include the guarded header file only once.

ContentLicense: CC BY-SA 4.0

Title: Header guards in C++ and C

Body:
At LearnCpp.com | 1.10 — A first look at the preprocessor. Under Header guards, there are those code snippets:

add.h:

#include "mymath.h"
int add(int x, int y);

subtract.h:

#include "mymath.h"
int subtract(int x, int y);

main.cpp:

#include "add.h"
#include "subtract.h"

In implementing the header guard, it is mentioned as follows:

#ifndef ADD_H
#define ADD_H

// your declarations here

#endif

What could the declaration be here? And, should int main() come after #endif?

Is adding _H a convention or a must do thing?

Thanks.

Body:
The FILENAME_H is a convention. If you really wanted, you could use #ifndef FLUFFY_KITTENS as a header guard (provided it was not defined anywhere else), but that would be a tricky bug if you defined it somewhere else, say as the number of kittens for something or other.

In the header file add.h the declarations are literally between #ifndef and #endif.

#ifndef ADD_H
#define ADD_H

#include "mymath.h"
int add(int x, int y);

#endif

Finally, int main() shouldn't be in a header file. It should always be in a .cpp file.

To clear it up:

#ifndef ADD_H basically means "if ADD_H has not been #defined in the file or in an included file, then compile the code  between #ifndef and #endif directives". So if you try to #include "add.h" more than once in a .cpp file, the compiler will see what the ADD_H was already #defined and will ignore the code between #ifndef and #endif. Header guards only prevent a header file from being included multiple times in the same .cpp file. Header guards don't prevent other .cpp files from including the header file. But all .cpp files can include the guarded header file only once.


问:
JSON-LD context vs. prefixes in Jena
The JSON-LD spec has an example showing a @context node being used to define the @type of a value.

In Jena, it seems a @context may be derived from a PrefixMap or specified by a JsonLDWriteContext (which has overloaded setters for a Java Object and a JSON string).

Can this example be achieved in Jena using the map approach or does it require the context object? Is there a Java Object that can be passed to create the JsonLDWriteContext in this example, or does a JSON string need to be parsed?

In other words, does Jena have any mechanism of deriving such a context without having the JSON explicitly provided?

```<code>{
  "@context":
  {
    "modified":
    {
      "@id": "http://purl.org/dc/terms/modified",
      "@type": "http://www.w3.org/2001/XMLSchema#dateTime"
    }
  },
...
  "@id": "http://example.com/docs/1",
  "modified": "2010-05-29T14:17:39+02:00",
...
}
</code>```

答:
There is a detailed set example at
https://github.com/apache/jena/blob/master/jena-arq/src-examples/arq/examples/riot/ExJsonLD.java

It includes an example passing in a JsonLdOptions object.

Title: JSON-LD context vs. prefixes in Jena

Body:
The JSON-LD spec has an example showing a @context node being used to define the @type of a value.

In Jena, it seems a @context may be derived from a PrefixMap or specified by a JsonLDWriteContext (which has overloaded setters for a Java Object and a JSON string).

Can this example be achieved in Jena using the map approach or does it require the context object? Is there a Java Object that can be passed to create the JsonLDWriteContext in this example, or does a JSON string need to be parsed?

In other words, does Jena have any mechanism of deriving such a context without having the JSON explicitly provided?

{
  "@context":
  {
    "modified":
    {
      "@id": "http://purl.org/dc/terms/modified",
      "@type": "http://www.w3.org/2001/XMLSchema#dateTime"
    }
  },
...
  "@id": "http://example.com/docs/1",
  "modified": "2010-05-29T14:17:39+02:00",
...
}


问:
How to handle downloads of an image from a nodejs server?
I am currently learning node.js, and recently came across a situation where I'd like to download an image stored on the server upon clicking a button on the webpage. I have created an endpoint, to which the controller passes two arguments:

- Name of the image to be downloaded (the directory is fixed)

- Name by which to download the image

I have tried the solutions given in Download a file from NodeJS Server using Express

I'm using angular to populate the buttons and trigger the download, as follows:

```<code><div class="btn-group" role="group" aria-label="Image tags">
    <button ng-repeat="tag in imageTags" type="button" class="btn btn-outline-warning" ng-click="download(tag)">{{tag}}</button>
</div>
</code>```

And here is my controller:

```<code>$scope.download = function(tagName) {
    tagName = tagName.replace(/\W+/g, '-');
    Clarifai.download(tagName, UploadSuccess.uploadedFile)
        // UploadSuccess.uploadedFile contains the name of the file to be downloaded.
        .success(function(data) {
            //do something
        });
}
</code>```

which calls the following factory method:

```<code>download: function(tagName, imageName) {
    return $http.get('/api/clarifai/tagDownload/' + tagName + "/" + imageName);
}
</code>```

And here's the relevant part of my routes file:

```<code>app.get('/api/clarifai/tagDownload/:tagName/:imageName', function(req, res) {
    // Ignore tagName for now.
    console.log("Begin download");
    var img = path.resolve('image_dump/OutputDump/' + req.params.imageName);
    // Returns the expected path for the file
    var filename = path.basename(img);
    var mimetype = mime.lookup(img);

    console.log(filename);
    console.log(mimetype);

    res.setHeader('Content-disposition', 'attachment; filename=' + filename);
    res.setHeader('Content-type', mimetype);

    var filestream = fs.createReadStream(img);
    filestream.pipe(res);
    res.on('finish', function(){
        console.log("Download complete");
    });
});
</code>```

So all the flow works till this point, and upon clicking one of the buttons, I get the output as follows:

```<code>Begin download
Jon-1477683540996.jpg
image/jpeg
GET /api/clarifai/tagDownload/people/Jon-1477683540996.jpg 200 5.296 ms -
Download complete
</code>```

But I see no sign of the downloaded file anywhere. No dialogs on any browser. All answers I've read so far seem to mention that the download is handled by the pipe call. But with no success for me.

I have also tried res.download(img), but with the same results.

My approach has been to handle this using the callback inside the controller. But I'm unable to figure out how to do so. What am I missing / doing wrong? Can somebody please point me in the right direction?

Thank you in advance.

答:
For the sake of completeness, here's how I solved the problem:

In my controller, instead of using:

$http.get('/api/clarifai/tagDownload/' + tagName + "/" + imageName);
```

<p>I had to do:</p>

<pre class="lang-js prettyprint-override"><code>path = "/api/clarifai/tagDownload/" + tagName + "/" + imageName;
$window.location.href = path;
</code>```

As adeneo had pointed out, the reason to this was that clicking on a button in Angular doesn't redirect. So, this had to be manually triggered using Angular's $window.location.href API.

Some alternate ways to do this can also be found in this answer: Using $window or $location to Redirect in AngularJS

Body:
I am currently learning node.js, and recently came across a situation where I'd like to download an image stored on the server upon clicking a button on the webpage. I have created an endpoint, to which the controller passes two arguments:

- Name of the image to be downloaded (the directory is fixed)

- Name by which to download the image

I have tried the solutions given in Download a file from NodeJS Server using Express

I'm using angular to populate the buttons and trigger the download, as follows:

    <button ng-repeat="tag in imageTags" type="button" class="btn btn-outline-warning" ng-click="download(tag)">{{tag}}</button>

And here is my controller:

$scope.download = function(tagName) {
    tagName = tagName.replace(/\W+/g, '-');
    Clarifai.download(tagName, UploadSuccess.uploadedFile)
        // UploadSuccess.uploadedFile contains the name of the file to be downloaded.
        .success(function(data) {
            //do something
        });
}

which calls the following factory method:

download: function(tagName, imageName) {
    return $http.get('/api/clarifai/tagDownload/' + tagName + "/" + imageName);
}

And here's the relevant part of my routes file:

app.get('/api/clarifai/tagDownload/:tagName/:imageName', function(req, res) {
    // Ignore tagName for now.
    console.log("Begin download");
    var img = path.resolve('image_dump/OutputDump/' + req.params.imageName);
    // Returns the expected path for the file
    var filename = path.basename(img);
    var mimetype = mime.lookup(img);

    console.log(filename);
    console.log(mimetype);

    res.setHeader('Content-disposition', 'attachment; filename=' + filename);
    res.setHeader('Content-type', mimetype);

    var filestream = fs.createReadStream(img);
    filestream.pipe(res);
    res.on('finish', function(){
        console.log("Download complete");
    });
});

So all the flow works till this point, and upon clicking one of the buttons, I get the output as follows:

Begin download
Jon-1477683540996.jpg
image/jpeg
GET /api/clarifai/tagDownload/people/Jon-1477683540996.jpg 200 5.296 ms -
Download complete

But I see no sign of the downloaded file anywhere. No dialogs on any browser. All answers I've read so far seem to mention that the download is handled by the pipe call. But with no success for me.

I have also tried res.download(img), but with the same results.

My approach has been to handle this using the callback inside the controller. But I'm unable to figure out how to do so. What am I missing / doing wrong? Can somebody please point me in the right direction?

Thank you in advance.

Body:
For the sake of completeness, here's how I solved the problem:

In my controller, instead of using:

$http.get('/api/clarifai/tagDownload/' + tagName + "/" + imageName);

I had to do:

path = "/api/clarifai/tagDownload/" + tagName + "/" + imageName;
$window.location.href = path;

As adeneo had pointed out, the reason to this was that clicking on a button in Angular doesn't redirect. So, this had to be manually triggered using Angular's $window.location.href API.

Some alternate ways to do this can also be found in this answer: Using $window or $location to Redirect in AngularJS


问:
options_for_select with multiple values

What I'm trying to get is a dropdown with 2 fields (name and account_code) as a value

<option value="1">ACC: John Doe</option>

But current code

```<code><%= select_tag :user_id, options_for_select(@users.map{|u| [u.name, u.account_code] }) %>
</code>```

outputs the following:
<option value="1">John Doe</option>

How do I make it display both user's account_code and name? Thanks!

答:
Try this:

```<code><%= select_tag :user_id, options_for_select(@users.map{|u| [u&.account_code+" "+u&.name, u.account_code] }) %>
</code>```

Hope this helps you.

Title: options_for_select with multiple values

Body:
What I'm trying to get is a dropdown with 2 fields (name and account_code) as a value

<option value="1">ACC: John Doe</option>

But current code

<%= select_tag :user_id, options_for_select(@users.map{|u| [u.name, u.account_code] }) %>

outputs the following:
<option value="1">John Doe</option>

How do I make it display both user's account_code and name? Thanks!

Body:
Try this:

<%= select_tag :user_id, options_for_select(@users.map{|u| [u&.account_code+" "+u&.name, u.account_code] }) %>

Hope this helps you.


问:
pyqt5 dialog not showing any widgets
I have created a dialog with Qt Creator and then translated the .ui file to .py file with

```<code> pyuic5 dialog.ui -o dialog.py
</code>```

The resulting code is the following

```<code>class Ui_dialog(object):
    def setupUi(self, dialog):
        dialog.setObjectName("dialog")
        dialog.resize(976, 725)
        self.verticalLayoutWidget = QtWidgets.QWidget(dialog)
        self.verticalLayoutWidget.setGeometry(QtCore.QRect(360, 210, 160, 80))
        self.verticalLayoutWidget.setObjectName("verticalLayoutWidget")
        self.verticalLayout = QtWidgets.QVBoxLayout(self.verticalLayoutWidget)
        self.verticalLayout.setObjectName("verticalLayout")
        self.pushButton = QtWidgets.QPushButton(self.verticalLayoutWidget)
        self.pushButton.setObjectName("pushButton")
        self.verticalLayout.addWidget(self.pushButton)

        self.retranslateUi(dialog)
        QtCore.QMetaObject.connectSlotsByName(dialog)

    def retranslateUi(self, dialog):
        _translate = QtCore.QCoreApplication.translate
        dialog.setWindowTitle(_translate("dialog", "Dialog"))
        self.pushButton.setText(_translate("dialog", "PushButton"))
</code>```

Now I'm trying to display the dialog from my main window with

```<code>dialog = QDialog()
dialog.ui = Ui_dialog()
dialog.ui.setupUi(self)
dialog.show()
dialog.exec_()
</code>```

The dialog is shown, but it's empty so there's no button or any other widgets I tried!?

答:
Ui_Dialog's setupUi method requires a widget to fill in, and in your case you should change the following:

```<code>dialog.ui.setupUi(self)
</code>```

to:

```<code>dialog.ui.setupUi(dialog)
</code>```

Title: pyqt5 dialog not showing any widgets

Body:
I have created a dialog with Qt Creator and then translated the .ui file to .py file with

 pyuic5 dialog.ui -o dialog.py

The resulting code is the following

class Ui_dialog(object):
    def setupUi(self, dialog):
        dialog.setObjectName("dialog")
        dialog.resize(976, 725)
        self.verticalLayoutWidget = QtWidgets.QWidget(dialog)
        self.verticalLayoutWidget.setGeometry(QtCore.QRect(360, 210, 160, 80))
        self.verticalLayoutWidget.setObjectName("verticalLayoutWidget")
        self.verticalLayout = QtWidgets.QVBoxLayout(self.verticalLayoutWidget)
        self.verticalLayout.setObjectName("verticalLayout")
        self.pushButton = QtWidgets.QPushButton(self.verticalLayoutWidget)
        self.pushButton.setObjectName("pushButton")
        self.verticalLayout.addWidget(self.pushButton)

        self.retranslateUi(dialog)
        QtCore.QMetaObject.connectSlotsByName(dialog)

    def retranslateUi(self, dialog):
        _translate = QtCore.QCoreApplication.translate
        dialog.setWindowTitle(_translate("dialog", "Dialog"))
        self.pushButton.setText(_translate("dialog", "PushButton"))

Now I'm trying to display the dialog from my main window with

dialog = QDialog()
dialog.ui = Ui_dialog()
dialog.ui.setupUi(self)
dialog.show()
dialog.exec_()

The dialog is shown, but it's empty so there's no button or any other widgets I tried!?

Body:
Ui_Dialog's setupUi method requires a widget to fill in, and in your case you should change the following:

dialog.ui.setupUi(self)

to:

dialog.ui.setupUi(dialog)


问:
explicit instantiation of static variable of a template class in different translation units
I was working with a template class that contains a static variable. The structure of code is as follows.

Header.h

```<code>template<class T> class Foo
{
public:
    static int count;
    Foo() {
        count++;
    }
    void printCount() {
        cout << count << endl;
    }
};
template<class T> int Foo<T>::count;
</code>```

Source.cpp

```<code>#include "Header.h"
template<> int Foo<int>::count = 5;
</code>```

main.cpp

```<code>#include <iostream>
using namespace std;
#include "Header.h"
int main()
{
    Foo<int> obj1;
    Foo<int> obj2;
    obj1.printCount();
    obj2.printCount();
    return 0;
}
</code>```

the output on xcode8.3.3 is:

```<code> 7
 7
</code>```

whereas the output on Visual Studio 2015 is:

```<code>2
2
</code>```

i.e. the specific instantiation overrides the generic instantiation in xcode8.3.3 but not in Visual Studio 2015.
Could someone explain this difference in behavior?
Thanks in advance.

答:
Your program is not valid:

[temp.expl.spec#6] If a template, a member template or a member of a class template is explicitly specialized then that specialization shall be declared before the first use of that specialization that would cause an implicit instantiation to take place, in every translation unit in which such a use occurs; no diagnostic is required.

in other words, translation units should agree on what a template name means.

The next standard paragraph laconically goes on with:

The placement of explicit specialization declarations for [... basically, any template whatsoever ...], can affect whether a program is well-formed according to the relative positioning of the explicit specialization declarations and their points of instantiation in the translation unit as specified above and below.
  When writing a specialization, be careful about its location; or to make it compile will be such a trial as to kindle its self-immolation.

Body:
I was working with a template class that contains a static variable. The structure of code is as follows.

Header.h

template<class T> class Foo
{
public:
    static int count;
    Foo() {
        count++;
    }
    void printCount() {
        cout << count << endl;
    }
};
template<class T> int Foo<T>::count;

Source.cpp

#include "Header.h"
template<> int Foo<int>::count = 5;

main.cpp

#include <iostream>
using namespace std;
#include "Header.h"
int main()
{
    Foo<int> obj1;
    Foo<int> obj2;
    obj1.printCount();
    obj2.printCount();
    return 0;
}

the output on xcode8.3.3 is:

 7
 7

whereas the output on Visual Studio 2015 is:

2
2

i.e. the specific instantiation overrides the generic instantiation in xcode8.3.3 but not in Visual Studio 2015.
Could someone explain this difference in behavior?
Thanks in advance.


问:
MongoDB: How to get the last updated timestamp of the last updated document in a collection
Is there a simple OR elegant method (or query that I can write) to retrieve the last updated timestamp (of the last updated document) in a collection. I can write a query like this to find the last inserted document

```<code>db.collection.find().limit(1).sort({$natural:-1})
</code>```

but I need information about the last updated document (it could be an insert or an update).

I know that one way is to query the oplog collection for the last record from a collection. But it seems like an expensive operation given the fact that oplog could be of very large size (also not trustworthy as it is a capped collection). Is there a better way to do this?

Thanks!

答:
You could get the last insert time same way you mentioned in the question:

```<code>db.collection.find().sort({'_id': -1}).limit(1)
</code>```

But, There isn't any good way to see the last update/delete time. But, If you are using replica sets you could get that from the oplog.

Or, you could add new field in document as 'lastModified'.
You can also checkout collection-hooks. I hope this will help

Body:
Is there a simple OR elegant method (or query that I can write) to retrieve the last updated timestamp (of the last updated document) in a collection. I can write a query like this to find the last inserted document

db.collection.find().limit(1).sort({$natural:-1})

but I need information about the last updated document (it could be an insert or an update).

I know that one way is to query the oplog collection for the last record from a collection. But it seems like an expensive operation given the fact that oplog could be of very large size (also not trustworthy as it is a capped collection). Is there a better way to do this?

Thanks!

Body:
You could get the last insert time same way you mentioned in the question:

db.collection.find().sort({'_id': -1}).limit(1)

But, There isn't any good way to see the last update/delete time. But, If you are using replica sets you could get that from the oplog.

Or, you could add new field in document as 'lastModified'.
You can also checkout collection-hooks. I hope this will help


问:
Extracting, and then use in a comparison, the object type within a vector appropriately. c++
I have a vector of pointers to vehicles which contains vehicles like cars, lorries, motorcycles. These vehicles have positions associated with them and these positions are tracked and drawn using drawPoint() in QT. I would like to know how to implement an alternative way of checking the object type of each element, i.e, without using typeid.

```<code>for (unsigned int jV = 0; jV < fRoadDisp->getCurrentLane(iLane)->getNVehiclesinLane(); jV++)
   {
       //QPainter painter(this); //already done outside loop
       QPen pointpenv(Qt::red);
       pointpenv.setWidth(5);
       QPen pointpenC(Qt::blue); // For a Car
       pointpenC.setWidth(5);
       QPen pointpenL(Qt::green); // For a Lorry
       pointpenL.setWidth(5);
       QPen pointpenM(Qt::yellow); // For a Motorcycle
       pointpenM.setWidth(5);

       double position = fRoadDisp->getCurrentLane(iLane)->getCurrentVehicle(jV)->getPosition();

       if(typeid(fRoadDisp->getCurrentLane(iLane)->getCurrentVehicle(jV)) == typeid(Car*)){painter.setPen(pointpenC);}
       else if(typeid(fRoadDisp->getCurrentLane(iLane)->getCurrentVehicle(jV)) == typeid(Lorry*)){painter.setPen(pointpenL);}
       else if(typeid(fRoadDisp->getCurrentLane(iLane)->getCurrentVehicle(jV)) == typeid(Motorcycle*)){painter.setPen(pointpenM);}

       painter.drawPoint(((iLane * (width()/fRoadDisp->getNLanes())) + width()/(2 *   fRoadDisp->getNLanes())), position * height()/300);
   }
</code>```

The above loops over all the vehicles in a vector of pointers to vehicles and just makes available different coloured pens for different vehicles, and, depending on which type of vehicle is being drawn, I would like the appropriate pen to be activated.

Currently, any points just appear white. A possible solution (I have been told) is to use static public variables, but I am not sure how to implement this in place of typeid.

Any help would be appreciated.

答:
I would solve this problem in the following way:

Declare an abstract class Vehicle, such ass:

```<code>class Vehicle
{
public:
  enum Type
  {
    Car,
    Lorry
  }
  virtual Type getType() const = 0;
};
</code>```

Derive all vehicle classes from this Vehicle class:

```<code>class Car : public Vehicle
{
  public:
  Type getType() const override { return Vehicle::Car; }
};
</code>```

etc.

In your drawing routines you will need to just:

```<code>if (fRoadDisp->getCurrentLane(iLane)->getCurrentVehicle(jV)->getType == Vehicle::Car)
{
  painter.setPen(pointpenC);
}
</code>```

Body:
I have a vector of pointers to vehicles which contains vehicles like cars, lorries, motorcycles. These vehicles have positions associated with them and these positions are tracked and drawn using drawPoint() in QT. I would like to know how to implement an alternative way of checking the object type of each element, i.e, without using typeid.

for (unsigned int jV = 0; jV < fRoadDisp->getCurrentLane(iLane)->getNVehiclesinLane(); jV++)
   {
       //QPainter painter(this); //already done outside loop
       QPen pointpenv(Qt::red);
       pointpenv.setWidth(5);
       QPen pointpenC(Qt::blue); // For a Car
       pointpenC.setWidth(5);
       QPen pointpenL(Qt::green); // For a Lorry
       pointpenL.setWidth(5);
       QPen pointpenM(Qt::yellow); // For a Motorcycle
       pointpenM.setWidth(5);

       double position = fRoadDisp->getCurrentLane(iLane)->getCurrentVehicle(jV)->getPosition();

       if(typeid(fRoadDisp->getCurrentLane(iLane)->getCurrentVehicle(jV)) == typeid(Car*)){painter.setPen(pointpenC);}
       else if(typeid(fRoadDisp->getCurrentLane(iLane)->getCurrentVehicle(jV)) == typeid(Lorry*)){painter.setPen(pointpenL);}
       else if(typeid(fRoadDisp->getCurrentLane(iLane)->getCurrentVehicle(jV)) == typeid(Motorcycle*)){painter.setPen(pointpenM);}

       painter.drawPoint(((iLane * (width()/fRoadDisp->getNLanes())) + width()/(2 *   fRoadDisp->getNLanes())), position * height()/300);
   }

The above loops over all the vehicles in a vector of pointers to vehicles and just makes available different coloured pens for different vehicles, and, depending on which type of vehicle is being drawn, I would like the appropriate pen to be activated.

Currently, any points just appear white. A possible solution (I have been told) is to use static public variables, but I am not sure how to implement this in place of typeid.

Any help would be appreciated.

Body:
I would solve this problem in the following way:

Declare an abstract class Vehicle, such ass:

class Vehicle
{
public:
  enum Type
  {
    Car,
    Lorry
  }
  virtual Type getType() const = 0;
};

Derive all vehicle classes from this Vehicle class:

class Car : public Vehicle
{
  public:
  Type getType() const override { return Vehicle::Car; }
};

etc.

In your drawing routines you will need to just:

if (fRoadDisp->getCurrentLane(iLane)->getCurrentVehicle(jV)->getType == Vehicle::Car)
{
  painter.setPen(pointpenC);
}


问:
Creating an instance from String in Java
If I have 2 classes, "A" and "B", how can I create a generic factory so I will only need to pass the class name as a string to receive an instance?

Example:

```<code>public static void factory(String name) {
     // An example of an implmentation I would need, this obviously doesn't work
      return new name.CreateClass();
}
</code>```

Thanks!

Joel

答:
```<code>Class c= Class.forName(className);
return c.getDeclaredConstructor().newInstance();//assuming you aren't worried about constructor .
</code>```

javadoc

For invoking constructor with argument

```<code> public static Object createObject(Constructor constructor,
      Object[] arguments) {

    System.out.println("Constructor: " + constructor.toString());
    Object object = null;

    try {
      object = constructor.newInstance(arguments);
      System.out.println("Object: " + object.toString());
      return object;
    } catch (InstantiationException e) {
      //handle it
    } catch (IllegalAccessException e) {
      //handle it
    } catch (IllegalArgumentException e) {
      //handle it
    } catch (InvocationTargetException e) {
      //handle it
    }
    return object;
  }
}
</code>```

have a look

ContentLicense: CC BY-SA 2.5

Body:
If I have 2 classes, "A" and "B", how can I create a generic factory so I will only need to pass the class name as a string to receive an instance?

Example:

public static void factory(String name) {
     // An example of an implmentation I would need, this obviously doesn't work
      return new name.CreateClass();
}

Thanks!

Joel

Body:
Class c= Class.forName(className);
return c.getDeclaredConstructor().newInstance();//assuming you aren't worried about constructor .

javadoc

For invoking constructor with argument

 public static Object createObject(Constructor constructor,
      Object[] arguments) {

    System.out.println("Constructor: " + constructor.toString());
    Object object = null;

    try {
      object = constructor.newInstance(arguments);
      System.out.println("Object: " + object.toString());
      return object;
    } catch (InstantiationException e) {
      //handle it
    } catch (IllegalAccessException e) {
      //handle it
    } catch (IllegalArgumentException e) {
      //handle it
    } catch (InvocationTargetException e) {
      //handle it
    }
    return object;
  }
}

have a look


问:
How to implement eloquent 'saving' event for all models , not individually
Based on  documentation of laravel eloquent event, all the eloquent event are triggered individually based on each model, is there any way to use 'creating' event or any other eloquent event to be triggered by all the Models

For example , if any Models is created , event A is triggered

答:
Listen for the Eloquent creating event that is fired. It is a 'string' event still not an object so you can do some ... wildcard matching here.

This is the string of the events that are fired from Eloquent:

```<code>"eloquent.{$event}: ".static::class
</code>```

So you could listen for "eloquent.creating: *" to catch all those string events for Eloquent creating for any Model.

```<code>Event::listen('eloquent.creating: *', function ($event, $model) {
    ....
});
</code>```

Obviously if you have defined your model to use custom event objects this would not be able to catch those.

You also could make a model observer, but you would have to register it to every model in your application you wanted to catch events for.

Body:
Listen for the Eloquent creating event that is fired. It is a 'string' event still not an object so you can do some ... wildcard matching here.

This is the string of the events that are fired from Eloquent:

"eloquent.{$event}: ".static::class

So you could listen for "eloquent.creating: *" to catch all those string events for Eloquent creating for any Model.

Event::listen('eloquent.creating: *', function ($event, $model) {
    ....
});

Obviously if you have defined your model to use custom event objects this would not be able to catch those.

You also could make a model observer, but you would have to register it to every model in your application you wanted to catch events for.


问:
How to count number of ObjectId occurrences in an array of ObjectIds' and attach the result to each document that is being returned?
I have a Tag schema:

```<code>const TagSchema = new Schema({
  label: {type: String, unique: true, minlength: 2},
  updatedAt: {type: Date, default: null},
  createdAt: {type: Date, default: new Date(), required: true},
  createdBy: {type: mongoose.Schema.Types.ObjectId, ref: 'Account', default: null}
});

const Tag = mongoose.model('Tag', TagSchema);
</code>```

Then I have a Page schema:

```<code>const PageSchema = new Schema({
  tags: {type: [{type: mongoose.Schema.Types.ObjectId, ref: 'Tag'}], default: [], maxlength: 5}
});

const Page = mongoose.model('Page', PageSchema);
</code>```

As you can see it contains a Tag reference in its tags array.

Now what I need to do is when I fetch all tags via /tags, I also need to count the number of times each tag is used in all Pages.

So if a Tag is used 2times across all Pages, it should set an .occurrences property on the returned tag. For example this would be a response from /tags:

```<code>[
 {_id: '192398dsf7asdsdds8f7d', label: 'tag 1', updatedAt: '20170102', createdAt: '20170101', createdBy: '01238198dsad8s7d78ad7', occurrences: 2},
 {_id: '19239asdasd8dsf7ds8f7d', label: 'tag 2', updatedAt: '20170102', createdAt: '20170101', createdBy: '01238198dsad8s7d78ad7', occurrences: 1},
 {_id: '192398dsf7zxccxads8f7d', label: 'tag 1', updatedAt: '20170102', createdAt: '20170101', createdBy: '01238198dsad8s7d78ad7', occurrences: 5},
]
</code>```

I would have imagined that I could achieve this pretty easily in a mongoose pre('find') hook like this:

```<code>TagSchema.pre('find', function() {

  Page.count({tags: this._id}, (err, total) => {
    this.occurrences = total;
  });
});
</code>```

However, there are two problems here:

Page.count throws an error saying it's not a function, which I don't understand why because I use it somewhere else perfectly fine. And Page has been imported properly. Suggesting that you can't use count in a hook or something similar.

this is not the Tag document.

So I guess that the way I am going about this is completely wrong.

Since I am a novice in MongoDB maybe someone can provide me with a better, working, solution to my problem?

答:
Ok first, you need getQuery() this allows you to access the properties that you are finding the tag with. so if you find the tag by _id, you will have access to it in the pre hook by this.getQuery()._id

Second, you are going to need to use the "Parallel" middleware, can be found in the docs. This allows the find method to wait until the done function is called, so it is gonna wait until the tag is updated with the new occurrences number.

As the object can no be accessed inn the pre hook as it is yet to be found, you are going to have to use findOneAndUpdate method in the pre hook.

So the code should look like :

The find method :

```<code>Tag.find({ _id: "foo"}, function (err, foundTag) {
  console.log(foundTag)
})
</code>```

The pre hook :

```<code>TagSchema.pre('find', true, function (next, done) {
  mongoose.models['Page'].count({ tags: this.getQuery()._id }, (err, total) => {
    mongoose.models['Tag'].findOneAndUpdate({ _id: this.getQuery()._id }, { occurrences: total }, function () {
      next()
      done()
    })
  });
});
</code>```

Body:
I have a Tag schema:

const TagSchema = new Schema({
  label: {type: String, unique: true, minlength: 2},
  updatedAt: {type: Date, default: null},
  createdAt: {type: Date, default: new Date(), required: true},
  createdBy: {type: mongoose.Schema.Types.ObjectId, ref: 'Account', default: null}
});

const Tag = mongoose.model('Tag', TagSchema);

Then I have a Page schema:

const PageSchema = new Schema({
  tags: {type: [{type: mongoose.Schema.Types.ObjectId, ref: 'Tag'}], default: [], maxlength: 5}
});

const Page = mongoose.model('Page', PageSchema);

As you can see it contains a Tag reference in its tags array.

Now what I need to do is when I fetch all tags via /tags, I also need to count the number of times each tag is used in all Pages.

So if a Tag is used 2times across all Pages, it should set an .occurrences property on the returned tag. For example this would be a response from /tags:

[
 {_id: '192398dsf7asdsdds8f7d', label: 'tag 1', updatedAt: '20170102', createdAt: '20170101', createdBy: '01238198dsad8s7d78ad7', occurrences: 2},
 {_id: '19239asdasd8dsf7ds8f7d', label: 'tag 2', updatedAt: '20170102', createdAt: '20170101', createdBy: '01238198dsad8s7d78ad7', occurrences: 1},
 {_id: '192398dsf7zxccxads8f7d', label: 'tag 1', updatedAt: '20170102', createdAt: '20170101', createdBy: '01238198dsad8s7d78ad7', occurrences: 5},
]

I would have imagined that I could achieve this pretty easily in a mongoose pre('find') hook like this:

TagSchema.pre('find', function() {

  Page.count({tags: this._id}, (err, total) => {
    this.occurrences = total;
  });
});

However, there are two problems here:

Page.count throws an error saying it's not a function, which I don't understand why because I use it somewhere else perfectly fine. And Page has been imported properly. Suggesting that you can't use count in a hook or something similar.

this is not the Tag document.

So I guess that the way I am going about this is completely wrong.

Since I am a novice in MongoDB maybe someone can provide me with a better, working, solution to my problem?

Body:
Ok first, you need getQuery() this allows you to access the properties that you are finding the tag with. so if you find the tag by _id, you will have access to it in the pre hook by this.getQuery()._id

Second, you are going to need to use the "Parallel" middleware, can be found in the docs. This allows the find method to wait until the done function is called, so it is gonna wait until the tag is updated with the new occurrences number.

As the object can no be accessed inn the pre hook as it is yet to be found, you are going to have to use findOneAndUpdate method in the pre hook.

So the code should look like :

The find method :

Tag.find({ _id: "foo"}, function (err, foundTag) {
  console.log(foundTag)
})

The pre hook :

TagSchema.pre('find', true, function (next, done) {
  mongoose.models['Page'].count({ tags: this.getQuery()._id }, (err, total) => {
    mongoose.models['Tag'].findOneAndUpdate({ _id: this.getQuery()._id }, { occurrences: total }, function () {
      next()
      done()
    })
  });
});


答:
Extend the model class:

```<code>use Auth;
use Illuminate\Database\Eloquent\Model;

class GeneralModel extends Model
{
  public static function boot()
  {
    parent::boot();

    static::creating(function ($model) {
        if (Auth::user()) {
            $model->created_by = Auth::user()->id;
            $model->updated_by = Auth::user()->id;
        }
    });
  }
}
</code>```

When you say create a say property object, it will be triggered. Use it for all the models you need this.

```<code>class Property extends GeneralModel
{
  //..
}
</code>```

Title: How to implement eloquent 'saving' event for all models , not individually

Body:
Based on  documentation of laravel eloquent event, all the eloquent event are triggered individually based on each model, is there any way to use 'creating' event or any other eloquent event to be triggered by all the Models

For example , if any Models is created , event A is triggered

Body:
Extend the model class:

use Auth;
use Illuminate\Database\Eloquent\Model;

class GeneralModel extends Model
{
  public static function boot()
  {
    parent::boot();

    static::creating(function ($model) {
        if (Auth::user()) {
            $model->created_by = Auth::user()->id;
            $model->updated_by = Auth::user()->id;
        }
    });
  }
}

When you say create a say property object, it will be triggered. Use it for all the models you need this.

class Property extends GeneralModel
{
  //..
}


问:
How to retrieve timestamp along with minimum value within an elastic aggregation
I am executing aggregations query on an elastic dataset
I want to retrieve the maximum and minimum values over a timespan
I achieve this with

```<code>"aggs": {
    "DateRangeFilter": {
      "filter": {
        "range": {
          "@timestamp": {
            "gte": "2015-10-16T11:13:17.000",
            "lte": "2015-10-16T12:29:47.000"
          }
        }
      },
      "aggs": {
        "min_chan4": {
          "min": {
            "field": "ch_004"
          }
        },
        "max_chan4": {
          "max": {
            "field": "ch_004"
          }
}
</code>```

and this gives me:

```<code>"DateRangeFilter": {
    "doc_count": 153,
    "min_chan4": {
      "value": 0.7463656663894653
    },
    "max_chan4": {
      "value": 5.170884132385254
    }
</code>```

which is great.

What i need is also to retrieve the time that each of these occurred
My documents look like this:

```<code>    "_source": {
      "GroupId": "blahblah",
      "@timestamp": "2015-10-14T12:41:30Z",
      "ch_004": 1.5608633995056154
    }
</code>```

so I would expect to be able to retrieve not only the min and max values over the given date range but also at what time (@timestamp) that min or max value was recorded

e.g. min value minX occurred at time t1, max value maxX occurred at time t2

答:
You can achieve it by using Top Hits Aggregation. example can be found here:</p>

```<code>{
  "aggs": {
    "DateRangeFilter": {
      "filter": {
        "range": {
          "@timestamp": {
            "gte": "2015-10-16T11:13:17.000",
            "lte": "2015-10-16T12:29:47.000"
          }
        }
      },
      "aggs": {
        "ch_004_min": {
          "top_hits": {
            "size": 1,
            "sort": [
              {
                "timestamp": {
                  "order": "asc"
                }
              }
            ]
          }
        },
        "ch_004_max": {
          "top_hits": {
            "size": 1,
            "sort": [
              {
                "timestamp": {
                  "order": "desc"
                }
              }
            ]
          }
        }
      }
    }
  }
}
</code>```

Body:
I am executing aggregations query on an elastic dataset
I want to retrieve the maximum and minimum values over a timespan
I achieve this with

"aggs": {
    "DateRangeFilter": {
      "filter": {
        "range": {
          "@timestamp": {
            "gte": "2015-10-16T11:13:17.000",
            "lte": "2015-10-16T12:29:47.000"
          }
        }
      },
      "aggs": {
        "min_chan4": {
          "min": {
            "field": "ch_004"
          }
        },
        "max_chan4": {
          "max": {
            "field": "ch_004"
          }
}

and this gives me:

"DateRangeFilter": {
    "doc_count": 153,
    "min_chan4": {
      "value": 0.7463656663894653
    },
    "max_chan4": {
      "value": 5.170884132385254
    }

which is great.

What i need is also to retrieve the time that each of these occurred
My documents look like this:

    "_source": {
      "GroupId": "blahblah",
      "@timestamp": "2015-10-14T12:41:30Z",
      "ch_004": 1.5608633995056154
    }

so I would expect to be able to retrieve not only the min and max values over the given date range but also at what time (@timestamp) that min or max value was recorded

e.g. min value minX occurred at time t1, max value maxX occurred at time t2

Body:
You can achieve it by using Top Hits Aggregation. example can be found here:

{
  "aggs": {
    "DateRangeFilter": {
      "filter": {
        "range": {
          "@timestamp": {
            "gte": "2015-10-16T11:13:17.000",
            "lte": "2015-10-16T12:29:47.000"
          }
        }
      },
      "aggs": {
        "ch_004_min": {
          "top_hits": {
            "size": 1,
            "sort": [
              {
                "timestamp": {
                  "order": "asc"
                }
              }
            ]
          }
        },
        "ch_004_max": {
          "top_hits": {
            "size": 1,
            "sort": [
              {
                "timestamp": {
                  "order": "desc"
                }
              }
            ]
          }
        }
      }
    }
  }
}


问:
do an exception on first td with Filter Table
He want to do an input box with a Filter Table options.
My input box is:

```<code><input class="form-control" id="myInput" type="text" placeholder="Search..">
</code>```

and this code to generate a table:

```<code>   $data = '<table class="table table-bordered table-striped">
                                            <tr>
                                                    <th>No.</th>
                                                    <th>Status</th>
                                                    <th>First Name</th>
                                                    <th>Last Name</th>
                                                    <th>Email Address</th>
                                                    <th>Update</th>
                                                    <th>Delete</th>
                                            </tr>';
    $query = "SELECT * FROM users";
</code>```

and my js is:

```<code>$(document).ready(function(){
  $("#myInput").on("keyup", function() {
    var value = $(this).val().toLowerCase();
    $("#myTable tr").filter(function() {
      $(this).toggle($(this).text().toLowerCase().indexOf(value) > -1)
    });
  });
});
</code>```

is it necessary to use a tbody or anything else to do a Filter Table?
or not’s possible to do an exception for the first  ?

very thanks!

答:
I do it!

Finally with this code:

```<code>$(function(){
    $("#myInput").on("keyup", function() {
        var $value = $(this).val().toLowerCase();
        $("#myTable tr:gt(0)").filter(function() {
            $(this).toggle($(this).text().toLowerCase().indexOf($value) > -1)
        });
    });
});
</code>```

Body:
He want to do an input box with a Filter Table options.
My input box is:

<input class="form-control" id="myInput" type="text" placeholder="Search..">

and this code to generate a table:

   $data = '

                                                    No.
                                                    Status
                                                    First Name
                                                    Last Name
                                                    Email Address
                                                    Update
                                                    Delete

';
    $query = "SELECT * FROM users";

and my js is:

$(document).ready(function(){
  $("#myInput").on("keyup", function() {
    var value = $(this).val().toLowerCase();
    $("#myTable tr").filter(function() {
      $(this).toggle($(this).text().toLowerCase().indexOf(value) > -1)
    });
  });
});

is it necessary to use a tbody or anything else to do a Filter Table?
or not’s possible to do an exception for the first  ?

very thanks!

Body:
I do it!

Finally with this code:

$(function(){
    $("#myInput").on("keyup", function() {
        var $value = $(this).val().toLowerCase();
        $("#myTable tr:gt(0)").filter(function() {
            $(this).toggle($(this).text().toLowerCase().indexOf($value) > -1)
        });
    });
});


问:
Change color of error messages in RMarkdown code output (HTML, PDF)
Is there a way to automatically make text color of errors red in R Markdown without manually editing the HTML later.

```<code>---
title: ""
---

#### Example 1

```{r e1, error = TRUE}
2 + "A"
```

#### Example 2

```{r e2, error = TRUE}
2 + 2
```
</code>```

In the above code, output of Example 1 would have to be red. Currently, I edit the generated HTML (add style="color:red;" to the appropriate tag) but I am wondering if there is an automatic way. Assume that it is not known before knitting whether the code will generate error.

答:
I stumbled here because I had the same question but for PDF output rather than HTML.

It turns out combining @Martin Schmelzer's Solution with some hints from @Yihui Xie found here helps to achieve the same behavior in a PDF output.

Add \usepackage{xcolor} to your YAML header and the following chunk to your .Rmd file.

```<code>```{r}
color_block = function(color) {
  function(x, options) sprintf('\\color{%s}\\begin{verbatim}%s\\end{verbatim}',
                               color, x)
}
knitr::knit_hooks$set(error = color_block('red'))
```
</code>```

The result is red error messages like

Body:
Is there a way to automatically make text color of errors red in R Markdown without manually editing the HTML later.

---
title: ""
---

#### Example 1

```{r e1, error = TRUE}
2 + "A"
```

#### Example 2

```{r e2, error = TRUE}
2 + 2
```

In the above code, output of Example 1 would have to be red. Currently, I edit the generated HTML (add style="color:red;" to the appropriate tag) but I am wondering if there is an automatic way. Assume that it is not known before knitting whether the code will generate error.

Body:
I stumbled here because I had the same question but for PDF output rather than HTML.

It turns out combining @Martin Schmelzer's Solution with some hints from @Yihui Xie found here helps to achieve the same behavior in a PDF output.

Add \usepackage{xcolor} to your YAML header and the following chunk to your .Rmd file.

```{r}
color_block = function(color) {
  function(x, options) sprintf('\\color{%s}\\begin{verbatim}%s\\end{verbatim}',
                               color, x)
}
knitr::knit_hooks$set(error = color_block('red'))
```

The result is red error messages like


问:
Why does my Android app keep telling me I need to define a ListView id when it is already defined?
Whenever I try to run my app, the following exception is thrown:

01-22 00:40:51.868: ERROR/AndroidRuntime(2219): java.lang.RuntimeException: Unable to start activity ComponentInfo{[Redacted]}: java.lang.RuntimeException: Your content must have a ListView whose id attribute is 'android.R.id.list'

Here is the markup for the ListView in question:

```<code><ListView
 android:id="@+id/list"
 android:layout_width="fill_parent"
 android:layout_height="fill_parent"
 android:dividerHeight="1px"></ListView>
</code>```

So, since the id is clearly defined as "list," what gives here? I've run through my code multiple times in the past couple of hours trying to track down the cause of this and I'm stumped. Can anyone offer any pointers?

答:
Probably your class ComponentInfo is extending the ListActivity therefore insure that your ListView object must have the following attribute in your layout XML file:

```<code>android:id="@android:id/list"
</code>```

Body:
Whenever I try to run my app, the following exception is thrown:

01-22 00:40:51.868: ERROR/AndroidRuntime(2219): java.lang.RuntimeException: Unable to start activity ComponentInfo{[Redacted]}: java.lang.RuntimeException: Your content must have a ListView whose id attribute is 'android.R.id.list'

Here is the markup for the ListView in question:

<ListView
 android:id="@+id/list"
 android:layout_width="fill_parent"
 android:layout_height="fill_parent"
 android:dividerHeight="1px"></ListView>

So, since the id is clearly defined as "list," what gives here? I've run through my code multiple times in the past couple of hours trying to track down the cause of this and I'm stumped. Can anyone offer any pointers?

Body:
Probably your class ComponentInfo is extending the ListActivity therefore insure that your ListView object must have the following attribute in your layout XML file:

android:id="@android:id/list"


问:
How to access local path from linux server java web application?
I've created a webapplication which creates folders when filling destination input ( for example => C:\xxx\xxx path).
When i run on my local (http:\localhost:8080), it works perfectly. it finds local windows path and creates folders.
But now i want to open this webapp to group of people, deployed tomcat on internal unix server (http:\ipnumber\portnumber).
The problem is that when user fills input with local destination, program code can not find the path or can not access local computer folder structure, it looks unix server folder structure.

How can i achieve this? I use angularjs for frontend with call restapi with http.post, the backend side is java.

```<code>    package com.ama.ist.controller;
    import java.util.HashMap;
    import java.util.Map;
    import java.util.UUID;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.http.HttpStatus;
    import org.springframework.http.ResponseEntity;
    import org.springframework.web.bind.annotation.CrossOrigin;
    import org.springframework.web.bind.annotation.RequestBody;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RequestMethod;
    import org.springframework.web.bind.annotation.RestController;
    import com.ama.ist.model.CustomErrorType;
    import com.ama.ist.model.Patch;
    import com.ama.ist.service.PatchService;
    @RestController
    public class PatchController {

    @Autowired
    private PatchService patchService;

    @CrossOrigin(origins = "http://ipnumber:portnumber")
    @RequestMapping(value = "/mk", method = RequestMethod.POST)
    public ResponseEntity<?> createFolder(@RequestBody Patch patch) {

        System.out.println("patch ddest: => " + patch.getDestination());
        String iscreatedstatus = patchService.create(patch);
        System.out.println("iscreatedstatus" + iscreatedstatus);
        if (!(iscreatedstatus.equals("Success"))) {
            System.out.println("if success" );
            return new ResponseEntity<Object>(new CustomErrorType("ER",iscreatedstatus), HttpStatus.NOT_FOUND);
        }
        System.out.println("if disinda success" );
            return new ResponseEntity<Object>(new CustomErrorType("OK",iscreatedstatus), HttpStatus.CREATED);
    }

//
    @RequestMapping("/resource")
      public Map<String,Object> home() {
        Map<String,Object> model = new HashMap<String,Object>();
        model.put("id", UUID.randomUUID().toString());
        model.put("content", "Hello World");
        return model;
      }

}
</code>```

This is Service

```<code>package com.ama.ist.service;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.springframework.stereotype.Service;
import org.tmatesoft.svn.core.SVNDepth;
import org.tmatesoft.svn.core.SVNException;
import org.tmatesoft.svn.core.SVNProperties;
import org.tmatesoft.svn.core.SVNURL;
import org.tmatesoft.svn.core.auth.BasicAuthenticationManager;
import org.tmatesoft.svn.core.auth.ISVNAuthenticationManager;
import org.tmatesoft.svn.core.wc.SVNCommitClient;
import org.tmatesoft.svn.core.wc.SVNWCUtil;

import com.ama.ist.model.Patch;
import com.ama.ist.model.User;

@Service
public class PatchService {

    public String create(Patch patch) {

        String ConstantPath = patch.getDestination();

        File testFile = new File("");
        String currentPath = testFile.getAbsolutePath();
        System.out.println("current path is: " + currentPath);

        System.out.println("ConstantPath => " + ConstantPath);
//      if (!(isValidPath(ConstantPath))) {
//          return "invalid Path";
//      }

        // System.out.println("Valid mi " + isValidPath(ConstantPath));

        String foldername = patch.getWinNum() + " - " + patch.getWinName();
        System.out.println(ConstantPath + foldername);

        File files = new File(ConstantPath + foldername);
        if (files.exists()) {
            return "The Folder is already created in that path";
        }

        File files1 = new File(ConstantPath + foldername + "\\Patch");
        File files2 = new File(ConstantPath + foldername + "\\Backup");
        File files3 = new File(ConstantPath + foldername + "\\Backup\\UAT");
        File files4 = new File(ConstantPath + foldername + "\\Backup\\PROD");

        if (!files.exists()) {
            if (files.mkdirs()) {
                files1.mkdir();
                files2.mkdir();
                files3.mkdir();
                files4.mkdir();

                createReadme(ConstantPath + foldername, patch);

                if (patch.isChecked()) {

                    System.out.println("patch.getDestination => " + patch.getDestination());
                    System.out.println("patch.getDetail => " + patch.getDetail());
                    System.out.println("patch.getSvnPath => " + patch.getSvnPath());
                    System.out.println("patch.getWinName => " + patch.getWinName());
                    System.out.println("patch.getWinNum => " + patch.getWinNum());

                    System.out.println("patch.getUserName => " + patch.getUser().getUserName());
                    System.out.println("patch.getPassword => " + patch.getUser().getPassword());
                    ImportSvn(patch);

                }

                System.out.println("Multiple directories are created!");
                return "Success";
            } else {
                System.out.println("Failed to create multiple directories!");
                return "Unknwon error";
            }
        } else {
            return "File name is already exists";
        }

    }

    public static boolean isValidPath(String path) {
        System.out.println("path => " + path);
        File f = new File(path);

        if (f.isDirectory()) {
            System.out.println("true => ");
            return true;
        } else {
            System.out.println("false => ");
            return false;
        }

    }

    public void createReadme(String path, Patch patch) {

        try {
            ClassLoader classLoader = getClass().getClassLoader();
            File file = new File(classLoader.getResource("Readme.txt").getFile());

            // System.out.println("!!!!!!!!!!" + new java.io.File("").getAbsolutePath());
            // File file = new File("resources/Readme.txt");
            System.out.println(file.getAbsolutePath());

            FileReader reader = new FileReader(file);
            BufferedReader bufferedReader = new BufferedReader(reader);

            String line;
            PrintWriter writer = new PrintWriter(path + "\\Readme.txt", "UTF-8");
            System.out.println(path + "\\Readme.txt");
            while ((line = bufferedReader.readLine()) != null) {

                line = line.replace("#Winnumber", Integer.toString(patch.getWinNum()));
                line = line.replace("#NameSurname", " ");
                line = line.replace("#Type", "Package");
                line = line.replace("#detail", patch.getDetail());

                SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
                String date = sdf.format(new Date());
                line = line.replace("#Date", date);

                line = line.replace("#Desc", patch.getWinName());

                writer.println(line);

                System.out.println(line);
            }
            reader.close();
            writer.close();

        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    public void ImportSvn(Patch patch) {

        String name = patch.getUser().getUserName();
        String password = patch.getUser().getPassword();
        // String filename = patch.getWinName()
        String filename = patch.getWinNum() + " - " + patch.getWinName();
        String url = patch.getSvnPath() + "/" + filename;

        ISVNAuthenticationManager authManager = new BasicAuthenticationManager(name, password);

        SVNCommitClient commitClient = new SVNCommitClient(authManager, SVNWCUtil.createDefaultOptions(true));
        File f = new File(patch.getDestination() + filename);
        try {
            String logMessage = filename;
            commitClient.doImport(f, // File/Directory to be imported
                    SVNURL.parseURIEncoded(url), // location within svn
                    logMessage, // svn comment
                    new SVNProperties(), // svn properties
                    true, // use global ignores
                    false, // ignore unknown node types
                    SVNDepth.INFINITY);
            // SVNClientManager cm =
            // SVNClientManager.newInstance(SVNWCUtil.createDefaultOptions(true),authManager);
            //
            // SVNUpdateClient uc = cm.getUpdateClient();
            // long[] l = uc.doUpdate(new File[]{dstPath},
            // SVNRevision.HEAD,SVNDepth.INFINITY, true,true);
        } catch (SVNException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

}
</code>```

This is Angularjs side

```<code>$scope.Create = function() {
    $scope.obj = [];
    console.log("$scope.svnPath" + $scope.patch.svnPath);
    console.log("$scope.userName" + $scope.patch.user.userName);
    $http({
        method : "POST",
        url : "http://ipnumber:port/patchinit/mk",
        data : $scope.patch
    }).then(function mySuccess(response) {

        console.log("Success!! ");
        $scope.obj = response.data;
        $scope.errorMessage = response.data.errorMessage;
        $scope.errorCode = response.data.errorCode;

    }, function myError(response) {

        //$scope.obj = response.statusText;
        $scope.errorMessage = response.data.errorMessage;
        $scope.errorCode = response.data.errorCode;

    });

}
</code>```

答:
You can share that folder on windows and mount that shared folder in unix. Once mounted, it can be easily accessed using samba(smb://192.168.1.117/Your_Folder).

Samba is standard on nearly all distributions of Linux and is commonly included as a basic system service on other Unix-based operating systems as well.

Body:
I've created a webapplication which creates folders when filling destination input ( for example => C:\xxx\xxx path).
When i run on my local (http:\localhost:8080), it works perfectly. it finds local windows path and creates folders.
But now i want to open this webapp to group of people, deployed tomcat on internal unix server (http:\ipnumber\portnumber).
The problem is that when user fills input with local destination, program code can not find the path or can not access local computer folder structure, it looks unix server folder structure.

How can i achieve this? I use angularjs for frontend with call restapi with http.post, the backend side is java.

    package com.ama.ist.controller;
    import java.util.HashMap;
    import java.util.Map;
    import java.util.UUID;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.http.HttpStatus;
    import org.springframework.http.ResponseEntity;
    import org.springframework.web.bind.annotation.CrossOrigin;
    import org.springframework.web.bind.annotation.RequestBody;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RequestMethod;
    import org.springframework.web.bind.annotation.RestController;
    import com.ama.ist.model.CustomErrorType;
    import com.ama.ist.model.Patch;
    import com.ama.ist.service.PatchService;
    @RestController
    public class PatchController {

    @Autowired
    private PatchService patchService;

    @CrossOrigin(origins = "http://ipnumber:portnumber")
    @RequestMapping(value = "/mk", method = RequestMethod.POST)
    public ResponseEntity<?> createFolder(@RequestBody Patch patch) {

        System.out.println("patch ddest: => " + patch.getDestination());
        String iscreatedstatus = patchService.create(patch);
        System.out.println("iscreatedstatus" + iscreatedstatus);
        if (!(iscreatedstatus.equals("Success"))) {
            System.out.println("if success" );
            return new ResponseEntity<Object>(new CustomErrorType("ER",iscreatedstatus), HttpStatus.NOT_FOUND);
        }
        System.out.println("if disinda success" );
            return new ResponseEntity<Object>(new CustomErrorType("OK",iscreatedstatus), HttpStatus.CREATED);
    }

//
    @RequestMapping("/resource")
      public Map<String,Object> home() {
        Map<String,Object> model = new HashMap<String,Object>();
        model.put("id", UUID.randomUUID().toString());
        model.put("content", "Hello World");
        return model;
      }

}

This is Service

package com.ama.ist.service;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.springframework.stereotype.Service;
import org.tmatesoft.svn.core.SVNDepth;
import org.tmatesoft.svn.core.SVNException;
import org.tmatesoft.svn.core.SVNProperties;
import org.tmatesoft.svn.core.SVNURL;
import org.tmatesoft.svn.core.auth.BasicAuthenticationManager;
import org.tmatesoft.svn.core.auth.ISVNAuthenticationManager;
import org.tmatesoft.svn.core.wc.SVNCommitClient;
import org.tmatesoft.svn.core.wc.SVNWCUtil;

import com.ama.ist.model.Patch;
import com.ama.ist.model.User;

@Service
public class PatchService {

    public String create(Patch patch) {

        String ConstantPath = patch.getDestination();

        File testFile = new File("");
        String currentPath = testFile.getAbsolutePath();
        System.out.println("current path is: " + currentPath);

        System.out.println("ConstantPath => " + ConstantPath);
//      if (!(isValidPath(ConstantPath))) {
//          return "invalid Path";
//      }

        // System.out.println("Valid mi " + isValidPath(ConstantPath));

        String foldername = patch.getWinNum() + " - " + patch.getWinName();
        System.out.println(ConstantPath + foldername);

        File files = new File(ConstantPath + foldername);
        if (files.exists()) {
            return "The Folder is already created in that path";
        }

        File files1 = new File(ConstantPath + foldername + "\\Patch");
        File files2 = new File(ConstantPath + foldername + "\\Backup");
        File files3 = new File(ConstantPath + foldername + "\\Backup\\UAT");
        File files4 = new File(ConstantPath + foldername + "\\Backup\\PROD");

        if (!files.exists()) {
            if (files.mkdirs()) {
                files1.mkdir();
                files2.mkdir();
                files3.mkdir();
                files4.mkdir();

                createReadme(ConstantPath + foldername, patch);

                if (patch.isChecked()) {

                    System.out.println("patch.getDestination => " + patch.getDestination());
                    System.out.println("patch.getDetail => " + patch.getDetail());
                    System.out.println("patch.getSvnPath => " + patch.getSvnPath());
                    System.out.println("patch.getWinName => " + patch.getWinName());
                    System.out.println("patch.getWinNum => " + patch.getWinNum());

                    System.out.println("patch.getUserName => " + patch.getUser().getUserName());
                    System.out.println("patch.getPassword => " + patch.getUser().getPassword());
                    ImportSvn(patch);

                }

                System.out.println("Multiple directories are created!");
                return "Success";
            } else {
                System.out.println("Failed to create multiple directories!");
                return "Unknwon error";
            }
        } else {
            return "File name is already exists";
        }

    }

    public static boolean isValidPath(String path) {
        System.out.println("path => " + path);
        File f = new File(path);

        if (f.isDirectory()) {
            System.out.println("true => ");
            return true;
        } else {
            System.out.println("false => ");
            return false;
        }

    }

    public void createReadme(String path, Patch patch) {

        try {
            ClassLoader classLoader = getClass().getClassLoader();
            File file = new File(classLoader.getResource("Readme.txt").getFile());

            // System.out.println("!!!!!!!!!!" + new java.io.File("").getAbsolutePath());
            // File file = new File("resources/Readme.txt");
            System.out.println(file.getAbsolutePath());

            FileReader reader = new FileReader(file);
            BufferedReader bufferedReader = new BufferedReader(reader);

            String line;
            PrintWriter writer = new PrintWriter(path + "\\Readme.txt", "UTF-8");
            System.out.println(path + "\\Readme.txt");
            while ((line = bufferedReader.readLine()) != null) {

                line = line.replace("#Winnumber", Integer.toString(patch.getWinNum()));
                line = line.replace("#NameSurname", " ");
                line = line.replace("#Type", "Package");
                line = line.replace("#detail", patch.getDetail());

                SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
                String date = sdf.format(new Date());
                line = line.replace("#Date", date);

                line = line.replace("#Desc", patch.getWinName());

                writer.println(line);

                System.out.println(line);
            }
            reader.close();
            writer.close();

        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    public void ImportSvn(Patch patch) {

        String name = patch.getUser().getUserName();
        String password = patch.getUser().getPassword();
        // String filename = patch.getWinName()
        String filename = patch.getWinNum() + " - " + patch.getWinName();
        String url = patch.getSvnPath() + "/" + filename;

        ISVNAuthenticationManager authManager = new BasicAuthenticationManager(name, password);

        SVNCommitClient commitClient = new SVNCommitClient(authManager, SVNWCUtil.createDefaultOptions(true));
        File f = new File(patch.getDestination() + filename);
        try {
            String logMessage = filename;
            commitClient.doImport(f, // File/Directory to be imported
                    SVNURL.parseURIEncoded(url), // location within svn
                    logMessage, // svn comment
                    new SVNProperties(), // svn properties
                    true, // use global ignores
                    false, // ignore unknown node types
                    SVNDepth.INFINITY);
            // SVNClientManager cm =
            // SVNClientManager.newInstance(SVNWCUtil.createDefaultOptions(true),authManager);
            //
            // SVNUpdateClient uc = cm.getUpdateClient();
            // long[] l = uc.doUpdate(new File[]{dstPath},
            // SVNRevision.HEAD,SVNDepth.INFINITY, true,true);
        } catch (SVNException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

}

This is Angularjs side

$scope.Create = function() {
    $scope.obj = [];
    console.log("$scope.svnPath" + $scope.patch.svnPath);
    console.log("$scope.userName" + $scope.patch.user.userName);
    $http({
        method : "POST",
        url : "http://ipnumber:port/patchinit/mk",
        data : $scope.patch
    }).then(function mySuccess(response) {

        console.log("Success!! ");
        $scope.obj = response.data;
        $scope.errorMessage = response.data.errorMessage;
        $scope.errorCode = response.data.errorCode;

    }, function myError(response) {

        //$scope.obj = response.statusText;
        $scope.errorMessage = response.data.errorMessage;
        $scope.errorCode = response.data.errorCode;

    });

}


问:
Vue Js multiple components into the app.vue
I have the following code and i am getting the following error:

```<code>Failed to mount component: template or render function not defined.
</code>```

I want to include top and bottom navigation to the app.vue
How can i achieve that?

Main.js:

```<code>new Vue({
   el: '#app',
   router,
   template: '<App/>',
   components: { 'App':App }
})
</code>```

App.vue:

```<code><template>
    <div id="app">
        <navigationtop></navigationtop>
        <navigationbottom></navigationbottom>
        <router-view/>
    </div>
</template>
<script>
    import navigationtop from './components/navigation/top'
    import navigationbottom from './components/navigation/bottom'

    export default {
        name: 'app',
        components: {
            'navigationtop': navigationtop,
            'navigationbottom': navigationbottom
        }
    }......
</code>```

Router:

```<code>export default new Router({
routes: [
  {
    path: '/',
    name: 'HelloWorld',
    component: HelloWorld
  }
 ]
 })
</code>```

HelloWorld:

```<code><template> </template>
<script>
export default {
  name: 'HelloWorld',
  data () {
    return {
      msg: 'Welcome to Your Vue.js App'}}}
</script>
</code>```

答:
Try to import your app like this:

```<code>import App from './foobar/App.vue'
</code>```

and render it inside your Vue({}) object like:

```<code>new Vue({
   el: '#app',
   router,
   render: h => h(App)
})
</code>```

Body:
I have the following code and i am getting the following error:

Failed to mount component: template or render function not defined.

I want to include top and bottom navigation to the app.vue
How can i achieve that?

Main.js:

new Vue({
   el: '#app',
   router,
   template: '<App/>',
   components: { 'App':App }
})

App.vue:

<template>

        <navigationtop></navigationtop>
        <navigationbottom></navigationbottom>
        <router-view/>

</template>

Body:
Try to import your app like this:

import App from './foobar/App.vue'

and render it inside your Vue({}) object like:

new Vue({
   el: '#app',
   router,
   render: h => h(App)
})


问:
How to add an attribute that contains a hyphen to a WTForms field
Calling a WTForms field object produces the rendered field, and any arguments are taken as attributes, for instance.

```<code>form.field(attribute='value')
</code>```

would return something like

```<code><input attribute='value'>
</code>```

How can I add HTML5 custom data attributes such as data-provide which contain hyphens, making them unparseable in python as a single keyword argument?

答:
It's not necessary to use a dictionary like that in the form.field function call. The ** unpacks the dictionary items into named parameters for the function, so just add the parameters instead:

{{ form.field( data-provide='foo') }}

But do so AFTER any required parameters for that field.
In other words, why unpack a dictionary right there when you can just add the parameters?

Body:
Calling a WTForms field object produces the rendered field, and any arguments are taken as attributes, for instance.

form.field(attribute='value')

would return something like

<input attribute='value'>

How can I add HTML5 custom data attributes such as data-provide which contain hyphens, making them unparseable in python as a single keyword argument?


问:
Printing to CSV causes a space between every character?
I am trying to print to CSV with Python3.6. When I print in console, it looks fine, but when I try to print to CSV, it prints l i k e | | t h i s.

i.e with spaces between each char, and | between each space.

I am calling the translate function here.

Sample response :

```<code>{
  "translations": [{
    "translation": "Hola"
  }],
  "word_count": 1,
  "character_count": 5
}
</code>```

Here are the relevant extracts :

```<code>with open('C:\\Users\\SimonTheKing\\Desktop\\file.csv', 'w') as csvfile:
    spamwriter = csv.writer(csvfile, delimiter=' ',
                            quotechar='|', quoting=csv.QUOTE_MINIMAL)

    # Print the contents
    for x in range(len(first_column)): #iterates over every row in an xlsx
        translation = language_translator.translate(
            model_id='123',
            text=first_column[x].value #reads from openpyxl xlsx
        )
        print(translation) #prints as expected
        spamwriter.writerow(translation) #prints a space between every char
</code>```

Can anyone offer some guidance please ?

答:
Writerow takes an iterable as an argument, so when you give it single row string, it treats the string as an iterable and writes it with the standard space(delimiter set earlier) between each element.

You will need to either set the row to a list  with [translation] or give it a list.

Body:
I am trying to print to CSV with Python3.6. When I print in console, it looks fine, but when I try to print to CSV, it prints l i k e | | t h i s.

i.e with spaces between each char, and | between each space.

I am calling the translate function here.

Sample response :

{
  "translations": [{
    "translation": "Hola"
  }],
  "word_count": 1,
  "character_count": 5
}

Here are the relevant extracts :

with open('C:\\Users\\SimonTheKing\\Desktop\\file.csv', 'w') as csvfile:
    spamwriter = csv.writer(csvfile, delimiter=' ',
                            quotechar='|', quoting=csv.QUOTE_MINIMAL)

    # Print the contents
    for x in range(len(first_column)): #iterates over every row in an xlsx
        translation = language_translator.translate(
            model_id='123',
            text=first_column[x].value #reads from openpyxl xlsx
        )
        print(translation) #prints as expected
        spamwriter.writerow(translation) #prints a space between every char

Can anyone offer some guidance please ?


问:
Ctags not working
I'm trying to understand a large code base. I need ctags to generate some tags so that I can jump to the function definition with ctrl + ].

Unfortunately, after running ctags -R * in the source diretory where some python script files resides, then vi open the python script, then cursor on which I want to jump to definition of, but all prompts E426: tag not found.

I tried creating a ~/.vimrc file, and adding set tags=~/Downloads/fast-rcnn/tools/tags, but still does not work, and when I open the generated tags file in the directory, seems only have tens of lines.

Can someone help me?

答:
turns out that set tags=~/Downloads/fast-rcnn/tools/tags missing colon :, adding it solve the problem, and follow the advice of Vim and Ctags tips and tricks
I change it to :set tags=./tags;/

Title: Ctags not working


问:
Undefined property: Illuminate\Pagination\LengthAwarePaginator::$hasDepartment
This is my controller.

```<code>public function index()
{
    $customers = $this->customerType->whereNull('deleted_at')->paginate(10);
    // please write the view code
    return view('admin.customer_type.index')->with(['customers' => $customers]);
}
</code>```

show me that error in blade file.someone solve that please, thanks

```<code><fieldset>
    <label for="visible">Department</label><br>
    <input name="hasDepartment" type="radio" value="ture" {!! $customers->hasDepartment == 'ture' ? 'checked' : '' !!}> True<br>
    <input name="hasDepartment" type="radio" value="false" {!! $customers->hasDepartment == 'false' ? 'checked' : '' !!}> False
</fieldset>
</code>```

答:
$customers is actually a paginator instance, you need to foreach on it to use every $customer like so :

```<code>@foreach ($customers as $customer)
    <fieldset>
        <label for="visible">Department</label><br>
        <input name="hasDepartment" type="radio" value="ture" {!! $customer->hasDepartment == 'ture' ? 'checked' : '' !!}> True<br>
        <input name="hasDepartment" type="radio" value="false" {!! $customer->hasDepartment == 'false' ? 'checked' : '' !!}> False
    </fieldset>
@endforeach
</code>```

Body:
This is my controller.

public function index()
{
    $customers = $this->customerType->whereNull('deleted_at')->paginate(10);
    // please write the view code
    return view('admin.customer_type.index')->with(['customers' => $customers]);
}

show me that error in blade file.someone solve that please, thanks

<fieldset>
    Department

    <input name="hasDepartment" type="radio" value="ture" {!! $customers->hasDepartment == 'ture' ? 'checked' : '' !!}> True

    <input name="hasDepartment" type="radio" value="false" {!! $customers->hasDepartment == 'false' ? 'checked' : '' !!}> False
</fieldset>

Body:
$customers is actually a paginator instance, you need to foreach on it to use every $customer like so :

@foreach ($customers as $customer)
    <fieldset>
        <label for="visible">Department</label><br>
        <input name="hasDepartment" type="radio" value="ture" {!! $customer->hasDepartment == 'ture' ? 'checked' : '' !!}> True<br>
        <input name="hasDepartment" type="radio" value="false" {!! $customer->hasDepartment == 'false' ? 'checked' : '' !!}> False
    </fieldset>
@endforeach


问:
How to combine the dataframes in a for loop
I have done with the web scraping with following code:

```<code>Number = soup.find('th',text = "Number of samples").find_next_sibling("td").text

for x in range(1,int(Number)+1):            #loop of function to parse the data format I want
    item = item_text.split('tooltip')[x].split("class")[0].replace('"','').replace(',','').replace(':','').replace("<br>"," ").replace("/","").replace("\\","")
    #print(item)

    TESTDATA=StringIO(item)

    df = pd.read_csv(TESTDATA, sep=" ",header=None)
    print(df)
</code>```

Now the result is in the following:

```<code>                0     1   2      3    4         5   6      7     8    9   \
0  TCGA-KK-A7B3-01A  Male NaN  Stage  not  reported NaN  Alive  FPKM  5.5
       10    11   12    13      14
0  Living  days  899  (2.5  years)
               0     1    2      3    4         5   6      7     8     9   \
0  TCGA-G9-6347-01A  Male NaN  Stage  not  reported NaN  Alive  FPKM  14.2
       10    11    12    13      14
0  Living  days  2089  (5.7  years)
...
</code>```

Now the problem is how to combine those separate dataframes into one dataframe so that it's easier to save to a whole csv file?

Thanks

答:
Use pd.concat

```<code>all_dataframes = []

for x in range(1,int(Number)+1):
    ....

    df = pd.read_csv(TESTDATA, sep=" ",header=None)
    all_dataframes.append(df)

concat_df = pd.concat(all_dataframes)
</code>```

Body:
I have done with the web scraping with following code:

Number = soup.find('th',text = "Number of samples").find_next_sibling("td").text

for x in range(1,int(Number)+1):            #loop of function to parse the data format I want
    item = item_text.split('tooltip')[x].split("class")[0].replace('"','').replace(',','').replace(':','').replace("
"," ").replace("/","").replace("\\","")
    #print(item)

    TESTDATA=StringIO(item)

    df = pd.read_csv(TESTDATA, sep=" ",header=None)
    print(df)

Now the result is in the following:

                0     1   2      3    4         5   6      7     8    9   \
0  TCGA-KK-A7B3-01A  Male NaN  Stage  not  reported NaN  Alive  FPKM  5.5
       10    11   12    13      14
0  Living  days  899  (2.5  years)
               0     1    2      3    4         5   6      7     8     9   \
0  TCGA-G9-6347-01A  Male NaN  Stage  not  reported NaN  Alive  FPKM  14.2
       10    11    12    13      14
0  Living  days  2089  (5.7  years)
...

Now the problem is how to combine those separate dataframes into one dataframe so that it's easier to save to a whole csv file?

Thanks

Body:
Use pd.concat

all_dataframes = []

for x in range(1,int(Number)+1):
    ....

    df = pd.read_csv(TESTDATA, sep=" ",header=None)
    all_dataframes.append(df)

concat_df = pd.concat(all_dataframes)


问:
How to tell the Activity type when loading a persisted workflow
Question:

Is there an easy way to find out what Activity Type was used to create a workflow?

Background:

I am writing my own WorkflowApplication based Windows Workflow 4 hosting engine and I am having some issues trying to load persisted workflows out of the database.  I am using the WorkflowApplication.Load(Guid) method to start the workflow, but this requires me to already create the WorkflowApplication.

Looking at the SqlWorkflowInstanceStore databases, I don't see the type name stored anywhere and I don't see an easy to to associate it short of making another table myself just to store that information.

答:
When you are using workflow services the relative URL is used to determine if a WorkflowServiceHost owns the workflow instance, this is done through the ServiceDeploymentsTable table in the database. There is no similar mechanism when you are using a WorkflowApplication so you have to roll your own.

One thing you could do is use property promotion to store the type in the InstancePromotedPropertiesTable. It will save you from creating a new table but is hardly an ideal way of solving the problem.