问:
ng-click not working in D3 generated svg
I'm using D3 with Angular and I want to insert some text elements into my svg and have an ng-click on them to fire off some functions in my controller.  However it seems the ng-click never even fires.  I've tried using $compile as suggested in the following posts:

How do I use angularjs directives in generated d3 html?

Angular ng-click's inside a dynamically created d3 chart are not working

neither of those solutions work for me.  it does appear the $compile is doing something because it appends the attributes role="button" and tabindex="0" to my element like so:

Before $compile:

```<code><svg>
   <text y="30" cursor="pointer" ng-click="alert('clicked')">CLICK ME</text>
</svg>
</code>```

After $compile:

```<code><svg>
   <text y="30" cursor="pointer" ng-click="alert('clicked')" role="button" tabindex="0">CLICK ME</text>
</svg>
</code>```

I'm wondering if something on the page may be stealing the click event? it seems that angular has added a click handler the the root html element.  I have never noticed this before

This is the directive code I have

```<code>.directive('clickMe', function ($compile) {
  return {
    restrict: 'A',
    link: function (scope, element, attributes) {
      var svg = d3.select(element[0])
        .append('svg');
        svg.append('text')
          .text('CLICK ME')
          .attr('y', '30')
          .attr('cursor', 'pointer')
          .attr('ng-click', 'alert(\'clicked\')');

      var compiledSvg = $compile(svg.node())(scope);
      element[0].children[0].replaceWith(compiledSvg[0]);
})
</code>```

A jsfiddle with the versions of D3 and Angular I'm using which illustrates the problem: https://jsfiddle.net/soultrip/604pts5v/3/

答:
I don't think that alert is in scope inside your template. Instead, create a method in your directive scope and call that on ngClick.

```<code>var myApp = angular.module('myApp', []);

myApp.directive('myDirective', function($compile) {
  return {
    restrict: 'A',
    link: function(scope, element, attributes) {
      let svg = d3.select(element[0])
        .append('svg');
      svg.append('text')
        .text('CLICK ME')
        .attr('y', '30')
        .attr('cursor', 'pointer')
        .attr('ng-click', 'showAlert(\'clicked\')');
      let compiledSvg = $compile(svg.node())(scope);
      element[0].children[0].replaceWith(compiledSvg[0]);

      scope.showAlert = function(message) {
        alert(message);
      };
    }
  }
});
</code>```

https://jsfiddle.net/604pts5v/5/

Body:
I'm using D3 with Angular and I want to insert some text elements into my svg and have an ng-click on them to fire off some functions in my controller.  However it seems the ng-click never even fires.  I've tried using $compile as suggested in the following posts:

How do I use angularjs directives in generated d3 html?

Angular ng-click's inside a dynamically created d3 chart are not working

neither of those solutions work for me.  it does appear the $compile is doing something because it appends the attributes role="button" and tabindex="0" to my element like so:

Before $compile:

<svg>
   <text y="30" cursor="pointer" ng-click="alert('clicked')">CLICK ME</text>
</svg>

After $compile:

<svg>
   <text y="30" cursor="pointer" ng-click="alert('clicked')" role="button" tabindex="0">CLICK ME</text>
</svg>

I'm wondering if something on the page may be stealing the click event? it seems that angular has added a click handler the the root html element.  I have never noticed this before

This is the directive code I have

