问:
How utilize user input later in another method
For the following, I'm having a difficult time understanding how to use my user input from (days) and utilizing it on the last line to calculate the # of hours and minutes based on the user input of (days).</p>

```<code>import java.util.Scanner;

public class LearnScanner {
    public static void main (String[] args) {
        first();
        next();
        third();
    }
    public static void first() {
        Scanner input = new Scanner(System.in);
        System.out.println("Welcome to Vacation Planner!!");
        System.out.print("What is your name?");
        String name = input.nextLine();
        System.out.print("Nice to meet you "+name +", where are you travelling to?");
        String destination = input.nextLine();
        System.out.print("Great! "+destination +" sounds like a great trip");
     }
    public static void next() {
        Scanner input = new Scanner(System.in);
        System.out.print("How many days are you going to spend travelling?");
        String days = input.nextLine();
        System.out.print("How much money in USD are you planning to spend on your trip?");
        String budget = input.nextLine();
        System.out.print("What is the three letter currency symbol for your travel destination?");
        String currency = input.nextLine();
        System.out.print("How many " + currency + " are there in 1 USD?");
        String currencyConversion = input.nextLine();
    }
    public static void third() {
        String days;
        String hours = days * 24;
        String minutes = hours * 60;

        System.out.println("If your are travelling for " + days + " days that is the same as " + hours + " hours or " + minutes + " minutes");
    }
}
</code>```

答:
Make your next() method return String, not void.

```<code>public static String next() {
    Scanner input = new Scanner(System.in);
    System.out.print("How many days are you going to spend travelling?");
    String days = input.nextLine();
    System.out.print("How much money in USD are you planning to spend on your trip?");
    String budget = input.nextLine();
    System.out.print("What is the three letter currency symbol for your travel destination?");
    String currency = input.nextLine();
    System.out.print("How many " + currency + " are there in 1 USD?");
    String currencyConversion = input.nextLine();
    return days;
}
</code>```

And then in your third() method change the following line of code:

```<code>String days;
</code>```

with

```<code>int days = Integer.valueOf(next());
</code>```

Change also the next two lines of code with the following:

```<code>int hours = days * 24;
int minutes = hours * 60;
</code>```

Body:
For the following, I'm having a difficult time understanding how to use my user input from (days) and utilizing it on the last line to calculate the # of hours and minutes based on the user input of (days).

import java.util.Scanner;

public class LearnScanner {
    public static void main (String[] args) {
        first();
        next();
        third();
    }
    public static void first() {
        Scanner input = new Scanner(System.in);
        System.out.println("Welcome to Vacation Planner!!");
        System.out.print("What is your name?");
        String name = input.nextLine();
        System.out.print("Nice to meet you "+name +", where are you travelling to?");
        String destination = input.nextLine();
        System.out.print("Great! "+destination +" sounds like a great trip");
     }
    public static void next() {
        Scanner input = new Scanner(System.in);
        System.out.print("How many days are you going to spend travelling?");
        String days = input.nextLine();
        System.out.print("How much money in USD are you planning to spend on your trip?");
        String budget = input.nextLine();
        System.out.print("What is the three letter currency symbol for your travel destination?");
        String currency = input.nextLine();
        System.out.print("How many " + currency + " are there in 1 USD?");
        String currencyConversion = input.nextLine();
    }
    public static void third() {
        String days;
        String hours = days * 24;
        String minutes = hours * 60;

        System.out.println("If your are travelling for " + days + " days that is the same as " + hours + " hours or " + minutes + " minutes");
    }
}

Body:
Make your next() method return String, not void.

public static String next() {
    Scanner input = new Scanner(System.in);
    System.out.print("How many days are you going to spend travelling?");
    String days = input.nextLine();
    System.out.print("How much money in USD are you planning to spend on your trip?");
    String budget = input.nextLine();
    System.out.print("What is the three letter currency symbol for your travel destination?");
    String currency = input.nextLine();
    System.out.print("How many " + currency + " are there in 1 USD?");
    String currencyConversion = input.nextLine();
    return days;
}

And then in your third() method change the following line of code:

String days;

with

int days = Integer.valueOf(next());

Change also the next two lines of code with the following:

int hours = days * 24;
int minutes = hours * 60;


来源: stackexchange

问:
jQuery to add Browser-Name into css-class
I'm using jQuery to detect the Users Browser-Agent and than add the browser-name as a css-class to the body. This works like magic with webkit and mozilla … but with msie it fails — but don't know why. For msie i also have to add not only the «msie», but also one class with the version-number of the used msie (like «msie7» or «msie8»).

Everything works, only the msie-section does not!

my (full) jQuery-Code:

```<code>    <script type="text/javascript">
<!--
(function($){
    $(function(){

        var $copy = $('div.SPA_printcontact').clone();
        var $body = $('body');

        $copy.insertAfter('#printdate');

        if($.browser.msie) {
            $body.addClass('msie')
            var userAgent = userAgent.substring(0,userAgent.indexOf('.'));
            var version = userAgent;
            $body.addClass('msie' + version)
        }
        if($.browser.webkit) {
            $body.addClass('webkit')
        }
        if($.browser.mozilla) {
            $body.addClass('mozilla')
        }

    });
}(jQuery));
-->
</script>
</code>```

答:
http://api.jquery.com/jQuery.browser/

Try using $.browser.version to get the version no instead

EDIT: This has been deprecated in jQuery v1.9 and upwards. Please refer to Tom's answer below.

ContentLicense: CC BY-SA 2.5

ContentLicense: CC BY-SA 3.0


问:
how to sum two fields
I'm trying to perform Arithmetic Operators and this is my query ,

```<code>SELECT

    GLB.BEGIN_BALANCE_DR_BEQ + GLB.BEGIN_BALANCE_CR_BEQ AS ACTIVITY,
    GLB.PERIOD_NET_DR + GLB.PERIOD_NET_CR AS BEG_BALANCE ,
    ACTIVITY + BEG_BALANCE AS END_BALANCE,
    SUM(ACTIVITY) AS TOTAL_ACT,
    SUM(BEG_BALANCE) AS TOTAL_BEG_BALANCE,
    SUM(END_BALANCE) AS TOTAL_END_BALANCE,
</code>```

But it didn't work , Can anyone guide me how can I fix it ?!

答:
You can't use alias in the same select level (and you can't use aggregation level and not aggregated  column without a proper group by)  in  yor case </p>

<p>you should use a subquery for a fast use of alias eg:  </p>

```<code>  SELECT
      SUM(ACTIVITY) AS TOTAL_ACT,
      SUM(BEG_BALANCE) AS TOTAL_BEG_BALANCE,
      SUM(END_BALANCE) AS TOTAL_END_BALANCE
      FROM(
        SELECT

        GLB.BEGIN_BALANCE_DR_BEQ + GLB.BEGIN_BALANCE_CR_BEQ AS ACTIVITY,
        GLB.PERIOD_NET_DR + GLB.PERIOD_NET_CR AS BEG_BALANCE ,
        ACTIVITY + BEG_BALANCE AS END_BALANCE
        FROM My_TABLE
      ) T
</code>```

Title: how to sum two fields

Body:
I'm trying to perform Arithmetic Operators and this is my query ,

SELECT

    GLB.BEGIN_BALANCE_DR_BEQ + GLB.BEGIN_BALANCE_CR_BEQ AS ACTIVITY,
    GLB.PERIOD_NET_DR + GLB.PERIOD_NET_CR AS BEG_BALANCE ,
    ACTIVITY + BEG_BALANCE AS END_BALANCE,
    SUM(ACTIVITY) AS TOTAL_ACT,
    SUM(BEG_BALANCE) AS TOTAL_BEG_BALANCE,
    SUM(END_BALANCE) AS TOTAL_END_BALANCE,

But it didn't work , Can anyone guide me how can I fix it ?!

Body:
You can't use alias in the same select level (and you can't use aggregation level and not aggregated  column without a proper group by)  in  yor case

you should use a subquery for a fast use of alias eg:

  SELECT
      SUM(ACTIVITY) AS TOTAL_ACT,
      SUM(BEG_BALANCE) AS TOTAL_BEG_BALANCE,
      SUM(END_BALANCE) AS TOTAL_END_BALANCE
      FROM(
        SELECT

        GLB.BEGIN_BALANCE_DR_BEQ + GLB.BEGIN_BALANCE_CR_BEQ AS ACTIVITY,
        GLB.PERIOD_NET_DR + GLB.PERIOD_NET_CR AS BEG_BALANCE ,
        ACTIVITY + BEG_BALANCE AS END_BALANCE
        FROM My_TABLE
      ) T


问:
MVC Razor Validation Errors showing on page load when no data has been posted
I'm messing around with data annotations. When I click on a link to go to a page, the validation messages are being displayed, but I would like to have the validation messages not show unless data has been posted.

View:

```<code>@Html.TextBoxFor(m => m.EmailAddress, new { @placeholder = "Enter Email", @class = "form-control" })
@Html.ValidationSummary(true, "Registration Failed. Check your credentials")
@Html.ValidationMessageFor(m => m.EmailAddress, "You must enter a valid Email Address.")
</code>```

Model:

```<code>[Required(ErrorMessage = "Email is required")]
[DataType(DataType.EmailAddress)]
[EmailAddress]
[Display(Name = "Email Address: ")]
public string EmailAddress { get; set; }
</code>```

Controller:

```<code>[HttpGet]
        public ActionResult AddUser()
        {
            return View();
        }

        [HttpPost]
        public ActionResult AddUser(UserCreateViewModel user)
        {
            if (ModelState.IsValid)
            {
                var success = UserRepository.AddUser(user);

                if (success)
                {
                    return View("Success");
                }
            }

            return View("AddUser");
        }
</code>```

Like I said, my problem occurs on page load of the AddUser view. When I click on the link to view the AddUser page, validation messages are showing after it loads, yet at this point no data has been posted and the model is empty.

答:
```<code>.field-validation-valid {
  display: none;
}
</code>```

Whenever the validation triggers on page load, this ".field-validation-valid" value is automatically added to the class attribute of the triggered input element.

By adding CSS to display none as that particular class's value, you'll no longer see the validation messages on initial page load.

The validation messages will still display normally after the particular input element has been touched.

Body:
I'm messing around with data annotations. When I click on a link to go to a page, the validation messages are being displayed, but I would like to have the validation messages not show unless data has been posted.

View:

@Html.TextBoxFor(m => m.EmailAddress, new { @placeholder = "Enter Email", @class = "form-control" })
@Html.ValidationSummary(true, "Registration Failed. Check your credentials")
@Html.ValidationMessageFor(m => m.EmailAddress, "You must enter a valid Email Address.")

Model:

[Required(ErrorMessage = "Email is required")]
[DataType(DataType.EmailAddress)]
[EmailAddress]
[Display(Name = "Email Address: ")]
public string EmailAddress { get; set; }

Controller:

[HttpGet]
        public ActionResult AddUser()
        {
            return View();
        }

        [HttpPost]
        public ActionResult AddUser(UserCreateViewModel user)
        {
            if (ModelState.IsValid)
            {
                var success = UserRepository.AddUser(user);

                if (success)
                {
                    return View("Success");
                }
            }

            return View("AddUser");
        }

Like I said, my problem occurs on page load of the AddUser view. When I click on the link to view the AddUser page, validation messages are showing after it loads, yet at this point no data has been posted and the model is empty.

Body:
.field-validation-valid {
  display: none;
}

Whenever the validation triggers on page load, this ".field-validation-valid" value is automatically added to the class attribute of the triggered input element.

By adding CSS to display none as that particular class's value, you'll no longer see the validation messages on initial page load.

The validation messages will still display normally after the particular input element has been touched.


