问:
How can I instantiate Services in MVC
I have an ASP.Net MVC 5 project using an Onion Architecture where I have repositories and services and I use Services from my controller. In my controller, I need to use the IGenericService variables I created, but how can I instantiate these variables? The problem being that my Service needs a IRepository for its constructor, and in turn IRepositoryneeds to be initialized too.

What I tried was AddSingleton(IGenericService<MyClass>, GenericService<MyClass>) in the method ConfigureServices(IServiceCollection services) in the Startup.cs file but it doesn't seem to help.

Edit As suggested my @Nkosi I am trying to resolve dependencies and followed this tutorial to do so : http://scottdorman.github.io/2016/03/17/integrating-asp.net-core-dependency-injection-in-mvc-4/ . My problem now is that I get an invalid operation exception  :

Unable to resolve service for type 'Repository.PrincipalServerContext' while attempting to activate 'WebExploitv2.Controllers.NavigationController'

My startup.cs looks like this now:

```<code>public partial class Startup
{
    public void Configuration(IAppBuilder app)
    {
        var services = new ServiceCollection();
        ConfigureAuth(app);
        ConfigureServices(services);
        var resolver = new DefaultDependencyResolver(services.BuildServiceProvider());
        DependencyResolver.SetResolver(resolver);
    }

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddControllerAsServices(typeof(Startup).Assembly.GetExportedTypes()
            .Where(t => !t.IsAbstract && !t.IsGenericTypeDefinition)
            .Where(t => typeof(IController).IsAssignableFrom(t)
                || t.Name.EndsWith("Controller", StringComparison.OrdinalIgnoreCase)));

        services.AddSingleton<IGenericRepository<Web_Documents>, GenericRepository<Web_Documents>>();
        services.AddSingleton<IGenericService<Web_Documents>, GenericService<Web_Documents>>();

        services.AddSingleton<IGenericRepository<Web_Categories>, GenericRepository<Web_Categories>>();
        services.AddSingleton<IGenericService<Web_Categories>, GenericService<Web_Categories>>();

        services.AddSingleton<IGenericService<Web_User_joint_Profils>, GenericService<Web_User_joint_Profils>>();
        services.AddSingleton<IGenericRepository<Web_User_joint_Profils>, GenericRepository<Web_User_joint_Profils>>();

        services.AddSingleton<IGenericRepository<Web_Group_joint_Profils>, GenericRepository<Web_Group_joint_Profils>>();
        services.AddSingleton<IGenericService<Web_Group_joint_Profils>, GenericService<Web_Group_joint_Profils>>();

        services.AddSingleton<IMenuService, MenuService>();
        services.AddSingleton<IMenuRepository, MenuRepository>();
    }
}
</code>```

I also added a DefaultDependencyResolver class :

```<code>public class DefaultDependencyResolver : IDependencyResolver
{
    protected IServiceProvider serviceProvider;

    public DefaultDependencyResolver(IServiceProvider serviceProvider)
    {
        this.serviceProvider = serviceProvider;
    }

    public object GetService(Type serviceType)
    {
        return this.serviceProvider.GetService(serviceType);
    }

    public IEnumerable<object> GetServices(Type serviceType)
    {
        return this.serviceProvider.GetServices(serviceType);
    }
}
</code>```

Next I have the ServiceProviderExtension class:

```<code>public static class ServiceProviderExtensions
{
    public static IServiceCollection AddControllerAsServices(this IServiceCollection services, IEnumerable<Type> controllerTypes)
    {
        foreach(var type in controllerTypes)
        {
            services.AddTransient(type);
        }
        return services;
    }
}
</code>```

Finally in my controller, I have Interfaces of GenericService which allows me to access Repository and in turn access my DB. I use the followed interfaces for instantiation

```<code>    private IGenericService<Web_User_joint_Profils> _userProfileService;
    private IGenericService<Web_Group_joint_Profils> _groupProfileService;
    private IGenericService<Web_Categories> _categoryService;
    PrincipalServerContext context;
    private NavigationController(PrincipalServerContext context, IGenericService<Web_User_joint_Profils> userProfileService, IGenericService<Web_Group_joint_Profils> groupProfileService, IGenericService<Web_Categories> categoryService)
    {
        _context = context;
        _userProfileService = userProfileService;
        _groupProfileService = groupProfileService;
        _categoryService = categoryService;
    }
</code>```

Note that My GenericService takes POCOs as generics in order to know where to look in Database. So for each of these in Startup.ConfigureServices(IServiceCollection services) I added an AddSingleton method to register these services and repositories with the DI container.
Any ideas why I get this exception?

答:
I wouldn't call services inside a startup.

Instance your IGenericService as a private readonly, then create the constructor to call in startup.cs or where ever you decide to use it.

```<code>private readonly IGenericService _genericService = new GenericService();
public IGenericService GenericService
{
    get{ return _genericService; }
    set{ _genericService = value; }
}
</code>```

Now you call your classes like:

```<code>GenericService.Method();
</code>```

Title: How can I instantiate Services in MVC

Body:
I have an ASP.Net MVC 5 project using an Onion Architecture where I have repositories and services and I use Services from my controller. In my controller, I need to use the IGenericService variables I created, but how can I instantiate these variables? The problem being that my Service needs a IRepository for its constructor, and in turn IRepositoryneeds to be initialized too.

What I tried was AddSingleton(IGenericService<MyClass>, GenericService<MyClass>) in the method ConfigureServices(IServiceCollection services) in the Startup.cs file but it doesn't seem to help.

Edit As suggested my @Nkosi I am trying to resolve dependencies and followed this tutorial to do so : http://scottdorman.github.io/2016/03/17/integrating-asp.net-core-dependency-injection-in-mvc-4/ . My problem now is that I get an invalid operation exception  :

Unable to resolve service for type 'Repository.PrincipalServerContext' while attempting to activate 'WebExploitv2.Controllers.NavigationController'

My startup.cs looks like this now:

public partial class Startup
{
    public void Configuration(IAppBuilder app)
    {
        var services = new ServiceCollection();
        ConfigureAuth(app);
        ConfigureServices(services);
        var resolver = new DefaultDependencyResolver(services.BuildServiceProvider());
        DependencyResolver.SetResolver(resolver);
    }

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddControllerAsServices(typeof(Startup).Assembly.GetExportedTypes()
            .Where(t => !t.IsAbstract && !t.IsGenericTypeDefinition)
            .Where(t => typeof(IController).IsAssignableFrom(t)
                || t.Name.EndsWith("Controller", StringComparison.OrdinalIgnoreCase)));

        services.AddSingleton<IGenericRepository<Web_Documents>, GenericRepository<Web_Documents>>();
        services.AddSingleton<IGenericService<Web_Documents>, GenericService<Web_Documents>>();

        services.AddSingleton<IGenericRepository<Web_Categories>, GenericRepository<Web_Categories>>();
        services.AddSingleton<IGenericService<Web_Categories>, GenericService<Web_Categories>>();

        services.AddSingleton<IGenericService<Web_User_joint_Profils>, GenericService<Web_User_joint_Profils>>();
        services.AddSingleton<IGenericRepository<Web_User_joint_Profils>, GenericRepository<Web_User_joint_Profils>>();

        services.AddSingleton<IGenericRepository<Web_Group_joint_Profils>, GenericRepository<Web_Group_joint_Profils>>();
        services.AddSingleton<IGenericService<Web_Group_joint_Profils>, GenericService<Web_Group_joint_Profils>>();

        services.AddSingleton<IMenuService, MenuService>();
        services.AddSingleton<IMenuRepository, MenuRepository>();
    }
}

I also added a DefaultDependencyResolver class :

public class DefaultDependencyResolver : IDependencyResolver
{
    protected IServiceProvider serviceProvider;

    public DefaultDependencyResolver(IServiceProvider serviceProvider)
    {
        this.serviceProvider = serviceProvider;
    }

    public object GetService(Type serviceType)
    {
        return this.serviceProvider.GetService(serviceType);
    }

    public IEnumerable<object> GetServices(Type serviceType)
    {
        return this.serviceProvider.GetServices(serviceType);
    }
}

Next I have the ServiceProviderExtension class:

public static class ServiceProviderExtensions
{
    public static IServiceCollection AddControllerAsServices(this IServiceCollection services, IEnumerable<Type> controllerTypes)
    {
        foreach(var type in controllerTypes)
        {
            services.AddTransient(type);
        }
        return services;
    }
}

Finally in my controller, I have Interfaces of GenericService which allows me to access Repository and in turn access my DB. I use the followed interfaces for instantiation

    private IGenericService<Web_User_joint_Profils> _userProfileService;
    private IGenericService<Web_Group_joint_Profils> _groupProfileService;
    private IGenericService<Web_Categories> _categoryService;
    PrincipalServerContext context;
    private NavigationController(PrincipalServerContext context, IGenericService<Web_User_joint_Profils> userProfileService, IGenericService<Web_Group_joint_Profils> groupProfileService, IGenericService<Web_Categories> categoryService)
    {
        _context = context;
        _userProfileService = userProfileService;
        _groupProfileService = groupProfileService;
        _categoryService = categoryService;
    }

Note that My GenericService takes POCOs as generics in order to know where to look in Database. So for each of these in Startup.ConfigureServices(IServiceCollection services) I added an AddSingleton method to register these services and repositories with the DI container.
Any ideas why I get this exception?

Body:
I wouldn't call services inside a startup.

Instance your IGenericService as a private readonly, then create the constructor to call in startup.cs or where ever you decide to use it.

private readonly IGenericService _genericService = new GenericService();
public IGenericService GenericService
{
    get{ return _genericService; }
    set{ _genericService = value; }
}

Now you call your classes like:

GenericService.Method();


来源: stackexchange

问:
How to detect text in a photo
I am researching into the best way to detect test in a photo using open source libraries.

I think the standard way is as follows (note: steps 1 - 4 all use OpenCV):

1) detect outline of document

2) transform document so it's flat and cropped, using said outline

3) Make the background of document white, using a filter

4) Feed resulting image to Tesseract

Is this the optimum process, or is there a better way, or better tools?
Also, what happens for case if the photo doesn't have a document outline (It's possible that step 1 & 2 are redundant)?

Is there anyway to automatically detect document orientation (i.e. portrait / landscape)?

答:
I think your process is fine. I've used a similar process for an Android project.

I think that the only way you can discover if a document is portrait/landscape is to reason with the length of the sides of the bounding box of your outline.