.directive('clickMe', function ($compile) {
  return {
    restrict: 'A',
    link: function (scope, element, attributes) {
      var svg = d3.select(element[0])
        .append('svg');
        svg.append('text')
          .text('CLICK ME')
          .attr('y', '30')
          .attr('cursor', 'pointer')
          .attr('ng-click', 'alert(\'clicked\')');

      var compiledSvg = $compile(svg.node())(scope);
      element[0].children[0].replaceWith(compiledSvg[0]);
})

A jsfiddle with the versions of D3 and Angular I'm using which illustrates the problem: https://jsfiddle.net/soultrip/604pts5v/3/

Body:
I don't think that alert is in scope inside your template. Instead, create a method in your directive scope and call that on ngClick.

var myApp = angular.module('myApp', []);

myApp.directive('myDirective', function($compile) {
  return {
    restrict: 'A',
    link: function(scope, element, attributes) {
      let svg = d3.select(element[0])
        .append('svg');
      svg.append('text')
        .text('CLICK ME')
        .attr('y', '30')
        .attr('cursor', 'pointer')
        .attr('ng-click', 'showAlert(\'clicked\')');
      let compiledSvg = $compile(svg.node())(scope);
      element[0].children[0].replaceWith(compiledSvg[0]);

      scope.showAlert = function(message) {
        alert(message);
      };
    }
  }
});

https://jsfiddle.net/604pts5v/5/


来源: stackexchange

问:
self refrence inside swift closure return nil some time
I am accessing instance method inside closure in swift, self reference become nil in some cases which result crash my program. I tried to access using [weak self] but it failed to call the instance method when self is nil.

```<code>[weak self] () -> () in
</code>```

答:
The whole point of [weak self] is to not create a reference to self (probably to avoid circular links and memory leaks) so that it can be released.  If that happens, then self will be nil.

You should either not use [weak self] or, better yet probably, be prepared to handle the case of self having been released and set to nil.

```<code>guard let strong = self else { return }
</code>```

Take the example:

```<code>import UIKit
import PlaygroundSupport

class Foo {
    let name : String

    init(name:String) {
        self.name = name

        DispatchQueue.main.asyncAfter(deadline: .now() + 1.0) { [weak self] in
            print(self!.name)
        }
    }
}

Foo(name:"freddie")

PlaygroundPage.current.needsIndefiniteExecution = true
</code>```

In this case, you'll get a crash, because self is released before the async callback is made.

You can either change the asyncAfter call to be:

```<code>        DispatchQueue.main.asyncAfter(deadline: .now() + 1.0) {
            print(self.name)
        }
</code>```

will guarantee that self isn't released until after the callback is made.

Or you can use something like:

```<code>        DispatchQueue.main.asyncAfter(deadline: .now() + 1.0) { [weak self] in
            guard let strong = self else { print("self released") ; return }
            print(strong.name)
        }
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am accessing instance method inside closure in swift, self reference become nil in some cases which result crash my program. I tried to access using [weak self] but it failed to call the instance method when self is nil.

[weak self] () -> () in

Body:
The whole point of [weak self] is to not create a reference to self (probably to avoid circular links and memory leaks) so that it can be released.  If that happens, then self will be nil.

You should either not use [weak self] or, better yet probably, be prepared to handle the case of self having been released and set to nil.

guard let strong = self else { return }

Take the example:

import UIKit
import PlaygroundSupport

class Foo {
    let name : String

    init(name:String) {
        self.name = name

        DispatchQueue.main.asyncAfter(deadline: .now() + 1.0) { [weak self] in
            print(self!.name)
        }
    }
}

Foo(name:"freddie")

PlaygroundPage.current.needsIndefiniteExecution = true

In this case, you'll get a crash, because self is released before the async callback is made.

You can either change the asyncAfter call to be:

        DispatchQueue.main.asyncAfter(deadline: .now() + 1.0) {
            print(self.name)
        }

will guarantee that self isn't released until after the callback is made.

Or you can use something like:

        DispatchQueue.main.asyncAfter(deadline: .now() + 1.0) { [weak self] in
            guard let strong = self else { print("self released") ; return }
            print(strong.name)
        }


问:
How to place a class using if condition to mark pagination active page using css for following code?
I am trying to put an if condition like <?php if($page===$x) {echo ' class="selected"';}?> to use CSS for marking the selected page in my pagination for the following code:

```<code><?php
$result = $DB_con->query('SELECT COUNT(*) FROM tbl_users');
$totalRecords = $result->fetchColumn();
$totalPages = max(1, ceil($totalRecords / $recordsPerPage));

for ($i=1; $i<=$totalPages; $i++) {
echo "<span class='navigations_items_span'>";

//if($page===$i) echo "<b>Visiting Page</b>";
echo "<b>Page </b>";
echo "<a href='index3.php?page=".$i."' class='navigation_item selected_navigation_item'>. ".$i.".</a>";

echo "</span>";
};
?>
</code>```

I wanted to place in the line : echo ". ".$i."."; but getting error each time, how to place if here?

please help.

答:
inside your for loop :

```<code>if($page == $i)
    $class = 'navigation_item selected_navigation_item';
else
    $class = '';

echo "<a href='index3.php?page=".$i."' class='".$class."'>. ".$i.".</a>";
</code>```

Body:
I am trying to put an if condition like <?php if($page===$x) {echo ' class="selected"';}?> to use CSS for marking the selected page in my pagination for the following code:

<?php
$result = $DB_con->query('SELECT COUNT(*) FROM tbl_users');
$totalRecords = $result->fetchColumn();
$totalPages = max(1, ceil($totalRecords / $recordsPerPage));

for ($i=1; $i<=$totalPages; $i++) {
echo "";

//if($page===$i) echo "Visiting Page";
echo "Page ";
echo ". ".$i.".";

echo "";
};
?>

I wanted to place in the line : echo ". ".$i."."; but getting error each time, how to place if here?

please help.

Body:
inside your for loop :

if($page == $i)
    $class = 'navigation_item selected_navigation_item';
else
    $class = '';

echo "<a href='index3.php?page=".$i."' class='".$class."'>. ".$i.".</a>";


问:
Display under sub-comment according to parent sub-comment
I have a problem to display sub-comments based on a parent sub-comment. I do not know if it's a twig or query problem or other.

I have a reply table that contains sub-comments that are linked to the comments in my comments table with the field (com_id).

Only the com_id field of my reply table also refers to the reply_id field of the same table if the reply_level is equal to 1 (see image, red line diagonal).

How do I make a query to select the reply_level (1), reply_id(6) based on the reply_id parent (reply_id (4)?

My twig code:

Comments

    {% for comment in comments %}

 {{ comment.author }} {{ comment.content }}

        <button type="button" class="btn-primary btn-xs buttonAnswer btnLevel0" value="{{ comment.id }}"  > answer </button>

        {% if replys is defined %}
            {% for reply in replys %}
                {% if reply.getComParent() == comment.id and reply.level == 0%}

 {{ reply.author }} {{ reply.content }}

                    <button type="button" class="btn-primary btn-xs buttonAnswer btnLevel1" value="{{ reply.id }}" data-level="{{ reply.level1 }}" > answer </button>
                {% endif %}

                    {% if reply.getComParent() ==  reply.id  and reply.level ==1 %}

 {{ reply.author }} {{ reply.content }}

                        <button type="button" class="btn-primary btn-xs buttonAnswer btnLevel2" value="{{ reply.id }}" data-level="{{ reply.level2 }}" > answer </button>
                    {% endif %}

            {% endfor %}
        {% endif %}

    {% else %}
       no comment(s).
    {% endfor %}```

result :

The child sub How does not appear. It appears that if I add a fourth main comment. It works from sub comment to comment but I can not call a sub-comment based on the parent sub-comment.

Thank you

答:
Can you try this logic:

```<code><div id="underReply1">
   {% if reply.getComParent() == comment.id and reply.level == 1 %}
   ...
</code>```

I think that's what you need. Since the reply id might not match the com parent. I'm not certain it will fix the problem, but please try it and see if those are the results you are expecting.

Body:
I have a problem to display sub-comments based on a parent sub-comment. I do not know if it's a twig or query problem or other.

I have a reply table that contains sub-comments that are linked to the comments in my comments table with the field (com_id).

Only the com_id field of my reply table also refers to the reply_id field of the same table if the reply_level is equal to 1 (see image, red line diagonal).

How do I make a query to select the reply_level (1), reply_id(6) based on the reply_id parent (reply_id (4)?

My twig code:

Comments

    {% for comment in comments %}

 {{ comment.author }} {{ comment.content }}

        <button type="button" class="btn-primary btn-xs buttonAnswer btnLevel0" value="{{ comment.id }}"  > answer </button>

        {% if replys is defined %}
            {% for reply in replys %}
                {% if reply.getComParent() == comment.id and reply.level == 0%}

 {{ reply.author }} {{ reply.content }}

                    <button type="button" class="btn-primary btn-xs buttonAnswer btnLevel1" value="{{ reply.id }}" data-level="{{ reply.level1 }}" > answer </button>
                {% endif %}

                    {% if reply.getComParent() ==  reply.id  and reply.level ==1 %}

 {{ reply.author }} {{ reply.content }}

                        <button type="button" class="btn-primary btn-xs buttonAnswer btnLevel2" value="{{ reply.id }}" data-level="{{ reply.level2 }}" > answer </button>
                    {% endif %}

            {% endfor %}
        {% endif %}

    {% else %}
       no comment(s).
    {% endfor %}

result :

The child sub How does not appear. It appears that if I add a fourth main comment. It works from sub comment to comment but I can not call a sub-comment based on the parent sub-comment.

Thank you

Body:
Can you try this logic:

<div id="underReply1">
   {% if reply.getComParent() == comment.id and reply.level == 1 %}
   ...

I think that's what you need. Since the reply id might not match the com parent. I'm not certain it will fix the problem, but please try it and see if those are the results you are expecting.


问:
Condor, Sun Grid Engine, or something else?
I'm trying to work out whether we should try out Condor or Sun Grid Engine at work (or possibly something else).

We often have lots of unused WinXp workstations.  The hope is that we could use wake-on-LAN, run all our jobs, and then shut down automatically.  We'd mainly be running Matlab, Java or Python simulations for either monte-carlo or parameter explorations.

With my limited knowledge of Condor, it sounds like using a the vm universe might be a convenient way of taking care of snapshots without having to modify existing code.

Is SGE or something else better than condor for this kind of work?

答: SGE doesn't exist... it's OGE, and it's very expensive.   Go with Condor.</p>

ContentLicense: CC BY-SA 2.5


问:
*ngIf with focus directive
In my app, I tried to place a button that shows/hides an input field with a boolean component property. If the button shows the input, focus should be set on the input. But it seems not to work. If I remove the *ngIf the focus directive works fine.

I created a plunker that shows what I mean. It's kind of difficult to describe my problem.

HTML in a component:

```<code><input *ngIf="filterShow.options"
       [focus]="filterFocus.options"
       [(ngModel)]="filter.options">

<button type="button"
        (click)="setShowFilter('options')">
  focus
</button>
</code>```

setShowFilter() method:

```<code>private setShowFilter(filter: string) {
  this.filterShow[filter] = !this.filterShow[filter];

  /* reset filter */
  this.filter[filter] = "";

  this.filterFocus[filter].emit(true);
}
</code>```

focus.directive.ts:

```<code>@Directive({
  selector: '[focus]'
})
export class FocusDirective implements OnInit {

  @Input('focus') focusEvent: EventEmitter<boolean>;

  constructor(private elementRef : ElementRef,
              private renderer   : Renderer   ) { }

  ngOnInit() {
    this.focusEvent.subscribe(event => {
      this.renderer
        .invokeElementMethod(this.elementRef.nativeElement, 'focus', []);
    });
  }
}
</code>```

答:
EventEmitters are for @Outputs, not for @Inputs.  Try something like this instead:

```<code>@Directive({
  selector: '[focus]'
})
export class FocusDirective implements OnChanges {

  @Input('focus') focus: boolean;

  constructor(private elementRef : ElementRef,
              private renderer   : Renderer   ) { }

  ngOnChanges() {
    if (this.focus) {
      this.renderer
        .invokeElementMethod(this.elementRef.nativeElement, 'focus', []);
    }
  }
}
</code>```

ContentLicense: CC BY-SA 4.0

Title: *ngIf with focus directive

Body:
In my app, I tried to place a button that shows/hides an input field with a boolean component property. If the button shows the input, focus should be set on the input. But it seems not to work. If I remove the *ngIf the focus directive works fine.

I created a plunker that shows what I mean. It's kind of difficult to describe my problem.

HTML in a component:

<input *ngIf="filterShow.options"
       [focus]="filterFocus.options"
       [(ngModel)]="filter.options">

<button type="button"
        (click)="setShowFilter('options')">
  focus
</button>

setShowFilter() method:

private setShowFilter(filter: string) {
  this.filterShow[filter] = !this.filterShow[filter];

  /* reset filter */
  this.filter[filter] = "";

  this.filterFocus[filter].emit(true);
}

focus.directive.ts:

@Directive({
  selector: '[focus]'
})
export class FocusDirective implements OnInit {

  @Input('focus') focusEvent: EventEmitter<boolean>;

  constructor(private elementRef : ElementRef,
              private renderer   : Renderer   ) { }

  ngOnInit() {
    this.focusEvent.subscribe(event => {
      this.renderer
        .invokeElementMethod(this.elementRef.nativeElement, 'focus', []);
    });
  }
}

Body:
EventEmitters are for @Outputs, not for @Inputs.  Try something like this instead:

@Directive({
  selector: '[focus]'
})
export class FocusDirective implements OnChanges {

  @Input('focus') focus: boolean;

  constructor(private elementRef : ElementRef,
              private renderer   : Renderer   ) { }

  ngOnChanges() {
    if (this.focus) {
      this.renderer
        .invokeElementMethod(this.elementRef.nativeElement, 'focus', []);
    }
  }
}


问:
Add image as frame to a gif
So I want to create a gif and add an image as a frame. I am using gifencoder. I've seen the examples and its pretty easy to add colors, txt etc, but I couldnt figure out how to do the same with an image. Do I need something like the png file stream.

ex: from website for color frame

```<code>let canvas = new Canvas(width, height);
var ctx = canvas.getContext('2d');
red rectangle
ctx.fillStyle = '#ff0000';
ctx.fillRect(0, 0, 320, 240);
encoder.addFrame(ctx);
</code>```

Edit:

I tried doing something like below and while the frames appear on my log as wanted the frames dont get added, no errors. Before someone suggests to convert to base64 the png/gif this module cant add such frames, that being said if you have another in mind that does please go ahead and say so.

```<code>fs.createReadStream('test.gif')
.pipe(new GIFDecoder) //gif-stream
.pipe(concat(function(frames) { //concat-frames
    console.log(frames);
    for (var i=0; i<frames.length; i++) {
        encoder.addFrame(frames[i]);
    }
}));
</code>```

whatever I have tried at best I get just a black gif, nothing more.

Edit 2:

Okay so the reason I am trying to add from from a gif the frame, was because it simply seemed easier. Below is the progress I have done trying to get an image, convert it to RGBA (i noticed the module accepts rgba format, not rgb, perhaps that's why it was always black) and afterwards add the frame. Adding the frame if I have the data is extremely easy as I simply call a method and push the data in, so I am going to leave that out.

```<code>var request = require('request').defaults({ encoding: null });

request.get('https://upload.wikimedia.org/wikipedia/commons/0/01/Quinlingpandabearr.jpg', function (error, response, body) {
    if (!error && response.statusCode == 200) {
        var img = new Canvas(105, 159);
        var context = img.getContext('2d');
        img.src = "data:" + response.headers["content-type"] + ";base64," + new Buffer(body).toString('base64');
        var img_to_rgba = context.getImageData(0, 0, img.width, img.height);
        console.log(img_to_rgba); //always returns 0, like my pic is completely black, its not.
    }
});
</code>```

答:
I've added an image as a frame to a gif, along side a blue square.

Here is the full code, tested and working fine for me:

```<code>var GIFEncoder = require('gifencoder');
var Canvas = require('canvas');
var fs = require('fs');

var encoder = new GIFEncoder(320, 240);

encoder.createReadStream().pipe(fs.createWriteStream('myanimated.gif'));

encoder.start();
encoder.setRepeat(0);
encoder.setDelay(500);
encoder.setQuality(10);

var canvas = new Canvas(320, 240);
var ctx = canvas.getContext('2d');

// blue rectangle frame
ctx.fillStyle = '#0000ff';
ctx.fillRect(0, 0, 320, 240);
encoder.addFrame(ctx);

// image frame
var data = fs.readFileSync(__dirname + '/image.jpg');
var img = new Canvas.Image;
img.src = data;
ctx.drawImage(img, 0, 0, 320, 240);
encoder.addFrame(ctx);

encoder.finish();
</code>```

Note that I'm using readFileSync this time, but you can use readFile too as in my other answer, depending on your code.
I've also change the size of the loaded image, to fit the square.

Title: Add image as frame to a gif

Body:
So I want to create a gif and add an image as a frame. I am using gifencoder. I've seen the examples and its pretty easy to add colors, txt etc, but I couldnt figure out how to do the same with an image. Do I need something like the png file stream.

ex: from website for color frame

let canvas = new Canvas(width, height);
var ctx = canvas.getContext('2d');
red rectangle
ctx.fillStyle = '#ff0000';
ctx.fillRect(0, 0, 320, 240);
encoder.addFrame(ctx);

Edit:

I tried doing something like below and while the frames appear on my log as wanted the frames dont get added, no errors. Before someone suggests to convert to base64 the png/gif this module cant add such frames, that being said if you have another in mind that does please go ahead and say so.

fs.createReadStream('test.gif')
.pipe(new GIFDecoder) //gif-stream
.pipe(concat(function(frames) { //concat-frames
    console.log(frames);
    for (var i=0; i<frames.length; i++) {
        encoder.addFrame(frames[i]);
    }
}));

whatever I have tried at best I get just a black gif, nothing more.

Edit 2:

Okay so the reason I am trying to add from from a gif the frame, was because it simply seemed easier. Below is the progress I have done trying to get an image, convert it to RGBA (i noticed the module accepts rgba format, not rgb, perhaps that's why it was always black) and afterwards add the frame. Adding the frame if I have the data is extremely easy as I simply call a method and push the data in, so I am going to leave that out.

var request = require('request').defaults({ encoding: null });

request.get('https://upload.wikimedia.org/wikipedia/commons/0/01/Quinlingpandabearr.jpg', function (error, response, body) {
    if (!error && response.statusCode == 200) {
        var img = new Canvas(105, 159);
        var context = img.getContext('2d');
        img.src = "data:" + response.headers["content-type"] + ";base64," + new Buffer(body).toString('base64');
        var img_to_rgba = context.getImageData(0, 0, img.width, img.height);
        console.log(img_to_rgba); //always returns 0, like my pic is completely black, its not.
    }
});

Body:
I've added an image as a frame to a gif, along side a blue square.

Here is the full code, tested and working fine for me:

var GIFEncoder = require('gifencoder');
var Canvas = require('canvas');
var fs = require('fs');

var encoder = new GIFEncoder(320, 240);

encoder.createReadStream().pipe(fs.createWriteStream('myanimated.gif'));

encoder.start();
encoder.setRepeat(0);
encoder.setDelay(500);
encoder.setQuality(10);

var canvas = new Canvas(320, 240);
var ctx = canvas.getContext('2d');

// blue rectangle frame
ctx.fillStyle = '#0000ff';
ctx.fillRect(0, 0, 320, 240);
encoder.addFrame(ctx);

// image frame
var data = fs.readFileSync(__dirname + '/image.jpg');
var img = new Canvas.Image;
img.src = data;
ctx.drawImage(img, 0, 0, 320, 240);
encoder.addFrame(ctx);

encoder.finish();

Note that I'm using readFileSync this time, but you can use readFile too as in my other answer, depending on your code.
I've also change the size of the loaded image, to fit the square.


问:
What is difference between method process.exit(1) and process.exit(0) in node.js?
In node.js applications i saw usage of both these methods process.exit(1) and process.exit(0). Can anybody give me the exact answer ?

答:
You can find the answer to your question in the documentation: https://nodejs.org/api/process.html#process_process_exit_code

Basically if you want to exit with success use 0 if you want to exit with failure use 1.


问:
Formatted toString()
I am beginner using the toString() method to return a formatted String. I am printing a deck of cards where each column is the different suit. Does anyone have any ideas? Here is the code I have:

```<code>public class DeckOfCards {
  public static void main(String[] args) {
    int[] deck = new int[52];
    //String[] suits = {"Spades", "Hearts", "Diamonds", "Clubs"};
    String[] suits = {"Clubs","Diamonds","Hearts","Spades"};
    //String[] ranks = {"Ace","King", "Queen", "Jack", "10", "9", "8", "7", "6", "5", "4", "3", "2"};
    String[] ranks = {"2", "3", "4", "5", "6", "7", "8", "9", "10", "Jack", "Queen", "King","Ace"};

    // Initialize cards
        for (int i = 0; i < deck.length; i++) {
            deck[i] = i;
        }

        // Shuffle the cards
        for (int i = 0; i < deck.length; i++) {
            int index = (int)(Math.random() * deck.length);
            int temp = deck[i];
            deck[i] = deck[index];
            deck[index] = temp;
        }

        // Display the all the cards
        for (int i = 0; i < 52; i++) {
            String suit = suits[deck[i] / 13];
            String rank = ranks[deck[i] % 13];
            System.out.println( rank + " of " + suit);
        }

        System.out.println("------------------------------");

        for(int i=0;i<deck.length;i++){
            for(int j=i;j<deck.length;j++){
                if(deck[j]==51-i){
                    int temp = deck[i];
                    deck[i] = deck[j];
                    deck[j] = temp;
                }
            }
        }

        // Display the all the cards
        for (int i = 0; i < 52; i++) {
            String suit = suits[deck[i] / 13];
            String rank = ranks[deck[i] % 13];
            System.out.printf( rank + " of " + suit + "\t");
        }

    }
  }
</code>```

The main area I believe will be in the toString() is here:

```<code>// Display the all the cards
        for (int i = 0; i < 52; i++) {
            String suit = suits[deck[i] / 13];
            String rank = ranks[deck[i] % 13];
            System.out.println( rank + " of " + suit);
        }
</code>```

How would I use this in the toString() method and also instantiate an object that can print this toString() method? Thank you for your time. So that it displays in order in a game of bridge I was thinking of an output like this:

```<code>Ace of Spades     Ace of Hearts     Ace of Diamonds     Ace of Clubs
...
// And so on until it reaches two of clubs
</code>```

Do any of these ways print it like such without one being extra spaced or if not what could be modified in the toString() to have it come out like that? Thank you for your time, again.

答:
Here is a sample code for making a Card and a Deck class too and printing out the whole deck.</p>

```<code>class Deck {
    ArrayList<Card> cards = new ArrayList<Card>();
    public Deck() {
        for(int i=0; i < 52; i++ ) {
            cards.add(new Card());
        }
    }

    @Override
    public String toString() {
        String response = "";
        for(int i=0; i<52; i++)
        {
            response = response + "\n" + i+1 + ". Card: " + cards.get(i).toString() ;
        }
        return response;
    }
}

class Card {

    private String suit;
    private String rank;

    @Override
    public String toString() {
        return "It's a " + suit + " " + rank;
    }

    public Card() {
        Random r = new Random();
        int rRank = r.nextInt(12);
        switch(rRank) {
            case 0: {
                this.rank = "Jack";
                break;
            }
            case 1: {
                this.rank = "Queen";
                break;
            }
            case 11: {
                this.rank = "King";
                break;
            }
            case 12: {
                this.rank = "Ace";
                break;
            }
            default: {
                this.rank = rRank + ""; //Don't blame me for it. :D
                break;
            }
        }
        int suit = r.nextInt(3);
        switch(suit) {
            case 0: {
                this.suit = "Club";
                break;
            }
            case 1: {
                this.suit = "Diamond";
                break;
            }
            case 2: {
                this.suit = "Heart";
                break;
            }
            case 3: {
                this.suit = "Spade";
                break;
            }
        }

    }

}

public class Stackoverflow {

    public static void main(String[] args) {
        Deck deck = new Deck();
        System.out.println(deck.toString());
    }

}
</code>```

Title: Formatted toString()

Body:
I am beginner using the toString() method to return a formatted String. I am printing a deck of cards where each column is the different suit. Does anyone have any ideas? Here is the code I have:

public class DeckOfCards {
  public static void main(String[] args) {
    int[] deck = new int[52];
    //String[] suits = {"Spades", "Hearts", "Diamonds", "Clubs"};
    String[] suits = {"Clubs","Diamonds","Hearts","Spades"};
    //String[] ranks = {"Ace","King", "Queen", "Jack", "10", "9", "8", "7", "6", "5", "4", "3", "2"};
    String[] ranks = {"2", "3", "4", "5", "6", "7", "8", "9", "10", "Jack", "Queen", "King","Ace"};

    // Initialize cards
        for (int i = 0; i < deck.length; i++) {
            deck[i] = i;
        }

        // Shuffle the cards
        for (int i = 0; i < deck.length; i++) {
            int index = (int)(Math.random() * deck.length);
            int temp = deck[i];
            deck[i] = deck[index];
            deck[index] = temp;
        }

        // Display the all the cards
        for (int i = 0; i < 52; i++) {
            String suit = suits[deck[i] / 13];
            String rank = ranks[deck[i] % 13];
            System.out.println( rank + " of " + suit);
        }

        System.out.println("------------------------------");

        for(int i=0;i<deck.length;i++){
            for(int j=i;j<deck.length;j++){
                if(deck[j]==51-i){
                    int temp = deck[i];
                    deck[i] = deck[j];
                    deck[j] = temp;
                }
            }
        }

        // Display the all the cards
        for (int i = 0; i < 52; i++) {
            String suit = suits[deck[i] / 13];
            String rank = ranks[deck[i] % 13];
            System.out.printf( rank + " of " + suit + "\t");
        }

    }
  }

The main area I believe will be in the toString() is here:

// Display the all the cards
        for (int i = 0; i < 52; i++) {
            String suit = suits[deck[i] / 13];
            String rank = ranks[deck[i] % 13];
            System.out.println( rank + " of " + suit);
        }

How would I use this in the toString() method and also instantiate an object that can print this toString() method? Thank you for your time. So that it displays in order in a game of bridge I was thinking of an output like this:

Ace of Spades     Ace of Hearts     Ace of Diamonds     Ace of Clubs
...
// And so on until it reaches two of clubs

Do any of these ways print it like such without one being extra spaced or if not what could be modified in the toString() to have it come out like that? Thank you for your time, again.

Body:
Here is a sample code for making a Card and a Deck class too and printing out the whole deck.

class Deck {
    ArrayList<Card> cards = new ArrayList<Card>();
    public Deck() {
        for(int i=0; i < 52; i++ ) {
            cards.add(new Card());
        }
    }

    @Override
    public String toString() {
        String response = "";
        for(int i=0; i<52; i++)
        {
            response = response + "\n" + i+1 + ". Card: " + cards.get(i).toString() ;
        }
        return response;
    }
}

class Card {

    private String suit;
    private String rank;

    @Override
    public String toString() {
        return "It's a " + suit + " " + rank;
    }

    public Card() {
        Random r = new Random();
        int rRank = r.nextInt(12);
        switch(rRank) {
            case 0: {
                this.rank = "Jack";
                break;
            }
            case 1: {
                this.rank = "Queen";
                break;
            }
            case 11: {
                this.rank = "King";
                break;
            }
            case 12: {
                this.rank = "Ace";
                break;
            }
            default: {
                this.rank = rRank + ""; //Don't blame me for it. :D
                break;
            }
        }
        int suit = r.nextInt(3);
        switch(suit) {
            case 0: {
                this.suit = "Club";
                break;
            }
            case 1: {
                this.suit = "Diamond";
                break;
            }
            case 2: {
                this.suit = "Heart";
                break;
            }
            case 3: {
                this.suit = "Spade";
                break;
            }
        }

    }

}

public class Stackoverflow {

    public static void main(String[] args) {
        Deck deck = new Deck();
        System.out.println(deck.toString());
    }

}


问:
Change width of tab in UITabBarController to adjust the sixth tab
I need six tabs in tab bar controller. When I add the sixth tab more tab was created and fifth and sixth tab is not shown. How can I decrease the width of item so that it gets adjusted to show all six tabs.</p>

答:
```<code>//Swift #3
class TabBarViewController: UITabBarController, UITabBarControllerDelegate {

    override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)
    self.tabBar.itemWidth = your width
     //(self.tabBar.frame.width) / (numberOfItems
    }
  }
</code>```


问:
Credit card payments and notifications on the Google App Engine
I ported gchecky to the google app engine. you can try it here

It implements both level 1 (cart submission) and level 2 (notifications from google checkout).

Is there any other payment option that works on the google app engine (paypal for example) and supports level 2 (notifications)?

答: Paypal has a SOAP interface. You can certainly access that from within GAE--though you might run into timeout issues while waiting for the response.</p>

OwnerDisplayName: massimo

OwnerDisplayName: Brian Clapper


答:
0 is a success code and 1 (or another number) can be a failure code.  0 will be used if nothing is specified.  Useful for passing information on the way out.  Answered on SO here:

https://stackoverflow.com/a/5266239/5463636

More info direct from the Node.js docs here:

https://nodejs.org/api/process.html#process_process_exit_code

Title: What is difference between method process.exit(1) and process.exit(0) in node.js?

Body: In node.js applications i saw usage of both these methods process.exit(1) and process.exit(0). Can anybody give me the exact answer ?


问:
Remove everything after some characters
I have two situations:

In the first, I may have a string like:

```<code>  Posted 03-20-2017 More info Go to Last Post
</code>```

And I may have a string like:

```<code>  Posted today More info Go to Last Post
</code>```

In both of the situations, I don't want anything from More Info...

I tried using gsub,but it doesn't work for both of the situations.  Does anyone have possible solution?

答:
This can be relatively easily accomplished by running split("More info") on your strings. What that does is breaks the string in to an array like so:

```<code>new_string  = "Posted today More info Go to Last Post"
new_string = new_string.split("More info")
# becomes ["Posted today ", " Go to Last Post"]
</code>```

What split does is it breaks a string apart in to an array, where each element is what preceded the argument. So if you have "1,2,3" then split(",") will return [1, 2, 3]

So to continue your solution, you can get the posting date like this:

```<code>new_string[0].strip
</code>```

.strip removes spaces at the front or back of a string, so you'll be left with just "Posted today"

Title: Remove everything after some characters

Body:
I have two situations:

In the first, I may have a string like:

  Posted 03-20-2017 More info Go to Last Post

And I may have a string like:

  Posted today More info Go to Last Post

In both of the situations, I don't want anything from More Info...

I tried using gsub,but it doesn't work for both of the situations.  Does anyone have possible solution?

Body:
This can be relatively easily accomplished by running split("More info") on your strings. What that does is breaks the string in to an array like so:

new_string  = "Posted today More info Go to Last Post"
new_string = new_string.split("More info")
# becomes ["Posted today ", " Go to Last Post"]

What split does is it breaks a string apart in to an array, where each element is what preceded the argument. So if you have "1,2,3" then split(",") will return [1, 2, 3]

So to continue your solution, you can get the posting date like this:

new_string[0].strip

.strip removes spaces at the front or back of a string, so you'll be left with just "Posted today"


问:
Annotate a plot using matplotlib - showing values in the plot
I have two lists: one with strings in it (liste_string) and one list with numbers in it (liste_summe).
The list with the strings contains Date-Values as a string.
I want to show the values from liste_summe in the plot, but it doesn't work.

```<code> plt.subplots_adjust(left=None, bottom=0.4, right=None, top=None, wspace=None, hspace=None)#Grösse des Fenster einrichten
plt.annotate(liste_summe, xy = (liste_summe, liste_datum))
plt.xticks(rotation = 90)#Schrägstellen der Beschriftung der x-Achse um x Grad
plt.ylim([y_min, y_max])
plt.plot(liste_string, liste_summe)
plt.show()
</code>```

When I execute this code I get this Error:

TypeError: float() argument must be a string or a number, not 'list'

Does any one has an idea?

答:
plt.annotate cannot work with lists. As seen in ♠the documentation it wants a string as its fist argument and a coordinate pair as it's second argument. Since the x value is the date, the first entry in the coordinate tuple must be the date (not the inverse). In order to annotate all points, you can use a loop; one call to plt.annotate per point to annotate.

```<code>import matplotlib.pyplot as plt

liste_summe = [1,2,3,1,4]
liste_datum = ["2017-02-05", "2017-02-06", "2017-02-09", "2017-02-12", "2017-02-24"]
liste_string = liste_datum

plt.figure()
plt.subplots_adjust(bottom=0.4)
for s, d in zip(liste_summe, liste_datum):
    plt.annotate(d, xy = (d,s ))
plt.xticks(rotation = 90)

plt.plot_date(liste_string, liste_summe)
plt.show()
</code>```

Body:
I have two lists: one with strings in it (liste_string) and one list with numbers in it (liste_summe).
The list with the strings contains Date-Values as a string.
I want to show the values from liste_summe in the plot, but it doesn't work.

 plt.subplots_adjust(left=None, bottom=0.4, right=None, top=None, wspace=None, hspace=None)#Grösse des Fenster einrichten
plt.annotate(liste_summe, xy = (liste_summe, liste_datum))
plt.xticks(rotation = 90)#Schrägstellen der Beschriftung der x-Achse um x Grad
plt.ylim([y_min, y_max])
plt.plot(liste_string, liste_summe)
plt.show()

When I execute this code I get this Error:

TypeError: float() argument must be a string or a number, not 'list'

Does any one has an idea?

Body:
plt.annotate cannot work with lists. As seen in ♠the documentation it wants a string as its fist argument and a coordinate pair as it's second argument. Since the x value is the date, the first entry in the coordinate tuple must be the date (not the inverse). In order to annotate all points, you can use a loop; one call to plt.annotate per point to annotate.

import matplotlib.pyplot as plt

liste_summe = [1,2,3,1,4]
liste_datum = ["2017-02-05", "2017-02-06", "2017-02-09", "2017-02-12", "2017-02-24"]
liste_string = liste_datum

plt.figure()
plt.subplots_adjust(bottom=0.4)
for s, d in zip(liste_summe, liste_datum):
    plt.annotate(d, xy = (d,s ))
plt.xticks(rotation = 90)

plt.plot_date(liste_string, liste_summe)
plt.show()


问:
How to squash commits after the pull request has been opened?
I've looked at all the possible answers on SO and also have read blogs but I think I've messed up pretty bad.

I tried -

git rebase -i upstream/master

and then changing pick to squash after the first line, but I was getting merge conflicts again and again. So finally I read an answer on SO which recommended this -

```<code>#!/bin/bash

if [ $# -ne 1 ]; then
    echo "Missing parameter: number of commits to squash."
    exit 1
fi

echo "Squashing $1 commits..."
git reset --soft HEAD~$1
git log --format=%B%n --reverse "HEAD@{1}" -n $1 > _msg.txt
git commit -t _msg.txt
rm _msg.txt
echo "Done!"
</code>```

So I tried git-squash 6 and I think this messed it up harder. If you need any more information just ask.

Heres the PR -

https://github.com/mushorg/glutton/pull/62

答:
I start with the upstream repository:

```<code>$ git clone https://github.com/mushorg/glutton
$ cd glutton
</code>```

And just to make my remote names look like yours:

```<code>$ git remote rename origin upstream
</code>```

Then I fetch your PR:

```<code>$ git fetch upstream pull/62/head
$ git checkout FETCH_HEAD
</code>```

You would obviously not need this step, since you already have your changes locally.

Just to confirm I'm looking at the same thing you are, I see the following changes:

```<code>$ git log --oneline master..
cdbca37 Merge branch 'master' of https://github.com/HashCode55/glutton
b37aafd SMTP responses fixed and random wait time added
f25198e supports random wait time for response
4cfcc1d random removed
f2bfed7 refactor
da3dbdb refactor
3bfb62c removed rand function
1bb8a43 SMTP responses fixed
088f6df merged
a383e09 Revert "Revert "removed""
f1bb1c2 Revert "removed"
97bac3f removed
97a0408 Changes
</code>```

A few things jump out there:

You will probably find things more manageable if you work on a feature branch rather than your own master branch.  That is, start with git checkout -b my-spiffy-feature before you start making any changes.  If you will be regularly contributing upstream, your life is easiest if your master branch always reflects the state of the upstream master branch at some point in time, because this permits you to update your local master branch with a simple git pull upstream master.

Avoiding merging code into your feature branches.  Regularly rebase on upstream/master if you need to incorporate upstream changes.

Avoid generating revert commits in your feature branch.  Just use git reset.

If you were to follow the above steps you would avoid all the conflicts and complication that brought you to this point.

The easiest way to squash all of these changes is probably start by resetting your current branch back to the upstream master branch:

```<code>$ git reset upstream/master
</code>```

This will reset the repository, but not your working directory, to the state of the upstream/master branch.  Since it doesn't modify the state of your working directory, this means that all your changes are preserved, but not the commit history.  At this point, we see:

```<code>$ git status
[...]
Changes not staged for commit:
  (use "git add <file>..." to update what will be committed)
  (use "git checkout -- <file>..." to discard changes in working directory)

    modified:   app/server.go
    modified:   smtp.go

no changes added to commit (use "git add" and/or "git commit -a")
</code>```

Now we can create a new commit:

```<code>$ git add -u
$ git commit
</code>```

Now you have a single commit on top of the upstream master branch.  You would then force push this to your own master branch, which would update the PR.

(NB: if you're worried about screwing something up or losing your changes or anything like that, either work on a new branch, or just make a local copy of your working directory and work on that instead.)

Body:
I've looked at all the possible answers on SO and also have read blogs but I think I've messed up pretty bad.

I tried -

git rebase -i upstream/master

and then changing pick to squash after the first line, but I was getting merge conflicts again and again. So finally I read an answer on SO which recommended this -

#!/bin/bash

if [ $# -ne 1 ]; then
    echo "Missing parameter: number of commits to squash."
    exit 1
fi

echo "Squashing $1 commits..."
git reset --soft HEAD~$1
git log --format=%B%n --reverse "HEAD@{1}" -n $1 > _msg.txt
git commit -t _msg.txt
rm _msg.txt
echo "Done!"

So I tried git-squash 6 and I think this messed it up harder. If you need any more information just ask.

Heres the PR -

https://github.com/mushorg/glutton/pull/62

Body:
I start with the upstream repository:

$ git clone https://github.com/mushorg/glutton
$ cd glutton

And just to make my remote names look like yours:

$ git remote rename origin upstream

Then I fetch your PR:

$ git fetch upstream pull/62/head
$ git checkout FETCH_HEAD

You would obviously not need this step, since you already have your changes locally.

Just to confirm I'm looking at the same thing you are, I see the following changes:

$ git log --oneline master..
cdbca37 Merge branch 'master' of https://github.com/HashCode55/glutton
b37aafd SMTP responses fixed and random wait time added
f25198e supports random wait time for response
4cfcc1d random removed
f2bfed7 refactor
da3dbdb refactor
3bfb62c removed rand function
1bb8a43 SMTP responses fixed
088f6df merged
a383e09 Revert "Revert "removed""
f1bb1c2 Revert "removed"
97bac3f removed
97a0408 Changes

A few things jump out there:

You will probably find things more manageable if you work on a feature branch rather than your own master branch.  That is, start with git checkout -b my-spiffy-feature before you start making any changes.  If you will be regularly contributing upstream, your life is easiest if your master branch always reflects the state of the upstream master branch at some point in time, because this permits you to update your local master branch with a simple git pull upstream master.

Avoiding merging code into your feature branches.  Regularly rebase on upstream/master if you need to incorporate upstream changes.

Avoid generating revert commits in your feature branch.  Just use git reset.

If you were to follow the above steps you would avoid all the conflicts and complication that brought you to this point.

The easiest way to squash all of these changes is probably start by resetting your current branch back to the upstream master branch:

$ git reset upstream/master

This will reset the repository, but not your working directory, to the state of the upstream/master branch.  Since it doesn't modify the state of your working directory, this means that all your changes are preserved, but not the commit history.  At this point, we see:

$ git status
[...]
Changes not staged for commit:
  (use "git add <file>..." to update what will be committed)
  (use "git checkout -- <file>..." to discard changes in working directory)

    modified:   app/server.go
    modified:   smtp.go

no changes added to commit (use "git add" and/or "git commit -a")

Now we can create a new commit:

$ git add -u
$ git commit

Now you have a single commit on top of the upstream master branch.  You would then force push this to your own master branch, which would update the PR.

(NB: if you're worried about screwing something up or losing your changes or anything like that, either work on a new branch, or just make a local copy of your working directory and work on that instead.)


问:
PHP MySQL fast inserting many rows
Currently, I am using prepared statements to insert a bunch of rows with underneath code:

UPDATED CODE:

```<code>$sql = $mysqli->prepare("INSERT INTO `TBLName` (Col1, Col2, Col3) Values(?, ?, ?)");
for ($i = 0; $i < 1000; $i++) {
    $sql->bind_param('sss', $Col1Data, $Col2Data, $Col3Data);
    $sql->execute();
    }
$sql->close();
</code>```

However, I have seen an article talking about Transaction being way faster... Could I use transaction in combination with the prepared statement or should I use it in a different way? Suppose that I have to insert 1000 rows per script run and the script get's triggered with an interval of 5 seconds, what is the best way to go for me?

答:
I recommend 100 to 1000 rows being inserted in a single INSERT statement.  (I don't think the code you presented will work without some more changes.)

And do the 100-1000 rows either with autocommit=1 or in a TRANSACTION.  This has the benefit of not hogging the system and not collecting lots of data to potentially "undo".  But the drawback of not doing all the rows atomically.

Less than 100 leads to extra overhead; more than 1000 gets into diminishing returns and other forms of overhead.

The 100-1000 is also Replication-friendly, rather than hogging the replication stream.

If you already have the data in a csv file, use LOAD DATA.

Title: PHP MySQL fast inserting many rows

Body:
Currently, I am using prepared statements to insert a bunch of rows with underneath code:

UPDATED CODE:

$sql = $mysqli->prepare("INSERT INTO `TBLName` (Col1, Col2, Col3) Values(?, ?, ?)");
for ($i = 0; $i < 1000; $i++) {
    $sql->bind_param('sss', $Col1Data, $Col2Data, $Col3Data);
    $sql->execute();
    }
$sql->close();

However, I have seen an article talking about Transaction being way faster... Could I use transaction in combination with the prepared statement or should I use it in a different way? Suppose that I have to insert 1000 rows per script run and the script get's triggered with an interval of 5 seconds, what is the best way to go for me?


问:
Python file to execute commands in docker
i want to cd to a certain directory in docker when a button is clicked , so i need a python command to do that , i tried

```<code>os.system("sudo docker start jolly_allen ;sudo docker exec -i -t    jolly_allen /bin/bash ; sudo docker exec -i -t jolly_allen -c cd    /   tensorflow")
</code>```

and

os.system("sudo docker run jolly_allen /bin/bash -c cd /tensorflow")

But nothing worked.

Thank you !

答:
Explore the Docker Python module and have fun:
https://docker-py.readthedocs.io/en/stable/</p>

Body:
i want to cd to a certain directory in docker when a button is clicked , so i need a python command to do that , i tried

os.system("sudo docker start jolly_allen ;sudo docker exec -i -t    jolly_allen /bin/bash ; sudo docker exec -i -t jolly_allen -c cd    /   tensorflow")

and

os.system("sudo docker run jolly_allen /bin/bash -c cd /tensorflow")

But nothing worked.

Thank you !