问:
How to declare optional property in Mantle?
Specific situation detail:

In my current photo app, There are such situation : allow user experience first without log in,
but no have some field(e.g:voted,purchased ,etc) in the JSON responded from backend. If user logged in,
the field is added in JSON .

I'll show off my implement details as following:

PhotoListResponseModel (directly inherit MTLModel)

```<code>@interface PhotoListResponseModel : MTLModel <MTLJSONSerializing>
...
@property (nonatomic, copy, readonly) NSNumber *foo;
@property (nonatomic, copy, readonly) NSArray<PhotoModel *> *subPhotos;

@end

@interface PhotoModel : MTLModel <MTLJSONSerializing>

@property (nonatomic, copy, readonly) NSNumber *photoID;
@property (nonatomic, copy, readonly) NSURL *imageUrl;
...
@end

@implementation PhotoListResponseModel
+ (NSDictionary *)JSONKeyPathsByPropertyKey {
   return @{@"foo": @"foo"
            @"subPhotos": @"photos"
            };
}

+ (NSValueTransformer *)subPhotosJSONTransformer {
    return [MTLJSONAdapter arrayTransformerWithModelClass:PhotoModel.class];
}

@end

@implementation PhotoModel
+ (NSDictionary *)JSONKeyPathsByPropertyKey {
    return @{
             @"photoID": @"id",
             @"userID": @"user_id",
             };
}

@end
</code>```

Correspondly, the JSON example as following:

noAuthPhoto.json

```<code>{
        "foo": 1,
        "photos": [
                   {
                   "id": 204748881,
                   "image_url": "https://foo1/bar1",
                   },
                   {
                   "id": 204996257,
                   "image_url": "https://foo2/bar2"
                   }
                   ],
                   …
                   …
    }
</code>```

AuthedPhoto.json

```<code>{
        "foo": 1,
        "photos": [
                   {
                   "id": 204748881,
                   "image_url": "https://foo1/bar2”,
                   "voted": false,
                   "purchased": false
                   },
                   {
                   "id": 204996257,
                   "image_url": "https://foo2/bar2”,
                   "voted": false,
                   "purchased": false
                   }
                 ],
                 ...
                 ...
    }
</code>```

So, how let new field can compatible my already existing code?

Optional Property? (I not know how to do this.)

Or add a subclass of inherit from PhotoListResponseModel & PhotoModel?

Or any good idea : )

Update: I noticed this information,but still don't know how to do it.

答:
Optional properties are only available in Swift, but similar idea for the Obj-C — objects with possible nil value — should work well. You can add the following NSNumber properties to your PhotoModel:

```<code>@property (nonatomic, strong) NSNumber *voted;
@property (nonatomic, strong) NSNumber *purchased;
</code>```

And assign your BOOL values from parsed JSON during PhotoModel object creation like this:

```<code>photoModelObject.voted = [NSNumber numberWithBool:[parsedJson valueForKey:@"voted"]];
photoModelObject.purchased = [NSNumber numberWithBool:[parsedJson valueForKey:@"purchased"]];
</code>```

Next, when you reference your photo object, just check if these properties have nil value. If they are — your user is not logged in and you don't need to show them. Otherwise, extract BOOL value from them like this:

```<code>if (photoModelObject.voted && photoMobelObject.purchased) {
    BOOL isVoted = [photoModelObject.voted boolValue];
    BOOL isPurchased = [photoModelObject.purchased boolValue];

    // Use booleans to present info for registered users
} else {
    // There is no info about votes and purchasing provided for the current user
}
</code>```

Body:
Specific situation detail:

In my current photo app, There are such situation : allow user experience first without log in,
but no have some field(e.g:voted,purchased ,etc) in the JSON responded from backend. If user logged in,
the field is added in JSON .

I'll show off my implement details as following:

PhotoListResponseModel (directly inherit MTLModel)

@interface PhotoListResponseModel : MTLModel <MTLJSONSerializing>
...
@property (nonatomic, copy, readonly) NSNumber *foo;
@property (nonatomic, copy, readonly) NSArray<PhotoModel *> *subPhotos;

@end

@interface PhotoModel : MTLModel <MTLJSONSerializing>

@property (nonatomic, copy, readonly) NSNumber *photoID;
@property (nonatomic, copy, readonly) NSURL *imageUrl;
...
@end

@implementation PhotoListResponseModel
+ (NSDictionary *)JSONKeyPathsByPropertyKey {
   return @{@"foo": @"foo"
            @"subPhotos": @"photos"
            };
}

+ (NSValueTransformer *)subPhotosJSONTransformer {
    return [MTLJSONAdapter arrayTransformerWithModelClass:PhotoModel.class];
}

@end

@implementation PhotoModel
+ (NSDictionary *)JSONKeyPathsByPropertyKey {
    return @{
             @"photoID": @"id",
             @"userID": @"user_id",
             };
}

@end

Correspondly, the JSON example as following:

noAuthPhoto.json

{
        "foo": 1,
        "photos": [
                   {
                   "id": 204748881,
                   "image_url": "https://foo1/bar1",
                   },
                   {
                   "id": 204996257,
                   "image_url": "https://foo2/bar2"
                   }
                   ],
                   …
                   …
    }

AuthedPhoto.json

{
        "foo": 1,
        "photos": [
                   {
                   "id": 204748881,
                   "image_url": "https://foo1/bar2”,
                   "voted": false,
                   "purchased": false
                   },
                   {
                   "id": 204996257,
                   "image_url": "https://foo2/bar2”,
                   "voted": false,
                   "purchased": false
                   }
                 ],
                 ...
                 ...
    }

So, how let new field can compatible my already existing code?

Optional Property? (I not know how to do this.)

Or add a subclass of inherit from PhotoListResponseModel & PhotoModel?

Or any good idea : )

Update: I noticed this information,but still don't know how to do it.

Body:
Optional properties are only available in Swift, but similar idea for the Obj-C — objects with possible nil value — should work well. You can add the following NSNumber properties to your PhotoModel:

@property (nonatomic, strong) NSNumber *voted;
@property (nonatomic, strong) NSNumber *purchased;

And assign your BOOL values from parsed JSON during PhotoModel object creation like this:

photoModelObject.voted = [NSNumber numberWithBool:[parsedJson valueForKey:@"voted"]];
photoModelObject.purchased = [NSNumber numberWithBool:[parsedJson valueForKey:@"purchased"]];

Next, when you reference your photo object, just check if these properties have nil value. If they are — your user is not logged in and you don't need to show them. Otherwise, extract BOOL value from them like this:

if (photoModelObject.voted && photoMobelObject.purchased) {
    BOOL isVoted = [photoModelObject.voted boolValue];
    BOOL isPurchased = [photoModelObject.purchased boolValue];

    // Use booleans to present info for registered users
} else {
    // There is no info about votes and purchasing provided for the current user
}


来源: stackexchange

问:
Updating imageview declared in parent class(which includes Navigation view) from derived class in android
Scenario:

Base class which includes Navigation drawer layout having header section as in usual apps. Header includes an imageview and textview. There's another activity lets say Profile which is extending from Base class in my case and I don't want to change this parent/child behaviour at this point.

Problem:

Profile activity has api call which updates the profile image on server. On getting success in response, I just want to update the navigation drawer ImageView regardless of user goes back to other activity or remains at Profile activity.

What I have tried so far are:

Declare ImageView in Base Activity as static and try to use Picasso to update image in Profile activity api response.

Declare ImageView in Base Activity as static and tried imageview.setBitmap() method.

Tried to use instance of Base class in Volley success method and use method of base class where I am trying to update ImageView.

Tried to use runOnUiThread() in api success response but of no success.
This doesn't make sense in my case as the user might not land on base activity while pressing back button. Below is the piece of code in Profile Activity where I am trying to update image in Base Activity

```<code>   private void uploadImage() {

    if (bm == null) {
        uploadProfile();
    }
    else {
        String REGISTER_URL = new SharedPreferenceManager(getApplicationContext()).getKeyFromSharedPrefFile("MySharedPrefs", "globalURL") + "users/mobileupload";

        StringRequest stringRequest = new StringRequest(Request.Method.POST, REGISTER_URL,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String s) {
                        navBarImage.setImageBitmap(bitmap); // where navBarImage is declared in BaseActivity Layout Navigation drawer in header layout
                     }
                },
                ....

        requestQueue.add(stringRequest);
    }
}
</code>```

Api call is working fine , image is uploading and updating smoothly if I logout and login again.

Now my question is whether there is a way to be able to update the view of parent class instantly ... and if yes, can you provide some example.

答:
For this, what you can do is:
First, create an interface and implement in the "Base Activity". Then pass instance of this interface to the Derived Activity and once you get the response from the server, call this interface method to send the updated image to BaseActivity.

In the BaseActivity where you have overridden the interface method, update the image using Picasso.
Hope it helps.

ContentLicense: CC BY-SA 4.0

Body:
Scenario:

Base class which includes Navigation drawer layout having header section as in usual apps. Header includes an imageview and textview. There's another activity lets say Profile which is extending from Base class in my case and I don't want to change this parent/child behaviour at this point.

Problem:

Profile activity has api call which updates the profile image on server. On getting success in response, I just want to update the navigation drawer ImageView regardless of user goes back to other activity or remains at Profile activity.

What I have tried so far are:

Declare ImageView in Base Activity as static and try to use Picasso to update image in Profile activity api response.

Declare ImageView in Base Activity as static and tried imageview.setBitmap() method.

Tried to use instance of Base class in Volley success method and use method of base class where I am trying to update ImageView.

Tried to use runOnUiThread() in api success response but of no success.
This doesn't make sense in my case as the user might not land on base activity while pressing back button. Below is the piece of code in Profile Activity where I am trying to update image in Base Activity

   private void uploadImage() {

    if (bm == null) {
        uploadProfile();
    }
    else {
        String REGISTER_URL = new SharedPreferenceManager(getApplicationContext()).getKeyFromSharedPrefFile("MySharedPrefs", "globalURL") + "users/mobileupload";

        StringRequest stringRequest = new StringRequest(Request.Method.POST, REGISTER_URL,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String s) {
                        navBarImage.setImageBitmap(bitmap); // where navBarImage is declared in BaseActivity Layout Navigation drawer in header layout
                     }
                },
                ....

        requestQueue.add(stringRequest);
    }
}

Api call is working fine , image is uploading and updating smoothly if I logout and login again.

Now my question is whether there is a way to be able to update the view of parent class instantly ... and if yes, can you provide some example.

ContentLicense: CC BY-SA 3.0


问:
How can I test an authentication challenge?
Dear fellow citizens of Earth.

I'm requesting a real life example where I can test the authentication challenge code snippet I found below. If it's not possible I would appreciate any suggestions on what to do so that I can validate it.

I have a feeling the code is working:

```<code>- (void)webView:(WKWebView *)webView didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition, NSURLCredential * _Nullable))completionHandler
{
    NSString *host = webView.URL.host;

    NSString *authenticationMethod = [[challenge protectionSpace] authenticationMethod];

    if ([authenticationMethod isEqualToString:NSURLAuthenticationMethodDefault]
        || [authenticationMethod isEqualToString:NSURLAuthenticationMethodHTTPBasic]
        || [authenticationMethod isEqualToString:NSURLAuthenticationMethodHTTPDigest]) {

        NSString *title = @"Authentication Challenge";

        NSString *message = [NSString stringWithFormat:@"%@ requires username and password.", host];

        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:title message:message preferredStyle:UIAlertControllerStyleAlert];

        [alertController addTextFieldWithConfigurationHandler:^(UITextField *textField) {

            textField.placeholder = @"Username";
        }];

        [alertController addTextFieldWithConfigurationHandler:^(UITextField *textField) {

            textField.placeholder = @"Password";

            textField.secureTextEntry = YES;
        }];

        [alertController addAction:[UIAlertAction actionWithTitle:@"Authenticate" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {

            NSString *username = ((UITextField *)alertController.textFields[0]).text;

            NSString *password = ((UITextField *)alertController.textFields[1]).text;

            NSURLCredential *credential = [[NSURLCredential alloc] initWithUser:username password:password persistence:NSURLCredentialPersistenceNone];

            completionHandler(NSURLSessionAuthChallengeUseCredential, credential);

        }]];

        [alertController addAction:[UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {

            completionHandler(NSURLSessionAuthChallengeCancelAuthenticationChallenge, nil);
        }]];

        [_delegate webView:self didReceiveAuthenticationChallengeWithAlertController:alertController];
    }
    else if ([authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust]) {

        completionHandler(NSURLSessionAuthChallengePerformDefaultHandling, nil);
    }
    else {

        completionHandler(NSURLSessionAuthChallengeCancelAuthenticationChallenge, nil);
    }
}
</code>```

Love and peace to all.

Source: https://github.com/ShingoFukuyama/WKWebViewTips

Older question: How can I properly implement an authentication challenge using a WKWebView?

答:
Usually you would just have to set specific breakpoints in your code and then manipulate some variables in the debugger console with statements like expr varName=@"test" to test code like this.

The interesting part here is how to even trigger the call to webView:didReceiveAuthenticationChallenge:

Use a HTTP Testing service like HTTPBin - e.g. this for an Basic Auth test

Write a simple WebServer with python, ruby etc. and test against it

configure the OSX-builtin Apache httpd to use Basic Auth for access, then test with the iOS Simulator against localhost. Here's a simple tutorial on how to configure the server. Be sure to check the comments, as some steps are outdated (e.g. the conf file is now located at /etc/apache2/httpd.conf)

Body:
Dear fellow citizens of Earth.

I'm requesting a real life example where I can test the authentication challenge code snippet I found below. If it's not possible I would appreciate any suggestions on what to do so that I can validate it.

I have a feeling the code is working:

- (void)webView:(WKWebView *)webView didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition, NSURLCredential * _Nullable))completionHandler
{
    NSString *host = webView.URL.host;

    NSString *authenticationMethod = [[challenge protectionSpace] authenticationMethod];

    if ([authenticationMethod isEqualToString:NSURLAuthenticationMethodDefault]
        || [authenticationMethod isEqualToString:NSURLAuthenticationMethodHTTPBasic]
        || [authenticationMethod isEqualToString:NSURLAuthenticationMethodHTTPDigest]) {

        NSString *title = @"Authentication Challenge";

        NSString *message = [NSString stringWithFormat:@"%@ requires username and password.", host];

        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:title message:message preferredStyle:UIAlertControllerStyleAlert];

        [alertController addTextFieldWithConfigurationHandler:^(UITextField *textField) {

            textField.placeholder = @"Username";
        }];

        [alertController addTextFieldWithConfigurationHandler:^(UITextField *textField) {

            textField.placeholder = @"Password";

            textField.secureTextEntry = YES;
        }];

        [alertController addAction:[UIAlertAction actionWithTitle:@"Authenticate" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {

            NSString *username = ((UITextField *)alertController.textFields[0]).text;

            NSString *password = ((UITextField *)alertController.textFields[1]).text;

            NSURLCredential *credential = [[NSURLCredential alloc] initWithUser:username password:password persistence:NSURLCredentialPersistenceNone];

            completionHandler(NSURLSessionAuthChallengeUseCredential, credential);

        }]];

        [alertController addAction:[UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {

            completionHandler(NSURLSessionAuthChallengeCancelAuthenticationChallenge, nil);
        }]];

        [_delegate webView:self didReceiveAuthenticationChallengeWithAlertController:alertController];
    }
    else if ([authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust]) {

        completionHandler(NSURLSessionAuthChallengePerformDefaultHandling, nil);
    }
    else {

        completionHandler(NSURLSessionAuthChallengeCancelAuthenticationChallenge, nil);
    }
}

Love and peace to all.

Source: https://github.com/ShingoFukuyama/WKWebViewTips

Older question: How can I properly implement an authentication challenge using a WKWebView?


问:
sys_connect_by_path in MSSQL
Please help me to convert the below query in MSSQL. </p>

```<code>select sys_connect_by_path(title, '/') "Path", ITEM_ID, PARENT_ID
from lib_items
where item_type = '1'start with title = 'root'
connect by prior item_id = parent_id
</code>```

答:
IN SQL-Server using a recursive common table expression  like this:

```<code>; WITH lib_items(title, item_id, parent_id)
       AS   (  SELECT title, item_id, parent_id
               FROM     (VALUES     ('root'  , 1, NULL)
                                ,   ('child1', 2, 1)
                                ,   ('child2', 3, 2)
                                ,   ('child3', 4, 1)
                                )   AS lib_items (title, item_id, parent_id)

           )
   ,  CTE AS
           (   SELECT   CAST (title AS VARCHAR(8000)) AS title, item_id, parent_id
               FROM     lib_items
               WHERE    parent_id IS NULL
               UNION ALL
               SELECT   CAST(P.Title + '\' +C.Title AS VARCHAR(8000)), C.item_id, C.parent_id
               FROM     lib_items AS c
               JOIN     CTE AS p ON c.parent_id = p.item_id
           )

SELECT   title, item_id, parent_id
FROM     CTE
</code>```

Result:

```<code>title              |item_id|parent_id
-------------------|----------------
root               | 1     | NULL
root\child1        | 2     | 1
root\child3        | 4     | 1
root\child1\child2 | 3     | 2
</code>```

Title: sys_connect_by_path in MSSQL

Body:
Please help me to convert the below query in MSSQL.

select sys_connect_by_path(title, '/') "Path", ITEM_ID, PARENT_ID
from lib_items
where item_type = '1'start with title = 'root'
connect by prior item_id = parent_id

Body:
IN SQL-Server using a recursive common table expression  like this:

; WITH lib_items(title, item_id, parent_id)
       AS   (  SELECT title, item_id, parent_id
               FROM     (VALUES     ('root'  , 1, NULL)
                                ,   ('child1', 2, 1)
                                ,   ('child2', 3, 2)
                                ,   ('child3', 4, 1)
                                )   AS lib_items (title, item_id, parent_id)

           )
   ,  CTE AS
           (   SELECT   CAST (title AS VARCHAR(8000)) AS title, item_id, parent_id
               FROM     lib_items
               WHERE    parent_id IS NULL
               UNION ALL
               SELECT   CAST(P.Title + '\' +C.Title AS VARCHAR(8000)), C.item_id, C.parent_id
               FROM     lib_items AS c
               JOIN     CTE AS p ON c.parent_id = p.item_id
           )

SELECT   title, item_id, parent_id
FROM     CTE

Result:

title              |item_id|parent_id
-------------------|----------------
root               | 1     | NULL
root\child1        | 2     | 1
root\child3        | 4     | 1
root\child1\child2 | 3     | 2


问:
How to return distinct rows in rails?
I have a model Program containing fields program_title, department_id and date. I have inserted two rows having same program title and date but different department_id.

```<code>Insert into programs(program_title,date,department_id) Values ("prog1","4/2/2017","1");
Insert into programs(program_title,date,department_id) Values ("prog1","4/2/2017","2");
</code>```

Now I want to return rows which will be distinct by program_title whatever be the department_id. I have tried,

```<code>@event_contents=Program.select(:id,:date,:program_title).distinct(:program_title)
</code>```

But still it returns both the rows. Any help is appreciated.

答:
SQL can only collapse rows where all values are the same when using DISTINCT. Because you are selecting id, which is different for every record, the rows are not distinct. E.g.:

```<code>---------------------------------
| id | program_title | date     |
---------------------------------
|  1 | prog1         | 4/2/2017 |
|  2 | prog1         | 4/2/2017 |
---------------------------------
</code>```

You'll need to exclude the id from your #select for it to work:

```<code>Program.select(:date, :program_title).distinct
</code>```

Title: How to return distinct rows in rails?

Body:
I have a model Program containing fields program_title, department_id and date. I have inserted two rows having same program title and date but different department_id.

Insert into programs(program_title,date,department_id) Values ("prog1","4/2/2017","1");
Insert into programs(program_title,date,department_id) Values ("prog1","4/2/2017","2");

Now I want to return rows which will be distinct by program_title whatever be the department_id. I have tried,

@event_contents=Program.select(:id,:date,:program_title).distinct(:program_title)

But still it returns both the rows. Any help is appreciated.

Body:
SQL can only collapse rows where all values are the same when using DISTINCT. Because you are selecting id, which is different for every record, the rows are not distinct. E.g.:

---------------------------------
| id | program_title | date     |
---------------------------------
|  1 | prog1         | 4/2/2017 |
|  2 | prog1         | 4/2/2017 |
---------------------------------

You'll need to exclude the id from your #select for it to work:

Program.select(:date, :program_title).distinct


问:
How do display CommentForm in IndexView ? Django
I have comments for each post and I want that users can just type their comments and submit them on the same page 'IndexView'

here is my views.py

```<code>def IndexView(request):

    if request.user.is_authenticated():
        base_template_name = 'blog/base.html'
    else:
        base_template_name = 'blog/visitor.html'

    form = CommentForm()
    posts = Post.objects.all()

    return render(request, 'blog/index.html', {'form':form,'posts':posts,'base_template_name':base_template_name})

def add_comment_to_post(request, pk):
    post = get_object_or_404(Post, pk=pk)
    if request.method == "POST":
        form = CommentForm(request.POST)
        if form.is_valid():
            comment = form.save(commit=False)
            comment.post = post
            comment.save()
            context = {'form':form}
            return render(request,'blog/index.html', context)
    else:
        form = CommentForm()
    return render(request, 'blog/index.html', {'form': form})
</code>```

In index.html I put this (it displays the field put cannot submit it):

```<code><form enctype="multipart/form-data" method="post" class="post-form">
    {% csrf_token %}
    {{ form.textc }}
    <button type="submit" class="save btn btn-default">Send</button>
</form>
</code>```

Here is my CommentForm in forms.py

```<code>    class CommentForm(forms.ModelForm):
        class Meta:
            model = Comment
            fields = ('textc',)
</code>```

And urls.py for index and comment

```<code>    url(r'^post/(?P<pk>\d+)/comment/$', views.add_comment_to_post, name='add_comment_to_post'),
    url(r'^$', views.IndexView, name = 'index'),
</code>```

[Edit]: Here is my models.py

```<code>class Post(models.Model):
    user = models.ForeignKey(User, null=True)
    title = models.CharField(max_length=200)
    image = models.CharField(max_length=1000, blank=True)
    #slug = models.SlugField(max_length=255, null=True, blank=True)
    text = tinymce_models.HTMLField()
    created_date = models.DateTimeField(default=timezone.now)
    published_date = models.DateTimeField(blank=True, null=True)

    def publish(self):
        self.published_date = timezone.now()
        self.save()

    def get_absolute_url (self):
        return reverse('blog:index')

    def __str__(self):
        return self.title

class Comment(models.Model):
    post = models.ForeignKey('blog.Post', null=True,related_name='comments')
    user = models.ForeignKey(User, max_length=200, blank=True, null=True)
    textc = models.TextField(null=True,max_length=200)
    created_date = models.DateTimeField(default=timezone.now)
    approved_comment = models.BooleanField(default=False)
</code>```

Thanks alot guys !

答:
That's because inside the IndexView view (a good naming convention is use snake_case when its a function - index_view - and CamelCase when its a class - IndexView), you're not handling the POST data. Because you are not defining any action attribute inside the <form>, this form will be posted to the same url (same view).

Put this, inside the IndexView view:

```<code>def IndexView(request):
    form = CommentForm()
    if request.user.is_authenticated():
        base_template_name = 'blog/base.html'
    else:
        base_template_name = 'blog/visitor.html'
    if request.method == "POST":
        form = CommentForm(request.POST)
        if form.is_valid():
            # handle here the form.cleaned_data.get('textc')
            # and then redirect, if necessary
    posts = Post.objects.all()
    return render(request, 'blog/index.html', {'form': form, 'posts': posts, 'base_template_name': base_template_name})
</code>```

Body:
I have comments for each post and I want that users can just type their comments and submit them on the same page 'IndexView'

here is my views.py

def IndexView(request):

    if request.user.is_authenticated():
        base_template_name = 'blog/base.html'
    else:
        base_template_name = 'blog/visitor.html'

    form = CommentForm()
    posts = Post.objects.all()

    return render(request, 'blog/index.html', {'form':form,'posts':posts,'base_template_name':base_template_name})

def add_comment_to_post(request, pk):
    post = get_object_or_404(Post, pk=pk)
    if request.method == "POST":
        form = CommentForm(request.POST)
        if form.is_valid():
            comment = form.save(commit=False)
            comment.post = post
            comment.save()
            context = {'form':form}
            return render(request,'blog/index.html', context)
    else:
        form = CommentForm()
    return render(request, 'blog/index.html', {'form': form})

In index.html I put this (it displays the field put cannot submit it):

<form enctype="multipart/form-data" method="post" class="post-form">
    {% csrf_token %}
    {{ form.textc }}
    <button type="submit" class="save btn btn-default">Send</button>
</form>

Here is my CommentForm in forms.py

    class CommentForm(forms.ModelForm):
        class Meta:
            model = Comment
            fields = ('textc',)

And urls.py for index and comment

    url(r'^post/(?P<pk>\d+)/comment/$', views.add_comment_to_post, name='add_comment_to_post'),
    url(r'^$', views.IndexView, name = 'index'),

[Edit]: Here is my models.py

class Post(models.Model):
    user = models.ForeignKey(User, null=True)
    title = models.CharField(max_length=200)
    image = models.CharField(max_length=1000, blank=True)
    #slug = models.SlugField(max_length=255, null=True, blank=True)
    text = tinymce_models.HTMLField()
    created_date = models.DateTimeField(default=timezone.now)
    published_date = models.DateTimeField(blank=True, null=True)

    def publish(self):
        self.published_date = timezone.now()
        self.save()

    def get_absolute_url (self):
        return reverse('blog:index')

    def __str__(self):
        return self.title

class Comment(models.Model):
    post = models.ForeignKey('blog.Post', null=True,related_name='comments')
    user = models.ForeignKey(User, max_length=200, blank=True, null=True)
    textc = models.TextField(null=True,max_length=200)
    created_date = models.DateTimeField(default=timezone.now)
    approved_comment = models.BooleanField(default=False)

Thanks alot guys !

Body:
That's because inside the IndexView view (a good naming convention is use snake_case when its a function - index_view - and CamelCase when its a class - IndexView), you're not handling the POST data. Because you are not defining any action attribute inside the <form>, this form will be posted to the same url (same view).

Put this, inside the IndexView view:

def IndexView(request):
    form = CommentForm()
    if request.user.is_authenticated():
        base_template_name = 'blog/base.html'
    else:
        base_template_name = 'blog/visitor.html'
    if request.method == "POST":
        form = CommentForm(request.POST)
        if form.is_valid():
            # handle here the form.cleaned_data.get('textc')
            # and then redirect, if necessary
    posts = Post.objects.all()
    return render(request, 'blog/index.html', {'form': form, 'posts': posts, 'base_template_name': base_template_name})


问:
SQL Server : adding more than 1 where clause for a single column on the same table
I have a Project table and each project has multiple employees connected to it with different roles. I want to be able to filter the projects with more than one employee for example I want to get all the projects where "Janet" is the Sales Rep and "Mark" is the Project manager... This is what I tried so far and it doesn't show the expected results:

```<code>SELECT
    p_Empl.First_Name,
    p_Resources.cRole, p_Resources.Project_ID,
    p_Resources.Resources_ID, p_Resources.Empl_ID,
    p_Project.Project_ID AS Expr1,
    p_Project.ProjectNum,
    p_Empl.Last_Name
FROM
    p_Project
LEFT OUTER JOIN
    p_Resources ON p_Project.Project_ID = p_Resources.Project_ID
LEFT OUTER JOIN
    p_Empl ON p_Resources.Empl_ID = p_Empl.ID
WHERE
    p_Project.Project_ID IN (SELECT p_Project.Project_ID
                             FROM p_Project
                             LEFT OUTER JOIN p_Client ON p_Project.Client_ID = p_Client.Client_ID
                             WHERE p_Project.Project_ID IN (SELECT p_Project.Project_ID
                                                            FROM p_Project
                                                            INNER JOIN p_Resources ON p_Resources.Project_ID = p_Project.Project_ID
                                                            INNER JOIN p_Empl ON p_Resources.Empl_ID = p_Empl.ID
                                                            WHERE p_Empl.First_Name = 'Mark'
                                                              AND p_Resources.cRole = 'Sales Manager'
                                                            ORDER BY p_Project.Project_ID)
                              AND p_Project.Project_ID IN (SELECT p_Project.Project_ID
                                                           FROM p_Project
                                                           INNER JOIN p_Resources ON p_Resources.Project_ID = p_Project.Project_ID
                                                           INNER JOIN p_Empl ON p_Resources.Empl_ID = p_Empl.ID
                                                           WHERE p_Empl.First_Name = 'Janet'
                                                             AND p_Resources.cRole = 'Project Manager'
                                                          ORDER BY p_Project.Project_ID)
                             GROUP BY
                                 p_Project.Project_ID, p_Client.ClientName, p_Project.ProjectName, p_Project.ProjectNum
                             ORDER BY
                                 p_Client.ClientName, p_Project.ProjectName, p_Project.ProjectNum
                             OFFSET (25 * (1)) ROWS FETCH NEXT (25) ROWS ONLY)
</code>```

I'm very new to SQL and to programming altogether. I would really appreciate if someone can help me with this. Thanks.

答:
If you want the projects, then I would use aggregation:

```<code>SELECT p.Project_ID , p.ProjectNum
FROM p_Project p JOIN
     p_Resources r
     ON p.Project_ID = r.Project_ID LEFT OUTER JOIN
     p_Empl e
     ON r.Empl_ID = e_Empl.ID
WHERE (e.First_Name = 'Mark' AND r.cRole = 'Sales Manager') OR
      (e.First_Name = 'Janet' AND r.cRole = 'Project Manager')
GROUP BY p.Project_ID , p.ProjectNum
HAVING COUNT(DISTINCT e.First_Name) = 2;
</code>```

If you want all the detail for the projects, I would do something like this:

```<code>WITH per as (
      SELECT . . .   -- all the columns you want
      FROM p_Project p JOIN
           p_Resources r
           ON p.Project_ID = r.Project_ID LEFT OUTER JOIN
           p_Empl e
           ON r.Empl_ID = e_Empl.ID
     )
SELECT per.*
FROM per
WHERE per.Projecdt_Id IN (SELECT per2.ProjectId
                          FROM per per2
                          WHERE (per2.First_Name = 'Mark' AND per2.cRole = 'Sales Manager') OR
                                (per2.First_Name = 'Janet' AND per2.cRole = 'Project Manager')
                          GROUP BY p.Project_ID
                          HAVING COUNT(DISTINCT e.First_Name) = 2
                         );
</code>```

Body:
I have a Project table and each project has multiple employees connected to it with different roles. I want to be able to filter the projects with more than one employee for example I want to get all the projects where "Janet" is the Sales Rep and "Mark" is the Project manager... This is what I tried so far and it doesn't show the expected results:

SELECT
    p_Empl.First_Name,
    p_Resources.cRole, p_Resources.Project_ID,
    p_Resources.Resources_ID, p_Resources.Empl_ID,
    p_Project.Project_ID AS Expr1,
    p_Project.ProjectNum,
    p_Empl.Last_Name
FROM
    p_Project
LEFT OUTER JOIN
    p_Resources ON p_Project.Project_ID = p_Resources.Project_ID
LEFT OUTER JOIN
    p_Empl ON p_Resources.Empl_ID = p_Empl.ID
WHERE
    p_Project.Project_ID IN (SELECT p_Project.Project_ID
                             FROM p_Project
                             LEFT OUTER JOIN p_Client ON p_Project.Client_ID = p_Client.Client_ID
                             WHERE p_Project.Project_ID IN (SELECT p_Project.Project_ID
                                                            FROM p_Project
                                                            INNER JOIN p_Resources ON p_Resources.Project_ID = p_Project.Project_ID
                                                            INNER JOIN p_Empl ON p_Resources.Empl_ID = p_Empl.ID
                                                            WHERE p_Empl.First_Name = 'Mark'
                                                              AND p_Resources.cRole = 'Sales Manager'
                                                            ORDER BY p_Project.Project_ID)
                              AND p_Project.Project_ID IN (SELECT p_Project.Project_ID
                                                           FROM p_Project
                                                           INNER JOIN p_Resources ON p_Resources.Project_ID = p_Project.Project_ID
                                                           INNER JOIN p_Empl ON p_Resources.Empl_ID = p_Empl.ID
                                                           WHERE p_Empl.First_Name = 'Janet'
                                                             AND p_Resources.cRole = 'Project Manager'
                                                          ORDER BY p_Project.Project_ID)
                             GROUP BY
                                 p_Project.Project_ID, p_Client.ClientName, p_Project.ProjectName, p_Project.ProjectNum
                             ORDER BY
                                 p_Client.ClientName, p_Project.ProjectName, p_Project.ProjectNum
                             OFFSET (25 * (1)) ROWS FETCH NEXT (25) ROWS ONLY)

I'm very new to SQL and to programming altogether. I would really appreciate if someone can help me with this. Thanks.

Body:
If you want the projects, then I would use aggregation:

SELECT p.Project_ID , p.ProjectNum
FROM p_Project p JOIN
     p_Resources r
     ON p.Project_ID = r.Project_ID LEFT OUTER JOIN
     p_Empl e
     ON r.Empl_ID = e_Empl.ID
WHERE (e.First_Name = 'Mark' AND r.cRole = 'Sales Manager') OR
      (e.First_Name = 'Janet' AND r.cRole = 'Project Manager')
GROUP BY p.Project_ID , p.ProjectNum
HAVING COUNT(DISTINCT e.First_Name) = 2;

If you want all the detail for the projects, I would do something like this:

WITH per as (
      SELECT . . .   -- all the columns you want
      FROM p_Project p JOIN
           p_Resources r
           ON p.Project_ID = r.Project_ID LEFT OUTER JOIN
           p_Empl e
           ON r.Empl_ID = e_Empl.ID
     )
SELECT per.*
FROM per
WHERE per.Projecdt_Id IN (SELECT per2.ProjectId
                          FROM per per2
                          WHERE (per2.First_Name = 'Mark' AND per2.cRole = 'Sales Manager') OR
                                (per2.First_Name = 'Janet' AND per2.cRole = 'Project Manager')
                          GROUP BY p.Project_ID
                          HAVING COUNT(DISTINCT e.First_Name) = 2
                         );


问:
Is there a plugin that allows me to automatically unminify the Javascript included on a site?
Is there a plugin, add-on, Greasemonkey script or something similar (at worst, an easy to use proxy?) that automatically unminifies the Javascript files included on a site?

I know about e.g. jsbeautifier.org but doing this externally doesn't allow me to set breakpoints in the unminified code, for example.

Typical use cases for me:

Analysing and learning from complex web frontends.

Debugging Greasemonkey scripts which interact with the existing code.

I'm primarily interested in a solution that works with Firebug, but if there's something for the dev tools of Chrome or Opera, I'd like to hear about it as well.

答:
If the script is only minified for whitespace, some of the solutions offered may work.  As you mention, JSBeautifier is a useful tool.

However, if the JavaScript you're looking at has been compressed with a tool such as YUI Compressor or Google Closure Compiler, the variables are going to be shortened and harder to understand.

To see this in action, compare the minified and unminified versions of jQuery (minified version uses Closure Compiler).

original: https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.js

minified: https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js

For the goal of learning JavaScript, I recommend learning from libraries and plugins written by some of the best JavaScript developers out there.  Look at the source code for jQuery, YUI, Moo Tools.  Look at code on GitHub by people like John Resig or Thomas Fuchs.  Read DailyJs and look at his examples.

I hope some of these tools help you in the process of learning.  These are the resources that have helped me most.

ContentLicense: CC BY-SA 2.5


问:
Exploding string and putting values in <select>
I have a column in my db, tip_sting:
1 row example(each one has the same format):

G1-11, G2-21, P2-50, P4-20, P100-2,

I'm using this when editing a item(I want to create(as many selects in the string) and put the values automaticaly in the select) :

https://jsfiddle.net/avrzwt6k/

So I was thinking of doing something like:

```<code>$pieces = explode(",", $tip_stingu);
$a=count($pieces); // piece1
echo $a;
echo '<br>';
echo $pieces[1]; // piece2
echo '<br>';
$tip_stinga=explode("-",$pieces);
</code>```

I just dont know how could I continue?

答:
Using PHP & Javascript you can do:

```<code><html>
<body>
<form id="example" name="example">
    <select name="myName" id="myID" onchange="updateText()">
        <?php
            $tip_stingu = "G1-11, G2-21, P2-50, P4-20, P100-2,";
            $pieces = explode(', ', $tip_sting);
            $piece1 = explode('-', $pieces[0])[1];
            foreach($pieces as $piece) {
                $tip_stinga = explode("-", $piece);
                echo ('<option value="'.$tip_stinga[1].'">'.$tip_stinga[0].'</option>');
            }
echo '</select><input type="text" value="'.$piece1.'" id="quantity" /><br />'
    ?>

</form>

    <script>
    function updateText() {
        document.getElementById("quantity").value = document.getElementById("myID").value;
    }
    </script>

</body>
</html>
</code>```

You also have a trailing comma at the end of your example, if that's a problem you can use:

```<code>echo ('<option value="'.rtrim($tip_stinga[1], ',').'">'.$tip_stinga[0].'</option>');
</code>```

instead of:

```<code>echo ('<option value="'.$tip_stinga[1].'">'.$tip_stinga[0].'</option>');
</code>```

Body:
I have a column in my db, tip_sting:
1 row example(each one has the same format):

G1-11, G2-21, P2-50, P4-20, P100-2,

I'm using this when editing a item(I want to create(as many selects in the string) and put the values automaticaly in the select) :

https://jsfiddle.net/avrzwt6k/

So I was thinking of doing something like:

$pieces = explode(",", $tip_stingu);
$a=count($pieces); // piece1
echo $a;
echo '
';
echo $pieces[1]; // piece2
echo '
';
$tip_stinga=explode("-",$pieces);

I just dont know how could I continue?

Body:
Using PHP & Javascript you can do:

<html>
<body>
<form id="example" name="example">
    <select name="myName" id="myID" onchange="updateText()">
        <?php
            $tip_stingu = "G1-11, G2-21, P2-50, P4-20, P100-2,";
            $pieces = explode(', ', $tip_sting);
            $piece1 = explode('-', $pieces[0])[1];
            foreach($pieces as $piece) {
                $tip_stinga = explode("-", $piece);
                echo ('<option value="'.$tip_stinga[1].'">'.$tip_stinga[0].'</option>');
            }
echo '</select><input type="text" value="'.$piece1.'" id="quantity" /><br />'
    ?>

</form>

    <script>
    function updateText() {
        document.getElementById("quantity").value = document.getElementById("myID").value;
    }
    </script>

</body>
</html>

You also have a trailing comma at the end of your example, if that's a problem you can use:

echo ('<option value="'.rtrim($tip_stinga[1], ',').'">'.$tip_stinga[0].'</option>');

instead of:

echo ('<option value="'.$tip_stinga[1].'">'.$tip_stinga[0].'</option>');


问:
404 when accessing resource Flask-Restful
```<code>from flask import g, request, session, render_template, flash, redirect, url_for
from flask import current_app as app

@app.route('/')
def home():
    return 'this works'

from flask_restful import Resource, Api
from app.extensions import api

class HelloWorld(Resource):
    def get(self):
        return {'Hello': 'World'}

api.add_resource(HelloWorld, '/test')  # Getting a 404 for this route on http://127.0.0.1:5000/test
</code>```

Extensions sets up the api variable:

```<code>api = Api()
api.init_app(app)
</code>```

I cannot figure out why I get a 404 when trying to access an api resource?

答:
Ok, the problem seems to be that the below ordering is wrong. I must add resources before I init the api.

```<code>api = Api()
api.init_app(app)
api.add_resource(HelloWorld, '/')
</code>```

Fix:

```<code>api = Api()
api.add_resource(HelloWorld, '/')
api.init_app(app)
</code>```

This is quite strange given that e.g. SQLAlchemy needs to call init_app before it is used...

Body:
from flask import g, request, session, render_template, flash, redirect, url_for
from flask import current_app as app

@app.route('/')
def home():
    return 'this works'

from flask_restful import Resource, Api
from app.extensions import api

class HelloWorld(Resource):
    def get(self):
        return {'Hello': 'World'}

api.add_resource(HelloWorld, '/test')  # Getting a 404 for this route on http://127.0.0.1:5000/test

Extensions sets up the api variable:

api = Api()
api.init_app(app)

I cannot figure out why I get a 404 when trying to access an api resource?

Body:
Ok, the problem seems to be that the below ordering is wrong. I must add resources before I init the api.

api = Api()
api.init_app(app)
api.add_resource(HelloWorld, '/')

Fix:

api = Api()
api.add_resource(HelloWorld, '/')
api.init_app(app)

This is quite strange given that e.g. SQLAlchemy needs to call init_app before it is used...


问:
Automapper returns null
I've the abstract class AbsProduct

```<code>public abstract class AbsProduct
{
    [Key]
    public int ID { get; set; }
    public int Price { get; set; }
    public int Category { get; set; }
    public string Name { get; set; }

    public abstract double Accept(IProductVisitor visitor);

}
</code>```

and the ProductDTO:

```<code>public class ProductDTO
{
    public int ID { get; set; }
    public int Price { get; set; }
    public int Category { get; set; }
    public string Name { get; set; }
}
</code>```

My configuration is

```<code>AutoMapper.Mapper.Initialize(config =>
{
    config.CreateMap<AbsProduct, ProductDTO>();
    config.CreateMap<ProductDTO, AbsProduct>();
});
</code>```

The problem is when I try to map ProductDTO to AbsProduct:

```<code>var product = AutoMapper.Mapper.Map<ProductDTO, AbsProduct>(productDTO);
</code>```

AutoMapper is returning null, but the source(productDTO) isn't null.

答:
You can't instantiate an abstract class.

Try create a type that derives from AbsProduct and use that type instead of it.

Title: Automapper returns null

Body:
I've the abstract class AbsProduct

public abstract class AbsProduct
{
    [Key]
    public int ID { get; set; }
    public int Price { get; set; }
    public int Category { get; set; }
    public string Name { get; set; }

    public abstract double Accept(IProductVisitor visitor);

}

and the ProductDTO:

public class ProductDTO
{
    public int ID { get; set; }
    public int Price { get; set; }
    public int Category { get; set; }
    public string Name { get; set; }
}

My configuration is

AutoMapper.Mapper.Initialize(config =>
{
    config.CreateMap<AbsProduct, ProductDTO>();
    config.CreateMap<ProductDTO, AbsProduct>();
});

The problem is when I try to map ProductDTO to AbsProduct:

var product = AutoMapper.Mapper.Map<ProductDTO, AbsProduct>(productDTO);

AutoMapper is returning null, but the source(productDTO) isn't null.


问:
jQuery get a comma delimited list of fields with certain class
Im trying to get a comma delimited list of field names with a class that are dynamically created.

My end goal is to get appliance_1,appliance_2,appliance_3 inside a hidden field

```<code><input type="hidden" name="tracker" id="appliance-tracker" value="appliance_1,appliance_2,appliance_3">

<input class="appliances" name="appliance_1">
<input class="appliances" name="appliance_2">
<input class="appliances" name="appliance_3">
<script>
$("#btn").click(function(){
$("#appliance-tracker").val($("input.appliances").serialize());
});
</script>
</code>```

it keeps setting the value as
appliance_1=&appliance_2=&appliance_3=

Is there an easy way to do this that im completely missing ?

答:
You can use .map()

var text = $("input.appliances").map(function() {
    return $(this).attr('name');
  })
  .get() //returns basic array
  .join(','); //create a string

console.log(text)```
<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>
<input class="appliances" name="appliance_1">
<input class="appliances" name="appliance_2">
<input class="appliances" name="appliance_3"></code>```

Body:
Im trying to get a comma delimited list of field names with a class that are dynamically created.

My end goal is to get appliance_1,appliance_2,appliance_3 inside a hidden field

<input type="hidden" name="tracker" id="appliance-tracker" value="appliance_1,appliance_2,appliance_3">

<input class="appliances" name="appliance_1">
<input class="appliances" name="appliance_2">
<input class="appliances" name="appliance_3">

it keeps setting the value as
appliance_1=&appliance_2=&appliance_3=

Is there an easy way to do this that im completely missing ?

Body:
You can use .map()

var text = $("input.appliances").map(function() {
    return $(this).attr('name');
  })
  .get() //returns basic array
  .join(','); //create a string

console.log(text)

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input class="appliances" name="appliance_1">
<input class="appliances" name="appliance_2">
<input class="appliances" name="appliance_3">


问:
Difference Between arr1.concat(arr2) And [].concat(arr1, arr2)
In JavaScript, I've encountered code written in two primary ways for concatenating two (or more) arrays that employ the .concat() method on the Array object. (Assume, in what follows, that arr1 and arr2 are generic arrays given as the arguments to the .concat() method). At times, I see

```<code>arr1.concat(arr2)
</code>```

while, at others, I see the following used:

```<code>[].concat(arr1, arr2)
</code>```

I have not, in practice, found there to be any observable difference between the two manners of expression. Neither mutates the original array(s). Both return an identical output.

What differences, if any, are there? Is one more performant over the other? Do Best Practices advise one in particular?

Many thanks for all help/feedback!

EDIT

Shoutout for the JSPerf benchmarking test. It seems, as was noted by some in comments, that arr1.concat(arr2) is the preferred (and more natural syntax) as compared to [].concat(arr1, arr2). (I suppose that comes a bit subjectively, but feel most would agree in retrospect). Even so, there's added value to be had in choosing the former syntax over the latter if for no other reason than the marginally improved performance that it comes with.

答:
Actually, using [].concat(arr1, arr2), you are setting by default that the result has to be an array. You can concat strings and arrays or just strings or only arrays - and the result will be always an array.

If you wish the result to be a string - use empty quotation marks instead of empty array at the beginning.

console.log([].concat([1,2,3], 'text'));
console.log([].concat('text', 'new'));
console.log(''.concat([1,2,3], [4,5,6]));```
</div>
</div>
</p>

<p>Using <code>arr1.concat(arr2)</code>, the type of the first element - in this case - <code>arr1</code>, will be the default type of newly made object. So if <code>arr1</code> is a string, even if <code>arr2</code> is an array - the result wil be typeof <code>string</code>. </p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>console.log([1,2,3].concat('text'));
console.log('text'.concat([1,2,3]));</code>```

In both cases - the original arrays or strings are not being mutated.

About the performance - there are no notable differences between them.

Body:
In JavaScript, I've encountered code written in two primary ways for concatenating two (or more) arrays that employ the .concat() method on the Array object. (Assume, in what follows, that arr1 and arr2 are generic arrays given as the arguments to the .concat() method). At times, I see

arr1.concat(arr2)

while, at others, I see the following used:

[].concat(arr1, arr2)

I have not, in practice, found there to be any observable difference between the two manners of expression. Neither mutates the original array(s). Both return an identical output.

What differences, if any, are there? Is one more performant over the other? Do Best Practices advise one in particular?

Many thanks for all help/feedback!

EDIT

Shoutout for the JSPerf benchmarking test. It seems, as was noted by some in comments, that arr1.concat(arr2) is the preferred (and more natural syntax) as compared to [].concat(arr1, arr2). (I suppose that comes a bit subjectively, but feel most would agree in retrospect). Even so, there's added value to be had in choosing the former syntax over the latter if for no other reason than the marginally improved performance that it comes with.

Body:
Actually, using [].concat(arr1, arr2), you are setting by default that the result has to be an array. You can concat strings and arrays or just strings or only arrays - and the result will be always an array.

If you wish the result to be a string - use empty quotation marks instead of empty array at the beginning.

console.log([].concat([1,2,3], 'text'));
console.log([].concat('text', 'new'));
console.log(''.concat([1,2,3], [4,5,6]));

Using arr1.concat(arr2), the type of the first element - in this case - arr1, will be the default type of newly made object. So if arr1 is a string, even if arr2 is an array - the result wil be typeof string.

console.log([1,2,3].concat('text'));
console.log('text'.concat([1,2,3]));

In both cases - the original arrays or strings are not being mutated.

About the performance - there are no notable differences between them.


问:
enter cash payed after i`m done choosing my order
Im using visual basic language on visual studio 2010.I want to be asked to enter the cash payed after im done picking the order, now it asks to enter cash after every item i choose.

below you'll find the code and screenshots

```<code>Dim choice As String
Dim price As Double
Dim quantity As Integer
Dim total As Double
Dim tpayable As Double
Dim cash As Double
Dim change As Double
Dim spaces As String = Space(4)
Private Sub menue_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
    Dim spaces As String = Space(4)

End Sub

Private Sub badd_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles badd.Click
    quantity = InputBox("enter item quantity", "quantity")

    If RadioButton1.Checked Then
        choice = "Potato soup"
        price = "80"
    ElseIf RadioButton2.Checked Then
        choice = "Salmon roll"
        price = "100"
    ElseIf RadioButton3.Checked Then
        choice = "Smoked salmon potatos"
        price = "75"
    End If
    If RadioButton4.Checked Then
        choice = "Lasagna"
        price = "250"
    ElseIf RadioButton5.Checked Then
        choice = "Cheese burger"
        price = "120"
    ElseIf RadioButton6.Checked Then
        choice = "Pizza"
        price = "450"

    ElseIf RadioButton7.Checked Then
        choice = "ugali & sukuma"
        price = "80"
    ElseIf RadioButton8.Checked Then
        choice = "Chicken fried noodles"
        price = "150"
    End If
    If RadioButton9.Checked Then
        choice = "Chocolate fudge cake"
        price = "250"
    ElseIf RadioButton10.Checked Then
        choice = "Ice cream"
        price = "150"
    ElseIf RadioButton11.Checked Then
        choice = "Carrot Cake"
        price = "230"
    End If
    If RadioButton12.Checked Then
        choice = "Black tea"
        price = "80"
    ElseIf RadioButton13.Checked Then
        choice = "White tea"
        price = "80"
    ElseIf RadioButton14.Checked Then
        choice = "Coffee"
        price = "80"
    End If
    If RadioButton15.Checked Then
        choice = "Coke"
        price = "60"

    ElseIf RadioButton16.Checked Then
        choice = "Milkshake"
        price = "110"

    ElseIf RadioButton17.Checked Then
        choice = "Fanta"
        price = "60"
    End If

    total = quantity * price
    tpayable += total

    txttpayable.Text = Str(tpayable)

    cash = InputBox("enter cash payed")

    txtcgiven.Text = Str(cash)

    change = cash - tpayable

    txtchange.Text = Str(change)

    ListBox1.Items.Add(String.Concat(choice & spaces & price & spaces & quantity & spaces & total & spaces & tpayable))

End Sub
</code>```

screenshot

答:
The application can't read your mind. It can only react to some input from you. You need to handle an appropriate event to let the application know that you have made all the appropriate selections and so it needs to prompt. Looking more closely at your code, it appears that you have several groups of RadioButtons. Assuming that the user must select one option from each group, you can handle the CheckedChanged event of all the RadioButtons and then check whether one is checked from each group.  Here's a simplified example using two groups of two that you can extend to any number of groups and controls:

```<code>Private Sub RadioButtons_CheckedChanged(sender As Object, e As EventArgs) Handles RadioButton1.CheckedChanged,
                                                                                RadioButton2.CheckedChanged,
                                                                                RadioButton3.CheckedChanged,
                                                                                RadioButton4.CheckedChanged
    If Panel1.Controls.OfType(Of RadioButton)().Any(Function(rb) rb.Checked) AndAlso
       Panel2.Controls.OfType(Of RadioButton)().Any(Function(rb) rb.Checked) Then
        'A selection has been made from each group.
    End If
End Sub
</code>```

This assumes that RadioButton1 and RadioButton2 are on Panel1 and RadioButton2 and RadioButton3 are on Panel2. As I said, there can be as many groups as you like and each group can contain as many options as you like. Each group can be on a Panel, a GroupBox or some other container.

Body:
Im using visual basic language on visual studio 2010.I want to be asked to enter the cash payed after im done picking the order, now it asks to enter cash after every item i choose.

below you'll find the code and screenshots

Dim choice As String
Dim price As Double
Dim quantity As Integer
Dim total As Double
Dim tpayable As Double
Dim cash As Double
Dim change As Double
Dim spaces As String = Space(4)
Private Sub menue_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
    Dim spaces As String = Space(4)

End Sub

Private Sub badd_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles badd.Click
    quantity = InputBox("enter item quantity", "quantity")

    If RadioButton1.Checked Then
        choice = "Potato soup"
        price = "80"
    ElseIf RadioButton2.Checked Then
        choice = "Salmon roll"
        price = "100"
    ElseIf RadioButton3.Checked Then
        choice = "Smoked salmon potatos"
        price = "75"
    End If
    If RadioButton4.Checked Then
        choice = "Lasagna"
        price = "250"
    ElseIf RadioButton5.Checked Then
        choice = "Cheese burger"
        price = "120"
    ElseIf RadioButton6.Checked Then
        choice = "Pizza"
        price = "450"

    ElseIf RadioButton7.Checked Then
        choice = "ugali & sukuma"
        price = "80"
    ElseIf RadioButton8.Checked Then
        choice = "Chicken fried noodles"
        price = "150"
    End If
    If RadioButton9.Checked Then
        choice = "Chocolate fudge cake"
        price = "250"
    ElseIf RadioButton10.Checked Then
        choice = "Ice cream"
        price = "150"
    ElseIf RadioButton11.Checked Then
        choice = "Carrot Cake"
        price = "230"
    End If
    If RadioButton12.Checked Then
        choice = "Black tea"
        price = "80"
    ElseIf RadioButton13.Checked Then
        choice = "White tea"
        price = "80"
    ElseIf RadioButton14.Checked Then
        choice = "Coffee"
        price = "80"
    End If
    If RadioButton15.Checked Then
        choice = "Coke"
        price = "60"

    ElseIf RadioButton16.Checked Then
        choice = "Milkshake"
        price = "110"

    ElseIf RadioButton17.Checked Then
        choice = "Fanta"
        price = "60"
    End If

    total = quantity * price
    tpayable += total

    txttpayable.Text = Str(tpayable)

    cash = InputBox("enter cash payed")

    txtcgiven.Text = Str(cash)

    change = cash - tpayable

    txtchange.Text = Str(change)

    ListBox1.Items.Add(String.Concat(choice & spaces & price & spaces & quantity & spaces & total & spaces & tpayable))

End Sub

screenshot

Body:
The application can't read your mind. It can only react to some input from you. You need to handle an appropriate event to let the application know that you have made all the appropriate selections and so it needs to prompt. Looking more closely at your code, it appears that you have several groups of RadioButtons. Assuming that the user must select one option from each group, you can handle the CheckedChanged event of all the RadioButtons and then check whether one is checked from each group.  Here's a simplified example using two groups of two that you can extend to any number of groups and controls:

Private Sub RadioButtons_CheckedChanged(sender As Object, e As EventArgs) Handles RadioButton1.CheckedChanged,
                                                                                RadioButton2.CheckedChanged,
                                                                                RadioButton3.CheckedChanged,
                                                                                RadioButton4.CheckedChanged
    If Panel1.Controls.OfType(Of RadioButton)().Any(Function(rb) rb.Checked) AndAlso
       Panel2.Controls.OfType(Of RadioButton)().Any(Function(rb) rb.Checked) Then
        'A selection has been made from each group.
    End If
End Sub

This assumes that RadioButton1 and RadioButton2 are on Panel1 and RadioButton2 and RadioButton3 are on Panel2. As I said, there can be as many groups as you like and each group can contain as many options as you like. Each group can be on a Panel, a GroupBox or some other container.


问:
C# use different keyboard layout in different text boxes automatically?
I would like to have three textboxes for user input, but for each textbox I would like a different keyboard layout to be used while entering text (without the need to manually change the kayboard layout).

In textxbox 1 I would like my normal (swedish) keyboard layout to be used while I write. In the second I would like to have Japanese Hiragana layout. And in the third I would like too have Japanese Katakana layout.

Is it possible to do?

As it is now I must manually change the keyboard layout with Windowskey+Space (this cycles through all keyboard layouts).

答:
Hope this works for you:

```<code>private void textBox1_Enter(object sender, EventArgs e)
{
    // Get index of current Input Language
    int currentLang = InputLanguage.InstalledInputLanguages.IndexOf(InputLanguage.CurrentInputLanguage);
    // Calculate next Input Language
    InputLanguage nextLang = ++currentLang == InputLanguage.InstalledInputLanguages.Count ? InputLanguage.InstalledInputLanguages[0] : InputLanguage.InstalledInputLanguages[currentLang];
    // Change current Language to the calculated:
    ChangeInputLanguage(nextLang);
}

public void ChangeInputLanguage(InputLanguage InputLang)
{
    // Check is this Language really installed. Raise exception to warn if it is not:
    if (InputLanguage.InstalledInputLanguages.IndexOf(InputLang) == -1)
            throw new ArgumentOutOfRangeException();
    // InputLAnguage changes here:
    InputLanguage.CurrentInputLanguage = InputLang;
}
</code>```

Here is the reference link - Change Input Language programmatically?

Body:
Hope this works for you:

private void textBox1_Enter(object sender, EventArgs e)
{
    // Get index of current Input Language
    int currentLang = InputLanguage.InstalledInputLanguages.IndexOf(InputLanguage.CurrentInputLanguage);
    // Calculate next Input Language
    InputLanguage nextLang = ++currentLang == InputLanguage.InstalledInputLanguages.Count ? InputLanguage.InstalledInputLanguages[0] : InputLanguage.InstalledInputLanguages[currentLang];
    // Change current Language to the calculated:
    ChangeInputLanguage(nextLang);
}

public void ChangeInputLanguage(InputLanguage InputLang)
{
    // Check is this Language really installed. Raise exception to warn if it is not:
    if (InputLanguage.InstalledInputLanguages.IndexOf(InputLang) == -1)
            throw new ArgumentOutOfRangeException();
    // InputLAnguage changes here:
    InputLanguage.CurrentInputLanguage = InputLang;
}

Here is the reference link - Change Input Language programmatically?


问:
Importing CSV into MySQL Workbench with text fields that have newlines in data
Tried loading csv from a spreadsheet into MySQL Workbench using a solution found here

```<code>LOAD DATA LOCAL INFILE '/path/to/your/csv/file/model.csv' INTO TABLE test.dummy FIELDS TERMINATED BY ',' ENCLOSED BY '"' LINES TERMINATED BY '\n';
</code>```

The data loaded but some cells in the spreadsheet already contain new line characters. In these cases the LOAD created a new record.

```<code>Mathematics Kindergarten,Counting,"Say the number sequence 0 to 1000 forward and backward by:
- 5s, 10s or 100s, using any starting point
- 3s, using starting points that are multiples of 3
- 4s, using starting points that are multiples of 4
- 25s, using starting points that are multiples of 25."
</code>```

With a Table Like in this format:

```<code> Course   |   Topic    | Description
</code>```

The data loaded like so:

```<code>Mathematics Kindergarten   |    Counting    | "Say the number sequence 0 to 1000 forward and backward by:
- 5s, 10s or 100s, using any starting point              |                |
- 3s, using starting points that are multiples of 3      |                |
- 4s, using starting points that are multiples of 4      |                |
- 25s, using starting points that are multiples of 25."  |                |
</code>```

How can I have the system recognize to load the data so that the whole cell contains the full description and it's not broke over X records.

答:
The steps had me return to the document that I exported the CSV. I had to sanitize the data.

Find and Replace Carriage Returns and Newline Character present in cells with \n.
Also found some other cells that had comma , into html number ,

This corrected the issues with the data import tool of MySQL Workbench.

Body:
Tried loading csv from a spreadsheet into MySQL Workbench using a solution found here

LOAD DATA LOCAL INFILE '/path/to/your/csv/file/model.csv' INTO TABLE test.dummy FIELDS TERMINATED BY ',' ENCLOSED BY '"' LINES TERMINATED BY '\n';

The data loaded but some cells in the spreadsheet already contain new line characters. In these cases the LOAD created a new record.

Mathematics Kindergarten,Counting,"Say the number sequence 0 to 1000 forward and backward by:
- 5s, 10s or 100s, using any starting point
- 3s, using starting points that are multiples of 3
- 4s, using starting points that are multiples of 4
- 25s, using starting points that are multiples of 25."

With a Table Like in this format:

 Course   |   Topic    | Description

The data loaded like so:

Mathematics Kindergarten   |    Counting    | "Say the number sequence 0 to 1000 forward and backward by:
- 5s, 10s or 100s, using any starting point              |                |
- 3s, using starting points that are multiples of 3      |                |
- 4s, using starting points that are multiples of 4      |                |
- 25s, using starting points that are multiples of 25."  |                |

How can I have the system recognize to load the data so that the whole cell contains the full description and it's not broke over X records.

Body:
The steps had me return to the document that I exported the CSV. I had to sanitize the data.

Find and Replace Carriage Returns and Newline Character present in cells with \n.
Also found some other cells that had comma , into html number &#44;

This corrected the issues with the data import tool of MySQL Workbench.


问:
How to print from two lists
I have two lists with diffrent itemsas follows:

```<code>numbers = ['1','2','3','4','5','6','7',]

days = ['mon','tue','wed','thu','fri','sat','sun',]
</code>```

I want to print from both to look like this:

```<code>result = 1
         mon
         2
         tue
         3
         wed
         4
         thu.....etc
</code>```

Is there such as code that does this?
Regards

答:
You can print such output with this.

```<code>for n, m in zip(numbers, days):
   print(n, m)
</code>```

Output -

1 mon
2 tue
3 wed
4 thu
5 fri
6 sat
7 sun

Hope it helps.

Update - zip function combines two equal-length collections (e.g. list) together and produces a tuple object.

Title: How to print from two lists

Body:
I have two lists with diffrent itemsas follows:

numbers = ['1','2','3','4','5','6','7',]

days = ['mon','tue','wed','thu','fri','sat','sun',]

I want to print from both to look like this:

result = 1
         mon
         2
         tue
         3
         wed
         4
         thu.....etc

Is there such as code that does this?
Regards

Body:
You can print such output with this.

for n, m in zip(numbers, days):
   print(n, m)

Output -

1 mon
2 tue
3 wed
4 thu
5 fri
6 sat
7 sun

Hope it helps.

Update - zip function combines two equal-length collections (e.g. list) together and produces a tuple object.


问:
recycler views both horizontal ans vertical scrolling
I need both horizontal scrolling and vertical scrolling. how can be it possible using recycler views, or should i use 2 way views? Any one help me please.
How will set the adapter for the same?</p>

答:
you can add recycler view to your layout file </p>

```<code><android.support.v7.widget.RecyclerView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@+id/recycler_view"
            xmlns:android="http://schemas.android.com/apk/res/android" />
</code>```

<p>In java file set its orientation to horizontal or vertical </p>

```<code>LinearLayoutManager LayoutManager = new LinearLayoutManager(this);
LayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);// or LinearLayoutManager.VERTICAL
RecyclerView.setLayoutManager(LayoutManager);
</code>```

Body:
you can add recycler view to your layout file

<android.support.v7.widget.RecyclerView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@+id/recycler_view"
            xmlns:android="http://schemas.android.com/apk/res/android" />

In java file set its orientation to horizontal or vertical

LinearLayoutManager LayoutManager = new LinearLayoutManager(this);
LayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);// or LinearLayoutManager.VERTICAL
RecyclerView.setLayoutManager(LayoutManager);


问:
What is the difference between new Some::Class and Some::Class->new() in Perl?
Many years ago I remember a fellow programmer counselling this:

```<code>new Some::Class;    # bad! (but why?)