I don't think there's an automatic way to do this, maybe you can find the most external contour approximable with a 4 segment polyline (all doable in opencv).
 In order to get this you'll have to work with  contour hierarchy and contous approximation (see cv2.approxPolyDP).

 This is how I would go for automatic outline detection.
 As I said, the rest of your algorithm seems just fine to me.

 PS. I'll leave my Android project GitHub link. I don't know if it can be useful to you, but here I specify the outline by dragging some handles, then transform the image and feed it to Tesseract, using Java and OpenCV. Yeah It's a very bad idea to do that in the main thread of an Android app and yeah, the app is not finished. I just wanted to experiment with OCR, so I didn't care much of performance and usability, since this was not intended to use, but just for studying.

ContentLicense: CC BY-SA 3.0

Title: How to detect text in a photo


问:
How to find distinct count of data frame particular column value
df:

```<code>Field1 Field2
1      2
3      4
5      6
1      7
3      8
</code>```

Please let me know how to find distinct count of df['Field1'], Results should be 3
In SQL we use query like this.

```<code>select count(distinct Field1) as Field1DistCount from df
</code>```

答:
I'm assuming you are using pandas?

```<code>import pandas as pd
print(df['COLUMN_NAME_HERE'].nunique())
</code>```

If you want a dataframe of the unique values you could do (and here is a good link to go along with it):

```<code>print(df['COLUMN_NAME_HERE'].unique())
</code>```

And if you want the counts of those unique values using value_counts:

```<code>print(df['COLUMN_NAME_HERE'].value_counts())
</code>```

Body:
df:

Field1 Field2
1      2
3      4
5      6
1      7
3      8

Please let me know how to find distinct count of df['Field1'], Results should be 3
In SQL we use query like this.

select count(distinct Field1) as Field1DistCount from df

Body:
I'm assuming you are using pandas?

import pandas as pd
print(df['COLUMN_NAME_HERE'].nunique())

If you want a dataframe of the unique values you could do (and here is a good link to go along with it):

print(df['COLUMN_NAME_HERE'].unique())

And if you want the counts of those unique values using value_counts:

print(df['COLUMN_NAME_HERE'].value_counts())


问:
Exec system command containing a semicolon in Ruby
Seems a silly question, but I'm struggling to find the answer.

I need to execute a really long command directly from ruby code to the shell, and this command has to contain a ; character.

If I try to escape it with \; doesn't work, if I try to substitute it with \%3b it executes but it doesn't substitute %3b with ;, so it doesn't work too.

I tried with exec, system, ` <code>#{str}</code> `, and I can't make it work. It always splits in two my command.

答:
You should have no problem placing a semicolon within a shell command as long as you quote it properly:

```<code>system('cat file | grep ";"')
# => someline with a ; in it

system("cat #{a_variable} | grep ';'")
# => this will work as well for finding ;
</code>```

I also find that Open3 module to be a bit easier to use for odder system calls / quoting issues (but it can be a bit difficult to get it working too -- trade offs):

```<code>require 'open3'
cmds = %w(grep ';' a_file)
stdout, status = Open3.capture2(*cmds)
</code>```

Body:
You should have no problem placing a semicolon within a shell command as long as you quote it properly:

system('cat file | grep ";"')
# => someline with a ; in it

system("cat #{a_variable} | grep ';'")
# => this will work as well for finding ;

I also find that Open3 module to be a bit easier to use for odder system calls / quoting issues (but it can be a bit difficult to get it working too -- trade offs):

require 'open3'
cmds = %w(grep ';' a_file)
stdout, status = Open3.capture2(*cmds)


问:
Encode each training image as a histogram of the number of times each vocabulary element shows up for Bag of Visual Words
I want to implement bag of visual words in MATLAB.  I used SURF features to extract features from the images and k-means to cluster those features into k clusters.  I now have k centroids and I want to know how many times each cluster is used by assigning each image feature to its closet neighbor. Finally, I'd like to create a histogram of this for each image.

I tried to use knnsearch function but it doesn't work in this case.

Here is my MATLAB code:

```<code>clc;
clear;
close all;
folder = 'CarData/TrainImages/cars';
filePattern = fullfile(folder, '*.pgm');
f=dir(filePattern);
files={f.name};
for k=1:numel(files)
    fullFileName = fullfile(folder, files{k});
    H = fspecial('log');
    image=imfilter(imread(fullFileName),H);
    temp =  detectSURFFeatures(image);
    [im_features, temp] = extractFeatures(image, temp);
    features{k}= im_features;

end

features = vertcat(features{:});
image_feats = [];
[assignments,centers] = kmeans(double(features),500);
vocab = centers';
</code>```

I have all images feature in features array and cluster center in centroid array

答:
You're almost there.  You don't even need to use knnsearch at all.  The assignments variable tells you which input feature mapped to which cluster.  assignments will give you a N x 1 vector where N is the total number of examples you have, or the total number of features in the input matrix features.  Each value assignments(i) tells you which cluster the example i (or row i) of features it maps to.  The cluster centroid dictated by assignments(i) would be given as centers(i, :).
 Therefore given how you've called kmeans, it will be a N x 1 vector where each element is from 1 to 500 with 500 being the total number of clusters desired.

Let's do the simple case where we only have one image in your codebook. If this is the case, all you have to do is create a histogram of the assignments variable.  The output histogram h will be a 500 x 1 vector with each element h(i) being the number of times an example used centroid i as its representation in your codebook.

Just use the histcounts function and make sure that you specify the bin ranges so that they coincide with each cluster ID.  You must make sure that you account for the ending bin, as the bin ranges are exclusive on the right edge so just add an additional bin to the end.

Something like this will work:

```<code>h = histcounts(assignments, 1 : 501);
</code>```

If you want something simpler and you don't want to worry about specifying the end bin, you can use accumarray to achieve the same result:

```<code>h = accumarray(assignments, 1);
</code>```

The effect of accumarray we assign key-value pairs where the key is the centroid that the example mapped to and the value is simply 1 for all keys.  accumarray will bin all values in assignments that share the same key and you do something with those values.  The default behaviour of accumarray is to sum all values, which is effectively computing the histogram.

However, you want to do this for multiple images, not just a single image.
 For Bag of Visual Words problems, we will certainly have more than one training image in our database.  Therefore, you want to find the histogram of the features for each image.  We can still use the above concept, but one thing I can suggest is you maintain a separate variable that tells you how many features were detected per image, then you can index into the assignments variable to help extract out the correct assigned centroid IDs, then build a histogram of those individually.  We can build a 2D matrix where each row delineates the histogram of each image.  Remember that in kmeans, each row tells you what cluster each example was assigned to independently of the other examples in your data.  Using that, you would use kmeans on the entire training dataset, then be smart about how you're accessing the assignments variable to extract out the assigned clusters for each input image.

Therefore, modify your code so that it looks something like this:

```<code>clc;
clear;
close all;
folder = 'CarData/TrainImages/cars';
filePattern = fullfile(folder, '*.pgm');
f=dir(filePattern);
files={f.name};
num_features = zeros(numel(files), 1); % New - for keeping track of # of features per image
for k=1:numel(files)
    fullFileName = fullfile(folder, files{k});
    H = fspecial('log');
    image=imfilter(imread(fullFileName),H);
    temp =  detectSURFFeatures(image);
    [im_features, temp] = extractFeatures(image, temp);
    num_features(k) = size(im_features, 1); % New - # of features per image
    features{k}= im_features;
end

features = vertcat(features{:});
num_clusters = 500; % Added to make the code adaptive
[assignments,centers] = kmeans(double(features), num_clusters);

counter = 1; % Keeps track of where we need to slice in assignments

% Go through each image and find their histograms
features_hist = zeros(numel(files), num_clusters); % Records the per image histograms
for k = 1 : numel(files)
    a = assignments(counter : counter + num_features(k) - 1); % Get the assignments
    h = histcounts(a, 1 : num_clusters + 1);
    % Or:
    % h = accumarray(a, 1).'; % Transpose to make it a row

    % Place in final output
    features_hist(k, :) = h;

    % Increment counter
    counter = counter + num_features(k);
end
</code>```

features_hist will now be a N x 500 matrix where each row is the histogram of each image you are seeking.  The final job would be to use a supervised machine learning algorithm (SVM, Neural Networks, etc.) where the expected labels is the description of each image you have assigned to the image accompanied by the histogram of each image as the input features.  The final result would be a learned model so that when you have a new image, calculate the SURF features, represent them in a histogram of features like we did above, then feed it into the classification model to give you the expected class or label that the image represents.

P.S. Deep Learning / CNNs do a much better job at this, but require much more time to train.  If you're looking at performance wise, don't use Bag of Visual Words but this is something very quick to implement and it's known to perform moderately well but that of course depends on the kinds of images you want to classify.

Body:
I want to implement bag of visual words in MATLAB.  I used SURF features to extract features from the images and k-means to cluster those features into k clusters.  I now have k centroids and I want to know how many times each cluster is used by assigning each image feature to its closet neighbor. Finally, I'd like to create a histogram of this for each image.

I tried to use knnsearch function but it doesn't work in this case.

Here is my MATLAB code:

clc;
clear;
close all;
folder = 'CarData/TrainImages/cars';
filePattern = fullfile(folder, '*.pgm');
f=dir(filePattern);
files={f.name};
for k=1:numel(files)
    fullFileName = fullfile(folder, files{k});
    H = fspecial('log');
    image=imfilter(imread(fullFileName),H);
    temp =  detectSURFFeatures(image);
    [im_features, temp] = extractFeatures(image, temp);
    features{k}= im_features;

end

features = vertcat(features{:});
image_feats = [];
[assignments,centers] = kmeans(double(features),500);
vocab = centers';

I have all images feature in features array and cluster center in centroid array

Body:
You're almost there.  You don't even need to use knnsearch at all.  The assignments variable tells you which input feature mapped to which cluster.  assignments will give you a N x 1 vector where N is the total number of examples you have, or the total number of features in the input matrix features.  Each value assignments(i) tells you which cluster the example i (or row i) of features it maps to.  The cluster centroid dictated by assignments(i) would be given as centers(i, :).
 Therefore given how you've called kmeans, it will be a N x 1 vector where each element is from 1 to 500 with 500 being the total number of clusters desired.

