问:
How do I avoid "anti-aliasing effect" when creating a PGraphics object that's smaller than the window, then scale it up to the windows size?
When ran, the program displays a 3D sphere rendered in a P3D environment in the PGraphics object 'g', which is shown by taking the rendered PGraphics object and displaying it through the image() method in the main graphics context, which happens to be P2D.

The purpose of the program is to show how window size doesn't always correlate with render size. If you play an old Widows98 game in full screen, the game most likely will be rendered at 480p no matter what, so taking it into full screen just decreases the pixels per inch, plus making the image appear blurry. Which is fine, since fullscreen at 480p is preferred over windowed mode ( esp. if you're on 4K X_X )

the mouse's y position in the window changes the 3d camera's field of view, and the x position changes the rendering resolution of the P3D context used to display the sphere. Additionally, the P3D context is drawn in the main (P2D) context through the image() method, and is 'forcefully'. displayed at the size of the window. So if the P3D render resolution is smaller than the window, then it will start to look blurry and more pixelated, and if the render resolution is larger, you get a strange sharpening effect.

Now, my program works fine as it is, but. Another purpose of the program is shadowed by this issue, it's how the 'crispness' of the sphere fades as the render resolution decreases. You might say that it's clearly shown, but what I'm looking for is an image where there is no "anti-alias" effect going on. I want the image to preserve the pixels as the resolution gets smaller, so you can see the actual shape of the sphere at say, 50 x 50 pixels.

The noSmooth() method doesn't seem to work, and before you tell me to just do

```<code>g.loadPixels();
</code>```

and then do a double for loop to draw the raw pixels to the 2d context. No, it's sloppy. I know that there must be some reason why this blurring is going on. I'm hoping that it's the image() method and that I should be using a different method or I should add another method before it to remove image blurring.

```<code>PGraphics g;

void setup(){
  size(1000,1000,P2D);
  frameRate(1000);
  noSmooth();
}

void draw(){
  background(200);
  float res = map(mouseX,0,width,0.75,128);
  if (res==0) {
    res=1;
  }

  g = createGraphics((int)(width/res),(int)(height/res),P3D);
  g.noSmooth(); // is this thing working?????
  float cameraZ = ((height/2.0) / tan(PI*60.0/360.0));

  g.beginDraw();
    g.perspective(radians(map(mouseY,0,height,0.1,160)), width/height, cameraZ/10.0, cameraZ*10.0);
    g.camera(g.width/2.0, g.height/2.0, (height/2.0) / tan(PI*30.0 / 180.0), g.width/2.0, g.height/2.0, 0, 0, 1, 0);

    g.background(200);
    g.translate(g.width/2 ,g.height/2);
    g.sphere(100);
  g.endDraw();

  image(g, 0, 0, width, height); // this is where it all comes together
  text("rendering resolution: "+g.width+" x "+g.height,0,14);
  text("fps: "+frameRate,0,14*2);
}
</code>```

答:
(Edit: This solution fixes the problem in the default renderer, but the OP is using the P2D renderer. The solution should be similar, so if somebody knows how to change the image interpolation mode in opengl, that's the answer.)

This is not really caused by anti-aliasing. It's caused by image scaling.

Also, it's much easier to help if you provide a MCVE, like this one:

```<code>PGraphics buffer;

void setup() {

  size(1000, 1000);

  buffer = createGraphics(100, 100);
  buffer.noSmooth();
  buffer.beginDraw();
  buffer.background(255);
  buffer.line(0, 0, width, height);
  buffer.endDraw();
}

void draw() {
  background(0);
  image(buffer, 0, 0, mouseX, mouseY);
}
</code>```

This code exhibits the same problem, but it's much easier to understand and work with.

Anyway, tracing through Processing's code, we can see that the image() function eventually calls the imageImpl() function in the PGraphics class here.

This function then draws your image using this code:

```<code>beginShape(QUADS);
texture(img);
vertex(x1, y1, u1, v1);
vertex(x1, y2, u1, v2);
vertex(x2, y2, u2, v2);
vertex(x2, y1, u2, v1);
endShape();
</code>```

The endShape() function is then implemented in the renderer, specifically the PGraphicsJava2D class, which calls the drawShape() function here:

```<code>protected void drawShape(Shape s) {
    if (fillGradient) {
      g2.setPaint(fillGradientObject);
      g2.fill(s);
    } else if (fill) {
      g2.setColor(fillColorObject);
      g2.fill(s);
    }
    if (strokeGradient) {
      g2.setPaint(strokeGradientObject);
      g2.draw(s);
    } else if (stroke) {
      g2.setColor(strokeColorObject);
      g2.draw(s);
    }
}
</code>```

Finally, that shows us that the Graphics2D.fill() function is being called, which is what actually draws your function.

The "problem" is that Graphics2D.fill() is scaling your image using an algorithm that causes some blurriness. We can consult the Java API and Google to figure out how to fix that though.

Specifically, this tutorial shows you how to set various rendering hints to change the scaling algorithm. We can use that in Processing like this:

```<code>import java.awt.Graphics2D;
import java.awt.RenderingHints;
import processing.awt.PGraphicsJava2D;

PGraphics buffer;

void setup() {

  size(1000, 1000);

  buffer = createGraphics(100, 100);
  buffer.noSmooth();
  buffer.beginDraw();
  buffer.background(255);
  buffer.line(0, 0, width, height);
  buffer.endDraw();
}

void draw() {

  if (mousePressed) {
    Graphics2D g2d = ((PGraphicsJava2D)g).g2;

    g2d.setRenderingHint(
      RenderingHints.KEY_INTERPOLATION,
      RenderingHints.VALUE_INTERPOLATION_NEAREST_NEIGHBOR);
  }

  background(0);
  image(buffer, 0, 0, mouseX, mouseY);
}
</code>```

First, we import the classes we're going to need. Then we get to the Graphics2D instance in the renderer, and finally we call its setRenderingHint() function. I wrapped it in an if(mousePressed) so you could easily see the difference. When you click the mouse, interpolation is set to nearest neighbor, and you no longer see the blurriness.

Also notice that my code uses the g variable that's inherited from the PApplet superclass, so you would have to change your g variable so it's no longer hiding it.

Body:
When ran, the program displays a 3D sphere rendered in a P3D environment in the PGraphics object 'g', which is shown by taking the rendered PGraphics object and displaying it through the image() method in the main graphics context, which happens to be P2D.

The purpose of the program is to show how window size doesn't always correlate with render size. If you play an old Widows98 game in full screen, the game most likely will be rendered at 480p no matter what, so taking it into full screen just decreases the pixels per inch, plus making the image appear blurry. Which is fine, since fullscreen at 480p is preferred over windowed mode ( esp. if you're on 4K X_X )

the mouse's y position in the window changes the 3d camera's field of view, and the x position changes the rendering resolution of the P3D context used to display the sphere. Additionally, the P3D context is drawn in the main (P2D) context through the image() method, and is 'forcefully'. displayed at the size of the window. So if the P3D render resolution is smaller than the window, then it will start to look blurry and more pixelated, and if the render resolution is larger, you get a strange sharpening effect.

Now, my program works fine as it is, but. Another purpose of the program is shadowed by this issue, it's how the 'crispness' of the sphere fades as the render resolution decreases. You might say that it's clearly shown, but what I'm looking for is an image where there is no "anti-alias" effect going on. I want the image to preserve the pixels as the resolution gets smaller, so you can see the actual shape of the sphere at say, 50 x 50 pixels.

The noSmooth() method doesn't seem to work, and before you tell me to just do

g.loadPixels();

and then do a double for loop to draw the raw pixels to the 2d context. No, it's sloppy. I know that there must be some reason why this blurring is going on. I'm hoping that it's the image() method and that I should be using a different method or I should add another method before it to remove image blurring.

PGraphics g;

void setup(){
  size(1000,1000,P2D);
  frameRate(1000);
  noSmooth();
}

void draw(){
  background(200);
  float res = map(mouseX,0,width,0.75,128);
  if (res==0) {
    res=1;
  }

  g = createGraphics((int)(width/res),(int)(height/res),P3D);
  g.noSmooth(); // is this thing working?????
  float cameraZ = ((height/2.0) / tan(PI*60.0/360.0));

  g.beginDraw();
    g.perspective(radians(map(mouseY,0,height,0.1,160)), width/height, cameraZ/10.0, cameraZ*10.0);
    g.camera(g.width/2.0, g.height/2.0, (height/2.0) / tan(PI*30.0 / 180.0), g.width/2.0, g.height/2.0, 0, 0, 1, 0);

    g.background(200);
    g.translate(g.width/2 ,g.height/2);
    g.sphere(100);
  g.endDraw();

  image(g, 0, 0, width, height); // this is where it all comes together
  text("rendering resolution: "+g.width+" x "+g.height,0,14);
  text("fps: "+frameRate,0,14*2);
}