Some::Class->new(); # good!
</code>```

Sadly now I cannot remember the/his reason why. :( Both forms will work correctly even if the constructor does not actually exist in the Some::Class module but instead is inherited from a parent somewhere.

Neither of these forms are the same as Some::Class::new(), which will not pass the name of the class as the first parameter to the constructor -- so this form is always incorrect.

Even if the two forms are equivalent, I find Some::Class->new() to be much more clear, as it follows the standard convention for calling a method on a module, and in perl, the 'new' method is not special - a constructor could be called anything, and new() could do anything (although of course we generally expect it to be a constructor).

答: Another problem is that new Some::Class happens at run time.  If there is an error and you testing never branches to this statement, you never know it until it happens in production.  It is better to use Some::Class->new unless you are doing dynamic programing.

OwnerDisplayName: Ether

Body:
Many years ago I remember a fellow programmer counselling this:

new Some::Class;    # bad! (but why?)

Some::Class->new(); # good!

Sadly now I cannot remember the/his reason why. :( Both forms will work correctly even if the constructor does not actually exist in the Some::Class module but instead is inherited from a parent somewhere.

Neither of these forms are the same as Some::Class::new(), which will not pass the name of the class as the first parameter to the constructor -- so this form is always incorrect.

Even if the two forms are equivalent, I find Some::Class->new() to be much more clear, as it follows the standard convention for calling a method on a module, and in perl, the 'new' method is not special - a constructor could be called anything, and new() could do anything (although of course we generally expect it to be a constructor).

LastEditorDisplayName: Ether

OwnerDisplayName: Shawn H Corey


问:
BufferedWriter adds too many lines?
I wanted to ask if there is a better solution than using StringBuilder to cut some part of a String, which is parsed from a method through BufferedWriter to a file ?

Without StringBuilder there is a bunch of much strings in the file, what happens with the rest of string, data-nirvana ?

```<code>  class TaskStartPart {
   public void calculHash() throws InterruptedException, IOException,  NoSuchAlgorithmException {
    try {
     DigestInputStream digestInputStream=null ;
     MessageDigest messageDigest=MessageDigest.getInstance("SHA-512") ;
     digestInputStream=new DigestInputStream(new TaskPart(new   File("C:\\Users\\win7p\\Documents/t")),messageDigest) ;
    while(digestInputStream.read()>=0) ;
     for(byte b: messageDigest.digest()) {
      hexRes2 += String.format("%02x",b);
     } sb = new StringBuilder(hexRes2);  //StringBuilder which adjust the string to be parsed
     dateiSpeichern(0,0,sb.substring(hexRes2.length() -  128,hexRes2.length())); System.out.println(sb.substring(hexRes2.length() - 128,hexRes2.length()));
        digestInputStream.close();
      } catch (IOException ex ) {ex.printStackTrace();}
     }
    }

  class TaskPart extends InputStream {
    private File mFile ;
    private List<File> mFiles ;
    private InputStream mInputStream ;

   public TaskPart(File file) throws FileNotFoundException {
    mFile=file ;
    if(file.isDirectory()) {
    mFiles=new ArrayList<File>(Arrays.asList(file.listFiles())) ;
    Collections.sort(mFiles) ;
    mInputStream=nextInputStream() ;
   } else {
     mFiles=new ArrayList<File>() ;
     mInputStream=new FileInputStream(file) ;
   }
  }

  @Override
  public int read() throws IOException {
   int result=mInputStream==null?-1:mInputStream.read() ;
   if(result<0 && (mInputStream=nextInputStream())!=null)
    return read() ;
    else return result ;
   }

   protected String getRelativePath(File file) {
   return   file.getAbsolutePath().substring(mFile.getAbsolutePath().length()) ;
   }

   protected InputStream nextInputStream() throws FileNotFoundException {
    if(!mFiles.isEmpty()) {
     File nextFile=mFiles.remove(0) ;
    return new SequenceInputStream(
    new ByteArrayInputStream(getRelativePath(nextFile).getBytes()),
    new TaskPart(nextFile)) ;
   }
   else return null ;
  }
 }

  private void dateiSpeichern(int i1, int i2, String hexR) throws  InterruptedException, IOException {
   try {
    String tF = new SimpleDateFormat("dd-MM-yyyy HH-mm-ss").format(new   Date().getTime());
   try (BufferedWriter writer = new BufferedWriter(new FileWriter("C:\\Users\\win7p\\Documents/hashLog.txt", true))) {
   writer.append(tF);
   writer.newLine();
   writer.append(dtf);
   writer.newLine();
   writer.append("Hash Value: ");
   writer.append(hexR); //without StringBuilder I would have much //strings added next to eachone line by line
 } //normal here is also a catch code.
</code>```

答:
You don't really need a StringBuilder, since you just load it with a single String and then you just take out a substring from it.

You can just use String#substring method.

Garbage collection will take care of unreachable object in both cases.

StringBuilder is meant for building a String,and is essentially a mutable char buffer,you use it when you want to mutate a String several times(which is not your case).

Title: BufferedWriter adds too many lines?

Body:
I wanted to ask if there is a better solution than using StringBuilder to cut some part of a String, which is parsed from a method through BufferedWriter to a file ?

Without StringBuilder there is a bunch of much strings in the file, what happens with the rest of string, data-nirvana ?

  class TaskStartPart {
   public void calculHash() throws InterruptedException, IOException,  NoSuchAlgorithmException {
    try {
     DigestInputStream digestInputStream=null ;
     MessageDigest messageDigest=MessageDigest.getInstance("SHA-512") ;
     digestInputStream=new DigestInputStream(new TaskPart(new   File("C:\\Users\\win7p\\Documents/t")),messageDigest) ;
    while(digestInputStream.read()>=0) ;
     for(byte b: messageDigest.digest()) {
      hexRes2 += String.format("%02x",b);
     } sb = new StringBuilder(hexRes2);  //StringBuilder which adjust the string to be parsed
     dateiSpeichern(0,0,sb.substring(hexRes2.length() -  128,hexRes2.length())); System.out.println(sb.substring(hexRes2.length() - 128,hexRes2.length()));
        digestInputStream.close();
      } catch (IOException ex ) {ex.printStackTrace();}
     }
    }

  class TaskPart extends InputStream {
    private File mFile ;
    private List<File> mFiles ;
    private InputStream mInputStream ;

   public TaskPart(File file) throws FileNotFoundException {
    mFile=file ;
    if(file.isDirectory()) {
    mFiles=new ArrayList<File>(Arrays.asList(file.listFiles())) ;
    Collections.sort(mFiles) ;
    mInputStream=nextInputStream() ;
   } else {
     mFiles=new ArrayList<File>() ;
     mInputStream=new FileInputStream(file) ;
   }
  }

  @Override
  public int read() throws IOException {
   int result=mInputStream==null?-1:mInputStream.read() ;
   if(result<0 && (mInputStream=nextInputStream())!=null)
    return read() ;
    else return result ;
   }

   protected String getRelativePath(File file) {
   return   file.getAbsolutePath().substring(mFile.getAbsolutePath().length()) ;
   }

   protected InputStream nextInputStream() throws FileNotFoundException {
    if(!mFiles.isEmpty()) {
     File nextFile=mFiles.remove(0) ;
    return new SequenceInputStream(
    new ByteArrayInputStream(getRelativePath(nextFile).getBytes()),
    new TaskPart(nextFile)) ;
   }
   else return null ;
  }
 }

  private void dateiSpeichern(int i1, int i2, String hexR) throws  InterruptedException, IOException {
   try {
    String tF = new SimpleDateFormat("dd-MM-yyyy HH-mm-ss").format(new   Date().getTime());
   try (BufferedWriter writer = new BufferedWriter(new FileWriter("C:\\Users\\win7p\\Documents/hashLog.txt", true))) {
   writer.append(tF);
   writer.newLine();
   writer.append(dtf);
   writer.newLine();
   writer.append("Hash Value: ");
   writer.append(hexR); //without StringBuilder I would have much //strings added next to eachone line by line
 } //normal here is also a catch code.


问:
Regexp.last_match - why is it useful?
In "Comprehensive Ruby programming course' e-book, I faced a chapter, where author (Jordan Hudgens) describes it like:

“The last thing we are going to try is to return all the integer values from the sentence.”

And he does it like this:

```<code>string = "The quick 12 brown foxes jumped over 10 lazy dogs"
p string.to_enum(:scan, /\d+/).map { Regexp.last_match }
</code>```

And it returns:

```<code>=> [#<MatchData "3">, #<MatchData "34">, #<MatchData "23">]
</code>```

I wonder why / when, this Regexp.last_match might be used or better to say - why this way is not more efficient than:

```<code>p string.to_enum(:scan, /\d+/).map { |i| p i }
</code>```

This outputs only an array of integers and seems for me as a more efficient way to get those numbers..

Anyone maybe could explain what might was the reasons for author to pick Regesp.last_match ?

答:
Here's a more verbose but possibly cleaner solution if you want an Enumerator of MatchData instances :

```<code>class String
  def matches(regex)
    position = 0
    Enumerator.new do |yielder|
      while match = regex.match(self, position)
        yielder << match
        position = match.end(0)
      end
    end
  end
end

string = 'The quick 12 brown foxes jumped over 10 lazy dogs'
p string.matches(/\d+/).to_a
# [#<MatchData "12">, #<MatchData "10">]
p (2**1000000).to_s.matches(/(\d)\1{5}/).first(2)
# [#<MatchData "444444" 1:"4">, #<MatchData "888888" 1:"8">]
</code>```

If you don't want to monkey patch String, you could define this method in Regex or as a stand-alone method with string and regex as parameters.

Title: Regexp.last_match - why is it useful?

Body:
In "Comprehensive Ruby programming course' e-book, I faced a chapter, where author (Jordan Hudgens) describes it like:

“The last thing we are going to try is to return all the integer values from the sentence.”

And he does it like this:

string = "The quick 12 brown foxes jumped over 10 lazy dogs"
p string.to_enum(:scan, /\d+/).map { Regexp.last_match }

And it returns:

=> [#<MatchData "3">, #<MatchData "34">, #<MatchData "23">]

I wonder why / when, this Regexp.last_match might be used or better to say - why this way is not more efficient than:

p string.to_enum(:scan, /\d+/).map { |i| p i }

This outputs only an array of integers and seems for me as a more efficient way to get those numbers..

Anyone maybe could explain what might was the reasons for author to pick Regesp.last_match ?

Body:
Here's a more verbose but possibly cleaner solution if you want an Enumerator of MatchData instances :

class String
  def matches(regex)
    position = 0
    Enumerator.new do |yielder|
      while match = regex.match(self, position)
        yielder << match
        position = match.end(0)
      end
    end
  end
end

string = 'The quick 12 brown foxes jumped over 10 lazy dogs'
p string.matches(/\d+/).to_a
# [#<MatchData "12">, #<MatchData "10">]
p (2**1000000).to_s.matches(/(\d)\1{5}/).first(2)
# [#<MatchData "444444" 1:"4">, #<MatchData "888888" 1:"8">]

If you don't want to monkey patch String, you could define this method in Regex or as a stand-alone method with string and regex as parameters.


问:
How do I create an incrementing filename in Python?
I'm creating a program that will create a file and save it to the directory with the filename sample.xml. Once the file is saved when i try to run the program again it overwrites the old file into the new one because they do have the same file name. How do I increment the file names so that whenever I try to run the code again it will going to increment the file name. and will not overwrite the existing one. I am thinking of checking the filename first on the directory and if they are the same the code will generate a new filename:</p>

```<code>fh = open("sample.xml", "w")
rs = [blockresult]
fh.writelines(rs)
fh.close()
</code>```

答:
```<code>def get_nonexistant_path(fname_path):
    """
    Get the path to a filename which does not exist by incrementing path.

    Examples
    --------
    >>> get_nonexistant_path('/etc/issue')
    '/etc/issue-1'
    >>> get_nonexistant_path('whatever/1337bla.py')
    'whatever/1337bla.py'
    """
    if not os.path.exists(fname_path):
        return fname_path
    filename, file_extension = os.path.splitext(fname_path)
    i = 1
    new_fname = "{}-{}{}".format(filename, i, file_extension)
    while os.path.exists(new_fname):
        i += 1
        new_fname = "{}-{}{}".format(filename, i, file_extension)
    return new_fname
</code>```

Before you open the file, call

```<code>fname = get_nonexistant_path("sample.xml")
</code>```

This will either give you 'sample.xml' or - if this alreay exists - 'sample-i.xml' where i is the lowest positive integer such that the file does not already exist.

I recommend using os.path.abspath("sample.xml"). If you have ~ as home directory, you might need to expand it first.

Please note that race conditions might occur with this simple code if you have multiple instances running at the same time. If this might be a problem, please check this question.

Body:
I'm creating a program that will create a file and save it to the directory with the filename sample.xml. Once the file is saved when i try to run the program again it overwrites the old file into the new one because they do have the same file name. How do I increment the file names so that whenever I try to run the code again it will going to increment the file name. and will not overwrite the existing one. I am thinking of checking the filename first on the directory and if they are the same the code will generate a new filename:

fh = open("sample.xml", "w")
rs = [blockresult]
fh.writelines(rs)
fh.close()

Body:
def get_nonexistant_path(fname_path):
    """
    Get the path to a filename which does not exist by incrementing path.

    Examples
    --------
    >>> get_nonexistant_path('/etc/issue')
    '/etc/issue-1'
    >>> get_nonexistant_path('whatever/1337bla.py')
    'whatever/1337bla.py'
    """
    if not os.path.exists(fname_path):
        return fname_path
    filename, file_extension = os.path.splitext(fname_path)
    i = 1
    new_fname = "{}-{}{}".format(filename, i, file_extension)
    while os.path.exists(new_fname):
        i += 1
        new_fname = "{}-{}{}".format(filename, i, file_extension)
    return new_fname

Before you open the file, call

fname = get_nonexistant_path("sample.xml")

This will either give you 'sample.xml' or - if this alreay exists - 'sample-i.xml' where i is the lowest positive integer such that the file does not already exist.

I recommend using os.path.abspath("sample.xml"). If you have ~ as home directory, you might need to expand it first.

Please note that race conditions might occur with this simple code if you have multiple instances running at the same time. If this might be a problem, please check this question.


问:
Reverse proxy in nginx for nextcloud?
How do I set a reverse proxy for nextcloud?
This is my current config but it doesn't work:

```<code>server {
  listen 8000;
  server_name cloud.prjctdesign.com;
  return 301 https://$host$request_uri;
}

server {
  listen 4430 ssl http2;
  server_name cloud.prjctdesign.com;

  ssl_certificate /certs/cloud.prjctdesign.com.crt;
  ssl_certificate_key /certs/cloud.prjctdesign.com.key;

  include /etc/nginx/conf/ssl_params.conf;

  client_max_body_size 10G; # change this value it according to $UPLOAD_MAX_SIZE

  location / {
    proxy_pass http://192.168.178.32;
    include /etc/nginx/conf/proxy_params;
  }
}
</code>```

Also I enabled SSL using a let's encrypt cert. I run Nextcloud in the official VM image provided by Nextcloud / Techandme

I believe there is something wrong with the HSTS but I have no idea how it works. Also I based my forwarding off of this

答:
I figured it out.
The reference to the ssl certificate is incorrect. Either run NGINX on the same server you are running nextcloud and redirect nginx to the position of the .cert file  as in these lines:

```<code> ssl_certificate /certs/cloud.prjctdesign.com.crt;
 ssl_certificate_key /certs/cloud.prjctdesign.com.key;
</code>```

or generate a new cert on the nginx server and point the config towards it.

Title: Reverse proxy in nginx for nextcloud?

Body:
How do I set a reverse proxy for nextcloud?
This is my current config but it doesn't work:

server {
  listen 8000;
  server_name cloud.prjctdesign.com;
  return 301 https://$host$request_uri;
}

server {
  listen 4430 ssl http2;
  server_name cloud.prjctdesign.com;

  ssl_certificate /certs/cloud.prjctdesign.com.crt;
  ssl_certificate_key /certs/cloud.prjctdesign.com.key;

  include /etc/nginx/conf/ssl_params.conf;

  client_max_body_size 10G; # change this value it according to $UPLOAD_MAX_SIZE

  location / {
    proxy_pass http://192.168.178.32;
    include /etc/nginx/conf/proxy_params;
  }
}

Also I enabled SSL using a let's encrypt cert. I run Nextcloud in the official VM image provided by Nextcloud / Techandme

I believe there is something wrong with the HSTS but I have no idea how it works. Also I based my forwarding off of this

Body:
I figured it out.
The reference to the ssl certificate is incorrect. Either run NGINX on the same server you are running nextcloud and redirect nginx to the position of the .cert file  as in these lines:

 ssl_certificate /certs/cloud.prjctdesign.com.crt;
 ssl_certificate_key /certs/cloud.prjctdesign.com.key;

or generate a new cert on the nginx server and point the config towards it.


问:
Ng2 Data sharing between components via Services
I am still facing the same problem, after following each steps.

Angular2 data Sharing

Still Not able to share the data between components via Shared Services.

My Workflow: After login via Login's Service, I wanted to share the UserDetails Response to the About Page.

I have only injected the Login Service in app.module.ts in @NgModule as providers

===Login Component=====

```<code>import { Component } from '@angular/core';
import { Http } from '@angular/http';
import { UserAccount } from '../model/userAccount.interface';
import { LoginService } from './login.service';
import { Router } from '@angular/router';

@Component({
selector: 'app-login',
templateUrl: './login.component.html',
})

export class LoginComponent  {

emailAddress : string;
password : string;
submitted : boolean;
errorMessage : string;

constructor(private loginService: LoginService, private router : Router) {
    this.submitted = false;
}

login() {
    // event.preventDefault();
    this.submitted = true;
    this.loginService.getLogin(this.emailAddress, this.password).subscribe(
        u => this.router.navigate(['/about']),
        error =>  this.errorMessage = <any>error);
}
</code>```

}

===Login Service====

```<code>@Injectable()
export class LoginService {
   private userAccount : UserAccount[];

  constructor (private http: Http) {}

getLogin(): Observable<UserAccount[]> {
  return this.http.get(this.url)
                .map(this.extractData);
}

private extractData(res: Response) {
  let body = res.json();
  this.userAccount = body.data.user[0]
  return this.userAccount || { };
}

 getUserDetails() {
  return this.userAccount;
}
}
</code>```

======About Component=====

```<code>export class AboutComponent implements OnInit{

// initialize a private variable _data, it's a BehaviorSubject
// private _data = new BehaviorSubject<UserAccount[]>([]);
userDetails : UserAccount[];
lService : LoginService;

constructor(loginService: LoginService) {
    this.lService = loginService;
    this.userDetails = this.lService.getUserDetails();
    console.log(this.userDetails);
}

ngOnInit() {

}
}
</code>```

答:
Change .map(this.extractData);

to

```<code>.map((res)=>this.extractData(res));
</code>```

or .map(this.extractData.bind(this));

your this is not refering to your component inside the map function in the first one.

Body:
I am still facing the same problem, after following each steps.

Angular2 data Sharing

Still Not able to share the data between components via Shared Services.

My Workflow: After login via Login's Service, I wanted to share the UserDetails Response to the About Page.

I have only injected the Login Service in app.module.ts in @NgModule as providers

===Login Component=====

import { Component } from '@angular/core';
import { Http } from '@angular/http';
import { UserAccount } from '../model/userAccount.interface';
import { LoginService } from './login.service';
import { Router } from '@angular/router';

@Component({
selector: 'app-login',
templateUrl: './login.component.html',
})

export class LoginComponent  {

emailAddress : string;
password : string;
submitted : boolean;
errorMessage : string;

constructor(private loginService: LoginService, private router : Router) {
    this.submitted = false;
}

login() {
    // event.preventDefault();
    this.submitted = true;
    this.loginService.getLogin(this.emailAddress, this.password).subscribe(
        u => this.router.navigate(['/about']),
        error =>  this.errorMessage = <any>error);
}

}

===Login Service====

@Injectable()
export class LoginService {
   private userAccount : UserAccount[];

  constructor (private http: Http) {}

getLogin(): Observable<UserAccount[]> {
  return this.http.get(this.url)
                .map(this.extractData);
}

private extractData(res: Response) {
  let body = res.json();
  this.userAccount = body.data.user[0]
  return this.userAccount || { };
}

 getUserDetails() {
  return this.userAccount;
}
}

======About Component=====

export class AboutComponent implements OnInit{

// initialize a private variable _data, it's a BehaviorSubject
// private _data = new BehaviorSubject<UserAccount[]>([]);
userDetails : UserAccount[];
lService : LoginService;

constructor(loginService: LoginService) {
    this.lService = loginService;
    this.userDetails = this.lService.getUserDetails();
    console.log(this.userDetails);
}

ngOnInit() {

}
}

Body:
Change .map(this.extractData);

to

.map((res)=>this.extractData(res));

or .map(this.extractData.bind(this));

your this is not refering to your component inside the map function in the first one.


问:
escape single quotes
I have a table like this...

```<code>select * from myescape;
+-----------+
| name      |
+-----------+
| shantanu' |
| kumar's   |
+-----------+
2 rows in set (0.00 sec)
</code>```

I need to replace the single quote ' with \'

I will also need to escape double quotes and backslash.

答:
Try this:</p>

```<code>SELECT REPLACE( REPLACE( name , "'", "\\'" ) , '"', '\\"' )
FROM myescape
</code>```

Title: escape single quotes

Body:
I have a table like this...

select * from myescape;
+-----------+
| name      |
+-----------+
| shantanu' |
| kumar's   |
+-----------+
2 rows in set (0.00 sec)

I need to replace the single quote ' with \'

I will also need to escape double quotes and backslash.

Body:
Try this:

SELECT REPLACE( REPLACE( name , "'", "\\'" ) , '"', '\\"' )
FROM myescape