问:
Add Token to headers request in TEST mode DRF
how is possible to add 'Authorization': 'Token' to TEST request in Django/DRF?

If i use simple requests.get(url, headers={'Authorization': 'Token'} all work perfect but how to do such request in TestCase?

答:
Ref: http://www.django-rest-framework.org/api-guide/testing/#credentialskwargs</p>

```<code>from rest_framework.authtoken.models import Token
from rest_framework.test import APIClient

# Include an appropriate `Authorization:` header on all requests.
token = Token.objects.get(user__username='lauren')
client = APIClient()
client.credentials(HTTP_AUTHORIZATION='Token ' + token.key)
</code>```

Body:
Ref: http://www.django-rest-framework.org/api-guide/testing/#credentialskwargs

from rest_framework.authtoken.models import Token
from rest_framework.test import APIClient

# Include an appropriate `Authorization:` header on all requests.
token = Token.objects.get(user__username='lauren')
client = APIClient()
client.credentials(HTTP_AUTHORIZATION='Token ' + token.key)


问:
Return two screens back in dynpro sequence
I want to develop the following logic:

The box "DISPLAY ALV" corresponds to the function module REUSE_ALV_GRID_DISPLAY.

With LEAVE TO SCREEN 0 I can't pass directly to DISPLAY ALV. Is it possible?

Thank you.

答: I can't say for sure if this will work but you should try 'set screen 0'.  I recently had to do this after programming a 'refresh' button into my ALV report, because after refreshing and re-displaying data, it took multiple 'green arrow' clicks to get out of the report. </p>

ContentLicense: CC BY-SA 4.0


问:
Angular extend error handler cyclic error
I am trying to extend the angular ErrorHandler so that I can redirect my application to another component and do some logging.

I created the error handler like so:

```<code>import { Router } from '@angular/router';
import { ErrorHandler, Injectable, Injector } from '@angular/core';

@Injectable()
export class GlobalErrorHandler implements ErrorHandler {
    constructor(
        private injector: Injector,
        private router: Router
    ) {}

    handleError(error) {
        this.router.navigateByUrl('/error');
        //throw error;
    }
}
</code>```

app.module:

```<code>providers:[ { provide: ErrorHandler, useClass: GlobalErrorHandler } ]
</code>```

When I try and load my application like this, I am getting the following error.

```<code>compiler.es5.js:11684 Uncaught Error: Provider parse errors:
Cannot instantiate cyclic dependency! Router ("[ERROR ->]"): in NgModule AppModule in ./AppModule@-1:-1
</code>```

It sounds like it is something to do with the router tat I am trying to import to be able to do the redirect.

Any thoughts?

答:
Instead of this

```<code>providers:[ { provide: ErrorHandler, useClass: GlobalErrorHandler } ]
</code>```

You should do this

```<code>providers:[ErrorHandler, GlobalErrorHandler]
</code>```

It's just a simple Array

Hope it helps

Body:
I am trying to extend the angular ErrorHandler so that I can redirect my application to another component and do some logging.

I created the error handler like so:

import { Router } from '@angular/router';
import { ErrorHandler, Injectable, Injector } from '@angular/core';

@Injectable()
export class GlobalErrorHandler implements ErrorHandler {
    constructor(
        private injector: Injector,
        private router: Router
    ) {}

    handleError(error) {
        this.router.navigateByUrl('/error');
        //throw error;
    }
}

app.module:

providers:[ { provide: ErrorHandler, useClass: GlobalErrorHandler } ]

When I try and load my application like this, I am getting the following error.

compiler.es5.js:11684 Uncaught Error: Provider parse errors:
Cannot instantiate cyclic dependency! Router ("[ERROR ->]"): in NgModule AppModule in ./AppModule@-1:-1

It sounds like it is something to do with the router tat I am trying to import to be able to do the redirect.

Any thoughts?

Body:
Instead of this

providers:[ { provide: ErrorHandler, useClass: GlobalErrorHandler } ]

You should do this

providers:[ErrorHandler, GlobalErrorHandler]

It's just a simple Array

Hope it helps


问:
How to delete the cache from UIWebview or dealloc UIWebview
Every time I load a new page with UIWebView the before loaded page is shown for a short time.

How can I clear that cache? Another possibility would be to dealloc UIWebview. I tried that but than my UIWebView is always "empty". How should the alloc and dealloc be done in this case?

I noticed that the UIWebView is consuming about 10 MB RAM. Now the UIWebView is loaded together with the ViewController. And the view is autoreleased as well as the UIWebView is autoreleased. Wouldn't it be better to dealloc the WebView each time?

Solution:

```<code>- (void) viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];

    CGRect frame = CGRectMake(0, 0, 320, 480);
    self.webView = [[[UIWebView alloc]initWithFrame:frame] autorelease];
    self.webView.scalesPageToFit = YES;
    [self.view addSubview:self.webView];
}

- (void) viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];

    [self.webView removeFromSuperview];
    self.webView = nil;
}
</code>```

答:
I did something simpler, I just set the webView's alpha to 0 on loadRequest and 1 on webViewDidFinishLoad.

```<code>thewebview.alpha=0.0;
thewebview.backgroundColor=[UIColor whiteColor];
[thewebview loadRequest:[NSURLRequest requestWithURL:url(str)]];
</code>```

and

```<code>- (void)webViewDidFinishLoad:(UIWebView *)webView {
    thewebview.alpha=1.0;
}
</code>```

(Actually I have a fade-in, as rendering f.ex. a PDF can take 1/5 seconds or so.)

Body:
Every time I load a new page with UIWebView the before loaded page is shown for a short time.

How can I clear that cache? Another possibility would be to dealloc UIWebview. I tried that but than my UIWebView is always "empty". How should the alloc and dealloc be done in this case?

I noticed that the UIWebView is consuming about 10 MB RAM. Now the UIWebView is loaded together with the ViewController. And the view is autoreleased as well as the UIWebView is autoreleased. Wouldn't it be better to dealloc the WebView each time?

Solution:

- (void) viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];

    CGRect frame = CGRectMake(0, 0, 320, 480);
    self.webView = [[[UIWebView alloc]initWithFrame:frame] autorelease];
    self.webView.scalesPageToFit = YES;
    [self.view addSubview:self.webView];
}

- (void) viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];

    [self.webView removeFromSuperview];
    self.webView = nil;
}

Body:
I did something simpler, I just set the webView's alpha to 0 on loadRequest and 1 on webViewDidFinishLoad.

thewebview.alpha=0.0;
thewebview.backgroundColor=[UIColor whiteColor];
[thewebview loadRequest:[NSURLRequest requestWithURL:url(str)]];

and

- (void)webViewDidFinishLoad:(UIWebView *)webView {
    thewebview.alpha=1.0;
}

(Actually I have a fade-in, as rendering f.ex. a PDF can take 1/5 seconds or so.)


问:
How do I exclude a directory when using `find`?
How do I exclude a specific directory when searching for *.js files using find?

```<code>find . -name '*.js'
</code>```

答:
For those of you on older versions of UNIX who cannot use -path or -not

Tested on SunOS 5.10 bash 3.2 and SunOS 5.11 bash 4.4

```<code>find . -type f -name "*" -o -type d -name "*excluded_directory*" -prune -type f
</code>```

Body:
How do I exclude a specific directory when searching for *.js files using find?

find . -name '*.js'

Body:
For those of you on older versions of UNIX who cannot use -path or -not

Tested on SunOS 5.10 bash 3.2 and SunOS 5.11 bash 4.4

find . -type f -name "*" -o -type d -name "*excluded_directory*" -prune -type f


问:
django admin login suddenly demanding csrf token
I was logging into my django admin console easily a few minutes ago. I must have changed something somewhere that caused this error when logging in as superuser:

Forbidden (403)
CSRF verification failed. Request aborted.

This error caught me off guard as I was logging in all night. Why would I suddenly need a csrf token for admin login? You would think the sign in form already has that. This is my admin.py:

```<code>from django.contrib import admin
from accounts.models import Image, Category, UserProfile

class ImageAdmin(admin.ModelAdmin):
    list_display    = ["__unicode__", "title", "created"]

admin.site.register(Image, GenericImageAdmin)

class CategoryAdmin(admin.ModelAdmin):
    list_display    = ["category"]

admin.site.register(Category, CategoryAdmin)

admin.site.register(UserProfile)
</code>```

答:
As a security measure, I had CSRF_COOKIE_SECURE = True in my settings. Trying to log into admin via localhost where there isn't HTTPS threw the forbidden error.

Set it to False to get it working on localhost

Body:
I was logging into my django admin console easily a few minutes ago. I must have changed something somewhere that caused this error when logging in as superuser:

Forbidden (403)
CSRF verification failed. Request aborted.

This error caught me off guard as I was logging in all night. Why would I suddenly need a csrf token for admin login? You would think the sign in form already has that. This is my admin.py:

from django.contrib import admin
from accounts.models import Image, Category, UserProfile

class ImageAdmin(admin.ModelAdmin):
    list_display    = ["__unicode__", "title", "created"]

admin.site.register(Image, GenericImageAdmin)

class CategoryAdmin(admin.ModelAdmin):
    list_display    = ["category"]

admin.site.register(Category, CategoryAdmin)

admin.site.register(UserProfile)


问:
Notify build status from Jenkins to Bitbucket Server
We have installed Jenkins v2.7.3 and Bitbucket Server v4.9.1 on premise and would like to send build status as notifications from Jenkins to Bitbucket Server.

So far I have only found solutions (1 and 2) for Bitbucket Cloud, but nothing for Bitbucket Server. Any tip on how to make this happen?

https://wiki.jenkins-ci.org/display/JENKINS/Bitbucket+Cloud+Build+Status+Notifier+Plugin

https://wiki.jenkins-ci.org/display/JENKINS/Bitbucket+OAuth+Plugin

答:
You need Stash Pull Request Builder Plugin
This Jenkins plugin builds pull requests from an Atlassian Stash server and will report the test results as a comment. This plugin was inspired by the GitHub & BitBucket pull request builder plugins

https://plugins.jenkins.io/stash-pullrequest-builder


问:
How do I read a file line by line while modifying lines as needed?
In Perl, I'm trying to read a file line by line and process each line, modifying it as required.
So far, the only way I'm reading to be able to do this is read the file into an array, modify each element of the array as needed, then when it's finished, output it back to the file.

Is there a better way to do this, perhaps some way I can replace single lines as I go along?

Right now, my processing code looks like this:

```<code>while (my $line = <FILE>)
{
    # process line here
    # ...........

    print FILE $line;
}
</code>```

My code seems to be very close, except that it's replacing one line after the line I'm currently in, so it seems that if I could back the file pointer up by one line, it would write to the correct place in the file.

Am I on the right track? What would I need to do from here to back up the file pointer so it writes to the same line I'm reading from?

Edit:

Out of the answers I received, both using local $^I and Tie::File worked nicely.
I ended up going with Tie::File so I wouldn't have to print out every line of the file. This way if something happens midway through the script, my file won't be messed up.

My new code looks like this:

```<code>use Tie::File;

chomp(my $filename = $ARGV[0]);
tie my @array, 'Tie::File', $filename or die $!;

foreach my $line(@array)
{
    # ...... line processing happens here .......
    # ...... $line is automatically written to file if $line is changed .......
}
</code>```

答:
May not be relevant to the problem, but quick changes to a file in-place can be done on the command line, e.g.

```<code># convert MS line endings to UNIX:
perl -p -i -e 's{\r\n}{\n}' my_file.txt
</code>```

The line is $_ in the code (the argument to -e) and the line is printed out, so it's an in-place version of something like this:

```<code>perl -e '$line = $_; $line =~ s{\r\n}{\n}; print $line' < windows.txt > unix.txt
</code>```