Let's do the simple case where we only have one image in your codebook. If this is the case, all you have to do is create a histogram of the assignments variable.  The output histogram h will be a 500 x 1 vector with each element h(i) being the number of times an example used centroid i as its representation in your codebook.

Just use the histcounts function and make sure that you specify the bin ranges so that they coincide with each cluster ID.  You must make sure that you account for the ending bin, as the bin ranges are exclusive on the right edge so just add an additional bin to the end.

Something like this will work:

h = histcounts(assignments, 1 : 501);

If you want something simpler and you don't want to worry about specifying the end bin, you can use accumarray to achieve the same result:

h = accumarray(assignments, 1);

The effect of accumarray we assign key-value pairs where the key is the centroid that the example mapped to and the value is simply 1 for all keys.  accumarray will bin all values in assignments that share the same key and you do something with those values.  The default behaviour of accumarray is to sum all values, which is effectively computing the histogram.

However, you want to do this for multiple images, not just a single image.
 For Bag of Visual Words problems, we will certainly have more than one training image in our database.  Therefore, you want to find the histogram of the features for each image.  We can still use the above concept, but one thing I can suggest is you maintain a separate variable that tells you how many features were detected per image, then you can index into the assignments variable to help extract out the correct assigned centroid IDs, then build a histogram of those individually.  We can build a 2D matrix where each row delineates the histogram of each image.  Remember that in kmeans, each row tells you what cluster each example was assigned to independently of the other examples in your data.  Using that, you would use kmeans on the entire training dataset, then be smart about how you're accessing the assignments variable to extract out the assigned clusters for each input image.

Therefore, modify your code so that it looks something like this:

clc;
clear;
close all;
folder = 'CarData/TrainImages/cars';
filePattern = fullfile(folder, '*.pgm');
f=dir(filePattern);
files={f.name};
num_features = zeros(numel(files), 1); % New - for keeping track of # of features per image
for k=1:numel(files)
    fullFileName = fullfile(folder, files{k});
    H = fspecial('log');
    image=imfilter(imread(fullFileName),H);
    temp =  detectSURFFeatures(image);
    [im_features, temp] = extractFeatures(image, temp);
    num_features(k) = size(im_features, 1); % New - # of features per image
    features{k}= im_features;
end

features = vertcat(features{:});
num_clusters = 500; % Added to make the code adaptive
[assignments,centers] = kmeans(double(features), num_clusters);

counter = 1; % Keeps track of where we need to slice in assignments

% Go through each image and find their histograms
features_hist = zeros(numel(files), num_clusters); % Records the per image histograms
for k = 1 : numel(files)
    a = assignments(counter : counter + num_features(k) - 1); % Get the assignments
    h = histcounts(a, 1 : num_clusters + 1);
    % Or:
    % h = accumarray(a, 1).'; % Transpose to make it a row

    % Place in final output
    features_hist(k, :) = h;

    % Increment counter
    counter = counter + num_features(k);
end

features_hist will now be a N x 500 matrix where each row is the histogram of each image you are seeking.  The final job would be to use a supervised machine learning algorithm (SVM, Neural Networks, etc.) where the expected labels is the description of each image you have assigned to the image accompanied by the histogram of each image as the input features.  The final result would be a learned model so that when you have a new image, calculate the SURF features, represent them in a histogram of features like we did above, then feed it into the classification model to give you the expected class or label that the image represents.

P.S. Deep Learning / CNNs do a much better job at this, but require much more time to train.  If you're looking at performance wise, don't use Bag of Visual Words but this is something very quick to implement and it's known to perform moderately well but that of course depends on the kinds of images you want to classify.


问:
A simple Python program where the user inputs "Heads" or "Tails"
I tried creating a simple Python program where the user inputs their choice of a side of a coin, heads or tails. I tried running it, but the output is consistently "Sadly, that is not the right side!". Could someone please tell me how to improve this code?</p>

```<code>import random

print ("Pick a side of the coin. Heads or Tails?")
input_coin = input()
input_coin = input_coin.lower
coin = random.choice(["heads", "tails"])

if input_coin == coin:
    print ("You picked the right side!")
else:
    print ("Sadly, that is not the right side!")
</code>```

答:
As lower is a method inside str you should call it as a method with ()

Instead of:

```<code> input_coin = input_coin.lower
</code>```

type:

```<code>input_coin = input_coin.lower()
</code>```

As  Baldrickk commented, you can do it with one line instead of two:

```<code>input_coin = input().lower()
</code>```

If you type: print (input_coin.lower)

You will get: <built-in method lower of str object at 0x7f901b5c2378>

Which is not what you expected I guess.

In order to execute the method you need to call it with parenthesis.

Body:
I tried creating a simple Python program where the user inputs their choice of a side of a coin, heads or tails. I tried running it, but the output is consistently "Sadly, that is not the right side!". Could someone please tell me how to improve this code?

import random

print ("Pick a side of the coin. Heads or Tails?")
input_coin = input()
input_coin = input_coin.lower
coin = random.choice(["heads", "tails"])

if input_coin == coin:
    print ("You picked the right side!")
else:
    print ("Sadly, that is not the right side!")

Body:
As lower is a method inside str you should call it as a method with ()

Instead of:

 input_coin = input_coin.lower

type:

input_coin = input_coin.lower()

As  Baldrickk commented, you can do it with one line instead of two:

input_coin = input().lower()

If you type: print (input_coin.lower)

You will get: <built-in method lower of str object at 0x7f901b5c2378>

Which is not what you expected I guess.

In order to execute the method you need to call it with parenthesis.


问:
sql restricted count query
I'm not certain how to structure a SQL query to return the number of rows where a column equals certain values.

For instance,

In table myTable, how can I return the count of all the rows where myColumn = "xyz" and where myColumn = "abc"? Is this possible with a single query?

To clarify, say there are 10 rows where myColumn = "xyx" and 7 rows where myColumn = "abc", the query would return something like:

```<code>firstCountResult: 10
secondCountResult: 7
</code>```

答:
You want to group the count by mycolumn so you do this</p>

```<code>select
         myColumn, count(*)
from
         myTable
where
         myColumn in ('xyz','abc')
group by
         myColumn
</code>```

ContentLicense: CC BY-SA 2.5

Title: sql restricted count query

Body:
I'm not certain how to structure a SQL query to return the number of rows where a column equals certain values.

For instance,

In table myTable, how can I return the count of all the rows where myColumn = "xyz" and where myColumn = "abc"? Is this possible with a single query?

To clarify, say there are 10 rows where myColumn = "xyx" and 7 rows where myColumn = "abc", the query would return something like:

firstCountResult: 10
secondCountResult: 7

Body:
You want to group the count by mycolumn so you do this

select
         myColumn, count(*)
from
         myTable
where
         myColumn in ('xyz','abc')
group by
         myColumn


问:
How to specify the arguments' order with getopts function?
```<code>test-fun(){
    OPTIND=1
    while  getopts  "waz" arg
    do
        case  $arg  in
            w)
                 echo  "ok w"
                ;;
            a)
                echo  "ok a"
                ;;
            z)
                echo  "ok z"
                ;;
        esac
    done
}
</code>```

For the above test-fun, test-fun  -wz result in

```<code>ok w
ok z
</code>```

test-fun  -zw result in

```<code>ok z
ok w
</code>```

I want to specify the arguments' order  for test-fun function,all arguments in the order w a z,if you input test-fun zw,an error occur wrong arguments' order for the function,how to fix it?

答:
Put the arguments in a variable with line feeds (vars), sort it and then process the new variable (vars1).    </p>

```<code>test-fun(){
OPTIND=1
while  getopts  "waz" arg
do
    vars=$vars"\n"$arg
done
vars1=$(printf $vars | sort)
for i in $vars1

do
    case  $arg  in
        w)
             echo  "ok w"
            ;;
        a)
            echo  "ok a"
            ;;
        z)
            echo  "ok z"
            ;;
    esac
done
}
</code>```

Body:
test-fun(){
    OPTIND=1
    while  getopts  "waz" arg
    do
        case  $arg  in
            w)
                 echo  "ok w"
                ;;
            a)
                echo  "ok a"
                ;;
            z)
                echo  "ok z"
                ;;
        esac
    done
}

For the above test-fun, test-fun  -wz result in

ok w
ok z

test-fun  -zw result in

ok z
ok w

I want to specify the arguments' order  for test-fun function,all arguments in the order w a z,if you input test-fun zw,an error occur wrong arguments' order for the function,how to fix it?

Body:
Put the arguments in a variable with line feeds (vars), sort it and then process the new variable (vars1).

test-fun(){
OPTIND=1
while  getopts  "waz" arg
do
    vars=$vars"\n"$arg
done
vars1=$(printf $vars | sort)
for i in $vars1

do
    case  $arg  in
        w)
             echo  "ok w"
            ;;
        a)
            echo  "ok a"
            ;;
        z)
            echo  "ok z"
            ;;
    esac
done
}


问:
command in for loop behaves differently (Batch file)
I'm running a command in a batch file[Just for info: this command runs a python script which generates different outputs]
The code is as follows:

```<code>:meshfunc
echo "starting command"
echo "!inst_dir!runME.bat -parameter1 !parameter2! !parameter1v! -script pythonscript.py"
echo start_time=!time!
for /F "delims=" %%i IN ('"!inst_dir!runME.bat -parameter1 !parameter2! !parameter1v! -script pythonscript.py"') DO (
    set cmdline=%%i
    echo currentENDline=!cmdline!
)
EXIT /B 0
</code>```

The output of the script is:

PS: I have stripped the output lines for obvious reasons, but they shouldn't matter here

So my questions is :
If i run the same command without a for loop , it will complete in maybe 30 sec without the warning at the end.
However, if I run it inside a for loop, it takes much longer about 3 mins and gives the warning at the end
Why am I'm getting the Warning at the end as shown. Why is this happening?

答:
Because for /F execute the command enclosed in parentheses and store all its output in a temporary disk file until the command ends; after that, it start to repeatedly execute the group of commands. In this way, if the output is very large, the temporary file needs to grow several times and such a process takes some time... It should be faster to redirect the output to a disk file and then process such a file with for /F:

```<code>:meshfunc
echo "starting command"
echo "!inst_dir!runME.bat -parameter1 !parameter2! !parameter1v! -script pythonscript.py"
echo start_time=!time!
call "!inst_dir!runME.bat" -parameter1 !parameter2! !parameter1v! -script pythonscript.py > output.txt
for /F "delims=" %%i IN (output.txt) DO (
    set cmdline=%%i
    echo currentENDline=!cmdline!
)
EXIT /B 0
</code>```