Body:
(Edit: This solution fixes the problem in the default renderer, but the OP is using the P2D renderer. The solution should be similar, so if somebody knows how to change the image interpolation mode in opengl, that's the answer.)

This is not really caused by anti-aliasing. It's caused by image scaling.

Also, it's much easier to help if you provide a MCVE, like this one:

PGraphics buffer;

void setup() {

  size(1000, 1000);

  buffer = createGraphics(100, 100);
  buffer.noSmooth();
  buffer.beginDraw();
  buffer.background(255);
  buffer.line(0, 0, width, height);
  buffer.endDraw();
}

void draw() {
  background(0);
  image(buffer, 0, 0, mouseX, mouseY);
}

This code exhibits the same problem, but it's much easier to understand and work with.

Anyway, tracing through Processing's code, we can see that the image() function eventually calls the imageImpl() function in the PGraphics class here.

This function then draws your image using this code:

beginShape(QUADS);
texture(img);
vertex(x1, y1, u1, v1);
vertex(x1, y2, u1, v2);
vertex(x2, y2, u2, v2);
vertex(x2, y1, u2, v1);
endShape();

The endShape() function is then implemented in the renderer, specifically the PGraphicsJava2D class, which calls the drawShape() function here:

protected void drawShape(Shape s) {
    if (fillGradient) {
      g2.setPaint(fillGradientObject);
      g2.fill(s);
    } else if (fill) {
      g2.setColor(fillColorObject);
      g2.fill(s);
    }
    if (strokeGradient) {
      g2.setPaint(strokeGradientObject);
      g2.draw(s);
    } else if (stroke) {
      g2.setColor(strokeColorObject);
      g2.draw(s);
    }
}

Finally, that shows us that the Graphics2D.fill() function is being called, which is what actually draws your function.

The "problem" is that Graphics2D.fill() is scaling your image using an algorithm that causes some blurriness. We can consult the Java API and Google to figure out how to fix that though.

Specifically, this tutorial shows you how to set various rendering hints to change the scaling algorithm. We can use that in Processing like this:

import java.awt.Graphics2D;
import java.awt.RenderingHints;
import processing.awt.PGraphicsJava2D;

PGraphics buffer;

void setup() {

  size(1000, 1000);

  buffer = createGraphics(100, 100);
  buffer.noSmooth();
  buffer.beginDraw();
  buffer.background(255);
  buffer.line(0, 0, width, height);
  buffer.endDraw();
}

void draw() {

  if (mousePressed) {
    Graphics2D g2d = ((PGraphicsJava2D)g).g2;

    g2d.setRenderingHint(
      RenderingHints.KEY_INTERPOLATION,
      RenderingHints.VALUE_INTERPOLATION_NEAREST_NEIGHBOR);
  }

  background(0);
  image(buffer, 0, 0, mouseX, mouseY);
}

First, we import the classes we're going to need. Then we get to the Graphics2D instance in the renderer, and finally we call its setRenderingHint() function. I wrapped it in an if(mousePressed) so you could easily see the difference. When you click the mouse, interpolation is set to nearest neighbor, and you no longer see the blurriness.

Also notice that my code uses the g variable that's inherited from the PApplet superclass, so you would have to change your g variable so it's no longer hiding it.


来源: stackexchange

问:
Posix Thread Locked: waiting forever
How to name a situation when a thread is locked waiting forever? I found several examples about when two threads collide, which is called a race condition:

```<code>A race condition occurs when two or more threads
can access shared data and they try to
change it at the same time
</code>```

But when a thread is stuck waiting forever for another thread, is there any specific term to name this situation, or yet is it still named as a race condition, even if we have two thread that do not try to access the shared data at the same time, but instead... one of the threads got locked waiting forever for the 2nd thread?

答:
If Thread_1 is waiting for Thread_2, and at the same time, Thread_2 is waiting for Thread_1. It's called dead-lock. When Dead-Lock occurred, it just like two threads tussle with each other.

Another situation is called live-lock. Live-lock is just the situation that there is a thread waiting forever for another thread. If Thread_2 is waiting for Thread_1. And Thread_2 want to get a write-lock from Thread_1. But at this time there comes another Thread_3. Thread_3 wants to get a write-lock from Thread_1, too. Unfortunately Thread_3 got a higher priority than Thread_2. So When Thread_1 free that write-lock. Thread_3 got that write-lock immediately. And there comes a Thread_4, Thread_4 has the same priority as Thread_3...

Thread_2 seems to be waiting for a write-lock forever. That's called a live-lock.
To avoid this problem, we can build a server-queue. Which thread came to queue early, we handle that earlier thread first.

Pthread gave us serval ways to lock a resource. We can use mutex or something other. But we must solve the issue after we using locks.

You could get more information about this topic in Concurrency Control.

ContentLicense: CC BY-SA 3.0

Title: Posix Thread Locked: waiting forever

Body:
How to name a situation when a thread is locked waiting forever? I found several examples about when two threads collide, which is called a race condition:

A race condition occurs when two or more threads
can access shared data and they try to
change it at the same time

But when a thread is stuck waiting forever for another thread, is there any specific term to name this situation, or yet is it still named as a race condition, even if we have two thread that do not try to access the shared data at the same time, but instead... one of the threads got locked waiting forever for the 2nd thread?


问:
Rails is only refreshing pages after a submit
I have a rails app with foundation. It is not firing the foundation jquery on every page. I have the correct foundation code in application.js:
//= require foundation

```<code>$(function(){
   $(document).foundation();
});
</code>```

If I refresh a page manually, it fires. If I just render the page using a link in the application, it does not fire.

I am using turbolinks in Rails 4.

答:
When using turbolinks, you will need to replace that javascript you have with this:

```<code>$(document).on('turbolinks:load', function() {
  $(document).foundation();
});
</code>```

NOTE: For older versions of turbolinks, use page:load instead of turbolinks:load

Body:
I have a rails app with foundation. It is not firing the foundation jquery on every page. I have the correct foundation code in application.js:
//= require foundation

$(function(){
   $(document).foundation();
});

If I refresh a page manually, it fires. If I just render the page using a link in the application, it does not fire.

I am using turbolinks in Rails 4.

Body:
When using turbolinks, you will need to replace that javascript you have with this:

$(document).on('turbolinks:load', function() {
  $(document).foundation();
});

NOTE: For older versions of turbolinks, use page:load instead of turbolinks:load


问:
How can I query two tables using php PDO?
I have two tables pre_application and applicants table. I want to query pre_application table for password and applicants table for application pin and if the two table have the records then applicant should be logged in. Below is my code:

```<code>if(isset($_POST['submit']) || $_SERVER['REQUEST_METHOD']=='POST'){

    try{
        $pin=$_POST['pin'];
        $pass=$_POST['password'];
        $stm=$dbh->query("SELECT password FROM pre_application WHERE password='$pass' UNION SELECT app_no FROM applicants WHERE app_no='$pin'");
        foreach($stm as $row);
        $appass=$row['password'];
        $appin=$row['app_no'];
        $name=$row['name'];
        if($stm) {
            header('location:approfile.php?applicant=$appass');
        } else {
            echo "<script> alert('Invalid Application Number or Password')</script>";
            exist();
        }
    } catch(Exception $e){
        echo $e->getMessage();
    }
}?>
</code>```

Someone should please help on the right syntax

答:
the UNION is not the correct solution for your case. The UNION, as it name suggests, will combine the data sets (you can also call it rows or records) of all subquery related together.

For your question, I assume that the pre_application and applicants table must be associated through a FOREIGN KEY (the most simple case, otherwise they can be associated via a bridging table, but I cannot tell what exactly there since I cannot see your table structures), otherwise, there is no precise way to link between a pin - password pair and to make sure every password - pin pairs are unique.

With the assumption that there is a column name app_id in the pre_application table that is the FOREIGN KEY of the id column in the applicants table, you can change your query to use JOIN  instead of UNION:

```<code> $stm=$dbh->query("SELECT password, pin
                   FROM pre_application pre
                   JOIN applicants app ON app.id = pre.app_id
                   WHERE password='$pass' AND app_no='$pin'");
</code>```

The JOIN match rows from pre_applications table to related one in the applicants table, check to see if these JOINING rows match the password and pin condition, and return the matching one.

You can do some more research about JOIN, UNION here:
https://dev.mysql.com/doc/refman/5.7/en/join.html

ContentLicense: CC BY-SA 4.0

Body:
I have two tables pre_application and applicants table. I want to query pre_application table for password and applicants table for application pin and if the two table have the records then applicant should be logged in. Below is my code:

if(isset($_POST['submit']) || $_SERVER['REQUEST_METHOD']=='POST'){

    try{
        $pin=$_POST['pin'];
        $pass=$_POST['password'];
        $stm=$dbh->query("SELECT password FROM pre_application WHERE password='$pass' UNION SELECT app_no FROM applicants WHERE app_no='$pin'");
        foreach($stm as $row);
        $appass=$row['password'];
        $appin=$row['app_no'];
        $name=$row['name'];
        if($stm) {
            header('location:approfile.php?applicant=$appass');
        } else {
            echo "";
            exist();
        }
    } catch(Exception $e){
        echo $e->getMessage();
    }
}?>

Someone should please help on the right syntax

Body:
the UNION is not the correct solution for your case. The UNION, as it name suggests, will combine the data sets (you can also call it rows or records) of all subquery related together.

For your question, I assume that the pre_application and applicants table must be associated through a FOREIGN KEY (the most simple case, otherwise they can be associated via a bridging table, but I cannot tell what exactly there since I cannot see your table structures), otherwise, there is no precise way to link between a pin - password pair and to make sure every password - pin pairs are unique.

With the assumption that there is a column name app_id in the pre_application table that is the FOREIGN KEY of the id column in the applicants table, you can change your query to use JOIN  instead of UNION:

 $stm=$dbh->query("SELECT password, pin
                   FROM pre_application pre
                   JOIN applicants app ON app.id = pre.app_id
                   WHERE password='$pass' AND app_no='$pin'");

The JOIN match rows from pre_applications table to related one in the applicants table, check to see if these JOINING rows match the password and pin condition, and return the matching one.

You can do some more research about JOIN, UNION here:
https://dev.mysql.com/doc/refman/5.7/en/join.html


问:
How to swap a disabled option DOM element to enabled?
I have a list with enabled and disabled option. I do know how to disable an option element but what I don't know how to enable it again.

```<code><select size="1" id="x">
  <option value="47" disabled="disabled">Value 47</option>
  ...

selectElement.options[i].disabled = 'disabled';
// ... how to enable?
</code>```

It should be done with Plain Javascript and no JavaScript Framework. (I wish I could use Prototype or a similar framework but I cannot introduce one of them.)

答:
Use setAttribute and removeAttribute:

```<code>selectElement.options[i].setAttribute("disabled", "disabled");
selectElement.options[i].removeAttribute("disabled");
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I have a list with enabled and disabled option. I do know how to disable an option element but what I don't know how to enable it again.

<select size="1" id="x">
  <option value="47" disabled="disabled">Value 47</option>
  ...

selectElement.options[i].disabled = 'disabled';
// ... how to enable?

It should be done with Plain Javascript and no JavaScript Framework. (I wish I could use Prototype or a similar framework but I cannot introduce one of them.)

Body:
Use setAttribute and removeAttribute:

selectElement.options[i].setAttribute("disabled", "disabled");
selectElement.options[i].removeAttribute("disabled");


问:
Just Upgraded To Xcode 8.3, now getting an error: "Type GameScene has no member: updateCounting"
My code was running and functioning like it should, until I recently updated to Xcode 8.3. Now my code fails to run, leaving me with the error: "Type GameScene has no member: updateCounting". I have read similar questions and solutions, but none were able to help solve the issue. I am still learning swift, so any help would be appreciated.

Here is my code:

```<code>    let highScoreDefault = UserDefaults.standard
    highScore = highScoreDefault.integer(forKey: "Highscore")
    highScoreLabel.text = "\(highScore)"

func scoreUpdate(_ currentTime: CFTimeInterval){

    if (score > highScore) {
        highScore = score
        highScoreLabel.text = NSString(format: "Highscore : %i", highScore) as String

        let highscoreDefault = UserDefaults.standard
        highscoreDefault.setValue(highScore, forKey: "Highscore")
        highscoreDefault.synchronize()

    }

    }

func updateCounting() {
        scoreLabel.text = String(self.score)
        finalScore.text = String(self.score)

        let highScoreDefault = UserDefaults.standard
        highScore = highScoreDefault.integer(forKey: " ")
        highScoreLabel.text = "\(highScore)"

    if (score > highScore) {
        highScore = score
        highScoreLabel.text = NSString(format: " %i", highScore) as String

        let highscoreDefault = UserDefaults.standard
        highscoreDefault.setValue(highScore, forKey: " ")
        highscoreDefault.synchronize()
    }

        self.score += 1
        print(score, terminator: " ")

    }

        timer = Timer.scheduledTimer(timeInterval: 0.1, target: self, selector: #selector(GameScene.updateCounting), userInfo: nil, repeats: true)

         // The above line of code is what's giving the error

        totalCoins = UserDefaults.standard.integer(forKey: "Total Coins")
        totalCoinLabel.text = "\(totalCoins)"
</code>```

答:
Suggested Solution

Try adding @objc before your function name like this:

```<code>@objc func updateCounting() {
    // function code here
}
</code>```

Then use #selector(self.updateCounting)

Working Example

I took your code and heavily simplified it. I started off with a new Single View project. I added a GameScene.swift file and modified the ViewController class. See code below. Run the project and you'll see the log show:

```<code>Updating count: 0
Updating count: 1
Updating count: 2
Updating count: 3
</code>```

GameScene.swift

```<code>import Foundation

class GameScene {
    var timer: Timer = Timer()
    var counter: Int = 0

    @objc func updateCounting(){
        print("Updating count: \(counter)")
        counter += 1
    }

    func updateTimer() {
        timer = Timer.scheduledTimer(timeInterval: 0.5, target: self, selector: #selector(updateCounting), userInfo: nil, repeats: true)
    }
}
</code>```

ViewController.swift

```<code>import UIKit

class ViewController: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()
        let game = GameScene()
        game.updateTimer()
    }
}
</code>```

Github link: https://github.com/starkindustries/TimerTestProject

Syntax Options That Work

The following options tested successfully in this example project:

selector: #selector(updateCounting)

selector: #selector(self.updateCounting)

selector: #selector(GameScene.updateCounting)

Let's say you want to add a parameter to your updateCounting function. Change your updateCounting method name to @objc func updateCounting(_ timer: Timer) and change your selector to selector: #selector(updateCounting(_:)

Syntax Discussion

As soon as I remove @objc the compiler shows this error:

Argument of '#selector' refers to instance method 'updateCounting'
  that is not exposed to Objective-C

One of the comments in another answer hinted at this too:

I needed to add write the target function like this: @objc func
  updateTime() {}
  Timer.scheduledTimer swift 3 pre iOS 10 compatibility

The Apple Documentation states:

The selector should have the following signature: timerFireMethod:
  (including a colon to indicate that the method takes an argument). The
  timer passes itself as the argument, thus the method would adopt the
  following pattern:
  - (void)timerFireMethod:(NSTimer *)timer https://developer.apple.com/reference/foundation/timer/1412416-scheduledtimer

Even though I was in the Swift version of the documentation, it displayed that Objective C version of the timerFireMethod. So maybe the Timer class expects an Objective C selector just like the compiler error complained about. However, the documentation states that the method should have one parameter (timer), but I just tested it successfully using a function without parameters.

Body:
My code was running and functioning like it should, until I recently updated to Xcode 8.3. Now my code fails to run, leaving me with the error: "Type GameScene has no member: updateCounting". I have read similar questions and solutions, but none were able to help solve the issue. I am still learning swift, so any help would be appreciated.

Here is my code:

    let highScoreDefault = UserDefaults.standard
    highScore = highScoreDefault.integer(forKey: "Highscore")
    highScoreLabel.text = "\(highScore)"

func scoreUpdate(_ currentTime: CFTimeInterval){

    if (score > highScore) {
        highScore = score
        highScoreLabel.text = NSString(format: "Highscore : %i", highScore) as String

        let highscoreDefault = UserDefaults.standard
        highscoreDefault.setValue(highScore, forKey: "Highscore")
        highscoreDefault.synchronize()

    }

    }

func updateCounting() {
        scoreLabel.text = String(self.score)
        finalScore.text = String(self.score)

        let highScoreDefault = UserDefaults.standard
        highScore = highScoreDefault.integer(forKey: " ")
        highScoreLabel.text = "\(highScore)"

    if (score > highScore) {
        highScore = score
        highScoreLabel.text = NSString(format: " %i", highScore) as String

        let highscoreDefault = UserDefaults.standard
        highscoreDefault.setValue(highScore, forKey: " ")
        highscoreDefault.synchronize()
    }

        self.score += 1
        print(score, terminator: " ")

    }

        timer = Timer.scheduledTimer(timeInterval: 0.1, target: self, selector: #selector(GameScene.updateCounting), userInfo: nil, repeats: true)

         // The above line of code is what's giving the error

        totalCoins = UserDefaults.standard.integer(forKey: "Total Coins")
        totalCoinLabel.text = "\(totalCoins)"

Body:
Suggested Solution

Try adding @objc before your function name like this:

@objc func updateCounting() {
    // function code here
}

Then use #selector(self.updateCounting)

Working Example

I took your code and heavily simplified it. I started off with a new Single View project. I added a GameScene.swift file and modified the ViewController class. See code below. Run the project and you'll see the log show:

Updating count: 0
Updating count: 1
Updating count: 2
Updating count: 3

GameScene.swift

import Foundation

class GameScene {
    var timer: Timer = Timer()
    var counter: Int = 0

    @objc func updateCounting(){
        print("Updating count: \(counter)")
        counter += 1
    }

    func updateTimer() {
        timer = Timer.scheduledTimer(timeInterval: 0.5, target: self, selector: #selector(updateCounting), userInfo: nil, repeats: true)
    }
}

ViewController.swift

import UIKit

class ViewController: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()
        let game = GameScene()
        game.updateTimer()
    }
}

Github link: https://github.com/starkindustries/TimerTestProject

Syntax Options That Work

The following options tested successfully in this example project:

selector: #selector(updateCounting)

selector: #selector(self.updateCounting)

selector: #selector(GameScene.updateCounting)

Let's say you want to add a parameter to your updateCounting function. Change your updateCounting method name to @objc func updateCounting(_ timer: Timer) and change your selector to selector: #selector(updateCounting(_:)

Syntax Discussion

As soon as I remove @objc the compiler shows this error:

Argument of '#selector' refers to instance method 'updateCounting'
  that is not exposed to Objective-C

One of the comments in another answer hinted at this too:

I needed to add write the target function like this: @objc func
  updateTime() {}
  Timer.scheduledTimer swift 3 pre iOS 10 compatibility

The Apple Documentation states:

The selector should have the following signature: timerFireMethod:
  (including a colon to indicate that the method takes an argument). The
  timer passes itself as the argument, thus the method would adopt the
  following pattern:
  - (void)timerFireMethod:(NSTimer *)timer https://developer.apple.com/reference/foundation/timer/1412416-scheduledtimer

Even though I was in the Swift version of the documentation, it displayed that Objective C version of the timerFireMethod. So maybe the Timer class expects an Objective C selector just like the compiler error complained about. However, the documentation states that the method should have one parameter (timer), but I just tested it successfully using a function without parameters.


问:
Converting a iterable of ordered dict's to pandas dataframe
I am iterating over OrderedDict's and want to store them as pandas dataframe. Is there a commend to do that? Currently, the code is:

One row in res looks like this:

OrderedDict([('field_id', 1), ('date', datetime.date(2016, 1, 3)), ('temp', 30.08), ('norm_temperature', None), ('prcp', 12.8848107785339), ('abcd', 0.0), ('efgh', None), ('ijkl', 1.38), ('lmno', None), ('poq', None)])

```<code>df = pd.DataFrame(res)
</code>```

I get this error: *** TypeError: data argument can't be an iterator

How do I store this iterator over ordered dict's into a dataframe?

答:
If res is like this:

```<code>res = iter([row1,row2,...])
</code>```

You can do it this way:

```<code>df = pd.DataFrame(*[res])
</code>```

Body:
I am iterating over OrderedDict's and want to store them as pandas dataframe. Is there a commend to do that? Currently, the code is:

One row in res looks like this:

OrderedDict([('field_id', 1), ('date', datetime.date(2016, 1, 3)), ('temp', 30.08), ('norm_temperature', None), ('prcp', 12.8848107785339), ('abcd', 0.0), ('efgh', None), ('ijkl', 1.38), ('lmno', None), ('poq', None)])

df = pd.DataFrame(res)

I get this error: *** TypeError: data argument can't be an iterator

How do I store this iterator over ordered dict's into a dataframe?

Body:
If res is like this:

res = iter([row1,row2,...])

You can do it this way:

df = pd.DataFrame(*[res])


问:
link to local disk
Is it possible to put a html link on a page that opens a file in local disk?

Like c:/myFolder/myfile.xls

This page is not actually going to be on web, but this feature would be needed for demostration purposes only. When the page is on web, the file is too, and link has url value.

答:
This would be a risky thing to do. As not everybody uses a PC, it will be different for a mac and a linux than a PC. Also not all browsers allow you to do it, such as Firefox, it dis-allows it due to potential security risks. But anyway here's the html code if you still wish to do it:</p>

```<code><a href="file:///C:/myFolder/myfile.xls">Click Here</a>
</code>```

Title: link to local disk

Body:
This would be a risky thing to do. As not everybody uses a PC, it will be different for a mac and a linux than a PC. Also not all browsers allow you to do it, such as Firefox, it dis-allows it due to potential security risks. But anyway here's the html code if you still wish to do it:

<a href="file:///C:/myFolder/myfile.xls">Click Here</a>


问:
After form submit, insert data into Mysql and redirect user to an url mydomain.com/entries/last_inserted_id
After I submit a form I want the next things to happen:

Insert data into Mysql.

Redirect the user to a template I have (entries.php). This template shows all the data from the new inserted row in the table.

User should be redirected to url: www.mydomain.com/entries/last_inserted_id which will be my new template url address, where I show to the user all the data he submited in the form and which can be later accessible by any user.

How should I do this?

I am thinking like something www.mydomain.com/entries/<?php get_last_id(); ?>

Where get_last_id() will be a function which obtains the last id(which is auto increment) inserted.

Any ideeas on how to redirect a user to a url containing the id of the inserted row, based on my template which address is fixed like: entries.php Maybe some javscript code to help me?

答:
```<code>header("Location: http://www.example.com/entries.php?id=$lastId");
</code>```

this code should be work

Body:
header("Location: http://www.example.com/entries.php?id=$lastId");

this code should be work


问:
modal is not displaying data separately
I want to update my table using bootstrap dialog , but I when I retrieve my datatable from server side and embed php code into my modal to show the table data into the modal, and choose what the user wants to update in that form. it is showing the data from every row of my table into the modal , how can I fix it?

form_modal

```<code><form id="product_update">
   <div class="row">
   <div class="form-group">
   <?php foreach ($product as $value): ?>
   <div class="col-xs-12">
      <label for="description">Name: </label>
      <input type="text" class="form-control" id="description" name="description" title="product description" value="<?php echo $value['descripcion']; ?>" required>
      <div>
      </div>
   </div>
   <div class="row">
      <div class="form-group">
         <div class="col-xs-8 col-sm-6">
            <label for="cost_price">Cost Price:</label>
            <div class="input-group"> <span class="input-group-addon">$</span>
               <input type="text" class="form-control input-group-lg reg_name" id="cost_price" name="cost_price" title="cost_price"  placeholder="Last name" value="<?php echo $value['precio_compra']; ?>" required>
            </div>
         </div>
         <div class="col-xs-8 col-sm-6">
            <label for="selling_price">Selling price: </label>
            <input type="text" class="form-control input-group-lg reg_name" id="selling_price" name="selling_price" title="selling_price" placeholder="Last name" value="<?php echo $value['precio_venta']; ?>" required>
         </div>
      </div>
   </div>
   <div class="row">
      <div class="form-group">
         <div class="col-xs-8 col-sm-6">
            <label for="wprice">Wholeprice: </label>
            <input type="text" class="form-control" id="wprice" name="wprice" title="wprice" value="<?php echo $value['precio_mayoreo']; ?>" required>
         </div>
         <div class="col-xs-8 col-sm-6">
            <label for="min_stock">Min stock: </label>
            <input type="text" class="form-control" id="min_stock" name="min_stock" title="min_stock" value="<?php echo $value['existencia_minima']; ?>" required>
         </div>
      </div>
   </div>
   <div class="row">
      <div class="form-group">
         <div class="col-xs-8 col-sm-6">
            <label for="stock">Stock: </label>
            <input type="text" class="form-control" id="stock" name="stock" title="stock" value="<?php echo $value['existencia']; ?>" required>
         </div>
         <div class="col-xs-8 col-sm-6">
            <label for="max_stock">Max stock: </label>
            <input type="text" class="form-control" id="max_stock" name="max_stock" title="max_stock" value="<?php echo $value['existencia_maxima']; ?>" required>
         </div>
      </div>
   </div>
  <?php endforeach ?>
   <div class="row">
      <div class="form-group">
         <div class="col-xs-8 col-sm-6">
            <label for="provider">Provider: </label>
            <select name="select-provider" id="select-provider">
                <option value="0">Select a provider</option>
                <?php foreach ($data as $value): ?>
                   <option value="<?php echo $value['id']; ?>"><?php echo $value['first_name'].' '.$value['last_name'] ?></option>
                <?php endforeach ?>
            </select>
         </div>
      </div>
   </div>
</form>
</code>```

modal js

```<code>$('#example tbody').on('click', 'a', function(event) {
    event.preventDefault();
    var data = table.row($(this).parents('tr')).data();
    hash = data[0];
    $("#product_update").validate();
    BootstrapDialog.show({
        type: BootstrapDialog.TYPE_WARNING,
        message: function(dialog) {
            var $message = $('<div></div>');
            var pageToLoad = dialog.getData('pageToLoad');
            $message.load(pageToLoad);

            return $message;
        },
        data: {
            'pageToLoad': URL_GET_VIEW_PRODUCT_UPDATE
        },
        closable: false,
        buttons: [{
            id: 'btn-ok',
            cssClass: 'btn-primary',
            icon: 'glyphicon glyphicon-send',
            label: ' Save',
            action: function(e) {
                var description = $('#description').val();
                var description = $('#description').val();
                var cost_price = $('#cost_price').val();
                var selling_price = $('#selling_price').val();
                var wprice = $('#wprice').val();
                var min_stock = $('#min_stock').val();
                var stock = $('#stock').val();
                var max_stock = $('#max_stock').val();
                var provider_id = $('#select_provider').val();
                if ($("#product_update").valid()) {
                    $.ajax({
                        url: URL_GET_UPDATE_PRODUCT,
                        type: 'POST',
                        data: { hash: hash, provider_id: provider_id, description: description, cost_price: cost_price,  selling_price: selling_price, wprice: wprice, min_stock: min_stock,   stock: stock, max_stock: max_stock },
                        success: function(data) {
                            console.log(data);
                            if (data.msg == 'successfully updated') {
                                $('#product_update')[0].reset();
                                table.ajax.reload();
                            } else if (data.min_stock == 'el stock no puede ser mayor al min') {
                                BootstrapDialog.show({
                                    type: BootstrapDialog.TYPE_DANGER,
                                    message: 'el stock no puede ser mayor al min'
                                });
                            }
                        }
                    });
                }
            }
        },{
            id: 'btn-cancel',
            cssClass: 'btn-danger',
            icon: 'glyphicon glyphicon-remove',
            label: ' Cancel',
            action: function(e) {
                e.close();
            }
        }]
    });
});
</code>```

model product

```<code>public function datatable(){
        $this->db->select('hash_id,codigo,descripcion,precio_compra,precio_venta,precio_mayoreo,existencia_minima,existencia,existencia_maxima,storelte_articulos.status');
        $this->db->from('storelte_articulos');
        $query = $this->db->get();
        return $query->result_array();
    }
    public function isExistsProduct($data){
        $this->db->select('descripcion');
        $this->db->from('storelte_articulos');
        $this->db->where('descripcion',$data['descripcion']);
        $query = $this->db->get();
        return $query->num_rows() == 0 ? false : true;
    }

    public function addProduct($data){
        $query = 'UPDATE storelte_articulos SET hash_id = MD5(id) WHERE id = LAST_INSERT_ID()';
        $this->db->insert('storelte_articulos',$data);
        $this->db->query($query);
    }

    public function updateProduct($data) {
        $this->db->where('md5(id)',$this->input->post('hash'));
        $this->db->update('storelte_articulos',$data);
    }

     public function get_product() {
    $this->db->select('codigo,descripcion,precio_compra,precio_venta,precio_mayoreo,existencia_minima,existencia_maxima,existencia');
    $this->db->from('storelte_articulos');
    $this->db->where('md5(id)', $this->input->post('hash'));
    $query = $this->db->get();
    return $query->result_array();
}
</code>```

modal img

答:
```<code>$this->db->select('hash_id,codigo,descripcion,precio_compra,precio_venta,precio_mayoreo,existencia_minima,existencia,existencia_maxima,storelte_articulos.status');
</code>```

You should add WHERE clause here. Basically you are selecting all rows if you don't add any kind of filtering in that clause. For example:

```<code>$this->db->select('hash_id,codigo,descripcion,precio_compra,precio_venta,precio_mayoreo,existencia_minima,existencia,existencia_maxima,storelte_articulos.status' WHERE hash_id='YOURHASHID')
</code>```

Title: modal is not displaying data separately

Body:
I want to update my table using bootstrap dialog , but I when I retrieve my datatable from server side and embed php code into my modal to show the table data into the modal, and choose what the user wants to update in that form. it is showing the data from every row of my table into the modal , how can I fix it?

form_modal

<form id="product_update">

   <?php foreach ($product as $value): ?>

      Name:
      <input type="text" class="form-control" id="description" name="description" title="product description" value="<?php echo $value['descripcion']; ?>" required>

            Cost Price:

 $
               <input type="text" class="form-control input-group-lg reg_name" id="cost_price" name="cost_price" title="cost_price"  placeholder="Last name" value="<?php echo $value['precio_compra']; ?>" required>

            Selling price:
            <input type="text" class="form-control input-group-lg reg_name" id="selling_price" name="selling_price" title="selling_price" placeholder="Last name" value="<?php echo $value['precio_venta']; ?>" required>

            Wholeprice:
            <input type="text" class="form-control" id="wprice" name="wprice" title="wprice" value="<?php echo $value['precio_mayoreo']; ?>" required>

            Min stock:
            <input type="text" class="form-control" id="min_stock" name="min_stock" title="min_stock" value="<?php echo $value['existencia_minima']; ?>" required>

            Stock:
            <input type="text" class="form-control" id="stock" name="stock" title="stock" value="<?php echo $value['existencia']; ?>" required>

            Max stock:
            <input type="text" class="form-control" id="max_stock" name="max_stock" title="max_stock" value="<?php echo $value['existencia_maxima']; ?>" required>

  <?php endforeach ?>

            Provider:
            <select name="select-provider" id="select-provider">
                <option value="0">Select a provider</option>
                <?php foreach ($data as $value): ?>
                   <option value="<?php echo $value['id']; ?>"><?php echo $value['first_name'].' '.$value['last_name'] ?></option>
                <?php endforeach ?>
            </select>

</form>

modal js

$('#example tbody').on('click', 'a', function(event) {
    event.preventDefault();
    var data = table.row($(this).parents('tr')).data();
    hash = data[0];
    $("#product_update").validate();
    BootstrapDialog.show({
        type: BootstrapDialog.TYPE_WARNING,
        message: function(dialog) {
            var $message = $('

');
            var pageToLoad = dialog.getData('pageToLoad');
            $message.load(pageToLoad);

            return $message;
        },
        data: {
            'pageToLoad': URL_GET_VIEW_PRODUCT_UPDATE
        },
        closable: false,
        buttons: [{
            id: 'btn-ok',
            cssClass: 'btn-primary',
            icon: 'glyphicon glyphicon-send',
            label: ' Save',
            action: function(e) {
                var description = $('#description').val();
                var description = $('#description').val();
                var cost_price = $('#cost_price').val();
                var selling_price = $('#selling_price').val();
                var wprice = $('#wprice').val();
                var min_stock = $('#min_stock').val();
                var stock = $('#stock').val();
                var max_stock = $('#max_stock').val();
                var provider_id = $('#select_provider').val();
                if ($("#product_update").valid()) {
                    $.ajax({
                        url: URL_GET_UPDATE_PRODUCT,
                        type: 'POST',
                        data: { hash: hash, provider_id: provider_id, description: description, cost_price: cost_price,  selling_price: selling_price, wprice: wprice, min_stock: min_stock,   stock: stock, max_stock: max_stock },
                        success: function(data) {
                            console.log(data);
                            if (data.msg == 'successfully updated') {
                                $('#product_update')[0].reset();
                                table.ajax.reload();
                            } else if (data.min_stock == 'el stock no puede ser mayor al min') {
                                BootstrapDialog.show({
                                    type: BootstrapDialog.TYPE_DANGER,
                                    message: 'el stock no puede ser mayor al min'
                                });
                            }
                        }
                    });
                }
            }
        },{
            id: 'btn-cancel',
            cssClass: 'btn-danger',
            icon: 'glyphicon glyphicon-remove',
            label: ' Cancel',
            action: function(e) {
                e.close();
            }
        }]
    });
});

model product

public function datatable(){
        $this->db->select('hash_id,codigo,descripcion,precio_compra,precio_venta,precio_mayoreo,existencia_minima,existencia,existencia_maxima,storelte_articulos.status');
        $this->db->from('storelte_articulos');
        $query = $this->db->get();
        return $query->result_array();
    }
    public function isExistsProduct($data){
        $this->db->select('descripcion');
        $this->db->from('storelte_articulos');
        $this->db->where('descripcion',$data['descripcion']);
        $query = $this->db->get();
        return $query->num_rows() == 0 ? false : true;
    }

    public function addProduct($data){
        $query = 'UPDATE storelte_articulos SET hash_id = MD5(id) WHERE id = LAST_INSERT_ID()';
        $this->db->insert('storelte_articulos',$data);
        $this->db->query($query);
    }

    public function updateProduct($data) {
        $this->db->where('md5(id)',$this->input->post('hash'));
        $this->db->update('storelte_articulos',$data);
    }

     public function get_product() {
    $this->db->select('codigo,descripcion,precio_compra,precio_venta,precio_mayoreo,existencia_minima,existencia_maxima,existencia');
    $this->db->from('storelte_articulos');
    $this->db->where('md5(id)', $this->input->post('hash'));
    $query = $this->db->get();
    return $query->result_array();
}

modal img

Body:
$this->db->select('hash_id,codigo,descripcion,precio_compra,precio_venta,precio_mayoreo,existencia_minima,existencia,existencia_maxima,storelte_articulos.status');

You should add WHERE clause here. Basically you are selecting all rows if you don't add any kind of filtering in that clause. For example:

$this->db->select('hash_id,codigo,descripcion,precio_compra,precio_venta,precio_mayoreo,existencia_minima,existencia,existencia_maxima,storelte_articulos.status' WHERE hash_id='YOURHASHID')


问:
Print specific child firebase db
I have the following database layout:

```<code>-PGroups
   -Date
      -GameTime
         -Entry Cost
</code>```

I know you can use the following to print out everything in PGroups

```<code>ref.child("PGroups").observeSingleEventOfType(.Value, withBlock: { (snapshot) in

                    //makes sure there are public
                    if (snapshot.hasChildren()){
                        print(snapshot.childrenCount) // I got the expected number of items
                        let enumerator = snapshot.children
                        while let rest = enumerator.nextObject() as! FIRDataSnapshot {
                            print(rest.value)
                        }
</code>```

Is there a way to just print out the "GameTime" Level children, or just the "Date" Children?

答:
You can try making a dictionary out of the data's children, something like this might work.

```<code>ref.child("PGroups").observeSingleEventOfType(.Value, withBlock: { (snapshot) in

   if let snapValue = snapshot.value as [String : [String : String]]{
      // Here try printing out the dictionary and seeing how to correctly get the right value out.
   }
</code>```

I'm a little confused about your database structure but you might have to create a dictionary one level deeper if this doesnt work, i.e. [String : [String : [String : String]]]. If you give a more detailed picture of the structure I could better help you get out the value you want.

Title: Print specific child firebase db

Body:
I have the following database layout:

-PGroups
   -Date
      -GameTime
         -Entry Cost

I know you can use the following to print out everything in PGroups

ref.child("PGroups").observeSingleEventOfType(.Value, withBlock: { (snapshot) in

                    //makes sure there are public
                    if (snapshot.hasChildren()){
                        print(snapshot.childrenCount) // I got the expected number of items
                        let enumerator = snapshot.children
                        while let rest = enumerator.nextObject() as! FIRDataSnapshot {
                            print(rest.value)
                        }

Is there a way to just print out the "GameTime" Level children, or just the "Date" Children?

Body:
You can try making a dictionary out of the data's children, something like this might work.

ref.child("PGroups").observeSingleEventOfType(.Value, withBlock: { (snapshot) in

   if let snapValue = snapshot.value as [String : [String : String]]{
      // Here try printing out the dictionary and seeing how to correctly get the right value out.
   }

I'm a little confused about your database structure but you might have to create a dictionary one level deeper if this doesnt work, i.e. [String : [String : [String : String]]]. If you give a more detailed picture of the structure I could better help you get out the value you want.


问:
command "pm2 reload all" can't restart
1.I use command

```<code>pm2 start pm2.json
</code>```

my pm2.json is

```<code>{
  "apps": [{
    "name": "test_pm2",
    "script": "www/app.js",
    "cwd": "/var/www/test_pm2",
    "exec_mode": "cluster",
    "instances": 0,
    "max_memory_restart": "1G",
    "autorestart": true,
    "node_args": [],
    "args": [],
    "env": {

    }
  }]
}
</code>```

2.then i use command

```<code>pm2 reload all
</code>```

and pm2 stop all process,but can't relaod my project,The command line is always waiting.
To visit my project throgh browser,the Nginx 502 error showed.
So i have to use commond pm2 start pm2.json to start.

My environment:
pm2 v2.4.0; node v6.9.5; npm v3.10.10

I hope someone can answer the confusion, thanks！

答:
answering my own question ！

The pm2.log is:

```<code>    ===============================================================================
2017-03-31 13:23:12: --- PM2 global error caught ---------------------------------------------------
2017-03-31 13:23:12: Time                 : Fri Mar 31 2017 13:23:12 GMT+0800 (CST)
2017-03-31 13:23:12: Cannot read property 'forEach' of null
2017-03-31 13:23:12: TypeError: Cannot read property 'forEach' of null
    at ChildProcess.onClose (/usr/lib/node_modules/pm2/lib/TreeKill.js:104:26)
    at emitTwo (events.js:106:13)
    at ChildProcess.emit (events.js:191:7)
    at maybeClose (internal/child_process.js:877:16)
    at Process.ChildProcess._handle.onexit (internal/child_process.js:226:5)
2017-03-31 13:23:12: ===============================================================================
2017-03-31 13:23:12: [PM2][%s] Resurrecting PM2
2017-03-31 13:23:12: Stopping app:tadx_sys id:_old_1
/usr/lib/node_modules/pm2/lib/TreeKill.js:104
    allData.match(/\d+/g).forEach(function (pid) {
                         ^

TypeError: Cannot read property 'forEach' of null
    at ChildProcess.onClose (/usr/lib/node_modules/pm2/lib/TreeKill.js:104:26)
    at emitTwo (events.js:106:13)
    at ChildProcess.emit (events.js:191:7)
    at maybeClose (internal/child_process.js:877:16)
    at Socket.<anonymous> (internal/child_process.js:334:11)
    at emitOne (events.js:96:13)
    at Socket.emit (events.js:188:7)
    at Pipe._handle.close [as _onclose] (net.js:498:12)
module.js:471
    throw err;
    ^

Error: Cannot find module '/var/www/tadx.borui-ad.com/undefined'
    at Function.Module._resolveFilename (module.js:469:15)
    at Function.Module._load (module.js:417:25)
    at Module.runMain (module.js:604:10)
    at run (bootstrap_node.js:394:7)
    at startup (bootstrap_node.js:149:9)
    at bootstrap_node.js:509:3
</code>```

I have found a solution for the issue in PM2 official GitHub page Go to issue url

Upgrade to PM2 greater than v2.4.0

Title: command "pm2 reload all" can't restart

Body:
1.I use command

pm2 start pm2.json

my pm2.json is

{
  "apps": [{
    "name": "test_pm2",
    "script": "www/app.js",
    "cwd": "/var/www/test_pm2",
    "exec_mode": "cluster",
    "instances": 0,
    "max_memory_restart": "1G",
    "autorestart": true,
    "node_args": [],
    "args": [],
    "env": {

    }
  }]
}

2.then i use command

pm2 reload all

and pm2 stop all process,but can't relaod my project,The command line is always waiting.
To visit my project throgh browser,the Nginx 502 error showed.
So i have to use commond pm2 start pm2.json to start.

My environment:
pm2 v2.4.0; node v6.9.5; npm v3.10.10

I hope someone can answer the confusion, thanks！

Body:
answering my own question ！

The pm2.log is:

    ===============================================================================
2017-03-31 13:23:12: --- PM2 global error caught ---------------------------------------------------
2017-03-31 13:23:12: Time                 : Fri Mar 31 2017 13:23:12 GMT+0800 (CST)
2017-03-31 13:23:12: Cannot read property 'forEach' of null
2017-03-31 13:23:12: TypeError: Cannot read property 'forEach' of null
    at ChildProcess.onClose (/usr/lib/node_modules/pm2/lib/TreeKill.js:104:26)
    at emitTwo (events.js:106:13)
    at ChildProcess.emit (events.js:191:7)
    at maybeClose (internal/child_process.js:877:16)
    at Process.ChildProcess._handle.onexit (internal/child_process.js:226:5)
2017-03-31 13:23:12: ===============================================================================
2017-03-31 13:23:12: [PM2][%s] Resurrecting PM2
2017-03-31 13:23:12: Stopping app:tadx_sys id:_old_1
/usr/lib/node_modules/pm2/lib/TreeKill.js:104
    allData.match(/\d+/g).forEach(function (pid) {
                         ^

TypeError: Cannot read property 'forEach' of null
    at ChildProcess.onClose (/usr/lib/node_modules/pm2/lib/TreeKill.js:104:26)
    at emitTwo (events.js:106:13)
    at ChildProcess.emit (events.js:191:7)
    at maybeClose (internal/child_process.js:877:16)
    at Socket.<anonymous> (internal/child_process.js:334:11)
    at emitOne (events.js:96:13)
    at Socket.emit (events.js:188:7)
    at Pipe._handle.close [as _onclose] (net.js:498:12)
module.js:471
    throw err;
    ^

Error: Cannot find module '/var/www/tadx.borui-ad.com/undefined'
    at Function.Module._resolveFilename (module.js:469:15)
    at Function.Module._load (module.js:417:25)
    at Module.runMain (module.js:604:10)
    at run (bootstrap_node.js:394:7)
    at startup (bootstrap_node.js:149:9)
    at bootstrap_node.js:509:3

I have found a solution for the issue in PM2 official GitHub page Go to issue url

Upgrade to PM2 greater than v2.4.0


问:
Empty object returned for uploaded files with connect-multiparty
Trying to get file details with connect-multiparty but its returning an empty object.

```<code>var express = require('express'),
    bodyParser = require('body-parser'),
    app = express();
var multiparty = require('connect-multiparty'),
    multipartyMiddleware = multiparty();
app.use( multipartyMiddleware );

app.post('/testupload1', function(req, res){
    var body = req.body;        var file = req.files;
    console.log(file)  // or console.log(body)  both empty.
 }
</code>```

Form :

```<code><form action="testupload1" method="post" enctype="multipart/form-data">

<input type="file" name="file"> <br />
<input type="submit" value="Upload">
</code>```

Get an empty object {} in the console when I upload a jpeg file. What am I doing wrong? Please help.

答:
I guess this may help you.

```<code>var express = require('express'),
bodyParser = require('body-parser'),
app = express();
var multiparty = require('connect-multiparty'),
multipartyMiddleware = multiparty();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));

app.post('/testupload1', multipartyMiddleware, function(req, res){
var file = req.files;
console.log(file)
});

    app.get('/file', function (req, res, next) {
    res.end('<!DOCTYPE html>'
        + '<html lang="en">'
        + '<head>'
        + '<meta charset="UTF-8">'
        + '<title>Title</title>'
        + '</head>'
        + '<body>'
        + '<form action="testupload1" method="post"        enctype="multipart/form-data">'
        + '<input type="file" name="file"> <br />'
        + '<input type="submit" value="Upload">'
        + '</form>'
        + '</body>'
        + '</html>')
        });

  app.listen(3008);
</code>```

Body:
Trying to get file details with connect-multiparty but its returning an empty object.

var express = require('express'),
    bodyParser = require('body-parser'),
    app = express();
var multiparty = require('connect-multiparty'),
    multipartyMiddleware = multiparty();
app.use( multipartyMiddleware );

app.post('/testupload1', function(req, res){
    var body = req.body;        var file = req.files;
    console.log(file)  // or console.log(body)  both empty.
 }

Form :

<form action="testupload1" method="post" enctype="multipart/form-data">

<input type="file" name="file">

<input type="submit" value="Upload">

Get an empty object {} in the console when I upload a jpeg file. What am I doing wrong? Please help.

Body:
I guess this may help you.

var express = require('express'),
bodyParser = require('body-parser'),
app = express();
var multiparty = require('connect-multiparty'),
multipartyMiddleware = multiparty();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));

app.post('/testupload1', multipartyMiddleware, function(req, res){
var file = req.files;
console.log(file)
});

    app.get('/file', function (req, res, next) {
    res.end('<!DOCTYPE html>'
        + '<html lang="en">'
        + '<head>'
        + '<meta charset="UTF-8">'
        + '<title>Title</title>'
        + '</head>'
        + '<body>'
        + '<form action="testupload1" method="post"        enctype="multipart/form-data">'
        + '<input type="file" name="file"> <br />'
        + '<input type="submit" value="Upload">'
        + '</form>'
        + '</body>'
        + '</html>')
        });

  app.listen(3008);


问:
What would be the best way in scala to convert between case classes?
I have a model class im getting back from an api inside my servcie, and when I return it to some client I want to use my own model to keep it simpler and cleaner for the client.

example :

```<code>case class ReturnedModel(succeed: Option[String], reason: Reason, transactionId: List[Int], opId: Option[Int])

case class MyReturnedModel(reason: String)
</code>```

I might need to do more of those in the future so I thought maybe there is a best practice to do it that I dont know of, thanks!

答:
If you have access to change the ReturnedModel, you could use traits like @pedrofurla has demonstrated.

If you are unable to modify the ReturnedModel, you could declare an implicit function to convert all instance of ReturnedModel to MyReturnedModel like this:

```<code>implicit def returnedModelToMyModel(returnedModel: ReturnedModel): MyReturnedModel = {

  // Have some logic to convert their model to your model
  MyReturnedModel(returnedModel.reason.toString)

}
</code>```

Then whenever you get a ReturnedModel from the API, you can use it anywhere you are expecting an instance of MyReturnedModel:

```<code>def doWork(myReturnedModel: MyReturnedModel) = { /* Logic that needs and instance of MyReturnedModel */ }

// Grab an instance of ReturnModel from the API
val returned: ReturnedModel = ???

// Will get converted when you need it to be an instance of MyReturnedModel
doWork(returned)
</code>```

The compiler will try to preform implicit conversions when it finds that the type you have passed is not correct, at which point it will look for an implicit conversion to satisfy the type conversion.

Body:
I have a model class im getting back from an api inside my servcie, and when I return it to some client I want to use my own model to keep it simpler and cleaner for the client.

example :

case class ReturnedModel(succeed: Option[String], reason: Reason, transactionId: List[Int], opId: Option[Int])

case class MyReturnedModel(reason: String)

I might need to do more of those in the future so I thought maybe there is a best practice to do it that I dont know of, thanks!

Body:
If you have access to change the ReturnedModel, you could use traits like @pedrofurla has demonstrated.

If you are unable to modify the ReturnedModel, you could declare an implicit function to convert all instance of ReturnedModel to MyReturnedModel like this:

implicit def returnedModelToMyModel(returnedModel: ReturnedModel): MyReturnedModel = {

  // Have some logic to convert their model to your model
  MyReturnedModel(returnedModel.reason.toString)

}

Then whenever you get a ReturnedModel from the API, you can use it anywhere you are expecting an instance of MyReturnedModel:

def doWork(myReturnedModel: MyReturnedModel) = { /* Logic that needs and instance of MyReturnedModel */ }

// Grab an instance of ReturnModel from the API
val returned: ReturnedModel = ???

// Will get converted when you need it to be an instance of MyReturnedModel
doWork(returned)

The compiler will try to preform implicit conversions when it finds that the type you have passed is not correct, at which point it will look for an implicit conversion to satisfy the type conversion.


问:
I can't see the menu of vscode in Ubuntu16 on Virtualbox
I download the deb file --vscode Version 1.10 , and double it to install in Ubuntu16 Virtualbox5.1, and when i lanch vscode , I can't use it and no menu just black screen

答: Not sure if this will necessarily fix your specific problem but I've seen strange UI/graphical glitches arise from having 3D acceleration enabled in VirtualBox. Sometimes switching that off and sticking with 2D resolves the issue. Might be worth a try to see if it makes a difference. </p>


问:
Django Timezone Issue
so I have model with a DateTimeField. Now when I store it in the database it gives me the correct time. However, when I print out the time, the time is ahead by 4 hours. This is probably due to some timezone issue. So I did some research and in my settings.py I have set a timezone:

```<code>TIME_ZONE = 'Canada/Eastern'
</code>```

But it still  doesn't work. Any ideas on how to solve this issue?

EDIT: How I define the field: Date = models.DateTimeField(auto_now_add=True)

答:
If you're using Mysql/SQLite, as database doesn't store timezone info, so, after you defined timezone in settings.py, Django will convert your local time to UTC time each time before insert into the database. Don't worry, each time before you use this DateTime filed,Django would convert it back to local time automatically.

I don't know if this explanation can solve your problem.Also,remember define USE_TZ =True in settings.py.

Title: Django Timezone Issue

Body:
so I have model with a DateTimeField. Now when I store it in the database it gives me the correct time. However, when I print out the time, the time is ahead by 4 hours. This is probably due to some timezone issue. So I did some research and in my settings.py I have set a timezone:

TIME_ZONE = 'Canada/Eastern'

But it still  doesn't work. Any ideas on how to solve this issue?

EDIT: How I define the field: Date = models.DateTimeField(auto_now_add=True)


问:
Tango/Unity - UI not blocking touches on screen
We are building an example that is similar to the "Kitten - Placing Virtual objects in AR" as shown here:

https://developers.google.com/tango/apis/unity/unity-howto-placing-objects.

Basically when you touch the screen, a kitten appears on the real world plane (floor).

In our app we have a side menu, with a few buttons and each shows a different game object.  We want to detect touch anywhere on the screen except where there is UI. We want the UI to block touches in Tango, and only allow touches to instantiate the related game objects on areas of the screen without UI elements.

The touch specific code is here:

```<code>void Update() {
    if (Input.touchCount == 1) {
        // Trigger placepictureframe function when single touch ended.
        Touch t = Input.GetTouch(0);
        if (t.phase == TouchPhase.Ended) {
            PlacePictureFrame(t.position);
        }
    }
}
</code>```

(The PlacePictureFrame() places a picture frame object at the touch position.)

I can't find any Tango examples which has touch and UI combined. I've tried an asset called LeanTouch to block touches behind UI elements but it doesn't seem to work with Tango specifically. Please help!

I have tried using method 5 from this:

How to detect events on UI and GameObjects with the new EventSystem API

and while it does add a PhysicsRaycaster to the TangoARCamera (which is tagged as MainCamera), the OnPointerDown method produces no debug logs no matter where you touch the screen. Tango is a special case so this is not a duplicate question.  See below:

```<code>using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;

public class PictureFrameUIController : MonoBehaviour, IPointerClickHandler {

    public GameObject m_pictureFrame;
    private TangoPointCloud m_pointCloud;

    void Start() {
        m_pointCloud = FindObjectOfType<TangoPointCloud>();
        addPhysicsRaycaster();
    }

    void addPhysicsRaycaster() {
        PhysicsRaycaster physicsRaycaster = GameObject.FindObjectOfType<PhysicsRaycaster>();
        if (physicsRaycaster == null) {
            Camera.main.gameObject.AddComponent<PhysicsRaycaster>();
        }
    }

    public void OnPointerClick(PointerEventData eventData) {
        Debug.Log("Clicked: " + eventData.pointerCurrentRaycast.gameObject.name);
        PlacePictureFrame(eventData.pointerCurrentRaycast.screenPosition);
    }

    //void Update() {
    //  if (Input.touchCount == 1) {
    //      // Trigger placepictureframe function when single touch ended.
    //      Touch t = Input.GetTouch(0);
    //      if (t.phase == TouchPhase.Ended) {
    //          PlacePictureFrame(t.position);
    //      }
    //  }
    //}

    void PlacePictureFrame(Vector2 touchPosition) {
        // Find the plane.
        Camera cam = Camera.main;
        Vector3 planeCenter;
        Plane plane;
        if (!m_pointCloud.FindPlane(cam, touchPosition, out planeCenter, out plane)) {
            Debug.Log("cannot find plane.");
            return;
        }

        // Place picture frame on the surface, and make it always face the camera.
        if (Vector3.Angle(plane.normal, Vector3.up) > 60.0f && Vector3.Angle(plane.normal, Vector3.up) < 140.0f) {
            Vector3 forward = plane.normal;
            // Vector3 right = Vector3.Cross(plane.normal, cam.transform.forward).normalized;
            // Vector3 forward = Vector3.Cross(right, plane.normal).normalized;
            Instantiate(m_pictureFrame, planeCenter, Quaternion.LookRotation(forward, Vector3.up));
        } else {
            Debug.Log("surface is not steep enough for picture frame to be placed on.");
        }
    }

    public void DeleteAllFrames() {
        GameObject[] frames = GameObject.FindGameObjectsWithTag("Frame");
        if (frames == null) {
            return;
        }
        foreach (GameObject frame in frames) {
            Destroy(frame);
        }
    }
}
</code>```

答:
If you want to detect a click anywhere on the screen except for where there is a UI control/component, you have to check if the pointer is over the UI with EventSystem.current.IsPointerOverGameObject(Input.GetTouch(0).fingerId).

If on desktop, use EventSystem.current.IsPointerOverGameObject(). You are using Tango so EventSystem.current.IsPointerOverGameObject(Input.GetTouch(0).fingerId). should be used.

```<code>void Update()
{
    if (Input.touchCount == 1)
    {
        //Trigger placepictureframe function when single touch ended.
        Touch t = Input.GetTouch(0);
        if (t.phase == TouchPhase.Ended)
        {
            //Make sure that pointer is not over UI before calling  PlacePictureFrame
            if (!EventSystem.current.IsPointerOverGameObject(Input.GetTouch(0).fingerId))
            {
                PlacePictureFrame(t.position);
            }
        }
    }
}
</code>```

Edit:

It seems like this works with TouchPhase.Began only.

Change t.phase == TouchPhase.Ended to t.phase == TouchPhase.Began and this should work as expected.  Make sure to test with a mobile device/tango instead of your mouse.

Body:
We are building an example that is similar to the "Kitten - Placing Virtual objects in AR" as shown here:

https://developers.google.com/tango/apis/unity/unity-howto-placing-objects.

Basically when you touch the screen, a kitten appears on the real world plane (floor).

In our app we have a side menu, with a few buttons and each shows a different game object.  We want to detect touch anywhere on the screen except where there is UI. We want the UI to block touches in Tango, and only allow touches to instantiate the related game objects on areas of the screen without UI elements.

The touch specific code is here:

void Update() {
    if (Input.touchCount == 1) {
        // Trigger placepictureframe function when single touch ended.
        Touch t = Input.GetTouch(0);
        if (t.phase == TouchPhase.Ended) {
            PlacePictureFrame(t.position);
        }
    }
}

(The PlacePictureFrame() places a picture frame object at the touch position.)

I can't find any Tango examples which has touch and UI combined. I've tried an asset called LeanTouch to block touches behind UI elements but it doesn't seem to work with Tango specifically. Please help!

I have tried using method 5 from this:

How to detect events on UI and GameObjects with the new EventSystem API

and while it does add a PhysicsRaycaster to the TangoARCamera (which is tagged as MainCamera), the OnPointerDown method produces no debug logs no matter where you touch the screen. Tango is a special case so this is not a duplicate question.  See below:

using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;

public class PictureFrameUIController : MonoBehaviour, IPointerClickHandler {

    public GameObject m_pictureFrame;
    private TangoPointCloud m_pointCloud;

    void Start() {
        m_pointCloud = FindObjectOfType<TangoPointCloud>();
        addPhysicsRaycaster();
    }

    void addPhysicsRaycaster() {
        PhysicsRaycaster physicsRaycaster = GameObject.FindObjectOfType<PhysicsRaycaster>();
        if (physicsRaycaster == null) {
            Camera.main.gameObject.AddComponent<PhysicsRaycaster>();
        }
    }

    public void OnPointerClick(PointerEventData eventData) {
        Debug.Log("Clicked: " + eventData.pointerCurrentRaycast.gameObject.name);
        PlacePictureFrame(eventData.pointerCurrentRaycast.screenPosition);
    }

    //void Update() {
    //  if (Input.touchCount == 1) {
    //      // Trigger placepictureframe function when single touch ended.
    //      Touch t = Input.GetTouch(0);
    //      if (t.phase == TouchPhase.Ended) {
    //          PlacePictureFrame(t.position);
    //      }
    //  }
    //}

    void PlacePictureFrame(Vector2 touchPosition) {
        // Find the plane.
        Camera cam = Camera.main;
        Vector3 planeCenter;
        Plane plane;
        if (!m_pointCloud.FindPlane(cam, touchPosition, out planeCenter, out plane)) {
            Debug.Log("cannot find plane.");
            return;
        }

        // Place picture frame on the surface, and make it always face the camera.
        if (Vector3.Angle(plane.normal, Vector3.up) > 60.0f && Vector3.Angle(plane.normal, Vector3.up) < 140.0f) {
            Vector3 forward = plane.normal;
            // Vector3 right = Vector3.Cross(plane.normal, cam.transform.forward).normalized;
            // Vector3 forward = Vector3.Cross(right, plane.normal).normalized;
            Instantiate(m_pictureFrame, planeCenter, Quaternion.LookRotation(forward, Vector3.up));
        } else {
            Debug.Log("surface is not steep enough for picture frame to be placed on.");
        }
    }

    public void DeleteAllFrames() {
        GameObject[] frames = GameObject.FindGameObjectsWithTag("Frame");
        if (frames == null) {
            return;
        }
        foreach (GameObject frame in frames) {
            Destroy(frame);
        }
    }
}

Body:
If you want to detect a click anywhere on the screen except for where there is a UI control/component, you have to check if the pointer is over the UI with EventSystem.current.IsPointerOverGameObject(Input.GetTouch(0).fingerId).

If on desktop, use EventSystem.current.IsPointerOverGameObject(). You are using Tango so EventSystem.current.IsPointerOverGameObject(Input.GetTouch(0).fingerId). should be used.

void Update()
{
    if (Input.touchCount == 1)
    {
        //Trigger placepictureframe function when single touch ended.
        Touch t = Input.GetTouch(0);
        if (t.phase == TouchPhase.Ended)
        {
            //Make sure that pointer is not over UI before calling  PlacePictureFrame
            if (!EventSystem.current.IsPointerOverGameObject(Input.GetTouch(0).fingerId))
            {
                PlacePictureFrame(t.position);
            }
        }
    }
}

Edit:

It seems like this works with TouchPhase.Began only.

Change t.phase == TouchPhase.Ended to t.phase == TouchPhase.Began and this should work as expected.  Make sure to test with a mobile device/tango instead of your mouse.


问:
VHDL pass range to procedure
I'm writing my own package to deal with generic matrix-like objects due to unavailability of VHDL-2008 (I'm only concerned with compilation and simulation for the time being).
My aim is getting a matrix M_out from a matrix M_in such that:

```<code>M_out(i downto 0, j downto 0) <= M_in(k+i downto k, l+j downto l);
</code>```

using a subroutine of sort. For, let's say, semantic convenience and analogy with software programming languages my subroutine prototype should ideally look something like this:

```<code>type matrix is array(natural range <>, natural range <>) of std_logic;
...
procedure slice_matrix(signal m_out: out matrix;
                       constant rows: natural range<>;
                       constant cols: natural range<>;
                       signal m_in: in matrix);
</code>```

The compiler does however regard this as an error:

```<code>** Error: custom_types.vhd(9): near "<>": syntax error
** Error: custom_types.vhd(9): near "<>": syntax error
</code>```

Is it possible to pass a range as an argument in some way or shall I surrender and pass 4 separate indexes to calculate it locally?

答:
An unconstrained index range natural range <> is not a VHDL object of class signal, variable, constant, or file. Thus it can not be passed into a subprogram. I wouldn't implement a slice operations as a procedure, because it's a function like behavior.

An implementation for working with matrices and slices thereof is provided by the PoC-Library. The implementation is provided in the vectors package.

```<code>function slm_slice(slm : T_SLM; RowIndex : natural; ColIndex : natural; Height : natural; Width : natural) return T_SLM is
  variable Result       : T_SLM(Height - 1 downto 0, Width - 1 downto 0)        := (others => (others => '0'));
begin
  for i in 0 to Height - 1 loop
    for j in 0 to Width - 1 loop
      Result(i, j)      := slm(RowIndex + i, ColIndex + j);
    end loop;
  end loop;
  return Result;
end function;
</code>```

More specialized functions to slice off a row or column can be found in that file too. It also provides procedures to assign parts of a matrix.

This package works in simulation and synthesis.

Unfortunately, slicing multi dimensional arrays will not be part of VHDL-2017. I'll make sure it's discuss for VHDL-202x again.

Passing ranges into a subprogram will be allowed in VHDL-2017. The language change LCS 2016-099 adds this capability.

Title: VHDL pass range to procedure

Body:
I'm writing my own package to deal with generic matrix-like objects due to unavailability of VHDL-2008 (I'm only concerned with compilation and simulation for the time being).
My aim is getting a matrix M_out from a matrix M_in such that:

M_out(i downto 0, j downto 0) <= M_in(k+i downto k, l+j downto l);

using a subroutine of sort. For, let's say, semantic convenience and analogy with software programming languages my subroutine prototype should ideally look something like this:

type matrix is array(natural range <>, natural range <>) of std_logic;
...
procedure slice_matrix(signal m_out: out matrix;
                       constant rows: natural range<>;
                       constant cols: natural range<>;
                       signal m_in: in matrix);

The compiler does however regard this as an error:

** Error: custom_types.vhd(9): near "<>": syntax error
** Error: custom_types.vhd(9): near "<>": syntax error

Is it possible to pass a range as an argument in some way or shall I surrender and pass 4 separate indexes to calculate it locally?

Body:
An unconstrained index range natural range <> is not a VHDL object of class signal, variable, constant, or file. Thus it can not be passed into a subprogram. I wouldn't implement a slice operations as a procedure, because it's a function like behavior.

An implementation for working with matrices and slices thereof is provided by the PoC-Library. The implementation is provided in the vectors package.

function slm_slice(slm : T_SLM; RowIndex : natural; ColIndex : natural; Height : natural; Width : natural) return T_SLM is
  variable Result       : T_SLM(Height - 1 downto 0, Width - 1 downto 0)        := (others => (others => '0'));
begin
  for i in 0 to Height - 1 loop
    for j in 0 to Width - 1 loop
      Result(i, j)      := slm(RowIndex + i, ColIndex + j);
    end loop;
  end loop;
  return Result;
end function;

More specialized functions to slice off a row or column can be found in that file too. It also provides procedures to assign parts of a matrix.

This package works in simulation and synthesis.

Unfortunately, slicing multi dimensional arrays will not be part of VHDL-2017. I'll make sure it's discuss for VHDL-202x again.

Passing ranges into a subprogram will be allowed in VHDL-2017. The language change LCS 2016-099 adds this capability.


问:
filter by text in specifiec property
I have an array of objects, like those

```<code>{ name: "task1", owner: "david", des: "task1 description" },
{ name: "task2", owner: "Smith", des: "task2 description" },
{ name: "task1", owner: "david", des: "task1 description" },
</code>```

also a select and textbox
and a table that shows them all.

i am looking a way to filter, the data in the table.
The user will select a value from drop-down and enter text in the textbox.

Then the table data will be filtered by text matches in selected value (object property) from drop-down.

Example:

choosing "name" from dropdown and write "task" in textbox will return all 3 items in array. text word is contained within all 3 records.

choosing "name" from dropdown and write "task1" in textbox will return record 1 and 3.

textbox value will be required for the filter to happen.

Can it be done with angularjs filter?

https://plnkr.co/edit/Afs7MOIziUOvFWzBY7qf?p=preview

答:
At that point it's probably easiest to write a custom filter. Custom filters are very easy and straightforward and allow you to control all aspects of how and when the filter is applied. Here is a working sample for your case - it's not very robust because it will break if you try to filter a numeric property, but it gives you the gist and something to build on and customize for your needs.

angular.module('myApp', [])
  .controller('myCtrl', function($scope) {
    $scope.cards = [{
        name: "task1",
        owner: "david",
        des: "task1 description"
      },
      {
        name: "task2",
        owner: "Smith",
        des: "task2 description"
      },
      {
        name: "task3",
        owner: "Smith",
        des: "task3 description"
      },
      {
        name: "task4",
        owner: "Davis",
        des: "task4 description"
      },
      {
        name: "task5",
        owner: "Thomas",
        des: "task5 description"
      },
      {
        name: "task6",
        owner: "david",
        des: "task6 description"
      }
    ];
  })
  .filter('myFilter', function() {
    return function(items, property, value) {
      // if items, property or value are missing return items by default
      if (!items || !property || !value) {
        return items;
      }
      // create an array to hold the matched items
      var out = [];
      angular.forEach(items, function(item) {
        // see if the item property value contains the desired value
        if (item[property].toLowerCase().includes(value.toLowerCase())) {
          out.push(item);
        }
      });
      // return the array of items
      return out;
    }
  });```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.2/angular.min.js"></script>

<body ng-app="myApp">
  <div ng-controller="myCtrl">
    <div>
      <select ng-model="filterProperty">
          <option value="">filter by</option>
          <option value="name">name</option>
          <option value="owner">owner</option>
          <option value="des">des</option>
        </select>
      <input ng-model="filterData" type="text" />
    </div>
    <table style="border: 1px solid">
      <tbody>
        <tr>
          <th>name</th>
          <th>owner</th>
          <th>description</th>
        </tr>
        <tr ng-repeat="x in cards | myFilter:filterProperty:filterData">
          <td>{{x.name}}</td>
          <td>{{x.owner}}</td>
          <td>{{x.des}}</td>
        </tr>
      </tbody>
    </table>
  </div>
</body></code>```

Title: filter by text in specifiec property

Body:
I have an array of objects, like those

{ name: "task1", owner: "david", des: "task1 description" },
{ name: "task2", owner: "Smith", des: "task2 description" },
{ name: "task1", owner: "david", des: "task1 description" },

also a select and textbox
and a table that shows them all.

i am looking a way to filter, the data in the table.
The user will select a value from drop-down and enter text in the textbox.

Then the table data will be filtered by text matches in selected value (object property) from drop-down.

Example:

choosing "name" from dropdown and write "task" in textbox will return all 3 items in array. text word is contained within all 3 records.

choosing "name" from dropdown and write "task1" in textbox will return record 1 and 3.

textbox value will be required for the filter to happen.

Can it be done with angularjs filter?

https://plnkr.co/edit/Afs7MOIziUOvFWzBY7qf?p=preview

Body:
At that point it's probably easiest to write a custom filter. Custom filters are very easy and straightforward and allow you to control all aspects of how and when the filter is applied. Here is a working sample for your case - it's not very robust because it will break if you try to filter a numeric property, but it gives you the gist and something to build on and customize for your needs.

angular.module('myApp', [])
  .controller('myCtrl', function($scope) {
    $scope.cards = [{
        name: "task1",
        owner: "david",
        des: "task1 description"
      },
      {
        name: "task2",
        owner: "Smith",
        des: "task2 description"
      },
      {
        name: "task3",
        owner: "Smith",
        des: "task3 description"
      },
      {
        name: "task4",
        owner: "Davis",
        des: "task4 description"
      },
      {
        name: "task5",
        owner: "Thomas",
        des: "task5 description"
      },
      {
        name: "task6",
        owner: "david",
        des: "task6 description"
      }
    ];
  })
  .filter('myFilter', function() {
    return function(items, property, value) {
      // if items, property or value are missing return items by default
      if (!items || !property || !value) {
        return items;
      }
      // create an array to hold the matched items
      var out = [];
      angular.forEach(items, function(item) {
        // see if the item property value contains the desired value
        if (item[property].toLowerCase().includes(value.toLowerCase())) {
          out.push(item);
        }
      });
      // return the array of items
      return out;
    }
  });

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.2/angular.min.js"></script>

<body ng-app="myApp">
  <div ng-controller="myCtrl">
    <div>
      <select ng-model="filterProperty">
          <option value="">filter by</option>
          <option value="name">name</option>
          <option value="owner">owner</option>
          <option value="des">des</option>
        </select>
      <input ng-model="filterData" type="text" />
    </div>
    <table style="border: 1px solid">
      <tbody>
        <tr>
          <th>name</th>
          <th>owner</th>
          <th>description</th>
        </tr>
        <tr ng-repeat="x in cards | myFilter:filterProperty:filterData">
          <td>{{x.name}}</td>
          <td>{{x.owner}}</td>
          <td>{{x.des}}</td>
        </tr>
      </tbody>
    </table>
  </div>
</body>


问:
svn: Item <folder> is out of date
[answer auto-selected by bounty system against my will]

I'm using subclipse, and always when delete a folder in Eclipse, and try to commit it, the following errors raise:

```<code>svn: Item <folder> is out of date
svn: DELETE of <folder>: 409 Conflict (http://myintranet)
</code>```

Deleting and commiting via command line works fine, but what's wrong with doing it via subclipse? Is anyone more experiencing this problem?

(I experienced this problem in Ubuntu 9.10 and 10.04; last Eclipse version; and subclipse 1.4 - as the next versions of subclipse have much more bugs)

--updated: Its when I delete folders, not files

答:
Subclipse has many problems like this. It works 90% of time, and then it just DOES NOT work as it should! I am using subclipse, since it is very well integrated into eclipse, and when I have problem or some bigger moves needed in svn (like merging some branch) I use Tortoisse.

I had the thing with directory like you. Then I just run the TortoiseSVN like @luiscolorado suggests, and it helped. Tortoise is so great tool (it has many great features for diffing, applying patches, getting patches and so on.).

Today I had a problem when I have removed a file, and someone had changed the same file! Then subclipse shows conflict (up to this point everything is ok), so I wanted to revert! But then the revert button is missing (disappears when inconflict mode!) so I have to do merge, and merge does not work, throws some kind of error. I didn't bother to read (maybe I should read and file it as a bug to subclipse maintainers ;-(), I knew the tortoisse will work, and you know what, it worked. There was a REVERT option.

So @Tom Brito, try command line, try Tortoisse, and then you can look at the subclipse changelog and file a bug. I think that subclipse just forgets to show us some directory changes and updates (or it is designed not to do it?), but I may be wrong.

Title: svn: Item <folder> is out of date

Body:
[answer auto-selected by bounty system against my will]

I'm using subclipse, and always when delete a folder in Eclipse, and try to commit it, the following errors raise:

svn: Item <folder> is out of date
svn: DELETE of <folder>: 409 Conflict (http://myintranet)

Deleting and commiting via command line works fine, but what's wrong with doing it via subclipse? Is anyone more experiencing this problem?

(I experienced this problem in Ubuntu 9.10 and 10.04; last Eclipse version; and subclipse 1.4 - as the next versions of subclipse have much more bugs)

--updated: Its when I delete folders, not files