Body:
In Perl, I'm trying to read a file line by line and process each line, modifying it as required.
So far, the only way I'm reading to be able to do this is read the file into an array, modify each element of the array as needed, then when it's finished, output it back to the file.

Is there a better way to do this, perhaps some way I can replace single lines as I go along?

Right now, my processing code looks like this:

while (my $line = <FILE>)
{
    # process line here
    # ...........

    print FILE $line;
}

My code seems to be very close, except that it's replacing one line after the line I'm currently in, so it seems that if I could back the file pointer up by one line, it would write to the correct place in the file.

Am I on the right track? What would I need to do from here to back up the file pointer so it writes to the same line I'm reading from?

Edit:

Out of the answers I received, both using local $^I and Tie::File worked nicely.
I ended up going with Tie::File so I wouldn't have to print out every line of the file. This way if something happens midway through the script, my file won't be messed up.

My new code looks like this:

use Tie::File;

chomp(my $filename = $ARGV[0]);
tie my @array, 'Tie::File', $filename or die $!;

foreach my $line(@array)
{
    # ...... line processing happens here .......
    # ...... $line is automatically written to file if $line is changed .......
}

Body:
May not be relevant to the problem, but quick changes to a file in-place can be done on the command line, e.g.

# convert MS line endings to UNIX:
perl -p -i -e 's{\r\n}{\n}' my_file.txt

The line is $_ in the code (the argument to -e) and the line is printed out, so it's an in-place version of something like this:

perl -e '$line = $_; $line =~ s{\r\n}{\n}; print $line' < windows.txt > unix.txt


问:
Maximum path sum for Mario in 2-d maze
I have a problem which goes something like this...

Mario is stuck in a 2d maze (M*N array). He is currently on the first row (any cell). He is restricted to 3 types of movements - down, left and right. Each cell has a fruit (with +ve or -ve value). A fruit is consumed when Mario passes through a cell and accordingly the points obtained either increase or decrease after which the fruit ceases to exist. The aim is to find the maximum points for Mario by getting him to the last row.

So I have boiled down the problem to the following ...

A 2d array of dimensions M*N is available. Each cell has either a +ve or -ve value. We can either move down, left or right, but in doing so we nullify the current cell(make it 0). We have to find the maximum sum possible for traversal from the first row to the last row.

The method I designed :

```<code>int maxVal(int[][] mat)
    {
        int r = mat.length;
        int c = mat[0].length;
        int[][] maxValues = new int[r][c];
        for (int i = 0; i < r; i++) {
            for (int j = 0; j < c; j++) {
                if (i == 0 && j == 0) {
                    maxValues[i][j] = mat[i][j];
                    mat[i][j] = 0;
                } else if (i == 0) {
                    maxValues[i][j] = maxValues[i][j - 1] + mat[i][j];
                    maxValues[i][j - 1] = 0;
                } else if (j == 0) {
                    maxValues[i][j] = maxValues[i - 1][j] + mat[i][j];
                    maxValues[i - 1][j] = 0;
                } else {
                    int temp = Math.max(maxValues[i][j - 1], maxValues[i - 1][j]);
                    if (j + 1 < c) {
                        temp = Math.max(temp, maxValues[i][j + 1]);
                        if (maxValues[i][j + 1] >= maxValues[i][j - 1]
                                && maxValues[i][j + 1] >= maxValues[i - 1][j]) {
                            maxValues[i][j + 1]=0;
                        }
                        else if (maxValues[i][j - 1] >= maxValues[i][j + 1]
                                && maxValues[i][j - 1] >= maxValues[i - 1][j]) {
                            maxValues[i][j - 1]=0;
                        }
                        else if (maxValues[i-1][j ] >= maxValues[i][j - 1]
                                && maxValues[i-1][j] >= maxValues[i][j+1]) {
                            maxValues[i-1][j]=0;
                        }
                    }
                    else{
                        if(maxValues[i-1][j ] >= maxValues[i][j - 1])
                            maxValues[i-1][j]=0;
                        else if(maxValues[i][j-1 ] >= maxValues[i-1][j ])
                            maxValues[i][j-1]=0;
                    }

                    temp += mat[i][j];
                    maxValues[i][j] = temp;
                }
            }
        }
        return maxValues[r - 1][c - 1];
    }
</code>```

I would like feedback as to what I am doing wrong as I am clearly overlooking something.

答: You should reconsider your approach. Your goal is to examine all possible paths, then choose the one with highest value. I suggest using a recursion approach.</p>

Title: Maximum path sum for Mario in 2-d maze

Body:
I have a problem which goes something like this...

Mario is stuck in a 2d maze (M*N array). He is currently on the first row (any cell). He is restricted to 3 types of movements - down, left and right. Each cell has a fruit (with +ve or -ve value). A fruit is consumed when Mario passes through a cell and accordingly the points obtained either increase or decrease after which the fruit ceases to exist. The aim is to find the maximum points for Mario by getting him to the last row.

So I have boiled down the problem to the following ...

A 2d array of dimensions M*N is available. Each cell has either a +ve or -ve value. We can either move down, left or right, but in doing so we nullify the current cell(make it 0). We have to find the maximum sum possible for traversal from the first row to the last row.

The method I designed :

int maxVal(int[][] mat)
    {
        int r = mat.length;
        int c = mat[0].length;
        int[][] maxValues = new int[r][c];
        for (int i = 0; i < r; i++) {
            for (int j = 0; j < c; j++) {
                if (i == 0 && j == 0) {
                    maxValues[i][j] = mat[i][j];
                    mat[i][j] = 0;
                } else if (i == 0) {
                    maxValues[i][j] = maxValues[i][j - 1] + mat[i][j];
                    maxValues[i][j - 1] = 0;
                } else if (j == 0) {
                    maxValues[i][j] = maxValues[i - 1][j] + mat[i][j];
                    maxValues[i - 1][j] = 0;
                } else {
                    int temp = Math.max(maxValues[i][j - 1], maxValues[i - 1][j]);
                    if (j + 1 < c) {
                        temp = Math.max(temp, maxValues[i][j + 1]);
                        if (maxValues[i][j + 1] >= maxValues[i][j - 1]
                                && maxValues[i][j + 1] >= maxValues[i - 1][j]) {
                            maxValues[i][j + 1]=0;
                        }
                        else if (maxValues[i][j - 1] >= maxValues[i][j + 1]
                                && maxValues[i][j - 1] >= maxValues[i - 1][j]) {
                            maxValues[i][j - 1]=0;
                        }
                        else if (maxValues[i-1][j ] >= maxValues[i][j - 1]
                                && maxValues[i-1][j] >= maxValues[i][j+1]) {
                            maxValues[i-1][j]=0;
                        }
                    }
                    else{
                        if(maxValues[i-1][j ] >= maxValues[i][j - 1])
                            maxValues[i-1][j]=0;
                        else if(maxValues[i][j-1 ] >= maxValues[i-1][j ])
                            maxValues[i][j-1]=0;
                    }

                    temp += mat[i][j];
                    maxValues[i][j] = temp;
                }
            }
        }
        return maxValues[r - 1][c - 1];
    }

I would like feedback as to what I am doing wrong as I am clearly overlooking something.


问:
Most efficient way of storing exact set membership?
I have N slots.  There are M slots occupied.

I want to be able to tell exactly whether each slot is occupied.  (No Bloom filter answers, please.)

What is the absolute most storage-space efficient way of storing this information for M << N?

Guess 0: A bitmap of N bits.

Guess 1: An array of the positions of the occupied slots.  Reasonably good for small M.

Guess 2: p0 + (M-1)p1 + (M-1)(M-2)p2 + ... where pX is the position of an occupied slot, among the remaining unoccupied slots.  This is slightly more efficient than guess 1, as the choice of unoccupied slot narrows as slots are filled.

Guess 2 still has a lot of waste; it includes the order in which the slots were filled, which is information that is not required.

What method is more efficient than Guess 2?

答:
Assuming that there is no other information about the distribution of the values (i.e., every possible sample of M values is equally probable) then the optimal compression technique is that given by @PeterdeRivaz, which is to simply using the ordinal of the enumeration of the sample out of the set of possible samples.

However, that is not trivial to compute, since the enumeration requires arithmetic on very large numbers.

Instead, it is possible to use a variant on Golomb compression, with only a small impact on the compression ratio.

Assume the numbers in the sample are in order. We start by computing the successive differences. Because we will never have two equal numbers, the sequence of differences will never include a 0; to gain a tiny additional compression, we start with one more than the first element of the sample, rather than the first element itself -- which means that the sequence never contains a 0 -- and then subtract one from each value. We now select some convenient number of bits k, and encode each value δ in the sequence as follows:

While δ > 2k, send a 1 bit and subtract 2k from δ

Now δ can be written in k bits. Send a 0 followed by the k-bit value of δ

We can choose k as ⌊log2(N/M)⌋, which means that N < 2k+1M. (Taking the ceiling would be another possibility.) Consequently, the number of 1 bits sent in all of the iterations of step 1 in the above algorithm is less than 2M (because each 1 accounts for 2k of the cumulative sum of the series, which is less than N). Each step 2 sends exactly k + 1 bits, and there are exactly M executions of step 2, one for each value in the sample. Thus, the total number of bits sent is somewhere between M × (k + 1) and M × (k + 2). But since we know k < log2(N/M) + 1, the total size of the transmission is certainly less than M log2 N - M log2 M + 3M). (We also have to send the parameters k and M, so there is a bit of overhead.)

Now, let's consider the optimal transmission size. There are N choose M possible samples, so the size of the enumeration index in bits will be log2(N choose M). If N ≫ M, we can approximate N choose M as NM/M!, and then using Stirling's approximation we get:

```<code>log(N choose M) ≈ M log N − M log M + M
</code>```

(That's actually a slight overestimate, but it is asymptotically correct.)

Thus, the difference between the compressed sequence and the information-theoretic limit is less than 2 bits per value. (In practice, it is generally around one bit per value, because step 1 executes far less than the maximum number of times.)

Body:
Assuming that there is no other information about the distribution of the values (i.e., every possible sample of M values is equally probable) then the optimal compression technique is that given by @PeterdeRivaz, which is to simply using the ordinal of the enumeration of the sample out of the set of possible samples.

However, that is not trivial to compute, since the enumeration requires arithmetic on very large numbers.

Instead, it is possible to use a variant on Golomb compression, with only a small impact on the compression ratio.

Assume the numbers in the sample are in order. We start by computing the successive differences. Because we will never have two equal numbers, the sequence of differences will never include a 0; to gain a tiny additional compression, we start with one more than the first element of the sample, rather than the first element itself -- which means that the sequence never contains a 0 -- and then subtract one from each value. We now select some convenient number of bits k, and encode each value δ in the sequence as follows:

While δ > 2k, send a 1 bit and subtract 2k from δ

Now δ can be written in k bits. Send a 0 followed by the k-bit value of δ

We can choose k as ⌊log2(N/M)⌋, which means that N < 2k+1M. (Taking the ceiling would be another possibility.) Consequently, the number of 1 bits sent in all of the iterations of step 1 in the above algorithm is less than 2M (because each 1 accounts for 2k of the cumulative sum of the series, which is less than N). Each step 2 sends exactly k + 1 bits, and there are exactly M executions of step 2, one for each value in the sample. Thus, the total number of bits sent is somewhere between M × (k + 1) and M × (k + 2). But since we know k < log2(N/M) + 1, the total size of the transmission is certainly less than M log2 N - M log2 M + 3M). (We also have to send the parameters k and M, so there is a bit of overhead.)

Now, let's consider the optimal transmission size. There are N choose M possible samples, so the size of the enumeration index in bits will be log2(N choose M). If N ≫ M, we can approximate N choose M as NM/M!, and then using Stirling's approximation we get:

log(N choose M) ≈ M log N − M log M + M

(That's actually a slight overestimate, but it is asymptotically correct.)

Thus, the difference between the compressed sequence and the information-theoretic limit is less than 2 bits per value. (In practice, it is generally around one bit per value, because step 1 executes far less than the maximum number of times.)


问:
EDSDK 3.6 macOS - 32bit vs 64bit and linking errors
I'm trying to use the Canon EDSDK (latest version, v3.6 as of writing) in a simple, C++, command-line program on macOS (Sierra 10.12.6).  I wish to utilize a simple Makefile environment and the usual apple compiler tools (llvm-clang) and avoid Xcode or any other heavy-weight IDE. The samples included with the SDK are all Xcode centric so I've had to roll my own here.

At present, I am able to compile a program to init the SDK and list connected cameras.  As soon as I execute any EDSDK command however, I am getting a dynamic linking error:

```<code>Error loading /Library/Frameworks/EDSDK.framework/Versions/A/DppCore.bundle/Contents/PlugIns/DppCoreG.bundle/Contents/MacOS/DppCoreG:  dlopen(/Library/Frameworks/EDSDK.framework/Versions/A/DppCore.bundle/Contents/PlugIns/DppCoreG.bundle/Contents/MacOS/DppCoreG, 262): no suitable image found
Did find: ... snip ... mach-o, but wrong architecture
</code>```

The same error lists twice (both for DppCoreG). Upon examination, DppCoreG is compiled for 64bit architecture:

```<code>file /Library/Frameworks/..snip../DppCoreG
/Library/Frameworks/..snip../DppCoreG: Mach-O 64-bit bundle x86_64
</code>```

However, there are other critical parts of the EDSDK that are compiled for 32bit architecture only:

```<code>file /...snip.../DPP.framework/DPP
/...snip.../DPP.framework/DPP: Mach-O dynamically linked shared library i386
</code>```

How do I resolve this? The path of least resistance so far is to compile to i386 architecture explicitly (and the documentation explicitly states EDSDK is not 64-bit compatible). All is well except this one dynamic linking error (and in fact everything I've tried so far, which is just listing connected cameras, seems to work okay) but it is something I'm sure I can't continue to ignore or allow to persist in a production version of this project.

Here's a minimal example to cause the DYLD error:

```<code>#include <EDSDK.h>
#include <EDSDKTypes.h>
#include <EDSDKErrors.h>

int main(int argc, char** argv) {
  EdsInitializeSDK();
  EdsTerminateSDK();
  return 0;
}
</code>```

And probably more informative is the command to compile:

```<code>c++ -D __MACOS__ -g -arch i386 -I./deps/mac/include -framework DPP -framework EDSDK -o min min.cpp
</code>```

I have the headers in the local include directory shown in the command and the frameworks installed under /Library/Frameworks.

Note that the c++ command is Apple LLVM version 8.1.0 (clang-802.0.42)

答: Since the 3.x version there is a split between intergrated versions of DPP RAW capabilities. The original DPP works in x86 mode only and allows inspection and conversion of CR2 files on cams up until a certain models. See the API doc for the list. For recent camera models which rely on the new 64bit DPP engine (v4+?, dppcoreg) you would need x86_64 bit build so it dynamically links to use the latest features. Quite some (Raw) features are dropped, and gradually make their way back in in beta state.</p>

Body:
I'm trying to use the Canon EDSDK (latest version, v3.6 as of writing) in a simple, C++, command-line program on macOS (Sierra 10.12.6).  I wish to utilize a simple Makefile environment and the usual apple compiler tools (llvm-clang) and avoid Xcode or any other heavy-weight IDE. The samples included with the SDK are all Xcode centric so I've had to roll my own here.

At present, I am able to compile a program to init the SDK and list connected cameras.  As soon as I execute any EDSDK command however, I am getting a dynamic linking error:

Error loading /Library/Frameworks/EDSDK.framework/Versions/A/DppCore.bundle/Contents/PlugIns/DppCoreG.bundle/Contents/MacOS/DppCoreG:  dlopen(/Library/Frameworks/EDSDK.framework/Versions/A/DppCore.bundle/Contents/PlugIns/DppCoreG.bundle/Contents/MacOS/DppCoreG, 262): no suitable image found
Did find: ... snip ... mach-o, but wrong architecture

The same error lists twice (both for DppCoreG). Upon examination, DppCoreG is compiled for 64bit architecture:

file /Library/Frameworks/..snip../DppCoreG
/Library/Frameworks/..snip../DppCoreG: Mach-O 64-bit bundle x86_64

However, there are other critical parts of the EDSDK that are compiled for 32bit architecture only:

file /...snip.../DPP.framework/DPP
/...snip.../DPP.framework/DPP: Mach-O dynamically linked shared library i386

How do I resolve this? The path of least resistance so far is to compile to i386 architecture explicitly (and the documentation explicitly states EDSDK is not 64-bit compatible). All is well except this one dynamic linking error (and in fact everything I've tried so far, which is just listing connected cameras, seems to work okay) but it is something I'm sure I can't continue to ignore or allow to persist in a production version of this project.

Here's a minimal example to cause the DYLD error:

#include <EDSDK.h>
#include <EDSDKTypes.h>
#include <EDSDKErrors.h>

int main(int argc, char** argv) {
  EdsInitializeSDK();
  EdsTerminateSDK();
  return 0;
}

And probably more informative is the command to compile:

c++ -D __MACOS__ -g -arch i386 -I./deps/mac/include -framework DPP -framework EDSDK -o min min.cpp

I have the headers in the local include directory shown in the command and the frameworks installed under /Library/Frameworks.

Note that the c++ command is Apple LLVM version 8.1.0 (clang-802.0.42)


问:
How can I convert JSON to CSV?
I have a JSON file I want to convert to a CSV file. How can I do this with Python?

I tried:

import json
import csv

f = open('data.json')
data = json.load(f)
f.close()

f = open('data.csv')
csv_file = csv.writer(f)
for item in data:
    csv_file.writerow(item)

f.close()
```
<p>However, it did not work. I am using Django and the error I received is:</p>
<pre class="lang-none prettyprint-override"><code>`file' object has no attribute 'writerow'`
</code>```

I then tried the following:

import json
import csv

f = open('data.json')
data = json.load(f)
f.close()

f = open('data.csv')
csv_file = csv.writer(f)
for item in data:
    f.writerow(item)  # ← changed

f.close()
```
<p>I then get the error:</p>
<pre class="lang-none prettyprint-override"><code>`sequence expected`
</code>```

Sample json file:

```<code>[{
        "pk": 22,
        "model": "auth.permission",
        "fields": {
            "codename": "add_logentry",
            "name": "Can add log entry",
            "content_type": 8
        }
    }, {
        "pk": 23,
        "model": "auth.permission",
        "fields": {
            "codename": "change_logentry",
            "name": "Can change log entry",
            "content_type": 8
        }
    }, {
        "pk": 24,
        "model": "auth.permission",
        "fields": {
            "codename": "delete_logentry",
            "name": "Can delete log entry",
            "content_type": 8
        }
    }, {
        "pk": 4,
        "model": "auth.permission",
        "fields": {
            "codename": "add_group",
            "name": "Can add group",
            "content_type": 2
        }
    }, {
        "pk": 10,
        "model": "auth.permission",
        "fields": {
            "codename": "add_message",
            "name": "Can add message",
            "content_type": 4
        }
    }
]
</code>```

答:
It is not a very smart way to do it, but I have had the same problem and this worked for me:</p>

```<code>import csv

f = open('data.json')
data = json.load(f)
f.close()

new_data = []

for i in data:
   flat = {}
   names = i.keys()
   for n in names:
      try:
         if len(i[n].keys()) > 0:
            for ii in i[n].keys():
               flat[n+"_"+ii] = i[n][ii]
      except:
         flat[n] = i[n]
   new_data.append(flat)

f = open(filename, "r")
writer = csv.DictWriter(f, new_data[0].keys())
writer.writeheader()
for row in new_data:
   writer.writerow(row)
f.close()
</code>```

Title: How can I convert JSON to CSV?

Body:
I have a JSON file I want to convert to a CSV file. How can I do this with Python?

I tried:

import json
import csv

f = open('data.json')
data = json.load(f)
f.close()

f = open('data.csv')
csv_file = csv.writer(f)
for item in data:
    csv_file.writerow(item)

f.close()

However, it did not work. I am using Django and the error I received is:

`file' object has no attribute 'writerow'`

I then tried the following:

import json
import csv

f = open('data.json')
data = json.load(f)
f.close()

f = open('data.csv')
csv_file = csv.writer(f)
for item in data:
    f.writerow(item)  # ← changed

f.close()

I then get the error:

`sequence expected`

Sample json file:

[{
        "pk": 22,
        "model": "auth.permission",
        "fields": {
            "codename": "add_logentry",
            "name": "Can add log entry",
            "content_type": 8
        }
    }, {
        "pk": 23,
        "model": "auth.permission",
        "fields": {
            "codename": "change_logentry",
            "name": "Can change log entry",
            "content_type": 8
        }
    }, {
        "pk": 24,
        "model": "auth.permission",
        "fields": {
            "codename": "delete_logentry",
            "name": "Can delete log entry",
            "content_type": 8
        }
    }, {
        "pk": 4,
        "model": "auth.permission",
        "fields": {
            "codename": "add_group",
            "name": "Can add group",
            "content_type": 2
        }
    }, {
        "pk": 10,
        "model": "auth.permission",
        "fields": {
            "codename": "add_message",
            "name": "Can add message",
            "content_type": 4
        }
    }
]

Body:
It is not a very smart way to do it, but I have had the same problem and this worked for me:

import csv

f = open('data.json')
data = json.load(f)
f.close()

new_data = []

for i in data:
   flat = {}
   names = i.keys()
   for n in names:
      try:
         if len(i[n].keys()) > 0:
            for ii in i[n].keys():
               flat[n+"_"+ii] = i[n][ii]
      except:
         flat[n] = i[n]
   new_data.append(flat)

f = open(filename, "r")
writer = csv.DictWriter(f, new_data[0].keys())
writer.writeheader()
for row in new_data:
   writer.writerow(row)
f.close()


问:
Heroku request from mobile phone
I'm working on a iPhone application that will communicate with a rails app hosted on Heroku. I'm wondering how i should size the server (how many dynos, workers, and what type of database)

From what i understand a worker can perform i single operation at a time (ex: performing a select in database), and a dyno can handle between 10 and 100 simultaneous request.

If the phone has a low connection, requests might take a long time, how will this affect my server ?

I guess the longer the request are the more concurrent request there will be, so it requires more dyno ?
But it shouldn't affect the required number of worker, right ?

And how about the standard database, apart from the 5Mo limit, is it too slow for 10 to 100 simultaneous request ? (each performing very simple
Select on a less than 5Mo database ?)

Thanks,
Vincent

答:
It's important to remember that a single dyno is single threaded, so if your response time (use New Relic here) is say 200ms you're (in theory) able to process 5 requests a second with a single dyno. Increasing dynos does not increase performance, it increases throughput - to put this in perspective we recently needed to scale an app rapidly after advertising and ended up running on around 45 dynos (probably overkill) and were dealing with around 5600 requests a minute so approximately 100 requests a second. Also remember that if a dyno is kept in use (long running request, upload etc) then if you don't have additional dynos to process then requests will be queued and that queue will eventually be timed out after 30 seconds.

We're running off the 20Gb database and have seen impressive figures in DB response time, of course the site is also using a Memcached layer too to keep it snappy.

Hope that helps,

John.

Title: Heroku request from mobile phone


问:
How to unlock jenkins on windows 10
I installed jenkins on my window 10 machine by using the msi I downloaded. It installed fine and has now launched the browser prompting me to unlock jenkins with the initialadminpassword. I can't find this file anywhere. I looked in the install directory C:\Program Files (x86)\Jenkins and I have checked the log files and no password was written to it. I even did a search on my whole C: for initialadminpassword and nothing came up. I do have a file called secret.key in my Jenkins install directory but the key in this file isn't working. Any ideas on how I can get around this would be very helpful

Thanks

答:
In addition to "How to “Unlock Jenkins”?", I use a groovy script in order to make sure an admin account was created.

That means:

I copy the groovy script in <Jenkins>/ref/init.groovy.d/security.groovy

I launch jenkins.war with -Djenkins.install.runSetupWizard=false

In that script, replace the path of the files with the username/password by a Windows path one:

```<code>def user = new File("/run/secrets/jenkins-adm-name").text.trim()
def pass = new File("/run/secrets/jenkins-adm-pass").text.trim()
</code>```

That way:

no wizard

one admin account with a username/password of my choosing.

Title: How to unlock jenkins on windows 10

Body:
In addition to "How to “Unlock Jenkins”?", I use a groovy script in order to make sure an admin account was created.

That means:

I copy the groovy script in <Jenkins>/ref/init.groovy.d/security.groovy

I launch jenkins.war with -Djenkins.install.runSetupWizard=false

In that script, replace the path of the files with the username/password by a Windows path one:

def user = new File("/run/secrets/jenkins-adm-name").text.trim()
def pass = new File("/run/secrets/jenkins-adm-pass").text.trim()

That way:

no wizard

one admin account with a username/password of my choosing.


问:
Compiler cannot handle std::invoke
What is the problem with this?

```<code>struct foo {
    void process(int, char, bool) {}
};

foo myfoo;

template <typename Method> struct thing {
    void doit() {
        Method m = Method{};
        (myfoo.*m)(5, 'a', true);
    }
};

int main() {
    thing<decltype(&foo::process)> t;
    t.doit();
}
</code>```

I think this isolates the problem.  What is the workaround if I have to use the type Method, as in the case of my original post below?

Original post:
In the following attempted test:

```<code>struct Foo { int play (char, bool) {return 3;} };
struct Bar { double jump (int, short, float) {return 5.8;} };
struct Baz { char run (double) {return 'b';} };

int main() {
    Foo foo;  Bar bar;  Baz baz;
    Functor<decltype(&Foo::play), decltype(&Bar::jump), decltype(&Baz::run)> func;
    func(foo, bar, baz, 'c', true, 5, 2, 4.5, 6.8);
}
</code>```

As you can predict, func is supposed to carry out

```<code>foo.play('c', true);  bar.jump(5, 2, 4.5);  baz.run(6.8);
</code>```

My implementation of the Functor class so far (ignoring perfect forwarding and such for now) is

```<code>template <typename... Members>
struct Functor {
    using m = many_members<Members...>;
    template <typename... Args>
    typename m::return_types operator()(Args... args) const { // perfect forwarding to do later
        auto t = std::make_tuple(args...);
        auto objects = utilities::tuple_head<sizeof...(Members)>(t);
        auto arguments = utilities::extract_subtuple<sizeof...(Members), sizeof...(Args) - sizeof...(Members)>(t);
        call(objects, arguments);  // Won't compile on GCC 7.2 or clang 6.0.
    }
private:
    template <typename Tuple1, typename Tuple2>
    auto call (Tuple1& objects, const Tuple2& args) const {
        std::invoke(typename utilities::nth_element<0, Members...>::type{}, std::get<0>(objects), 'c', true);
    }
};
</code>```

where my last line using std::invoke is just to test the concept before I continue.  It however will not compile on either GCC 7.2 or clang 6.0, so I cannot continue with the generalization.  Any workaround here, or a completely different implementation altogether?

Here is everything I have so far:

```<code>namespace utilities {
    template <std::size_t N, typename... Ts>
    struct nth_element : std::tuple_element<N, std::tuple<Ts...>> { };

    template <std::size_t Skip, std::size_t Take, typename Tuple>
    auto extract_subtuple (const Tuple&, std::enable_if_t<(Take == 0)>* = nullptr) {
        return std::tuple<>();
    }

    template <std::size_t Skip, std::size_t Take, typename Tuple>
    auto extract_subtuple (const Tuple& tuple, std::enable_if_t<(Take > 0)>* = nullptr) {
        return std::tuple_cat (std::make_tuple(std::get<Skip>(tuple)), extract_subtuple<Skip + 1, Take - 1>(tuple));
    }

    template <std::size_t N, typename Tuple>
    auto tuple_head (const Tuple& tuple) {
        return extract_subtuple<0, N>(tuple);
    }
}

template <typename Rs, typename Ts, typename ArgsPacks, typename AllArgs, typename... Members> struct many_members_h;

template <typename Rs, typename Ts, typename ArgsPacks, typename AllArgs>
struct many_members_h<Rs, Ts, ArgsPacks, AllArgs> {
    using return_types = Rs;
    using classes = Ts;
    using args_packs = ArgsPacks;
    using all_args = AllArgs;
};

template <typename... Rs, typename... Ts, typename... ArgsPacks, typename... AllArgs, typename R, typename T, typename... Args, typename... Rest>
struct many_members_h<std::tuple<Rs...>, std::tuple<Ts...>, std::tuple<ArgsPacks...>, std::tuple<AllArgs...>, R(T::*)(Args...), Rest...> :
    many_members_h<std::tuple<Rs..., R>, std::tuple<Ts..., T>, std::tuple<ArgsPacks..., std::tuple<Args...>>, std::tuple<AllArgs..., Args...>, Rest...> { };

template <typename... Members>
struct many_members : many_members_h<std::tuple<>, std::tuple<>, std::tuple<>, std::tuple<>, Members...> { };

template <typename... Members>
struct Functor {
    using m = many_members<Members...>;
    template <typename... Args>
    typename m::return_types operator()(Args... args) const { // perfect forwarding to do later
        auto t = std::make_tuple(args...);
        auto objects = utilities::tuple_head<sizeof...(Members)>(t);
        auto arguments = utilities::extract_subtuple<sizeof...(Members), sizeof...(Args) - sizeof...(Members)>(t);
        call(objects, arguments);  // Won't compile on GCC 7.2 or clang 6.0.
    }
private:
    template <typename Tuple1, typename Tuple2>
    auto call (Tuple1& objects, const Tuple2& args) const {
        std::invoke(typename utilities::nth_element<0, Members...>::type{}, std::get<0>(objects), 'c', true);
    }
};

// Testing
#include <iostream>

struct Foo { int play (char, bool) {return 3;} };
struct Bar { double jump (int, short, float) {return 5.8;} };
struct Baz { char run (double) {return 'b';} };

int main() {
    Foo foo;  Bar bar;  Baz baz;
    Functor<decltype(&Foo::play), decltype(&Bar::jump), decltype(&Baz::run)> func;
    func(foo, bar, baz, 'c', true, 5, 2, 4.5, 6.8);
}
</code>```

答:
Thanks to aschepler's answer and advice to use auto... instead of typename... for the member function pointers, I was able to carry the original goal:

```<code>#include <tuple>
#include <functional>  // std::invoke
#include <type_traits>
#include <utility>

namespace utilities {
    template <std::size_t N, auto I, auto... Is>
    struct nth_element : nth_element<N - 1, Is...> { };

    template <auto I, auto... Is>
    struct nth_element<0, I, Is...> {
        static constexpr decltype(I) value = I;
    };

    template <std::size_t N, typename Pack> struct nth_index;

    template <std::size_t N, std::size_t... Is>
    struct nth_index<N, std::index_sequence<Is...>> : nth_element<N, Is...> { };

    template <std::size_t Skip, std::size_t Take, typename Tuple>
    auto extract_subtuple (const Tuple&, std::enable_if_t<(Take == 0)>* = nullptr) {
        return std::tuple<>();
    }

    template <std::size_t Skip, std::size_t Take, typename Tuple>
    auto extract_subtuple (const Tuple& tuple, std::enable_if_t<(Take > 0)>* = nullptr) {
        return std::tuple_cat (std::make_tuple(std::get<Skip>(tuple)), extract_subtuple<Skip + 1, Take - 1>(tuple));
    }

    template <std::size_t N, typename Tuple>
    auto tuple_head (const Tuple& tuple) {
        return extract_subtuple<0, N>(tuple);
    }

    template <typename F, typename T, typename Tuple, std::size_t... Is>
    decltype(auto) invoke_with_tuple_h (F&& f, T&& t, Tuple&& tuple, std::index_sequence<Is...>&&) {
        return std::invoke(std::forward<F>(f), std::forward<T>(t), std::get<Is>(std::forward<Tuple>(tuple))...);
    }

    template <typename F, typename T, typename Tuple>
    decltype(auto) invoke_with_tuple (F&& f, T&& t, Tuple&& tuple) {
        return invoke_with_tuple_h (std::forward<F>(f), std::forward<T>(t), std::forward<Tuple>(tuple), std::make_index_sequence<std::tuple_size_v<std::decay_t<Tuple>>>{});
    }

    template <typename PartialSums, std::size_t Sum, std::size_t... Is> struct all_partial_sums_h;

    template <std::size_t... PartialSums, std::size_t Sum>
    struct all_partial_sums_h<std::index_sequence<PartialSums...>, Sum> {
        using type = std::index_sequence<PartialSums..., Sum>;
        using type_without_last_sum = std::index_sequence<PartialSums...>;  // We define this because this is what we need actually.
    };

    template <std::size_t... PartialSums, std::size_t Sum, std::size_t First, std::size_t... Rest>
    struct all_partial_sums_h<std::index_sequence<PartialSums...>, Sum, First, Rest...> :
        all_partial_sums_h<std::index_sequence<PartialSums..., Sum>, Sum + First, Rest...> { };

    template <typename Pack> struct all_partial_sums;

    template <std::size_t... Is>
    struct all_partial_sums<std::index_sequence<Is...>> : all_partial_sums_h<std::index_sequence<>, 0, Is...> { };

    template <typename Pack> struct pack_size;

    template <template <typename...> class P, typename... Ts>
    struct pack_size<P<Ts...>> : std::integral_constant<std::size_t, sizeof...(Ts)> { };

    template <typename PackOfPacks> struct get_pack_sizes;

    template <template <typename...> class P, typename... Packs>
    struct get_pack_sizes<P<Packs...>> {
        using type = std::index_sequence<pack_size<Packs>::value...>;
    };
}

template <typename Method> struct method_traits;

template <typename R, typename C, typename... Args>
struct method_traits<R(C::*)(Args...)> {
    using return_type = R;
    using class_type = C;
    using args_type = std::tuple<Args...>;
};

template <typename Rs, typename Cs, typename ArgsPacks, auto... Members> struct many_members_h;

template <typename Rs, typename Cs, typename ArgsPacks>
struct many_members_h<Rs, Cs, ArgsPacks> {
    using return_types = Rs;
    using classes = Cs;
    using args_packs = ArgsPacks;
};

template <typename... Rs, typename... Cs, typename... ArgsPacks, auto F, auto... Rest>
struct many_members_h<std::tuple<Rs...>, std::tuple<Cs...>, std::tuple<ArgsPacks...>, F, Rest...> :
    many_members_h<std::tuple<Rs..., typename method_traits<decltype(F)>::return_type>, std::tuple<Cs..., typename method_traits<decltype(F)>::class_type>, std::tuple<ArgsPacks..., typename method_traits<decltype(F)>::args_type>, Rest...> { };

template <auto... Members>
struct many_members : many_members_h<std::tuple<>, std::tuple<>, std::tuple<>, Members...> { };

template <auto... Members>
struct Functor {
    using m = many_members<Members...>;
    using starting_points = typename utilities::all_partial_sums<typename utilities::get_pack_sizes<typename m::args_packs>::type>::type;

    template <typename... Args>
    typename m::return_types operator()(Args&&... args) const {
        constexpr std::size_t M = sizeof...(Members);
        auto t = std::make_tuple(std::forward<Args>(args)...);
        auto objects = utilities::tuple_head<M>(t);
        auto arguments = utilities::extract_subtuple<M, sizeof...(Args) - M>(t);
        return call(objects, arguments, std::make_index_sequence<M>{});
    }
private:
    template <typename Tuple1, typename Tuple2, std::size_t... Is>
    auto call (Tuple1& objects, const Tuple2& args, std::index_sequence<Is...>&&) const {  // perfect forwarding to do later
        return std::make_tuple(call_helper<Is>(objects, args)...);
    }
    template <std::size_t N, typename Tuple1, typename Tuple2>
    auto call_helper (Tuple1& objects, const Tuple2& args) const {  // perfect forwarding to do later
        constexpr std::size_t s = std::tuple_size_v<std::tuple_element_t<N, typename m::args_packs>>;;
        constexpr std::size_t a = utilities::nth_index<N, starting_points>::value;
        const auto args_tuple = utilities::extract_subtuple<a, s>(args);
        return utilities::invoke_with_tuple (utilities::nth_element<N, Members...>::value, std::get<N>(objects), args_tuple);
    }
};

// Testing
#include <iostream>

struct Foo { int play (char c, bool b) { std::cout << std::boolalpha << "Foo::play(" << c << ", " << b << ") called.\n";  return 3; }  };
struct Bar { double jump (int a, short b, float c) { std::cout << "Bar::jump(" << a << ", " << b << ", " << c << ") called.\n";  return 5.8; } };
struct Baz { char run (double d) { std::cout << "Baz::run(" << d << ") called.\n";  return 'b'; } };

int main() {
    Foo foo;  Bar bar;  Baz baz;
    Functor<&Foo::play, &Bar::jump, &Baz::run> func;
    const auto tuple = func(foo, bar, baz, 'c', true, 5, 2, 4.5, 6.8);
    std::cin.get();
}
</code>```

Output:

```<code>Baz::run(6.8) called.
Bar::jump(5, 2, 4.5) called.
Foo::play(c, true) called.
</code>```

Title: Compiler cannot handle std::invoke

Body:
What is the problem with this?

struct foo {
    void process(int, char, bool) {}
};

foo myfoo;

template <typename Method> struct thing {
    void doit() {
        Method m = Method{};
        (myfoo.*m)(5, 'a', true);
    }
};

int main() {
    thing<decltype(&foo::process)> t;
    t.doit();
}

I think this isolates the problem.  What is the workaround if I have to use the type Method, as in the case of my original post below?

Original post:
In the following attempted test:

struct Foo { int play (char, bool) {return 3;} };
struct Bar { double jump (int, short, float) {return 5.8;} };
struct Baz { char run (double) {return 'b';} };

int main() {
    Foo foo;  Bar bar;  Baz baz;
    Functor<decltype(&Foo::play), decltype(&Bar::jump), decltype(&Baz::run)> func;
    func(foo, bar, baz, 'c', true, 5, 2, 4.5, 6.8);
}

As you can predict, func is supposed to carry out

foo.play('c', true);  bar.jump(5, 2, 4.5);  baz.run(6.8);

My implementation of the Functor class so far (ignoring perfect forwarding and such for now) is

template <typename... Members>
struct Functor {
    using m = many_members<Members...>;
    template <typename... Args>
    typename m::return_types operator()(Args... args) const { // perfect forwarding to do later
        auto t = std::make_tuple(args...);
        auto objects = utilities::tuple_head<sizeof...(Members)>(t);
        auto arguments = utilities::extract_subtuple<sizeof...(Members), sizeof...(Args) - sizeof...(Members)>(t);
        call(objects, arguments);  // Won't compile on GCC 7.2 or clang 6.0.
    }
private:
    template <typename Tuple1, typename Tuple2>
    auto call (Tuple1& objects, const Tuple2& args) const {
        std::invoke(typename utilities::nth_element<0, Members...>::type{}, std::get<0>(objects), 'c', true);
    }
};

where my last line using std::invoke is just to test the concept before I continue.  It however will not compile on either GCC 7.2 or clang 6.0, so I cannot continue with the generalization.  Any workaround here, or a completely different implementation altogether?

Here is everything I have so far:

namespace utilities {
    template <std::size_t N, typename... Ts>
    struct nth_element : std::tuple_element<N, std::tuple<Ts...>> { };

    template <std::size_t Skip, std::size_t Take, typename Tuple>
    auto extract_subtuple (const Tuple&, std::enable_if_t<(Take == 0)>* = nullptr) {
        return std::tuple<>();
    }

    template <std::size_t Skip, std::size_t Take, typename Tuple>
    auto extract_subtuple (const Tuple& tuple, std::enable_if_t<(Take > 0)>* = nullptr) {
        return std::tuple_cat (std::make_tuple(std::get<Skip>(tuple)), extract_subtuple<Skip + 1, Take - 1>(tuple));
    }

    template <std::size_t N, typename Tuple>
    auto tuple_head (const Tuple& tuple) {
        return extract_subtuple<0, N>(tuple);
    }
}

template <typename Rs, typename Ts, typename ArgsPacks, typename AllArgs, typename... Members> struct many_members_h;

template <typename Rs, typename Ts, typename ArgsPacks, typename AllArgs>
struct many_members_h<Rs, Ts, ArgsPacks, AllArgs> {
    using return_types = Rs;
    using classes = Ts;
    using args_packs = ArgsPacks;
    using all_args = AllArgs;
};

template <typename... Rs, typename... Ts, typename... ArgsPacks, typename... AllArgs, typename R, typename T, typename... Args, typename... Rest>
struct many_members_h<std::tuple<Rs...>, std::tuple<Ts...>, std::tuple<ArgsPacks...>, std::tuple<AllArgs...>, R(T::*)(Args...), Rest...> :
    many_members_h<std::tuple<Rs..., R>, std::tuple<Ts..., T>, std::tuple<ArgsPacks..., std::tuple<Args...>>, std::tuple<AllArgs..., Args...>, Rest...> { };

template <typename... Members>
struct many_members : many_members_h<std::tuple<>, std::tuple<>, std::tuple<>, std::tuple<>, Members...> { };

template <typename... Members>
struct Functor {
    using m = many_members<Members...>;
    template <typename... Args>
    typename m::return_types operator()(Args... args) const { // perfect forwarding to do later
        auto t = std::make_tuple(args...);
        auto objects = utilities::tuple_head<sizeof...(Members)>(t);
        auto arguments = utilities::extract_subtuple<sizeof...(Members), sizeof...(Args) - sizeof...(Members)>(t);
        call(objects, arguments);  // Won't compile on GCC 7.2 or clang 6.0.
    }
private:
    template <typename Tuple1, typename Tuple2>
    auto call (Tuple1& objects, const Tuple2& args) const {
        std::invoke(typename utilities::nth_element<0, Members...>::type{}, std::get<0>(objects), 'c', true);
    }
};

// Testing
#include <iostream>

struct Foo { int play (char, bool) {return 3;} };
struct Bar { double jump (int, short, float) {return 5.8;} };
struct Baz { char run (double) {return 'b';} };

int main() {
    Foo foo;  Bar bar;  Baz baz;
    Functor<decltype(&Foo::play), decltype(&Bar::jump), decltype(&Baz::run)> func;
    func(foo, bar, baz, 'c', true, 5, 2, 4.5, 6.8);
}

Body:
Thanks to aschepler's answer and advice to use auto... instead of typename... for the member function pointers, I was able to carry the original goal:

#include <tuple>
#include <functional>  // std::invoke
#include <type_traits>
#include <utility>

namespace utilities {
    template <std::size_t N, auto I, auto... Is>
    struct nth_element : nth_element<N - 1, Is...> { };

    template <auto I, auto... Is>
    struct nth_element<0, I, Is...> {
        static constexpr decltype(I) value = I;
    };

    template <std::size_t N, typename Pack> struct nth_index;

    template <std::size_t N, std::size_t... Is>
    struct nth_index<N, std::index_sequence<Is...>> : nth_element<N, Is...> { };

    template <std::size_t Skip, std::size_t Take, typename Tuple>
    auto extract_subtuple (const Tuple&, std::enable_if_t<(Take == 0)>* = nullptr) {
        return std::tuple<>();
    }

    template <std::size_t Skip, std::size_t Take, typename Tuple>
    auto extract_subtuple (const Tuple& tuple, std::enable_if_t<(Take > 0)>* = nullptr) {
        return std::tuple_cat (std::make_tuple(std::get<Skip>(tuple)), extract_subtuple<Skip + 1, Take - 1>(tuple));
    }

    template <std::size_t N, typename Tuple>
    auto tuple_head (const Tuple& tuple) {
        return extract_subtuple<0, N>(tuple);
    }

    template <typename F, typename T, typename Tuple, std::size_t... Is>
    decltype(auto) invoke_with_tuple_h (F&& f, T&& t, Tuple&& tuple, std::index_sequence<Is...>&&) {
        return std::invoke(std::forward<F>(f), std::forward<T>(t), std::get<Is>(std::forward<Tuple>(tuple))...);
    }

    template <typename F, typename T, typename Tuple>
    decltype(auto) invoke_with_tuple (F&& f, T&& t, Tuple&& tuple) {
        return invoke_with_tuple_h (std::forward<F>(f), std::forward<T>(t), std::forward<Tuple>(tuple), std::make_index_sequence<std::tuple_size_v<std::decay_t<Tuple>>>{});
    }

    template <typename PartialSums, std::size_t Sum, std::size_t... Is> struct all_partial_sums_h;

    template <std::size_t... PartialSums, std::size_t Sum>
    struct all_partial_sums_h<std::index_sequence<PartialSums...>, Sum> {
        using type = std::index_sequence<PartialSums..., Sum>;
        using type_without_last_sum = std::index_sequence<PartialSums...>;  // We define this because this is what we need actually.
    };

    template <std::size_t... PartialSums, std::size_t Sum, std::size_t First, std::size_t... Rest>
    struct all_partial_sums_h<std::index_sequence<PartialSums...>, Sum, First, Rest...> :
        all_partial_sums_h<std::index_sequence<PartialSums..., Sum>, Sum + First, Rest...> { };

    template <typename Pack> struct all_partial_sums;

    template <std::size_t... Is>
    struct all_partial_sums<std::index_sequence<Is...>> : all_partial_sums_h<std::index_sequence<>, 0, Is...> { };

    template <typename Pack> struct pack_size;

    template <template <typename...> class P, typename... Ts>
    struct pack_size<P<Ts...>> : std::integral_constant<std::size_t, sizeof...(Ts)> { };

    template <typename PackOfPacks> struct get_pack_sizes;

    template <template <typename...> class P, typename... Packs>
    struct get_pack_sizes<P<Packs...>> {
        using type = std::index_sequence<pack_size<Packs>::value...>;
    };
}

template <typename Method> struct method_traits;

template <typename R, typename C, typename... Args>
struct method_traits<R(C::*)(Args...)> {
    using return_type = R;
    using class_type = C;
    using args_type = std::tuple<Args...>;
};

template <typename Rs, typename Cs, typename ArgsPacks, auto... Members> struct many_members_h;

template <typename Rs, typename Cs, typename ArgsPacks>
struct many_members_h<Rs, Cs, ArgsPacks> {
    using return_types = Rs;
    using classes = Cs;
    using args_packs = ArgsPacks;
};

template <typename... Rs, typename... Cs, typename... ArgsPacks, auto F, auto... Rest>
struct many_members_h<std::tuple<Rs...>, std::tuple<Cs...>, std::tuple<ArgsPacks...>, F, Rest...> :
    many_members_h<std::tuple<Rs..., typename method_traits<decltype(F)>::return_type>, std::tuple<Cs..., typename method_traits<decltype(F)>::class_type>, std::tuple<ArgsPacks..., typename method_traits<decltype(F)>::args_type>, Rest...> { };

template <auto... Members>
struct many_members : many_members_h<std::tuple<>, std::tuple<>, std::tuple<>, Members...> { };

template <auto... Members>
struct Functor {
    using m = many_members<Members...>;
    using starting_points = typename utilities::all_partial_sums<typename utilities::get_pack_sizes<typename m::args_packs>::type>::type;

    template <typename... Args>
    typename m::return_types operator()(Args&&... args) const {
        constexpr std::size_t M = sizeof...(Members);
        auto t = std::make_tuple(std::forward<Args>(args)...);
        auto objects = utilities::tuple_head<M>(t);
        auto arguments = utilities::extract_subtuple<M, sizeof...(Args) - M>(t);
        return call(objects, arguments, std::make_index_sequence<M>{});
    }
private:
    template <typename Tuple1, typename Tuple2, std::size_t... Is>
    auto call (Tuple1& objects, const Tuple2& args, std::index_sequence<Is...>&&) const {  // perfect forwarding to do later
        return std::make_tuple(call_helper<Is>(objects, args)...);
    }
    template <std::size_t N, typename Tuple1, typename Tuple2>
    auto call_helper (Tuple1& objects, const Tuple2& args) const {  // perfect forwarding to do later
        constexpr std::size_t s = std::tuple_size_v<std::tuple_element_t<N, typename m::args_packs>>;;
        constexpr std::size_t a = utilities::nth_index<N, starting_points>::value;
        const auto args_tuple = utilities::extract_subtuple<a, s>(args);
        return utilities::invoke_with_tuple (utilities::nth_element<N, Members...>::value, std::get<N>(objects), args_tuple);
    }
};

// Testing
#include <iostream>

struct Foo { int play (char c, bool b) { std::cout << std::boolalpha << "Foo::play(" << c << ", " << b << ") called.\n";  return 3; }  };
struct Bar { double jump (int a, short b, float c) { std::cout << "Bar::jump(" << a << ", " << b << ", " << c << ") called.\n";  return 5.8; } };
struct Baz { char run (double d) { std::cout << "Baz::run(" << d << ") called.\n";  return 'b'; } };

int main() {
    Foo foo;  Bar bar;  Baz baz;
    Functor<&Foo::play, &Bar::jump, &Baz::run> func;
    const auto tuple = func(foo, bar, baz, 'c', true, 5, 2, 4.5, 6.8);
    std::cin.get();
}

Output:

Baz::run(6.8) called.
Bar::jump(5, 2, 4.5) called.
Foo::play(c, true) called.


问:
Get-Process Couldn't Connect to remote machine
I was recently attempting to setup a script using powershell so that I could monitor a critical process on a remote computer.

```<code>Get-Process -ComputerName myremotepc myprocess
</code>```

This was giving me the following error.

```<code>Get-Process : Couldn't connect to remote machine.
At line:1 char:1
+ Get-Process -ComputerName myremotepc myprocess
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo          : NotSpecified: (:) [Get-Process],     InvalidOperationException
+ FullyQualifiedErrorId :     System.InvalidOperationException,Microsoft.PowerShell.Commands.GetProcessCommand
</code>```

After checking to see that the correct services were enabled. I still can not connect.

答:
Do note it states explicitly that PSRemoting does not need to be enabled.  The difference was likely your elevated prompt or a firewall exception.

```<code>PS C:\> Get-Help Get-Process -Parameter 'ComputerName'

-ComputerName <String[]>
    Specifies the computers for which this cmdlet gets active processes. The default is the local computer.

    Type the NetBIOS name, an IP address, or a fully qualified domain name (FQDN) of one or more computers. To specify the local computer, type the computer name, a dot (.), or localhost.

    This parameter does not rely on Windows PowerShell remoting. You can use the ComputerName parameter of this cmdlet even if your computer is not configured to run remote commands.

    Required?                    false
    Position?                    named
    Default value                None
    Accept pipeline input?       True (ByPropertyName)
    Accept wildcard characters?  false
</code>```

Body:
I was recently attempting to setup a script using powershell so that I could monitor a critical process on a remote computer.

Get-Process -ComputerName myremotepc myprocess

This was giving me the following error.

Get-Process : Couldn't connect to remote machine.
At line:1 char:1
+ Get-Process -ComputerName myremotepc myprocess
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo          : NotSpecified: (:) [Get-Process],     InvalidOperationException
+ FullyQualifiedErrorId :     System.InvalidOperationException,Microsoft.PowerShell.Commands.GetProcessCommand

After checking to see that the correct services were enabled. I still can not connect.

Body:
Do note it states explicitly that PSRemoting does not need to be enabled.  The difference was likely your elevated prompt or a firewall exception.

PS C:\> Get-Help Get-Process -Parameter 'ComputerName'

-ComputerName <String[]>
    Specifies the computers for which this cmdlet gets active processes. The default is the local computer.

    Type the NetBIOS name, an IP address, or a fully qualified domain name (FQDN) of one or more computers. To specify the local computer, type the computer name, a dot (.), or localhost.

    This parameter does not rely on Windows PowerShell remoting. You can use the ComputerName parameter of this cmdlet even if your computer is not configured to run remote commands.

    Required?                    false
    Position?                    named
    Default value                None
    Accept pipeline input?       True (ByPropertyName)
    Accept wildcard characters?  false


问:
How to use a custom time in browser to test for client vs server time difference
I just wrote a little piece of code to show the server time in a webpage. At the moment I just have one machine so I cannot test if the code is working.

Is there a way to tell the browser to use a time configuration different from the one configured in the OS? I have used plugins for Firefox to test different locales, I wonder if there are similar options for time tests.

Thanks.

答:
This an easies way I tried to chang time zone and test it for windows 7 ^
I use tzutil

tzutil /s "Eastern Standard Time"
and save it to suitable .bat file e.g Eastern_Standard_Time_zone.bat and use default_time_zone.bat conain your original system time zone to get it back after finishin tesing . this will change your time zone in blink .
reference


问:
Maven Release Plugin use in Jenkins Pipeline
I'm using Jenkins Pipeline to automatically build and deploy my Java apps. I also use maven-release-plugin to perform Maven deploy to Artifactory.

The problem is my Jenkinsfile (or Jenkins Pipeline Configuration) :

We commit a version 0.1.00-SNAPSHOT on release branch

Jenkins Pipeline get the code, and perform maven release

Maven Release changes the version to 0.1.00

Maven Release tags GIT branch, commit and deploy the artifact

Maven Release changes the version to 0.2.00-SNAPSHOT and commit

Jenkins Pipeline detect a change in GIT, so triggers a new build

You understood that the last step creates an infinite loop, even if there is no useful commit.

Here is the interesting part of my Jenkinsfile :

```<code>sshagent([git_credential]) {
    sh "${maven_bin} --settings ${maven_settings} -DreleaseVersion=${release_version} -DdevelopmentVersion=${development_version} release:prepare release:perform -B"
}
</code>```

How can I break the loop (avoid Jenkins to trigger new build when Maven commits on GIT)?

Thanks

答:
IMHO with the advent of git and pull requests, I don't think using maven-release-plugin or maven-version-plugin with a Jenkins pipeline is a good idea.

Using Multibranch Pipeline with the versioning technique mentioned here is more in line with continuous delivery:
https://axelfontaine.com/blog/dead-burried.html

Using the versioning technique above, the pom.xml now looks like this:

```<code><project>
    ...
    <version>${revision}</version>

    <properties>
        <!-- Sane default when no revision property is passed in from the commandline -->
        <revision>0-SNAPSHOT</revision>
    </properties>

    <scm>
        <connection>scm:git:your-git-repo-url</connection>
    </scm>

    <distributionManagement>
        <repository>
            <id>artifact-repository</id>
            <url>your-artifact-repo-url</url>
        </repository>
    </distributionManagement>

    <build>
        <plugins>
            <plugin>
                <artifactId>maven-scm-plugin</artifactId>
                <version>1.9.5</version>
                <configuration>
                   <tag>${project.artifactId}-${project.version}</tag>
                </configuration>
            </plugin>
        </plugins>
    </build>
    ...
</project>
</code>```

You can now produce releases on your Jenkins server very easily by configuring a Multibranch Pipeline with a Jenkinsfile to build on all branches and deploy only from master branch:

```<code>pipeline {
  agent any
  environment {
    REVISION = "0.0.${env.BUILD_ID}"
  }
  triggers {
    pollSCM('')
  }
  options {
    disableConcurrentBuilds()
    buildDiscarder(logRotator(numToKeepStr: '30'))
  }
  tools {
    maven '3.5.2'
    jdk 'jdk8'
  }
  stages {
    stage ('Initialize') {
      steps {
        sh '''
          echo "PATH = ${PATH}"
          echo "M2_HOME = ${M2_HOME}"
        '''
      }
    }
    stage ('Build') {
      steps {
        sh 'mvn clean package'
      }
    }
    stage ('Deploy') {
      when {
        branch 'master'
      }
      steps {
        script {
          currentBuild.displayName = "${REVISION}"
        }
        sh 'mvn deploy scm:tag -Drevision=${REVISION}'
      }
    }
  }
}
</code>```

See https://jenkins.io/blog/2017/02/07/declarative-maven-project/#set-up on how to configure a Multibranch Pipeline.

With this technique you develop only on non-master branches. Then create a pull request to merge your changes back to master branch. This should then deploy your artifact automatically to your artifact repository.

Addendum

When publishing to a Maven repository using the above method, the pom.xml will not have the proper version. To get Maven to publish the proper version, use the flatten-maven-plugin: http://www.mojohaus.org/flatten-maven-plugin/usage.html.

Also, check out: https://maven.apache.org/maven-ci-friendly.html

Body:
I'm using Jenkins Pipeline to automatically build and deploy my Java apps. I also use maven-release-plugin to perform Maven deploy to Artifactory.

The problem is my Jenkinsfile (or Jenkins Pipeline Configuration) :

We commit a version 0.1.00-SNAPSHOT on release branch

Jenkins Pipeline get the code, and perform maven release

Maven Release changes the version to 0.1.00

Maven Release tags GIT branch, commit and deploy the artifact

Maven Release changes the version to 0.2.00-SNAPSHOT and commit

Jenkins Pipeline detect a change in GIT, so triggers a new build

You understood that the last step creates an infinite loop, even if there is no useful commit.

Here is the interesting part of my Jenkinsfile :

sshagent([git_credential]) {
    sh "${maven_bin} --settings ${maven_settings} -DreleaseVersion=${release_version} -DdevelopmentVersion=${development_version} release:prepare release:perform -B"
}

How can I break the loop (avoid Jenkins to trigger new build when Maven commits on GIT)?

Thanks

Body:
IMHO with the advent of git and pull requests, I don't think using maven-release-plugin or maven-version-plugin with a Jenkins pipeline is a good idea.

Using Multibranch Pipeline with the versioning technique mentioned here is more in line with continuous delivery:
https://axelfontaine.com/blog/dead-burried.html

Using the versioning technique above, the pom.xml now looks like this:

<project>
    ...
    <version>${revision}</version>

    <properties>
        <!-- Sane default when no revision property is passed in from the commandline -->
        <revision>0-SNAPSHOT</revision>
    </properties>

    <scm>
        <connection>scm:git:your-git-repo-url</connection>
    </scm>

    <distributionManagement>
        <repository>
            <id>artifact-repository</id>
            <url>your-artifact-repo-url</url>
        </repository>
    </distributionManagement>

    <build>
        <plugins>
            <plugin>
                <artifactId>maven-scm-plugin</artifactId>
                <version>1.9.5</version>
                <configuration>
                   <tag>${project.artifactId}-${project.version}</tag>
                </configuration>
            </plugin>
        </plugins>
    </build>
    ...
</project>

You can now produce releases on your Jenkins server very easily by configuring a Multibranch Pipeline with a Jenkinsfile to build on all branches and deploy only from master branch:

pipeline {
  agent any
  environment {
    REVISION = "0.0.${env.BUILD_ID}"
  }
  triggers {
    pollSCM('')
  }
  options {
    disableConcurrentBuilds()
    buildDiscarder(logRotator(numToKeepStr: '30'))
  }
  tools {
    maven '3.5.2'
    jdk 'jdk8'
  }
  stages {
    stage ('Initialize') {
      steps {
        sh '''
          echo "PATH = ${PATH}"
          echo "M2_HOME = ${M2_HOME}"
        '''
      }
    }
    stage ('Build') {
      steps {
        sh 'mvn clean package'
      }
    }
    stage ('Deploy') {
      when {
        branch 'master'
      }
      steps {
        script {
          currentBuild.displayName = "${REVISION}"
        }
        sh 'mvn deploy scm:tag -Drevision=${REVISION}'
      }
    }
  }
}

See https://jenkins.io/blog/2017/02/07/declarative-maven-project/#set-up on how to configure a Multibranch Pipeline.

With this technique you develop only on non-master branches. Then create a pull request to merge your changes back to master branch. This should then deploy your artifact automatically to your artifact repository.

Addendum

When publishing to a Maven repository using the above method, the pom.xml will not have the proper version. To get Maven to publish the proper version, use the flatten-maven-plugin: http://www.mojohaus.org/flatten-maven-plugin/usage.html.

Also, check out: https://maven.apache.org/maven-ci-friendly.html


问:
Prevent "Send error report to Microsoft"
I'm working on a rather large project, and its unlikely will catch everything. I've found the event that notifies me of unhandled exceptions, however I haven't found a way to programmatically shut off the windows error dialog. Ideally, if there is an unhandled exception, I would like to have that event fired, provide a dialog box telling the user that there is a problem, and then to close gracefully. Is there any way to do this? I realize I could wrap the highest layer in a try catch, but I was hoping for something a little more elegant. </p>

答:
This is what we did.</p>

```<code>static void Main() {
    try
    {
        SubMain();
    }
    catch (Exception e)
    {
        HandleUnhandledException(e);
    }
}

private static void SubMain()
{
    // Setup unhandled exception handlers
    AppDomain.CurrentDomain.UnhandledException += // CLR
       new UnhandledExceptionEventHandler(OnUnhandledException);
     Application.ThreadException += // Windows Forms
       new System.Threading.ThreadExceptionEventHandler(
           OnGuiUnhandledException);
     Application.EnableVisualStyles();
     Application.SetCompatibleTextRenderingDefault(false);
     Application.Run(new frmMain());
}

// CLR unhandled exception
private static void OnUnhandledException(Object sender,
   UnhandledExceptionEventArgs e)
{
    HandleUnhandledException(e.ExceptionObject);
}

// Windows Forms unhandled exception
private static void OnGuiUnhandledException(Object sender,
   System.Threading.ThreadExceptionEventArgs e)
{
    HandleUnhandledException(e.Exception);
}
</code>```

OwnerDisplayName: Steve

LastEditorDisplayName: Rich B

Body:
This is what we did.

static void Main() {
    try
    {
        SubMain();
    }
    catch (Exception e)
    {
        HandleUnhandledException(e);
    }
}

private static void SubMain()
{
    // Setup unhandled exception handlers
    AppDomain.CurrentDomain.UnhandledException += // CLR
       new UnhandledExceptionEventHandler(OnUnhandledException);
     Application.ThreadException += // Windows Forms
       new System.Threading.ThreadExceptionEventHandler(
           OnGuiUnhandledException);
     Application.EnableVisualStyles();
     Application.SetCompatibleTextRenderingDefault(false);
     Application.Run(new frmMain());
}

// CLR unhandled exception
private static void OnUnhandledException(Object sender,
   UnhandledExceptionEventArgs e)
{
    HandleUnhandledException(e.ExceptionObject);
}

// Windows Forms unhandled exception
private static void OnGuiUnhandledException(Object sender,
   System.Threading.ThreadExceptionEventArgs e)
{
    HandleUnhandledException(e.Exception);
}

OwnerDisplayName: Aaron Smith


问:
flex-wrap not working as expected in Safari
On the homepage of http://www.shopifyexperte.de/ there are two flex-box modules, one under "Kundenstimmen" and one under "Neueste Beiträge...". The inner boxes are supposed to wrap when they go below 220px and not grow above 30% width. This works in latest Chrome, FF and Opera (all on Mac), but in Safari 8.0.5 (Mac) and any iOS browser the boxes never form a row even if there's enough room. They always wrap, each one on a row of its own.

The CSS for the container:

.homepage-testimonial-container {
 display: flex;
 display: -webkit-flex;
 -webkit-flex: 1;
 flex: 1;
 -webkit-flex-direction: row;
 flex-direction: row;
 -webkit-flex-wrap: wrap;
 flex-wrap: wrap;
 -webkit-justify-content: space-between;
 justify-content: space-between;
 -webkit-align-items: flex-start;
 align-items: flex-start;
 margin-top: 1em;
}```
</div>
</div>
</p>

<p>The CSS for the boxes inside the container:</p>

<p><div class="snippet" data-lang="js" data-hide="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>.homepage-testimonial {
 margin-bottom: 1em;
 min-width: 220px;
 max-width: 30%;
 -webkit-flex: 1 1 auto;
 flex: 1 1 auto;
}</code>```

If I disable -webkit-flex-wrap (effectively setting it to nowrap), all boxes line up in a row but eventually overflow the container when the browser window gets too narrow.

Is this some kind of bug in Safari/Webkit or am I doing something wrong here?

答:
I'm using Safari 11.0.1 and the bug persists. I use Bootstrap 3 combined with display: flex on my .row elements. I added following to my css to target the column elements. There seems to be something about the width percentages in Safari that aren't being honored correctly.</p>

```<code>.row [class*=col-]{
    margin:0 -.3px;
}
</code>```

Body:
On the homepage of http://www.shopifyexperte.de/ there are two flex-box modules, one under "Kundenstimmen" and one under "Neueste Beiträge...". The inner boxes are supposed to wrap when they go below 220px and not grow above 30% width. This works in latest Chrome, FF and Opera (all on Mac), but in Safari 8.0.5 (Mac) and any iOS browser the boxes never form a row even if there's enough room. They always wrap, each one on a row of its own.

The CSS for the container:

.homepage-testimonial-container {
 display: flex;
 display: -webkit-flex;
 -webkit-flex: 1;
 flex: 1;
 -webkit-flex-direction: row;
 flex-direction: row;
 -webkit-flex-wrap: wrap;
 flex-wrap: wrap;
 -webkit-justify-content: space-between;
 justify-content: space-between;
 -webkit-align-items: flex-start;
 align-items: flex-start;
 margin-top: 1em;
}

The CSS for the boxes inside the container:

.homepage-testimonial {
 margin-bottom: 1em;
 min-width: 220px;
 max-width: 30%;
 -webkit-flex: 1 1 auto;
 flex: 1 1 auto;
}

If I disable -webkit-flex-wrap (effectively setting it to nowrap), all boxes line up in a row but eventually overflow the container when the browser window gets too narrow.

Is this some kind of bug in Safari/Webkit or am I doing something wrong here?

Body:
I'm using Safari 11.0.1 and the bug persists. I use Bootstrap 3 combined with display: flex on my .row elements. I added following to my css to target the column elements. There seems to be something about the width percentages in Safari that aren't being honored correctly.

.row [class*=col-]{
    margin:0 -.3px;
}


问:
Going from page A to B based on a condition
I have an HTML page that uses JavaScript/Ajax/PHP to login a user.  Based on the return value from the login (ie type of the user), I want to load a certain HTML page (all the pages are similar in layout but they have different contents)

I was wondering what's the right/best way to do this. Few ideas come to mind:

Based on the value returned, I can load .html file . So I can direct to mainpage1.html, mainpage2.html..etc

In the mainpage, Icould have javascript code that would check the passed in "type" and then replace the visible contents with the right contents (huge if/else condition that has all the possible HTML contents)

Run PHP script that would send the HTML contents from the server based on the type.

Offcourse other solutions/ways are welcome. What do you think is the right/common way to achieve this?

答:
I would go for the 3rd option,

if you redirect based on the type you will be misusing Ajax / not a good practice.

dangerous / not recommended / poor practice to do all the validations on the client side with JS.

Running a server side script to send the right content based on the right condition seem to be your best bet as you will have more control and more flexibility and security.

Of course i'm assuming this is very basic, i would recommend using a router on the server side to handle your routes and redirections if needed.


问:
C# WPF - Change control content when another control event occurs
I'm quite new to WPF and MVVM and I'm trying to create a custom WindowChrome with all the standard Window features. I'm struggling with the Maximize/Minimize window Button content: I want the content to change when the user double clicks the WindowChrome bar, in order to show the right icon:

When I double click the bar, the result should be:

I managed to change the content with the Button Triggers, but how can I change it when another control event occurs?

Thanks in advance for the help!

答:
Give the Button a Style with triggers that set the content based on the value of Window.WindowState. This isn't an event. The button reflects the current state of the window.

```<code><Style TargetType="Button">
    <Style.Triggers>
        <DataTrigger
            Binding="{Binding WindowState, RelativeSource={RelativeSource AncestorType=Window}}"
            Value="Maximized">
            <Setter Property="Content">
                <Setter.Value>
                    <!-- I don't know if you're using a Path or what -->
                    <Path Stroke="White" Data="..." />
                </Setter.Value>
            </Setter>
        </DataTrigger>
        <DataTrigger
            Binding="{Binding WindowState, RelativeSource={RelativeSource AncestorType=Window}}"
            Value="Normal">
            <Setter Property="Content">
                <Setter.Value>
                    <!-- I don't know if you're using a Path or what -->
                    <Path Stroke="White" Data="..." />
                </Setter.Value>
            </Setter>
        </DataTrigger>
    </Style.Triggers>
</Style>
</code>```

It would be wiser to set the Template of the button instead, because there’s only one copy of each of those Paths, and if you reuse the style twice, they can’t be shared.

If there's some reason why this won't work with your code, show me your code.

Body:
Give the Button a Style with triggers that set the content based on the value of Window.WindowState. This isn't an event. The button reflects the current state of the window.

<Style TargetType="Button">
    <Style.Triggers>
        <DataTrigger
            Binding="{Binding WindowState, RelativeSource={RelativeSource AncestorType=Window}}"
            Value="Maximized">
            <Setter Property="Content">
                <Setter.Value>
                    <!-- I don't know if you're using a Path or what -->
                    <Path Stroke="White" Data="..." />
                </Setter.Value>
            </Setter>
        </DataTrigger>
        <DataTrigger
            Binding="{Binding WindowState, RelativeSource={RelativeSource AncestorType=Window}}"
            Value="Normal">
            <Setter Property="Content">
                <Setter.Value>
                    <!-- I don't know if you're using a Path or what -->
                    <Path Stroke="White" Data="..." />
                </Setter.Value>
            </Setter>
        </DataTrigger>
    </Style.Triggers>
</Style>

It would be wiser to set the Template of the button instead, because there’s only one copy of each of those Paths, and if you reuse the style twice, they can’t be shared.

If there's some reason why this won't work with your code, show me your code.