Body:
I'm running a command in a batch file[Just for info: this command runs a python script which generates different outputs]
The code is as follows:

:meshfunc
echo "starting command"
echo "!inst_dir!runME.bat -parameter1 !parameter2! !parameter1v! -script pythonscript.py"
echo start_time=!time!
for /F "delims=" %%i IN ('"!inst_dir!runME.bat -parameter1 !parameter2! !parameter1v! -script pythonscript.py"') DO (
    set cmdline=%%i
    echo currentENDline=!cmdline!
)
EXIT /B 0

The output of the script is:

PS: I have stripped the output lines for obvious reasons, but they shouldn't matter here

So my questions is :
If i run the same command without a for loop , it will complete in maybe 30 sec without the warning at the end.
However, if I run it inside a for loop, it takes much longer about 3 mins and gives the warning at the end
Why am I'm getting the Warning at the end as shown. Why is this happening?

Body:
Because for /F execute the command enclosed in parentheses and store all its output in a temporary disk file until the command ends; after that, it start to repeatedly execute the group of commands. In this way, if the output is very large, the temporary file needs to grow several times and such a process takes some time... It should be faster to redirect the output to a disk file and then process such a file with for /F:

:meshfunc
echo "starting command"
echo "!inst_dir!runME.bat -parameter1 !parameter2! !parameter1v! -script pythonscript.py"
echo start_time=!time!
call "!inst_dir!runME.bat" -parameter1 !parameter2! !parameter1v! -script pythonscript.py > output.txt
for /F "delims=" %%i IN (output.txt) DO (
    set cmdline=%%i
    echo currentENDline=!cmdline!
)
EXIT /B 0


问:
How to keep word wrap (and other) settings in Visual Studio 2015
Using Visual Studio 2015 Enterprise, I prefer to keep word wrap on since I do a lot of work on multiple files at a time so I keep 2 documents stacked side-by-side most of the time.

Horizontal scrolling, therefore, is not only inconvenient and annoying, but also confusing, so I turn word wrap on.

In my settings, I have it enabled for all languages (and in the specific settings for every language as well) but it doesn't seem to actually happen unless I go to Edit > Advanced > Word Wrap

Is there a config file or registry entry that I can edit so that Word Wrap stays a thing permanently?

答:
Two possible scenarios for VS resetting word wrap:

You are accidentally pressing the shortuct Ctrl+E+W.
How can I toggle word wrap in Visual Studio.NET?

You are missing Visual Studio fix KB3165756.
Visual Studio 2015 losing settings


问:
C++98 proper check for a null pointer
C++11 introduced the nullptr keyword, which I don't have available.

I suppose there is the NULL macro from C, which I read about using in C++ from some stuff here and here, but I'm still unsure what's the proper way of checking for a null pointer in this older standard of C++.

I essentially want to be able to write this code for my test case with Boost Test:

```<code>aWrapperDataStructure x;
BOOST_CHECK_NE(x.get_ptr(), static_cast<decltype(x.get_ptr())>(nullptr));
</code>```

But maybe, as Tutorials Point suggested, something like this is more appropriate given the constraints:

```<code>BOOST_CHECK(x.get_ptr()); //true when not NULL
</code>```

Something about that throws me off though, so I'm wondering what the best practice is here. If it's somewhere online, or on SO, it's been long buried and I can't find it. Thank you!

答:
I don't feel right answering my own question here because I'm definitely not qualified to, but I read this answer here (It's still tagged C++ despite newer standards) from James Kanze:

If you use g++, you really should use NULL.

which is definitely good enough for me. I found these expressions for checking a null pointer though:

```<code>(p != NULL) //requires #include <stddef.h>

(p != 0)

(p)
</code>```

And of these 3, the last one which I had mentioned in my question, does an implicit conversion from a pointer to a bool (hiss). Using != and == at least does an explicit conversion to a bool, and moreover, using NULL shows your intent of checking a null pointer.

Therefore, I think even when not using g++, the expression (p != NULL) is the most appropriate way for the older C++ standard. (However, I'll still cede to someone else's expertise and mark their answer; I'm just an undergraduate student.)

Title: C++98 proper check for a null pointer

Body:
C++11 introduced the nullptr keyword, which I don't have available.

I suppose there is the NULL macro from C, which I read about using in C++ from some stuff here and here, but I'm still unsure what's the proper way of checking for a null pointer in this older standard of C++.

I essentially want to be able to write this code for my test case with Boost Test:

aWrapperDataStructure x;
BOOST_CHECK_NE(x.get_ptr(), static_cast<decltype(x.get_ptr())>(nullptr));

But maybe, as Tutorials Point suggested, something like this is more appropriate given the constraints:

BOOST_CHECK(x.get_ptr()); //true when not NULL

Something about that throws me off though, so I'm wondering what the best practice is here. If it's somewhere online, or on SO, it's been long buried and I can't find it. Thank you!

Body:
I don't feel right answering my own question here because I'm definitely not qualified to, but I read this answer here (It's still tagged C++ despite newer standards) from James Kanze:

If you use g++, you really should use NULL.

which is definitely good enough for me. I found these expressions for checking a null pointer though:

(p != NULL) //requires #include <stddef.h>

(p != 0)

(p)

And of these 3, the last one which I had mentioned in my question, does an implicit conversion from a pointer to a bool (hiss). Using != and == at least does an explicit conversion to a bool, and moreover, using NULL shows your intent of checking a null pointer.

Therefore, I think even when not using g++, the expression (p != NULL) is the most appropriate way for the older C++ standard. (However, I'll still cede to someone else's expertise and mark their answer; I'm just an undergraduate student.)

ContentLicense: CC BY-SA 4.0


问:
Hibernate: how do you adjust the default logging level (SJF4J and JDK 1.4 logger)?
I have a JavaSE/Hibernate test app (shell-based). I put the following JARs into the project's lib dir:

```<code>antlr-2.7.6.jar
commons-collections-3.1.jar
commons-lang-2.5.jar
dom4j-1.6.1.jar
hibernate-jpa-2.0-api-1.0.0.Final.jar
hibernate3.jar
javassist-3.12.0.GA.jar
jta-1.1.jar
slf4j-api-1.6.1.jar
slf4j-jdk14-1.6.1.jar
</code>```

As you can see, I'm using SLF4J with the JDK 1.4 logger. When I run my test app from the shell, Hibernate is very verbose because it is set to the INFO level by default:

```<code>09.12.2010 02:23:14 org.hibernate.annotations.common.Version <clinit>
INFO: Hibernate Commons Annotations 3.2.0.Final
09.12.2010 02:23:14 org.hibernate.cfg.Environment <clinit>
INFO: Hibernate 3.6.0.Final
09.12.2010 02:23:14 org.hibernate.cfg.Environment <clinit>
INFO: hibernate.properties not found
09.12.2010 02:23:14 org.hibernate.cfg.Environment buildBytecodeProvider
INFO: Bytecode provider name : javassist
09.12.2010 02:23:14 org.hibernate.cfg.Environment <clinit>
INFO: using JDK 1.4 java.sql.Timestamp handling
09.12.2010 02:23:14 org.hibernate.ejb.Version <clinit>
INFO: Hibernate EntityManager 3.6.0.Final
09.12.2010 02:23:15 org.hibernate.cfg.AnnotationBinder bindClass
INFO: Binding entity from annotated class: tld.standalone.bbstats.model.Game
09.12.2010 02:23:15 org.hibernate.cfg.annotations.EntityBinder bindTable
INFO: Bind entity tld.standalone.bbstats.model.Game on table Games
09.12.2010 02:23:15 org.hibernate.cfg.AnnotationBinder bindClass
INFO: Binding entity from annotated class: tld.standalone.bbstats.model.Roster
09.12.2010 02:23:15 org.hibernate.cfg.annotations.EntityBinder bindTable
INFO: Bind entity tld.standalone.bbstats.model.Roster on table Rosters
.
.
.
</code>```

How do I adjust the Hibernate logging level, to say WARNING?

EclipseLink for example let's you specify the level via a property (persistence.xml):

```<code><property name="eclipselink.logging.level" value="INFO" />
<property name="eclipselink.logging.level.sql" value="FINE" />
</code>```

Is there an equivalent in Hibernate?

答:
In my logging.properties file, I set:</p>

```<code>org.hibernate.SQL.level=FINEST // Show SQL statements
org.hibernate.type.level=FINEST // Show the bind parameter values
</code>```

Body:
I have a JavaSE/Hibernate test app (shell-based). I put the following JARs into the project's lib dir:

antlr-2.7.6.jar
commons-collections-3.1.jar
commons-lang-2.5.jar
dom4j-1.6.1.jar
hibernate-jpa-2.0-api-1.0.0.Final.jar
hibernate3.jar
javassist-3.12.0.GA.jar
jta-1.1.jar
slf4j-api-1.6.1.jar
slf4j-jdk14-1.6.1.jar

As you can see, I'm using SLF4J with the JDK 1.4 logger. When I run my test app from the shell, Hibernate is very verbose because it is set to the INFO level by default:

09.12.2010 02:23:14 org.hibernate.annotations.common.Version <clinit>
INFO: Hibernate Commons Annotations 3.2.0.Final
09.12.2010 02:23:14 org.hibernate.cfg.Environment <clinit>
INFO: Hibernate 3.6.0.Final
09.12.2010 02:23:14 org.hibernate.cfg.Environment <clinit>
INFO: hibernate.properties not found
09.12.2010 02:23:14 org.hibernate.cfg.Environment buildBytecodeProvider
INFO: Bytecode provider name : javassist
09.12.2010 02:23:14 org.hibernate.cfg.Environment <clinit>
INFO: using JDK 1.4 java.sql.Timestamp handling
09.12.2010 02:23:14 org.hibernate.ejb.Version <clinit>
INFO: Hibernate EntityManager 3.6.0.Final
09.12.2010 02:23:15 org.hibernate.cfg.AnnotationBinder bindClass
INFO: Binding entity from annotated class: tld.standalone.bbstats.model.Game
09.12.2010 02:23:15 org.hibernate.cfg.annotations.EntityBinder bindTable
INFO: Bind entity tld.standalone.bbstats.model.Game on table Games
09.12.2010 02:23:15 org.hibernate.cfg.AnnotationBinder bindClass
INFO: Binding entity from annotated class: tld.standalone.bbstats.model.Roster
09.12.2010 02:23:15 org.hibernate.cfg.annotations.EntityBinder bindTable
INFO: Bind entity tld.standalone.bbstats.model.Roster on table Rosters
.
.
.

How do I adjust the Hibernate logging level, to say WARNING?

EclipseLink for example let's you specify the level via a property (persistence.xml):

<property name="eclipselink.logging.level" value="INFO" />
<property name="eclipselink.logging.level.sql" value="FINE" />

Is there an equivalent in Hibernate?

Body:
In my logging.properties file, I set:

org.hibernate.SQL.level=FINEST // Show SQL statements
org.hibernate.type.level=FINEST // Show the bind parameter values


问:
Is there a way to prevent usage of unimplemented functions during compile time?
often I encounter hacks like

```<code>//lets say this is some class that still doesnt support...
//...all the functionality that it should based on the design docs
void MyClass::MyFunction()
{
  throw std::exception("not implemented");
}
</code>```

I guess this is a bad practice, but that aside:

Is there a way to do the same thing during compilation, but only if the function is used (aka if it is unused compile should succeed).

Edit: Im also interested in virtual mem functions.

答:
Old question, but still...

I use a couple of simple helper for this. It'll give an error link-time that's fairly readable:

```<code>// Not implemented is not implemented :-)thing, it'll break:
struct NotImplHelper { static void notimplemented(); };
#define notimplemented() NotImplHelper::notimplemented();
#if defined(DEBUG) || defined(_DEBUG)
#define notimplementedvirtual() throw std::exception();
#else
#define notimplementedvirtual() static_assert(false, "You should implement virtual function calls before moving to production.");
#endif
</code>```

Usage:

```<code>//lets say this is some class that still doesnt support...
//...all the functionality that it should based on the design docs
void MyClass::MyFunction()
{
    notimplemented();
    // or notimplementedvirtual() if MyFunction() is virtual...
}
</code>```

Rationale:

IMHO if you use a function in your program, it should be available. When you try to compile something that you haven't implemented yet, it should give a compile-time or link-time error.

F.ex., in MSVC++ this'll give:

```<code>1>Test.obj : error LNK2019: unresolved external symbol "public: static void __cdecl NotImplHelper::notimplemented(void)" (?notimplemented@NotImplHelper@@SAXXZ) referenced in function "[blahblahblah]"
</code>```

Note that the 'referenced function' is there in MSVC++. I haven't tested it in other compilers.

As for not-implemented virtual function calls, the only option you have it to throw an exception. Not having these implemented in your debugger while developing is fine - however, the moment stuff gets serious, these might be called by your program, so they should be available. A static_assert ensures the latter. (So: combined with any continuous integration package, it'll basically fail.)

Obviously most people will accidentally mix up notimplemented and notimplementedvirtual. In reality this ain't a big problem: a simple solution is to always use the former, unless you want to get rid of the error because it's a WIP.

Body:
often I encounter hacks like

//lets say this is some class that still doesnt support...
//...all the functionality that it should based on the design docs
void MyClass::MyFunction()
{
  throw std::exception("not implemented");
}

I guess this is a bad practice, but that aside:

Is there a way to do the same thing during compilation, but only if the function is used (aka if it is unused compile should succeed).

Edit: Im also interested in virtual mem functions.

Body:
Old question, but still...

I use a couple of simple helper for this. It'll give an error link-time that's fairly readable:

// Not implemented is not implemented :-)thing, it'll break:
struct NotImplHelper { static void notimplemented(); };
#define notimplemented() NotImplHelper::notimplemented();
#if defined(DEBUG) || defined(_DEBUG)
#define notimplementedvirtual() throw std::exception();
#else
#define notimplementedvirtual() static_assert(false, "You should implement virtual function calls before moving to production.");
#endif

Usage:

//lets say this is some class that still doesnt support...
//...all the functionality that it should based on the design docs
void MyClass::MyFunction()
{
    notimplemented();
    // or notimplementedvirtual() if MyFunction() is virtual...
}

Rationale:

IMHO if you use a function in your program, it should be available. When you try to compile something that you haven't implemented yet, it should give a compile-time or link-time error.

F.ex., in MSVC++ this'll give:

1>Test.obj : error LNK2019: unresolved external symbol "public: static void __cdecl NotImplHelper::notimplemented(void)" (?notimplemented@NotImplHelper@@SAXXZ) referenced in function "[blahblahblah]"

Note that the 'referenced function' is there in MSVC++. I haven't tested it in other compilers.

As for not-implemented virtual function calls, the only option you have it to throw an exception. Not having these implemented in your debugger while developing is fine - however, the moment stuff gets serious, these might be called by your program, so they should be available. A static_assert ensures the latter. (So: combined with any continuous integration package, it'll basically fail.)

Obviously most people will accidentally mix up notimplemented and notimplementedvirtual. In reality this ain't a big problem: a simple solution is to always use the former, unless you want to get rid of the error because it's a WIP.


问:
How to install Charles Proxy 4 in Ubuntu 16.04
I was able to install Charles Proxy 3 (sudo apt install charles-proxy3) but unable to find the package for 4.

https://www.charlesproxy.com/documentation/installation/apt-repository/

答:
You'll have to perform a manual installation, as it is not yet in the Debian repositories. To do so, just download the tarball from https://www.charlesproxy.com/download/, extract it with

```<code>tar xvzf charles-proxy-4.1.3_amd64.tar.gz
</code>```

and run the /bin/charles binary with:

```<code>cd charles/bin
sudo ./charles
</code>```

You may then uninstall charles3 from your computer by:

```<code>sudo apt-get remove charles-proxy
</code>```

Body:
You'll have to perform a manual installation, as it is not yet in the Debian repositories. To do so, just download the tarball from https://www.charlesproxy.com/download/, extract it with

tar xvzf charles-proxy-4.1.3_amd64.tar.gz

and run the /bin/charles binary with:

cd charles/bin
sudo ./charles

You may then uninstall charles3 from your computer by:

sudo apt-get remove charles-proxy


问:
Jquery sorting array of numbers and strings alphabetically
I am trying to sort an array of objects with numbers and strings. The sorting with number columns works fine, but the one with strings seems to have some issues. I can't figure out the problem here....

result = [{
      "title": "test",
      "client": "test",
      "price": 5000,
      "calories": 10,
      "eggless": "false",
      "date": "2017-09-09"
    }, {
      "title": "Cinnamon Sugar Fried Apples",
      "client": "Frodo Baggins",
      "price": 1100,
      "calories": 1997.07,
      "eggless": true,
      "date": "2017-07-06"
    }, {
      "title": "Cinnamon, Apple, Oatmeal Cake",
      "client": "Bruce Banner",
      "price": 390,
      "calories": 2007.07,
      "eggless": false,
      "date": "2017-07-09"
    }, {
      "title": "Cinnamon, Apple, Oatmeal Cake",
      "client": "Bruce Banner",
      "price": 390,
      "calories": 2007.07,
      "eggless": false,
      "date": "2017-07-09"
    }, {
      "title": "Chocolate Pancakes With Fruits",
      "client": "Bilbo Baggins",
      "price": 300,
      "calories": 1997.07,
      "eggless": true,
      "date": "2017-07-04"
    }, {
      "title": "Chocolate Pancakes With Fruits",
      "client": "Bilbo Baggins",
      "price": 300,
      "calories": 1997.07,
      "eggless": true,
      "date": "2017-07-04"
    }, {
      "title": "Cinnamon-Apple Bread",
      "client": "Tony Stark",
      "price": 250,
      "calories": 1500,
      "eggless": true,
      "date": "2017-07-08"
    }, {
      "title": "Cinnamon-Apple Bread",
      "client": "Tony Stark",
      "price": 250,
      "calories": 1500,
      "eggless": true,
      "date": "2017-07-08"
    }, {
      "title": "Pecan Tart",
      "client": "Scrats Squirrel",
      "price": 210,
      "calories": 1999,
      "eggless": true,
      "date": "2017-07-08"
    }, {
      "title": "Pecan Tart",
      "client": "Scrats Squirrel",
      "price": 210,
      "calories": 1999,
      "eggless": true,
      "date": "2017-07-08"
    }, {
      "title": "Cinnamon Sugar Fried Apples",
      "client": "Frodo Baggins",
      "price": 200,
      "calories": 1997.07,
      "eggless": true,
      "date": "2017-07-06"
    }];

    let column = "title";
    let sortOrder = "sort-asc";
    if ($.isNumeric(result[0][column])) {
      result.sort(function(first, second) {
        if (sortOrder === "sort-asc") return first[column] - second[column];
        else if (sortOrder === "sort-desc") return second[column] - first[column]; //first[column] < second[column];
      });
    } else {
      if (sortOrder === "sort-asc") result.sort();
      else if (sortOrder === "sort-desc") result.sort().reverse();
    }
    console.log(result);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script></code>```

答:
You should use String.localeCompare

```<code>else {
    result.sort(function (first, second) {
        if (sortOrder === "sort-asc") return first[column].localeCompare(second[column]);
        else if (sortOrder === "sort-desc") return second[column].localeCompare(first[column]); //first[column] < second[column];
    });
}
console.log(result);
</code>```

Body:
You should use String.localeCompare

else {
    result.sort(function (first, second) {
        if (sortOrder === "sort-asc") return first[column].localeCompare(second[column]);
        else if (sortOrder === "sort-desc") return second[column].localeCompare(first[column]); //first[column] < second[column];
    });
}
console.log(result);


问:
Error in evaluating the test script when retrieving a string from the response in postman
From the below response structure i want to retrieve the id field and save it in the environment variable in postman.

I tried all possible methods to do it but unable to do so.

```<code>{
    "childMaxAge": 13,
    "selectedForBooking": [
        {
            "id": "0661be61-d0ae-411009-a96d-64229a",
            "firstName": "Test",
            "gender": {
                "code": "MALE",
                "name": "Male"
            }
   ]
}
</code>```

i have tried the below and it also doesn't work.

```<code>tests["Status code is 201"] = responseCode.code === 201;
var data = JSON.parse(responseBody);
console.log(data);
var custid=JSON.parse(data.selectedForBooking[0].id);
tests ["selectedForBooking"]= postman.setEnvironmentVariable("CustId1", custid);
</code>```

but it gives error :

There was an error in evaluating the test script:  JSONError: Unexpected token '6' at 1:2 0661be61-d0ae-411009-a96d-64229a ^

答:
Have a look to POSTMAN : parsing a JSON response, how deep can I go into the response?

I used to have a similar problem, I was trying to reach

```<code>body.entries[0].attributes.device.type
</code>```

I managed getting the value by doing

```<code>body.entries[0].attributes['device.type']
</code>```

make sure you use single quotes (I don't know why ...)

Hope this helps

Alexandre

Body:
From the below response structure i want to retrieve the id field and save it in the environment variable in postman.

I tried all possible methods to do it but unable to do so.

{
    "childMaxAge": 13,
    "selectedForBooking": [
        {
            "id": "0661be61-d0ae-411009-a96d-64229a",
            "firstName": "Test",
            "gender": {
                "code": "MALE",
                "name": "Male"
            }
   ]
}

i have tried the below and it also doesn't work.

tests["Status code is 201"] = responseCode.code === 201;
var data = JSON.parse(responseBody);
console.log(data);
var custid=JSON.parse(data.selectedForBooking[0].id);
tests ["selectedForBooking"]= postman.setEnvironmentVariable("CustId1", custid);

but it gives error :

There was an error in evaluating the test script:  JSONError: Unexpected token '6' at 1:2 0661be61-d0ae-411009-a96d-64229a ^

Body:
Have a look to POSTMAN : parsing a JSON response, how deep can I go into the response?

I used to have a similar problem, I was trying to reach

body.entries[0].attributes.device.type

I managed getting the value by doing

body.entries[0].attributes['device.type']

make sure you use single quotes (I don't know why ...)

Hope this helps

Alexandre


问:
OpenID authentication to Google Apps via Perl and Net::OpenID::Consumer fails
I asked this over on Google's support forums for Apps integration, but got zero response. Maybe somebody here can help steer me in the right direction.

I'm trying to integrate a Perl application with Google Apps, and I'm having some trouble with the OpenID authentication. I've been using this PHP tutorial from Google as a kind of reference, since there are no Perl examples I can find.

My initial file, index.cgi (referred by manifest.xml, and the starting point of the OpenID transaction) is as follows:

```<code>use Net::OpenID::Consumer;
use CGI;
# ...

my $q = CGI->new();

my $domain = $q->param('domain');
if (!$domain) {
    print $q->header(), 'Provide domain please.';
    exit 0;
}
# my website
my $root = 'http://www.example.com/';

my $csr = Net::OpenID::Consumer->new(
     # The user agent which sends the openid off to the server
     ua => LWP::UserAgent->new,
     # Who we are
     required_root => $root,
     # Consumer Key Secret from Google Apps Marketplace
     consumer_secret => 'Zzzzzz9zzAAAAA....'
);

my $claimed_id = $csr->claimed_identity(
    'https://www.google.com/accounts/o8/site-xrds?hd=' . $domain);

if ($claimed_id) {
    my $check_url = $claimed_id->check_url(
        # Upon validation, the user will be returned here, and real
        # work may begin
        return_to => $root . '/return.cgi',
        trust_root => $root
    );
    print $q->redirect($check_url);
}
else {
    print $q->header(), "Error";
}
</code>```

This part seems to be working. That is, I get redirected to return.cgi with a bunch of openid.* parameters. However, at this point I get the following error:

no_identity_server The provided URL doesn't declare its OpenID identity server

I'm using the latest version of the Net::OpenID::Consumer module.

Here are the significant bits of return.cgi:

```<code>my $q = CGI->new();
my $csr = Net::OpenID::Consumer->new(
     ua => LWP::UserAgent->new,
     # The root of our URL
     required_root => 'http://www.example.com/',
     # Our password.
     consumer_secret => 'Zzzzzz9zzAAAAA....',
     # Where to get the information from.
     args  => $q
);

print $q->header();
$csr->handle_server_response(
     not_openid => sub {
         print "That's not an OpenID message. Did you just type in the URL?";
     },
     setup_required => sub {
         my $setup_url = shift;
         print 'You need to do something <a href="#">here</a>.';
     },
     cancelled => sub {
         print 'You cancelled your login.';
     },
     verified => sub {
         my $vident = shift;
         my $url = $vident->url;
         print "You are verified as '$url'. ** FIN **";
     },
     error => sub { die "Can't figure it out: ", @_; }
);
</code>```

As you can imagine, I'm wanting the verified sub to fire, but instead I'm getting an error. Anything obvious I'm missing? Any help would be appreciated.

答:
So the solution, it turns out, is to switch modules. I changed to the skimpily documented Net::Google::FederatedLogin, and things are now working. The code is as follows (substitute example.com below for your actual developer's domain).

In your Google Apps Marketplace vendor profile, add the URL to index.cgi in the Application Manifest:

```<code>...
<Url>http://www.example.com/index.cgi?from=google&domain=${DOMAIN_NAME}</Url>
...
</code>```

Then add the following code to your servers.

index.cgi

```<code>use CGI;
use Net::Google::FederatedLogin;

my $q = CGI->new();

my $domain = $q->param('domain');
if (!$domain) {
    print $q->header(), 'Provide domain please.';
    exit 0;
}

my $fl = Net::Google::FederatedLogin->new(
    claimed_id =>
        'https://www.google.com/accounts/o8/site-xrds?hd=' . $domain,
    return_to =>
        'http://www.example.com/return.cgi',
    extensions => [
        {
            ns          => 'ax',
            uri         => 'http://openid.net/srv/ax/1.0',
            attributes  => {
                mode        => 'fetch_request',
                required    => 'email',
                type        => {
                    email => 'http://axschema.org/contact/email'
                }
            }
        }
    ] );

print $q->redirect($fl->get_auth_url());
</code>```

return.cgi

```<code>use CGI;
use Net::Google::FederatedLogin;

my $q = CGI->new();
print $q->header();

my $fl = Net::Google::FederatedLogin->new(
    cgi => $q,
    return_to =>
        'http://www.example.com/return.cgi' );

eval { $fl->verify_auth(); };
if ($@) {
    print 'Error: ' . $@;
}
else {
    # we've authenticated and gotten attributes --
    my $ext = $fl->get_extension('http://openid.net/srv/ax/1.0');
    print $ext->get_parameter('value.email');
}
</code>```

(For a full sample, plus OAuth access to user data, see this post on my blog.)

Body:
I asked this over on Google's support forums for Apps integration, but got zero response. Maybe somebody here can help steer me in the right direction.

I'm trying to integrate a Perl application with Google Apps, and I'm having some trouble with the OpenID authentication. I've been using this PHP tutorial from Google as a kind of reference, since there are no Perl examples I can find.

My initial file, index.cgi (referred by manifest.xml, and the starting point of the OpenID transaction) is as follows:

use Net::OpenID::Consumer;
use CGI;
# ...

my $q = CGI->new();

my $domain = $q->param('domain');
if (!$domain) {
    print $q->header(), 'Provide domain please.';
    exit 0;
}
# my website
my $root = 'http://www.example.com/';

my $csr = Net::OpenID::Consumer->new(
     # The user agent which sends the openid off to the server
     ua => LWP::UserAgent->new,
     # Who we are
     required_root => $root,
     # Consumer Key Secret from Google Apps Marketplace
     consumer_secret => 'Zzzzzz9zzAAAAA....'
);

my $claimed_id = $csr->claimed_identity(
    'https://www.google.com/accounts/o8/site-xrds?hd=' . $domain);

if ($claimed_id) {
    my $check_url = $claimed_id->check_url(
        # Upon validation, the user will be returned here, and real
        # work may begin
        return_to => $root . '/return.cgi',
        trust_root => $root
    );
    print $q->redirect($check_url);
}
else {
    print $q->header(), "Error";
}

This part seems to be working. That is, I get redirected to return.cgi with a bunch of openid.* parameters. However, at this point I get the following error:

no_identity_server The provided URL doesn't declare its OpenID identity server

I'm using the latest version of the Net::OpenID::Consumer module.

Here are the significant bits of return.cgi:

my $q = CGI->new();
my $csr = Net::OpenID::Consumer->new(
     ua => LWP::UserAgent->new,
     # The root of our URL
     required_root => 'http://www.example.com/',
     # Our password.
     consumer_secret => 'Zzzzzz9zzAAAAA....',
     # Where to get the information from.
     args  => $q
);

print $q->header();
$csr->handle_server_response(
     not_openid => sub {
         print "That's not an OpenID message. Did you just type in the URL?";
     },
     setup_required => sub {
         my $setup_url = shift;
         print 'You need to do something here.';
     },
     cancelled => sub {
         print 'You cancelled your login.';
     },
     verified => sub {
         my $vident = shift;
         my $url = $vident->url;
         print "You are verified as '$url'. ** FIN **";
     },
     error => sub { die "Can't figure it out: ", @_; }
);

As you can imagine, I'm wanting the verified sub to fire, but instead I'm getting an error. Anything obvious I'm missing? Any help would be appreciated.

Body:
So the solution, it turns out, is to switch modules. I changed to the skimpily documented Net::Google::FederatedLogin, and things are now working. The code is as follows (substitute example.com below for your actual developer's domain).

In your Google Apps Marketplace vendor profile, add the URL to index.cgi in the Application Manifest:

...
<Url>http://www.example.com/index.cgi?from=google&amp;domain=${DOMAIN_NAME}</Url>
...

Then add the following code to your servers.

index.cgi

use CGI;
use Net::Google::FederatedLogin;

my $q = CGI->new();

my $domain = $q->param('domain');
if (!$domain) {
    print $q->header(), 'Provide domain please.';
    exit 0;
}

my $fl = Net::Google::FederatedLogin->new(
    claimed_id =>
        'https://www.google.com/accounts/o8/site-xrds?hd=' . $domain,
    return_to =>
        'http://www.example.com/return.cgi',
    extensions => [
        {
            ns          => 'ax',
            uri         => 'http://openid.net/srv/ax/1.0',
            attributes  => {
                mode        => 'fetch_request',
                required    => 'email',
                type        => {
                    email => 'http://axschema.org/contact/email'
                }
            }
        }
    ] );

print $q->redirect($fl->get_auth_url());

return.cgi

use CGI;
use Net::Google::FederatedLogin;

my $q = CGI->new();
print $q->header();

my $fl = Net::Google::FederatedLogin->new(
    cgi => $q,
    return_to =>
        'http://www.example.com/return.cgi' );

eval { $fl->verify_auth(); };
if ($@) {
    print 'Error: ' . $@;
}
else {
    # we've authenticated and gotten attributes --
    my $ext = $fl->get_extension('http://openid.net/srv/ax/1.0');
    print $ext->get_parameter('value.email');
}

(For a full sample, plus OAuth access to user data, see this post on my blog.)


问:
SQL: How to filter a set in join operation?
I have 3 tables.

```<code>CREATE TABLE students (
  student_id   INT         NOT NULL,
  student_name VARCHAR(10) NOT NULL,
  PRIMARY KEY (student_id)
);

CREATE TABLE courses (
  course_id   INT         NOT NULL,
  course_name VARCHAR(10) NOT NULL,
  PRIMARY KEY (course_id)
);

CREATE TABLE student_courses (
  student_id INT NOT NULL,
  course_id  INT
);
</code>```

I want to get all students that assigned to more than 2 courses. Here is my try:

```<code>SELECT
  s.student_name,
  c.course_name
FROM students s
  JOIN student_courses sc
    ON s.student_id = sc.student_id
  JOIN courses c
    ON c.course_id = sc.course_id
WHERE s.student_id
  IN (SELECT s.student_id
      FROM students s
        JOIN student_courses sci
          ON s.student_id = sci.student_id
        JOIN courses ci
          ON ci.course_id = sci.course_id
      GROUP BY s.student_id
      HAVING COUNT(s.student_id) > 2);
</code>```

It works. But I think it should be a simpler way to do it.

答:
Technically this will suffice:

```<code>SELECT student_id FROM student_courses GROUP BY student_id HAVING count(*) > 2
</code>```

It returns the student ID for any student assigned to more than 2 courses

If you want more info about the student, you can alias this query and join additional tables to it

```<code>SELECT ... FROM students s INNER JOIN
(SELECT student_id FROM student_courses GROUP BY student_id HAVING count(*) > 2) a ON a.student_id = s.id
</code>```

Note that your spec is at loggerheads with your "it works" code, because that code says HAVING count(*) > 1

"Try and avoid using IN on lists any longer than those you'd be willing to write by hand" is a rule of thumb I've always sought to implement

Body:
I have 3 tables.

CREATE TABLE students (
  student_id   INT         NOT NULL,
  student_name VARCHAR(10) NOT NULL,
  PRIMARY KEY (student_id)
);

CREATE TABLE courses (
  course_id   INT         NOT NULL,
  course_name VARCHAR(10) NOT NULL,
  PRIMARY KEY (course_id)
);

CREATE TABLE student_courses (
  student_id INT NOT NULL,
  course_id  INT
);

I want to get all students that assigned to more than 2 courses. Here is my try:

SELECT
  s.student_name,
  c.course_name
FROM students s
  JOIN student_courses sc
    ON s.student_id = sc.student_id
  JOIN courses c
    ON c.course_id = sc.course_id
WHERE s.student_id
  IN (SELECT s.student_id
      FROM students s
        JOIN student_courses sci
          ON s.student_id = sci.student_id
        JOIN courses ci
          ON ci.course_id = sci.course_id
      GROUP BY s.student_id
      HAVING COUNT(s.student_id) > 2);

It works. But I think it should be a simpler way to do it.

Body:
Technically this will suffice:

SELECT student_id FROM student_courses GROUP BY student_id HAVING count(*) > 2

It returns the student ID for any student assigned to more than 2 courses

If you want more info about the student, you can alias this query and join additional tables to it

SELECT ... FROM students s INNER JOIN
(SELECT student_id FROM student_courses GROUP BY student_id HAVING count(*) > 2) a ON a.student_id = s.id

Note that your spec is at loggerheads with your "it works" code, because that code says HAVING count(*) > 1

"Try and avoid using IN on lists any longer than those you'd be willing to write by hand" is a rule of thumb I've always sought to implement


问:
Using windows authentication how to Remove login prompt in Internet Explorer when website is host on IIS
When i host an application on IIS and set the windows authentication, after doing all configuration it will still prompt for credentials.

I followed the below steps to allow automatic login with Internet explorer :

Open Internet explorer go to Settings > Select the "Security" tab

Select "Local Intranet" and select the "Custom Level" button

Scroll down to "User Authentication" > "Logon"

Check the box next to "Enable logon in intranet zone only"

Restart IE.

When I open my application it will still prompt for login.

I have added web config settings to allow Windows authentication as below :

```<code><system.web>
<authentication mode="Windows"/>
<authorization>
<deny users="?"/>
<allow users="*"/>
</authorization>
</system.web>
</code>```

I m hosted my website on http://192.192.8.52:8089/ Check if required.
Please let me know where I am going wrong.

Thanks.

答:
Think about how you are navigating to your intranet site. You're navigating by IP address. If you do a tracert 192.192.8.52 in command prompt, you'll see that you are ignoring your DNS and navigating directly to the computer. You need to create a Forward Lookup Zone in your DNS Manager so the user is passed through the DNS.

In your DNS Manager, under Forward Lookup Zones -> YourDomain, create a New Host (A)... which points to 192.192.8.52. Then use that HostName you just created to navigate to your server http://HostNameYouMade. You can't be automatically authenticated through DNS unless you touch the DNS to get to the page. If you're going by IP, then you bypass the DNS and go straight to the computer (server).

After you're done, you can see with tracert HostNameYouMade that it will touch the DNS and resolve its IP. Your site should now know that a DNS user is connecting to a DNS host and is authenticated or not.

Body:
When i host an application on IIS and set the windows authentication, after doing all configuration it will still prompt for credentials.

I followed the below steps to allow automatic login with Internet explorer :

Open Internet explorer go to Settings > Select the "Security" tab

Select "Local Intranet" and select the "Custom Level" button

Scroll down to "User Authentication" > "Logon"

Check the box next to "Enable logon in intranet zone only"

Restart IE.

When I open my application it will still prompt for login.

I have added web config settings to allow Windows authentication as below :

<system.web>
<authentication mode="Windows"/>
<authorization>
<deny users="?"/>
<allow users="*"/>
</authorization>
</system.web>

I m hosted my website on http://192.192.8.52:8089/ Check if required.
Please let me know where I am going wrong.

Thanks.


问:
How to translate (multiple) id fields to title in phpmyadmin by using sql query?
Given a table User has three fields (all store different group id):

```<code>group, additional_group, display_group
2, 3, 4
</code>```

Another table Group has

```<code>id, title
2, admin
3, editor
4, subscriber
</code>```

How to get all three fields translated to title?

Code:

```<code>SELECT * FROM `users`
</code>```

Result:

```<code>2, 3, 4
</code>```

Expected result:

```<code>admin, editor, subscriber
</code>```

With my limited SQL knowledge, all I can come up with is translating one field:

```<code>SELECT *, group.title FROM `users` LEFT JOIN `group` WHERE users.group = group.id
</code>```

答:
LEFT JOIN once for each title:

```<code>select u.*, g1.title. g2.title, g3.title
from `users` u
LEFT JOIN `group` g1 ON u.group = g1.id
LEFT JOIN `group` g2 ON u.additional_group = g2.id
LEFT JOIN `group` g3 ON u.display_group = g3.id
</code>```

Body:
Given a table User has three fields (all store different group id):

group, additional_group, display_group
2, 3, 4

Another table Group has

id, title
2, admin
3, editor
4, subscriber

How to get all three fields translated to title?

Code:

SELECT * FROM `users`

Result:

2, 3, 4

Expected result:

admin, editor, subscriber

With my limited SQL knowledge, all I can come up with is translating one field:

SELECT *, group.title FROM `users` LEFT JOIN `group` WHERE users.group = group.id

Body:
LEFT JOIN once for each title:

select u.*, g1.title. g2.title, g3.title
from `users` u
LEFT JOIN `group` g1 ON u.group = g1.id
LEFT JOIN `group` g2 ON u.additional_group = g2.id
LEFT JOIN `group` g3 ON u.display_group = g3.id


问:
ListBox throwing ArgumentOutOfRangeException when adding to DataSource
I'm trying use a BindingList as a DataSource for a ListBox in C# WinForms, but whenever I try to add items to the BindingList, I get an ArgumentOutOfRangeException thrown.  The following code demonstrates the problem (assume a form with ListBox listBox1):

```<code>BindingList<string> dataSource = new BindingList<string>();
listBox1.DataSource = dataSource;
dataSource.Add("Test1"); // Exception, here.
</code>```

Note that if dataSource already has items in it, I do not get the exception:

```<code>BindingList<string> dataSource = new BindingList<string>();
dataSource.Add("Test1");
listBox1.DataSource = dataSource;
dataSource.Add("Test2"); // Appears to work correctly.
</code>```

I can work around the problem by setting the DataSource property to null before adding an item, and re-setting the DataSource afterward, but this feels like a hack, and I'd like to be able to avoid doing so.

Is there a (non-hack) way to use an empty DataSource on a ListBox, such that adding items to it doesn't throw exceptions?

Edit: Stack Trace:

System.Windows.Forms.dll!System.Windows.Forms.ListBox.SelectedIndex.set(int
  value) + 0x1ec bytes

    System.Windows.Forms.dll!System.Windows.Forms.ListControl.DataManager_PositionChanged(object
  sender, System.EventArgs e) + 0x2e
  bytes

    System.Windows.Forms.dll!System.Windows.Forms.CurrencyManager.OnPositionChanged(System.EventArgs
  e) + 0x39 bytes

    System.Windows.Forms.dll!System.Windows.Forms.CurrencyManager.ChangeRecordState(int
  newPosition, bool validating, bool
  endCurrentEdit, bool
  firePositionChange, bool pullData) +
  0x14f bytes

    System.Windows.Forms.dll!System.Windows.Forms.CurrencyManager.List_ListChanged(object
  sender,
  System.ComponentModel.ListChangedEventArgs
  e) + 0x2e4 bytes

    System.dll!System.ComponentModel.BindingList.OnListChanged(System.ComponentModel.ListChangedEventArgs
  e) + 0x17 bytes

    System.dll!System.ComponentModel.BindingList.FireListChanged(System.ComponentModel.ListChangedType
  type, int index) + 0x35 bytes

    System.dll!System.ComponentModel.BindingList.InsertItem(int
  index, System._Canon item) + 0x3f
  bytes

    mscorlib.dll!System.Collections.ObjectModel.Collection.Add(System._Canon
  item) + 0x76 bytes

答:
Do you possibly have an event handler attached to some event on your ListBox that could be causing this? I am not able to reproduce the behavior you're describing.

I created a completely blank WinForms project, with a single ListBox bound to a BindingList<string>, added the value "Test" to the list (after setting the ListBox.DataSource property), and the item "Test" appeared in the box, as expected.

I'd take a look at your ListBox as well as your BindingList<string> to see if either one has some attached event handlers you might be missing.

Body:
I'm trying use a BindingList as a DataSource for a ListBox in C# WinForms, but whenever I try to add items to the BindingList, I get an ArgumentOutOfRangeException thrown.  The following code demonstrates the problem (assume a form with ListBox listBox1):

BindingList<string> dataSource = new BindingList<string>();
listBox1.DataSource = dataSource;
dataSource.Add("Test1"); // Exception, here.

Note that if dataSource already has items in it, I do not get the exception:

BindingList<string> dataSource = new BindingList<string>();
dataSource.Add("Test1");
listBox1.DataSource = dataSource;
dataSource.Add("Test2"); // Appears to work correctly.

I can work around the problem by setting the DataSource property to null before adding an item, and re-setting the DataSource afterward, but this feels like a hack, and I'd like to be able to avoid doing so.

Is there a (non-hack) way to use an empty DataSource on a ListBox, such that adding items to it doesn't throw exceptions?

Edit: Stack Trace:

System.Windows.Forms.dll!System.Windows.Forms.ListBox.SelectedIndex.set(int
  value) + 0x1ec bytes

    System.Windows.Forms.dll!System.Windows.Forms.ListControl.DataManager_PositionChanged(object
  sender, System.EventArgs e) + 0x2e
  bytes

    System.Windows.Forms.dll!System.Windows.Forms.CurrencyManager.OnPositionChanged(System.EventArgs
  e) + 0x39 bytes

    System.Windows.Forms.dll!System.Windows.Forms.CurrencyManager.ChangeRecordState(int
  newPosition, bool validating, bool
  endCurrentEdit, bool
  firePositionChange, bool pullData) +
  0x14f bytes

    System.Windows.Forms.dll!System.Windows.Forms.CurrencyManager.List_ListChanged(object
  sender,
  System.ComponentModel.ListChangedEventArgs
  e) + 0x2e4 bytes

    System.dll!System.ComponentModel.BindingList.OnListChanged(System.ComponentModel.ListChangedEventArgs
  e) + 0x17 bytes

    System.dll!System.ComponentModel.BindingList.FireListChanged(System.ComponentModel.ListChangedType
  type, int index) + 0x35 bytes

    System.dll!System.ComponentModel.BindingList.InsertItem(int
  index, System._Canon item) + 0x3f
  bytes

    mscorlib.dll!System.Collections.ObjectModel.Collection.Add(System._Canon
  item) + 0x76 bytes


问:
Get creation date and time of a folder in batch script
I am trying to get the creation date and time of a specific folder in Windows.
Based on this answer, I have tried the following:

```<code>@echo off
set path_of_folder="C:\folderA\folderB\"

if exist %path_of_folder% (
  echo Path exists.
  for /f "skip=5 tokens=1,2 delims= " %%a in ('dir /a-d /tc %path_of_folder%') do set "dt=%%a"
    echo Created on: %%a, %%b
  )
)
else (
  echo Path does not exist.
)

pause
</code>```

Where I get this output:

```<code>Path exists.
Created on: 05/07/2017, 17:42
Created on: 05/07/2017, 17:42
Created on: 05/07/2017, 17:42
Created on: 05/07/2017, 17:42
Created on: 4, File(s)
Created on: 0, Dir(s)
</code>```

Which I am sure it shows the creation dates for each of the files (4 for my example) inside the folderB.

I am looking on saving the creation date and time only for the top folder folderB; can anyone suggest/show how this can be achieved and not get all the other creation date/times as well?

Note that on the answer given on the attached link, there is a exit /b 0 right after the echo Created on: %%a, %%b command which I cannot add on my script since there are several other commands I want to execute after I get the system date and time.

答:
@ECHO OFF
SETLOCAL
set "path_of_folder=C:\sql2016\mssql13.sqlexpress03"

if exist "%path_of_folder%" (
  echo Path exists.
  for /f "skip=5 tokens=1,2,4 delims= " %%a in (
   'dir /ad /tc "%path_of_folder%\."') do IF "%%c"=="." (
    set "dt=%%a"
    echo Created on: %%a, %%b
  )
) else (
  echo Path does not exist.
)

GOTO :EOF
```

I used a different target directory and since I run from the prompt, I've replaced the pause.

Note that the variable containing the path now has no closing \, nor is it quoted. This facilitates making modifications, but means that where required, references to that variable need to be "quoted".

Simply pick up the name part of the directory in %%c. Therefore you need a listing of directories hence /ad. The directoryname of interest is . so only execute the assignment and report if the directoryname found is "."

The skip=5 is redundant and can be removed if you prefer. the if filter ensures that the . directory is reported.

Body:
I am trying to get the creation date and time of a specific folder in Windows.
Based on this answer, I have tried the following:

@echo off
set path_of_folder="C:\folderA\folderB\"

if exist %path_of_folder% (
  echo Path exists.
  for /f "skip=5 tokens=1,2 delims= " %%a in ('dir /a-d /tc %path_of_folder%') do set "dt=%%a"
    echo Created on: %%a, %%b
  )
)
else (
  echo Path does not exist.
)

pause

Where I get this output:

Path exists.
Created on: 05/07/2017, 17:42
Created on: 05/07/2017, 17:42
Created on: 05/07/2017, 17:42
Created on: 05/07/2017, 17:42
Created on: 4, File(s)
Created on: 0, Dir(s)

Which I am sure it shows the creation dates for each of the files (4 for my example) inside the folderB.

I am looking on saving the creation date and time only for the top folder folderB; can anyone suggest/show how this can be achieved and not get all the other creation date/times as well?

Note that on the answer given on the attached link, there is a exit /b 0 right after the echo Created on: %%a, %%b command which I cannot add on my script since there are several other commands I want to execute after I get the system date and time.

Body:
@ECHO OFF
SETLOCAL
set "path_of_folder=C:\sql2016\mssql13.sqlexpress03"

if exist "%path_of_folder%" (
  echo Path exists.
  for /f "skip=5 tokens=1,2,4 delims= " %%a in (
   'dir /ad /tc "%path_of_folder%\."') do IF "%%c"=="." (
    set "dt=%%a"
    echo Created on: %%a, %%b
  )
) else (
  echo Path does not exist.
)

GOTO :EOF

I used a different target directory and since I run from the prompt, I've replaced the pause.

Note that the variable containing the path now has no closing \, nor is it quoted. This facilitates making modifications, but means that where required, references to that variable need to be "quoted".

Simply pick up the name part of the directory in %%c. Therefore you need a listing of directories hence /ad. The directoryname of interest is . so only execute the assignment and report if the directoryname found is "."

The skip=5 is redundant and can be removed if you prefer. the if filter ensures that the . directory is reported.


问:
Angular 2: ngx-popover close by hitting ESC key
I am refering this ngx-popover in component

ngx-popover Question is now how I can close the popover by hitting ESC key

Here is my code

```<code><div style="margin-bottom: 1em;" class="comment" *ngIf="myPopover2">
                        <popover-content #myPopover2
                                         placement="left"
                                         [animation]="true"
                                         [closeOnClickOutside]="true" [ng2-draggable]="true">
                            <button class="button_close" (click)="myPopover2.hide()">
                                <i class="fa fa-chevron-right" aria-hidden="true"></i>
                            </button>
                            <comment></comment>
                        </popover-content>
                    <button [ngClass]="{'container-element': myPopover2}" type="button" (keydown)="CloseEvent($event)" class="btn btn-labeled btn-default btn-block button_style" [popover]="myPopover2">
                        </span>
                    </button>
                </div>
</code>```

Please help me

答:
```<code>  popoverVisible: boolean = true;

  constructor(@Inject(DOCUMENT) private document) {}

  @HostListener('document:keydown', ['$event'])
  handleKeyboardEvent(event: KeyboardEvent) {
    if (event.keyCode === 27) { // 27===ESC
      this.popoverVisible = false;
    }
  }
</code>```

and then on the popover-element: *ngIf="popoverVisible"

Body:
I am refering this ngx-popover in component

ngx-popover Question is now how I can close the popover by hitting ESC key

Here is my code

                        <popover-content #myPopover2
                                         placement="left"
                                         [animation]="true"
                                         [closeOnClickOutside]="true" [ng2-draggable]="true">
                            <button class="button_close" (click)="myPopover2.hide()">

                            </button>
                            <comment></comment>
                        </popover-content>
                    <button [ngClass]="{'container-element': myPopover2}" type="button" (keydown)="CloseEvent($event)" class="btn btn-labeled btn-default btn-block button_style" [popover]="myPopover2">

                    </button>

Please help me

Body:
  popoverVisible: boolean = true;

  constructor(@Inject(DOCUMENT) private document) {}

  @HostListener('document:keydown', ['$event'])
  handleKeyboardEvent(event: KeyboardEvent) {
    if (event.keyCode === 27) { // 27===ESC
      this.popoverVisible = false;
    }
  }

and then on the popover-element: *ngIf="popoverVisible"


问:
Nativescript - clearing a gesture event
I'm setting a gesture callback as follows:

```<code>observer = layout.on(gestures.GestureTypes.swipe, function (args:  gestures.SwipeGestureEventData)
{
    console.log("Swipe dir=" + args.direction );
});
</code>```

This is being done in the page loaded event.

However, the returned observer value is undefined

答:
You can directly stop observing the swipe event for your layout

```<code>layout.on("swipe", (args:  gestures.SwipeGestureEventData) => {
    console.log("Swipe dir = " + args.direction );
});

...

layout.off("swipe");
</code>```

Title: Nativescript - clearing a gesture event

Body:
I'm setting a gesture callback as follows:

observer = layout.on(gestures.GestureTypes.swipe, function (args:  gestures.SwipeGestureEventData)
{
    console.log("Swipe dir=" + args.direction );
});

This is being done in the page loaded event.

However, the returned observer value is undefined

Body:
You can directly stop observing the swipe event for your layout

layout.on("swipe", (args:  gestures.SwipeGestureEventData) => {
    console.log("Swipe dir = " + args.direction );
});

...

layout.off("swipe");