问:
Android/Java - pause thread
I'm new to this, so maybe it's trivial to everybody, but I just can't figure out, why this isn't working. I've read about it, tried many way, and still not working. So I want to pause a thread in android (java). I want this to run, freeze the screen for 1 sec, and continue working. That's all. Why isn't this working?

```<code>public class Game extends Activity {

public void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.game);

        runner.join();
        runner.start();

        // do stuff

        pause();

        // do stuff

}

private boolean running = true;
private boolean paused = false;

public void setRunning(boolean run) {
    running = run;
}

public void pause() {
    paused = true;
}

Thread runner = new Thread() {

    public void run() {

        while (running) {

            try {

                //do stuff

                Thread.sleep(100);

                while (paused) {
                    try {
                        Thread.sleep(1000);
                    } catch (Exception e) {
                    } finally {
                        paused = false;
                    }
                }

            } catch (Exception e) {
            }
        }

    }

};
</code>```

}

答:
if you need freeze screen, you only need use SystemClock.sleep(millis).//1000 = 1 second
Android use a main thread for your interface very different . Your code try stop it like a java program.

Example

```<code> @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_login);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    SystemClock.sleep(1000);
</code>```

...

or search info like this:

```<code>//this is similar to your thread
   new Thread(new Runnable() {
       @Override
       public void run() {
           //some code
           int val = 1+ 1; //code here dont interrupt main thread

           //this code run on main thread
           mActivity.runOnUiThread(new Runnable() {
               @Override
               public void run() {
                   //freeze Views
                   SystemClock.sleep(1000);// 1 second
               }
           });

       }
   });
</code>```

Title: Android/Java - pause thread

Body:
I'm new to this, so maybe it's trivial to everybody, but I just can't figure out, why this isn't working. I've read about it, tried many way, and still not working. So I want to pause a thread in android (java). I want this to run, freeze the screen for 1 sec, and continue working. That's all. Why isn't this working?

public class Game extends Activity {

public void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.game);

        runner.join();
        runner.start();

        // do stuff

        pause();

        // do stuff

}

private boolean running = true;
private boolean paused = false;

public void setRunning(boolean run) {
    running = run;
}

public void pause() {
    paused = true;
}

Thread runner = new Thread() {

    public void run() {

        while (running) {

            try {

                //do stuff

                Thread.sleep(100);

                while (paused) {
                    try {
                        Thread.sleep(1000);
                    } catch (Exception e) {
                    } finally {
                        paused = false;
                    }
                }

            } catch (Exception e) {
            }
        }

    }

};

}

Body:
if you need freeze screen, you only need use SystemClock.sleep(millis).//1000 = 1 second
Android use a main thread for your interface very different . Your code try stop it like a java program.

Example

 @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_login);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    SystemClock.sleep(1000);

...

or search info like this:

//this is similar to your thread
   new Thread(new Runnable() {
       @Override
       public void run() {
           //some code
           int val = 1+ 1; //code here dont interrupt main thread

           //this code run on main thread
           mActivity.runOnUiThread(new Runnable() {
               @Override
               public void run() {
                   //freeze Views
                   SystemClock.sleep(1000);// 1 second
               }
           });

       }
   });


来源: stackexchange

问:
Spring Cloud Gateway - Return 503 when no Service Instance Available
Trying out Spring Cloud Gateway with Spring Boot microservices registered/discovered via Eureka server. The setup is working fine and clients can call the discovered services via the gateway without problem which is great.

Now, I am trying to test a scenario where a client calls a service (via the gateway) for which currently there are no instances available to service the call (i.e. service is down). When we test this scenario, the default behaviour is that the client gets a 500 Internal Server Error response. What would be the simplest way to change this default behaviour to return a 503 Service Unavilable response instead?

Current Stack:

```<code>Java 8
Spring Boot 2.0.0.M6
Spring Cloud 2.0.0.M3
Spring Cloud Starter Eureka 2.0.0.M2 (in Gateway JVM)
Spring Cloud Starter Netflix Ribbon 2.0.0.M3 (in Gateway JVM)
Spring Cloud Starter Netflix Eureka Server 2.0.0.M3 (in Eureka Server JVM)
</code>```

答:
In the end we have decided to leave the error response as it is. i.e. HTTP 500 - Unable to find instance for test-service-name. We have however added functionality to the Gateway's Routing mechanism to include an enabled: true|false flag to each Route which now allows us to temporarily enable/disable access to those microservices as desired. We are doing this by re-building Routes which are marked with enabled: false to include a GatewayFilter in them which returns:

```<code>Mono.error(new WebRequestException(HttpStatus.SERVICE_UNAVAILABLE, "SERVICE_UNAVAILABLE",
            "Service is down for maintenance"));
</code>```

whenever a call to that enabled: false Route is called.

The WebRequestException is our own Throwable class which we then intercept in our own WebExceptionHandler which handles the ServerWebExchange's ServerHttpResponse as needed.

Note 1: The Gateway is using spring-boot-starter-webflux within.

Note 2: Whenever we change the state of a Route's enabled flag we: 1) Re-build the Route, 2) Call CachingRouteLocator Bean's .refresh() method in order for the Route to be re-cached with|without the GatewayFilter in place.

ContentLicense: CC BY-SA 3.0

Body:
Trying out Spring Cloud Gateway with Spring Boot microservices registered/discovered via Eureka server. The setup is working fine and clients can call the discovered services via the gateway without problem which is great.

Now, I am trying to test a scenario where a client calls a service (via the gateway) for which currently there are no instances available to service the call (i.e. service is down). When we test this scenario, the default behaviour is that the client gets a 500 Internal Server Error response. What would be the simplest way to change this default behaviour to return a 503 Service Unavilable response instead?

Current Stack:

Java 8
Spring Boot 2.0.0.M6
Spring Cloud 2.0.0.M3
Spring Cloud Starter Eureka 2.0.0.M2 (in Gateway JVM)
Spring Cloud Starter Netflix Ribbon 2.0.0.M3 (in Gateway JVM)
Spring Cloud Starter Netflix Eureka Server 2.0.0.M3 (in Eureka Server JVM)

Body:
In the end we have decided to leave the error response as it is. i.e. HTTP 500 - Unable to find instance for test-service-name. We have however added functionality to the Gateway's Routing mechanism to include an enabled: true|false flag to each Route which now allows us to temporarily enable/disable access to those microservices as desired. We are doing this by re-building Routes which are marked with enabled: false to include a GatewayFilter in them which returns:

Mono.error(new WebRequestException(HttpStatus.SERVICE_UNAVAILABLE, "SERVICE_UNAVAILABLE",
            "Service is down for maintenance"));

whenever a call to that enabled: false Route is called.

The WebRequestException is our own Throwable class which we then intercept in our own WebExceptionHandler which handles the ServerWebExchange's ServerHttpResponse as needed.

Note 1: The Gateway is using spring-boot-starter-webflux within.

Note 2: Whenever we change the state of a Route's enabled flag we: 1) Re-build the Route, 2) Call CachingRouteLocator Bean's .refresh() method in order for the Route to be re-cached with|without the GatewayFilter in place.


问:
How to get the values of multiple textFields in UITableView with dynamic cells?
In a UIViewController I have a UITableView with 1 Dynamic Prototype cell of class type TextInputTableViewCell.

 In the Content View of the prototype cell I am adding a textField.

How can I populate the text fields with data from userInfo?

How can I get the data of each textField once they are edited by the user?

I have read on SO that I should use tags, but others said that this method is prone to bugs and fragile. Anyway, I don't know how to get the data from the fields using tags or other method. Please advise.

```<code>import Foundation
import UIKit
import Firebase

 class TextInputTableViewCell: UITableViewCell, UITextFieldDelegate{
      @IBOutlet weak var textField: UITextField!

     //closure when the text changes
     var textChangedCallBack: ((_ cell: TextInputTableViewCell, _ text:String) -> ())?
      //Delegate method called when the text field loses focus
     func textFieldDidEndEditing(_ textField: UITextField) {
    textChangedCallBack?(self,textField.text!)
  }
}//end of class TextInputTableViewCell

class EditProfile: UIViewController, UITableViewDelegate,UITableViewDataSource,UITextFieldDelegate {

 var dbRef:FIRDatabaseReference! //create a reference to Firebase
 var userInfo = [FireBaseData]() //this array will hold all data under userType in Firebase

@IBOutlet weak var tableView: UITableView!
@IBAction func saveToFirebase(_ sender: Any) {

 //will post data from text fields  to firebase
}

struct Item {
    var name:String
    var editable:Bool
}

let placeHolderItems = [
    Item(name: "Name", editable: false),
    Item(name: "Phone Number", editable: true),
    Item(name: "Email", editable: true),
    Item(name: "Flat Number", editable: true),
    Item(name: "Street Address", editable: true),
    Item(name: "Postcode", editable: true)
]

override func viewDidLoad() {
    super.viewDidLoad()

   self.dbRef = FIRDatabase.database().reference().child("Cleaners")
    self.tableView.delegate = self
    self.tableView.dataSource = self
}

   override func viewWillAppear(_ animated: Bool) {
     super.viewWillAppear(true)

   //get user's profile from firebase
    self.startObservingDB { (userProfile) in

        if userProfile.count > 0 {
            self.userInfo = userProfile
             self.tableView.reloadData()
        }
    }

func numberOfSections(in tableView: UITableView) -> Int {
    return 1
}

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return placeHolderItems.count
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "TextInputCell") as! TextInputTableViewCell

    cell.textField.isEnabled = placeHolderItems[indexPath.row].editable
    cell.textField.placeholder = placeHolderItems[indexPath.row].name

 //After viewWillAppear finishes, self.userInfo will have the profile of
 //the user. How can I get here each textField  of the tableView so I can
   //populate each one of them with data from  self.userInfo?

         if !self.userInfo.isEmpty{

switch indexPath.row{
    case 0:
         cell.textField.text = self.userInfo[0].FirstName + " " + self.userInfo[indexPath.row].LastName
    case 1:
        cell.textField.text = self.userInfo[0].PhoneNumber

    case 2: cell.textField.text = self.userInfo[0].EmailAddress

    case 3: cell.textField.text = self.userInfo[0].FlatNumber

    case 4: cell.textField.text = self.userInfo[0].StreetAddress

    case 5: cell.textField.text = self.userInfo[0].PostCode

    default:
        break
     }
 }

    cell.textChangedCallBack = {(cell, text) in

        //get the cell's current index path
        if let path = tableView.indexPath(for: cell) {

            //get the item at that row
            var item = self.placeHolderItems[path.row]

            //update the item with the new name
        }
    }

    return cell
  }
 }//end of EditProfileclass

extension EditProfile {

  //get user's profile in order to populate it in tableView
   func startObservingDB(callback:@escaping ((_ snapShot: [FireBaseData]) -> Void)) {

    //check if user is singed in
    guard let uid = FIRAuth.auth()?.currentUser?.uid  else {
        return
    }

    dbRef.child(uid).child("profile").observeSingleEvent(of: .value, with: { (snapshot: FIRDataSnapshot) in
        var profileData = [FireBaseData]()

        for keyVal in snapshot.children{

            let userData = FireBaseData(snapshot: keyVal as! FIRDataSnapshot)
            profileData.append(userData)
                       }
        callback(profileData)

    }, withCancel: { (Error:Any) in
        print("error is \(Error as! String)")

    })
    dbRef.removeAllObservers()

}//end of startObserving

}//end of EditProfile Class
</code>```

答:
The usual problem to be solved is: The user has a edited a text field in a table view cell, and now we want to update the data model accordingly. But which cell contains this text field?

The notion "which" really means: what is the index path represented by the containing cell? If we knew that, we could easily update the model, because if our table view data source is correctly designed, we already know how to access the model by means of the index path.

So what I do is simply walk up the view hierarchy from the text field to the cell, and then ask the table view what index path this cell represents. This is a commonly used pattern in my apps:

```<code>func textFieldDidEndEditing(_ textField: UITextField) {
    var v : UIView = textField
    repeat { v = v.superview! } while !(v is UITableViewCell)
    let cell = v as! MyCell // or UITableViewCell or whatever
    let ip = self.tableView.indexPath(for:cell)!
    // and now we have the index path! update the model
}
</code>```

Body:
In a UIViewController I have a UITableView with 1 Dynamic Prototype cell of class type TextInputTableViewCell.

 In the Content View of the prototype cell I am adding a textField.

How can I populate the text fields with data from userInfo?

How can I get the data of each textField once they are edited by the user?

I have read on SO that I should use tags, but others said that this method is prone to bugs and fragile. Anyway, I don't know how to get the data from the fields using tags or other method. Please advise.

import Foundation
import UIKit
import Firebase

 class TextInputTableViewCell: UITableViewCell, UITextFieldDelegate{
      @IBOutlet weak var textField: UITextField!

     //closure when the text changes
     var textChangedCallBack: ((_ cell: TextInputTableViewCell, _ text:String) -> ())?
      //Delegate method called when the text field loses focus
     func textFieldDidEndEditing(_ textField: UITextField) {
    textChangedCallBack?(self,textField.text!)
  }
}//end of class TextInputTableViewCell

class EditProfile: UIViewController, UITableViewDelegate,UITableViewDataSource,UITextFieldDelegate {

 var dbRef:FIRDatabaseReference! //create a reference to Firebase
 var userInfo = [FireBaseData]() //this array will hold all data under userType in Firebase

@IBOutlet weak var tableView: UITableView!
@IBAction func saveToFirebase(_ sender: Any) {

 //will post data from text fields  to firebase
}

struct Item {
    var name:String
    var editable:Bool
}

let placeHolderItems = [
    Item(name: "Name", editable: false),
    Item(name: "Phone Number", editable: true),
    Item(name: "Email", editable: true),
    Item(name: "Flat Number", editable: true),
    Item(name: "Street Address", editable: true),
    Item(name: "Postcode", editable: true)
]

override func viewDidLoad() {
    super.viewDidLoad()

   self.dbRef = FIRDatabase.database().reference().child("Cleaners")
    self.tableView.delegate = self
    self.tableView.dataSource = self
}

   override func viewWillAppear(_ animated: Bool) {
     super.viewWillAppear(true)

   //get user's profile from firebase
    self.startObservingDB { (userProfile) in

        if userProfile.count > 0 {
            self.userInfo = userProfile
             self.tableView.reloadData()
        }
    }

func numberOfSections(in tableView: UITableView) -> Int {
    return 1
}

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return placeHolderItems.count
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "TextInputCell") as! TextInputTableViewCell

    cell.textField.isEnabled = placeHolderItems[indexPath.row].editable
    cell.textField.placeholder = placeHolderItems[indexPath.row].name

 //After viewWillAppear finishes, self.userInfo will have the profile of
 //the user. How can I get here each textField  of the tableView so I can
   //populate each one of them with data from  self.userInfo?

         if !self.userInfo.isEmpty{

switch indexPath.row{
    case 0:
         cell.textField.text = self.userInfo[0].FirstName + " " + self.userInfo[indexPath.row].LastName
    case 1:
        cell.textField.text = self.userInfo[0].PhoneNumber

    case 2: cell.textField.text = self.userInfo[0].EmailAddress

    case 3: cell.textField.text = self.userInfo[0].FlatNumber

    case 4: cell.textField.text = self.userInfo[0].StreetAddress

    case 5: cell.textField.text = self.userInfo[0].PostCode

    default:
        break
     }
 }

    cell.textChangedCallBack = {(cell, text) in

        //get the cell's current index path
        if let path = tableView.indexPath(for: cell) {

            //get the item at that row
            var item = self.placeHolderItems[path.row]

            //update the item with the new name
        }
    }

    return cell
  }
 }//end of EditProfileclass

extension EditProfile {

  //get user's profile in order to populate it in tableView
   func startObservingDB(callback:@escaping ((_ snapShot: [FireBaseData]) -> Void)) {

    //check if user is singed in
    guard let uid = FIRAuth.auth()?.currentUser?.uid  else {
        return
    }

    dbRef.child(uid).child("profile").observeSingleEvent(of: .value, with: { (snapshot: FIRDataSnapshot) in
        var profileData = [FireBaseData]()

        for keyVal in snapshot.children{

            let userData = FireBaseData(snapshot: keyVal as! FIRDataSnapshot)
            profileData.append(userData)
                       }
        callback(profileData)

    }, withCancel: { (Error:Any) in
        print("error is \(Error as! String)")

    })
    dbRef.removeAllObservers()

}//end of startObserving

}//end of EditProfile Class

Body:
The usual problem to be solved is: The user has a edited a text field in a table view cell, and now we want to update the data model accordingly. But which cell contains this text field?

The notion "which" really means: what is the index path represented by the containing cell? If we knew that, we could easily update the model, because if our table view data source is correctly designed, we already know how to access the model by means of the index path.

So what I do is simply walk up the view hierarchy from the text field to the cell, and then ask the table view what index path this cell represents. This is a commonly used pattern in my apps:

func textFieldDidEndEditing(_ textField: UITextField) {
    var v : UIView = textField
    repeat { v = v.superview! } while !(v is UITableViewCell)
    let cell = v as! MyCell // or UITableViewCell or whatever
    let ip = self.tableView.indexPath(for:cell)!
    // and now we have the index path! update the model
}


问:
Simplify a code in R
I have written a code that runs through the columns of a dataframe and returns TRUE if it has a number 1 in any of them, and sends the value to a vector with the same size as a column of the dataframe. I would like to know if there is a way to simplify the code snippet below, since I will have to repeat it for several numbers.</p>

```<code>n1 <- (tab[, 2]==1|  tab[, 3]==1 | tab[, 4]==1 | tab[, 5]==1 |
     tab[, 6]==1 | tab[, 7]==1 | tab[, 8]==1 | tab[, 9]==1 |
     tab[, 10]==1 | tab[, 11]==1 | tab[, 12]==1 | tab[, 13]==1 |
     tab[, 14]==1 | tab[, 15]==1 | tab[, 16]==1)
</code>```

答:
One possible solution is the following: you search for == 1 numbers in the dataframe and then Reduce the rows of that with the | operator:

```<code>tab <- data.frame(a = 1:10, b = 2:11)

apply(tab == 1, 1, function(x) {
  Reduce("|", x)
})
</code>```

For this example it will give you the ouput of:

```<code>[1]  TRUE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE
</code>```

Or one even simpler solution is:

```<code>apply(tab, 1, function(x) {
  any(x == 1)
})
</code>```

Title: Simplify a code in R

Body:
I have written a code that runs through the columns of a dataframe and returns TRUE if it has a number 1 in any of them, and sends the value to a vector with the same size as a column of the dataframe. I would like to know if there is a way to simplify the code snippet below, since I will have to repeat it for several numbers.

n1 <- (tab[, 2]==1|  tab[, 3]==1 | tab[, 4]==1 | tab[, 5]==1 |
     tab[, 6]==1 | tab[, 7]==1 | tab[, 8]==1 | tab[, 9]==1 |
     tab[, 10]==1 | tab[, 11]==1 | tab[, 12]==1 | tab[, 13]==1 |
     tab[, 14]==1 | tab[, 15]==1 | tab[, 16]==1)

Body:
One possible solution is the following: you search for == 1 numbers in the dataframe and then Reduce the rows of that with the | operator:

tab <- data.frame(a = 1:10, b = 2:11)

apply(tab == 1, 1, function(x) {
  Reduce("|", x)
})

For this example it will give you the ouput of:

[1]  TRUE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE

Or one even simpler solution is:

apply(tab, 1, function(x) {
  any(x == 1)
})


问:
How to install OpenCV+Python on Mac?
I am trying to install OpenCV+Python on Mac. I am trying to do this in six steps by running commands at terminal (after step2):

Step1: Install Xcode

Step2: Install Homebrew

Step3: Install Python2 and Python3

1) brew install python python3

2) brew linkapps python

```<code>brew linkapps python3
</code>```

4) which python

```<code>which python3
</code>```

Step4: Install Python libraries by installing a virtual environment

Step5: Install OpenCV

Step6: Symlink OpenCV+Python to virtual environment

The problem is that which python must give output /usr/local/bin/python and not /usr/bin/python as it gives by default so that the virtual environment can be installed to install then the Python libraries.

I removed the link by running unlink /usr/bin/python and I created a symlink by running ln -s /usr/local/Cellar/python /usr/bin/python (python and python3 are installed by default at /usr/local/Cellar/).

However now which python gives me no output even though I have created the symlink. Why is this?

How can I change the output of which command to install finally OpenCV+Python on Mac?

Any better idea to install OpenCV+Python on Mac with most of the useful libraries or virtual environments etc? (Obviously I know how to do the installation without all these)

P.S. I followed this link: https://www.learnopencv.com/install-opencv3-on-macos/

答:
Finally, I did not solve the problem with which output even though I discuss it with really experienced people.

Finally, I downloaded PyCharm and I did the following:

1) Installed pip (Python package manager) by opening a project at PyCharm and going to PyCharm Community Edition (top bar) -> Preferences -> Project -> Project interpreter -> Press '+' -> Search and find pip (with the search bar) -> Press 'Install Package'

2) Type and enter pip install opencv-python (https://pypi.python.org/pypi/opencv-python) at the terminal

3) Follow the process at (1) to install/import opencv-python in PyCharm

4) Write import cv2 at the top of your source code

By not implementing the more extensive installation process described by the links that I posted above, I did not install the virtual environment which is highly recommended in order to avoid conflicts between various projects. But I think that I can make it without it for the moment!

Title: How to install OpenCV+Python on Mac?

Body:
I am trying to install OpenCV+Python on Mac. I am trying to do this in six steps by running commands at terminal (after step2):

Step1: Install Xcode

Step2: Install Homebrew

Step3: Install Python2 and Python3

1) brew install python python3

2) brew linkapps python

brew linkapps python3

4) which python

which python3

Step4: Install Python libraries by installing a virtual environment

Step5: Install OpenCV

Step6: Symlink OpenCV+Python to virtual environment

The problem is that which python must give output /usr/local/bin/python and not /usr/bin/python as it gives by default so that the virtual environment can be installed to install then the Python libraries.

I removed the link by running unlink /usr/bin/python and I created a symlink by running ln -s /usr/local/Cellar/python /usr/bin/python (python and python3 are installed by default at /usr/local/Cellar/).

However now which python gives me no output even though I have created the symlink. Why is this?

How can I change the output of which command to install finally OpenCV+Python on Mac?

Any better idea to install OpenCV+Python on Mac with most of the useful libraries or virtual environments etc? (Obviously I know how to do the installation without all these)

P.S. I followed this link: https://www.learnopencv.com/install-opencv3-on-macos/


问:
Image with transparency over video
Im using C# in VS2017 and have a Vlc Control to play a video.

I want to overlap some part of the video with a PNG image with transparency. In VS2017, elements are transparent to their parent. So, to make the image be transparent to the video I have to set it as child of the video.

But if I do that, the image doesn't display at all. Video is always refreshing and overlapping the image (even if I do a constant BringToFront in the image).

So, I change the Parent of the image to the form. Now the image displays, but through it's transparency I see the form's background, not the video.

Target platform is Windows. Is there any solution for this?

答:
It's not very clear how you're using libvlc.

Do you have to blend the image with the control itself? Shouldn't you blend any given image with the video frames?

If so, try using --alphamask-mask filter:

```<code>   --alphamask-mask=<string>
     Transparency mask
     Alpha blending transparency mask. Uses a png alpha channel.
</code>```

If you're using libvlc.net you can do this by adding an option:

```<code>vlcContext.StartupOptions.AddOption(<options>);
</code>```

Title: Image with transparency over video

Body:
It's not very clear how you're using libvlc.

Do you have to blend the image with the control itself? Shouldn't you blend any given image with the video frames?

If so, try using --alphamask-mask filter:

   --alphamask-mask=<string>
     Transparency mask
     Alpha blending transparency mask. Uses a png alpha channel.

If you're using libvlc.net you can do this by adding an option:

vlcContext.StartupOptions.AddOption(<options>);


问:
Change the XPath-root of an XmlDocument in .net (C#)?
When selecting from an XmlDocument by e.g. the XPath-method SelectSingleNode we get an XmlNode that consist of the first matching node, lets call it <node1>. If we do further selection on <node1> then one might expect that the XPath-root now is this node, but this is incorrect, the root is still the same as in the original XmlDocument. Here's an example:

```<code>XmlDocument xd = new XmlDocument();
xd.LoadXml(@"<root>
                 <subroot>
                     <elm>test1</elm>
                     <elm>test2</elm>
                     <elm>test3</elm>
                 </subroot>
             </root>");
XmlNode xnSubRoot = xd.SelectSingleNode("/root/subroot");

//This is the XPath I want to be able to use, but it returns null.
XmlNode xnElm = xnSubRoot.SelectSingleNode("/subroot/elm");

//This works, but the XPath-root is the same as in the original document.
xnElm = xnSubRoot.SelectSingleNode("/root/subroot/elm");
</code>```

Is there any way to "fix" the root of xnSubRoot so that I can use the XPath I want? The reason for my question is because I have a case where I'm calling a webservice that returns an XmlNode where the OuterXml-property shows a structure of "/Data/SubElement/..." and so on, but when running XPath "/Data" then null is returned, only "/SubElement" works, i.e. the XPath-root seems to be one level lower than the actual document-root.

I'm sure there is a perfectly reasonable explanation for this, or that I'm missing something vital. However I really can't seem to find anything, even though I've read http://msdn.microsoft.com/en-us/library/d271ytdx(VS.80).aspx.

N.B. I do realize that it would be possible to use the XPath "//subroot/elm", but then I might also get other elements further down in the XML structure.

答:
This works:

```<code>XmlNode xnSubRoot = xd.SelectSingleNode("/root/subroot");
XmlNode xnElm = xnSubRoot.SelectSingleNode("elm");
</code>```

And so does this:

```<code>XmlNode xnRoot = xd.SelectSingleNode("/root");
XmlNode xnElm = xnRoot.SelectSingleNode("subroot/elm");
</code>```

ContentLicense: CC BY-SA 2.5

Body:
When selecting from an XmlDocument by e.g. the XPath-method SelectSingleNode we get an XmlNode that consist of the first matching node, lets call it <node1>. If we do further selection on <node1> then one might expect that the XPath-root now is this node, but this is incorrect, the root is still the same as in the original XmlDocument. Here's an example:

XmlDocument xd = new XmlDocument();
xd.LoadXml(@"<root>
                 <subroot>
                     <elm>test1</elm>
                     <elm>test2</elm>
                     <elm>test3</elm>
                 </subroot>
             </root>");
XmlNode xnSubRoot = xd.SelectSingleNode("/root/subroot");

//This is the XPath I want to be able to use, but it returns null.
XmlNode xnElm = xnSubRoot.SelectSingleNode("/subroot/elm");

//This works, but the XPath-root is the same as in the original document.
xnElm = xnSubRoot.SelectSingleNode("/root/subroot/elm");

Is there any way to "fix" the root of xnSubRoot so that I can use the XPath I want? The reason for my question is because I have a case where I'm calling a webservice that returns an XmlNode where the OuterXml-property shows a structure of "/Data/SubElement/..." and so on, but when running XPath "/Data" then null is returned, only "/SubElement" works, i.e. the XPath-root seems to be one level lower than the actual document-root.

I'm sure there is a perfectly reasonable explanation for this, or that I'm missing something vital. However I really can't seem to find anything, even though I've read http://msdn.microsoft.com/en-us/library/d271ytdx(VS.80).aspx.

N.B. I do realize that it would be possible to use the XPath "//subroot/elm", but then I might also get other elements further down in the XML structure.

Body:
This works:

XmlNode xnSubRoot = xd.SelectSingleNode("/root/subroot");
XmlNode xnElm = xnSubRoot.SelectSingleNode("elm");

And so does this:

XmlNode xnRoot = xd.SelectSingleNode("/root");
XmlNode xnElm = xnRoot.SelectSingleNode("subroot/elm");


问:
Loop through foreach without knowing the index
I would like to Loop throught services but I don't know the index name. They come randomly, example I got 8 and 9 but I do not know them.

```<code>"2": {
    "first_name": "khalfan",
    "last_name": "mussa",
    "date": "2017-06-06 09:21:36",
    "gender": "male",
    "services": {
        "8": {
            "name": "See a Doctor",
            "results": ""
    },
         "9": {
            "name": "Kichocho",
            "results": "FD- 73"
              }
    }
},
</code>```

答:
The following are four available options:

```<code><?php
$arr = ["2" => [
          ["first_name"=> "khalfan",
           "last_name"=> "mussa",
           "date"=>"2017-06-06 09:21:36",
           "gender"=> "male"],
          ["services" =>
             ["8" => ["name" => "See a Doctor","results"=> ""],
              "9" => ["name"=> "Kichocho","results"=> "FD- 73"]
             ]
          ]
]];

for ($i=0, $max=count($arr["2"]); $i < $max; $i++) {
      if ( isset( $arr["2"][$i]["services"])) {
        $a = $arr["2"][$i]["services"];
        foreach($a as $e) {
           echo $e["name"],"\t";
           echo $e["results"],"\n";
        }
      }
      continue;

}
</code>```

See live code

The advantage here is that the code does work with a foreach as per the OP's request.  But the code is involved and not as fast as it could be, owing to that if conditional.

Another solution that is faster:

```<code><?php
$arr = ["2" => [
          ["first_name"=> "khalfan",
           "last_name"=> "mussa",
           "date"=>"2017-06-06 09:21:36",
           "gender"=> "male"],
          ["services" =>
             ["8" => ["name" => "See a Doctor","results"=> ""],
              "9" => ["name"=> "Kichocho","results"=> "FD- 73"]
             ]
          ]
]];
$count = count($arr["2"]);
$last = $count - 1; // b/c of zero-based indexing

foreach ($arr as $e) {
      foreach($e[$last]["services"] as $a) {
           echo $a["name"],"\t";
           echo $a["results"],"\n";
      }
}

// Or an easier solution without resorting to foreach:
array_walk_recursive($arr,function($item,$key) {
          if ($key == "name") echo $item,"\t";
          if ($key == "results") echo $item,"\n";
});
</code>```

See live code

Whether $arr["2"] contains two elements or more as long as the last one is the "services" associate array, this foreach code works.  But, this type of "array walk" can best be carried out with a built-in function designed for this very purpose, array_walk_recursive.  With this function, you don't have to worry about how to construct the perfect foreach; the iteration occurs behind the scenes and all you need is to supply a callback. array_walk_recursive will drill down to the "services" element and if there is one or more associative arrays with keys of "name" and "results", then their respective values display.

The fourth possibility is one of those "why would you" situations.  Why take an array and json_encode it and then json_decode it back to an array and then apply array_walk_recursive?  But, the code does work:

```<code><?php
$arr = ["2" => [
          ["first_name"=> "khalfan",
           "last_name"=> "mussa",
           "date"=>"2017-06-06 09:21:36",
           "gender"=> "male"],
          ["services" =>
             ["8" => ["name" => "See a Doctor","results"=> ""],
              "9" => ["name"=> "Kichocho","results"=> "FD- 73"]
             ]
          ]
]];
$result=json_decode(json_encode($arr),true);
array_walk_recursive($result, function($value,$key){
   if ($key == "name" ) { echo $value,"\t";}
   if ($key == "results") { echo $value,"\n";}
});
</code>```

See live code

Body:
I would like to Loop throught services but I don't know the index name. They come randomly, example I got 8 and 9 but I do not know them.

"2": {
    "first_name": "khalfan",
    "last_name": "mussa",
    "date": "2017-06-06 09:21:36",
    "gender": "male",
    "services": {
        "8": {
            "name": "See a Doctor",
            "results": ""
    },
         "9": {
            "name": "Kichocho",
            "results": "FD- 73"
              }
    }
},

Body:
The following are four available options:

<?php
$arr = ["2" => [
          ["first_name"=> "khalfan",
           "last_name"=> "mussa",
           "date"=>"2017-06-06 09:21:36",
           "gender"=> "male"],
          ["services" =>
             ["8" => ["name" => "See a Doctor","results"=> ""],
              "9" => ["name"=> "Kichocho","results"=> "FD- 73"]
             ]
          ]
]];

for ($i=0, $max=count($arr["2"]); $i < $max; $i++) {
      if ( isset( $arr["2"][$i]["services"])) {
        $a = $arr["2"][$i]["services"];
        foreach($a as $e) {
           echo $e["name"],"\t";
           echo $e["results"],"\n";
        }
      }
      continue;

}

See live code

The advantage here is that the code does work with a foreach as per the OP's request.  But the code is involved and not as fast as it could be, owing to that if conditional.

Another solution that is faster:

<?php
$arr = ["2" => [
          ["first_name"=> "khalfan",
           "last_name"=> "mussa",
           "date"=>"2017-06-06 09:21:36",
           "gender"=> "male"],
          ["services" =>
             ["8" => ["name" => "See a Doctor","results"=> ""],
              "9" => ["name"=> "Kichocho","results"=> "FD- 73"]
             ]
          ]
]];
$count = count($arr["2"]);
$last = $count - 1; // b/c of zero-based indexing

foreach ($arr as $e) {
      foreach($e[$last]["services"] as $a) {
           echo $a["name"],"\t";
           echo $a["results"],"\n";
      }
}

// Or an easier solution without resorting to foreach:
array_walk_recursive($arr,function($item,$key) {
          if ($key == "name") echo $item,"\t";
          if ($key == "results") echo $item,"\n";
});

See live code

Whether $arr["2"] contains two elements or more as long as the last one is the "services" associate array, this foreach code works.  But, this type of "array walk" can best be carried out with a built-in function designed for this very purpose, array_walk_recursive.  With this function, you don't have to worry about how to construct the perfect foreach; the iteration occurs behind the scenes and all you need is to supply a callback. array_walk_recursive will drill down to the "services" element and if there is one or more associative arrays with keys of "name" and "results", then their respective values display.

The fourth possibility is one of those "why would you" situations.  Why take an array and json_encode it and then json_decode it back to an array and then apply array_walk_recursive?  But, the code does work:

<?php
$arr = ["2" => [
          ["first_name"=> "khalfan",
           "last_name"=> "mussa",
           "date"=>"2017-06-06 09:21:36",
           "gender"=> "male"],
          ["services" =>
             ["8" => ["name" => "See a Doctor","results"=> ""],
              "9" => ["name"=> "Kichocho","results"=> "FD- 73"]
             ]
          ]
]];
$result=json_decode(json_encode($arr),true);
array_walk_recursive($result, function($value,$key){
   if ($key == "name" ) { echo $value,"\t";}
   if ($key == "results") { echo $value,"\n";}
});

See live code


问:
how to sum records in columns of a particular row with the answer in same row
How can I sum the fees, bus, and snacks and the result to show on same row under total? e.g 100+20+500 = 620.

The data

```<code>salary recurrent repairs_maint .....   TOTAL
=============================================
100       20      250    250  .....     620
==============================================
20   10  200      100    100.....      430
==============================================
</code>```

The PHP code

```<code><?php
      $add=mysqli_query($conn,'SELECT SUM(salary),SUM(recurrent),SUM(repairs_maint),SUM(creditors) ,SUM(petty_cash) ,SUM(capital_expenses)from `monthly_expenditure`');
      while($row1=mysqli_fetch_array($add))
      {
        $mark=$row1['SUM(salary)'];
        $mark1=$row1['SUM(recurrent)'];
        $mark3=$row1['SUM(repairs_maint)'];
        $mark4=$row1['SUM(creditors)'];
        $mark5=$row1['SUM(petty_cash)'];
        $mark6=$row1['SUM(capital_expenses)'];
     ?>

      <tr>
      <th></th>
      <th>Total  =</th>
        <th><?php echo $mark ?></th>
        <th><?php echo $mark1 ?></th>
        <th><?php echo $mark3 ?></th>
        <th><?php echo $mark4 ?></th>
        <th><?php echo $mark5 ?></th>
        <th><?php echo $mark6 ?></th>
</code>```

答:
Your description is little bit confusing. If I understand correctly than you want to sum all given attributes for each id. Following query may work:</p>

```<code>select t.id,t.a as salary,t.b as recurrent,t.c as repairs_maint,
       t.d as creditors,t.e as petty_cash,t.f as capital_expenses
       (t.a + t.b + t.c + t.d + t.e + t.f) as total
from
(SELECT SUM(salary) as a,
      SUM(recurrent) as b,
      SUM(repairs_maint) as c,
      SUM(creditors) as d,
      SUM(petty_cash) as e,
      SUM(capital_expenses) as f
from monthly_expenditure
group by id) t
group by t.id;
</code>```

Body:
How can I sum the fees, bus, and snacks and the result to show on same row under total? e.g 100+20+500 = 620.

The data

salary recurrent repairs_maint .....   TOTAL
=============================================
100       20      250    250  .....     620
==============================================
20   10  200      100    100.....      430
==============================================

The PHP code

<?php
      $add=mysqli_query($conn,'SELECT SUM(salary),SUM(recurrent),SUM(repairs_maint),SUM(creditors) ,SUM(petty_cash) ,SUM(capital_expenses)from `monthly_expenditure`');
      while($row1=mysqli_fetch_array($add))
      {
        $mark=$row1['SUM(salary)'];
        $mark1=$row1['SUM(recurrent)'];
        $mark3=$row1['SUM(repairs_maint)'];
        $mark4=$row1['SUM(creditors)'];
        $mark5=$row1['SUM(petty_cash)'];
        $mark6=$row1['SUM(capital_expenses)'];
     ?>

      Total  =
        <?php echo $mark ?>
        <?php echo $mark1 ?>
        <?php echo $mark3 ?>
        <?php echo $mark4 ?>
        <?php echo $mark5 ?>
        <?php echo $mark6 ?>

Body:
Your description is little bit confusing. If I understand correctly than you want to sum all given attributes for each id. Following query may work:

select t.id,t.a as salary,t.b as recurrent,t.c as repairs_maint,
       t.d as creditors,t.e as petty_cash,t.f as capital_expenses
       (t.a + t.b + t.c + t.d + t.e + t.f) as total
from
(SELECT SUM(salary) as a,
      SUM(recurrent) as b,
      SUM(repairs_maint) as c,
      SUM(creditors) as d,
      SUM(petty_cash) as e,
      SUM(capital_expenses) as f
from monthly_expenditure
group by id) t
group by t.id;


问:
Why does NumberFormatter drop monetary fraction digits in format()
Why do the following two lines

```<code>$fmt = new NumberFormatter('en_US', NumberFormatter::CURRENCY);
echo $fmt->format(12.34, NumberFormatter::CURRENCY);
</code>```

output $12.00 ?

答:
It's because you're using the NumberFormatter::CURRENCY constant as the second argument to format().

In the predefined constants section of the NumberFormatter documentation, the constants are grouped under which methods they should be used with.

NumberFormatter::CURRENCY has a value of 2 and should be used when constructing the formatter, as you have done. A value of 2 in the format() function corresponds to NumberFormatter::TYPE_INT64.

You should just be able to call format(12.34) without a second argument.

```<code>$fmt = new NumberFormatter('en_US', NumberFormatter::CURRENCY);
echo $fmt->format(12.34);
</code>```

Body:
Why do the following two lines

$fmt = new NumberFormatter('en_US', NumberFormatter::CURRENCY);
echo $fmt->format(12.34, NumberFormatter::CURRENCY);

output $12.00 ?

Body:
It's because you're using the NumberFormatter::CURRENCY constant as the second argument to format().

In the predefined constants section of the NumberFormatter documentation, the constants are grouped under which methods they should be used with.

NumberFormatter::CURRENCY has a value of 2 and should be used when constructing the formatter, as you have done. A value of 2 in the format() function corresponds to NumberFormatter::TYPE_INT64.

You should just be able to call format(12.34) without a second argument.

$fmt = new NumberFormatter('en_US', NumberFormatter::CURRENCY);
echo $fmt->format(12.34);


问:
Customizing Shopify Themes
E-commerce intermediate, Shopify and Ruby on Rails newbie.

How does one go about customizing Shopify files? I have a purchased a theme but want to make some changes to the .liquid files.

Do I have to I unzip, edit, re-zip and upload in the Shopify admin section? is this supported? What are best practices for customizing themes?

答:
You can get started with the instructions here, which can be done straight from the admin interface.

Once you've gained some experience there (try some of the shopify/liquid tutorials), you can take a more comprehensive/custom approach. And btw, you don't need to know Rails, just the Ruby language. In fact, you can even hack away at the liquid codebase if you want.

Good luck!

Title: Customizing Shopify Themes


问:
On Premise Microsoft Cognitive Services
The data being sent to Cognitive Services (say LUIS) might contain some information which we do not wish to expose outside the enterprise. Therefore , would like to know how can this be achieved??</p>

答: For LUIS, you can set log=off in the URL you send. That will disable logging of utterances. Document is here: https://learn.microsoft.com/en-us/azure/cognitive-services/luis/luis-resources-faq. </p>

Title: On Premise Microsoft Cognitive Services


问:
Running Visual Studio 2017 with Angular 4 and Angular CLI
Is it possible to run an Angular CLI generated project in Visual Studio 2017?

I tried generating a Hello World application and Visual Studio 2017 can't run it.

```<code>ng new HelloWorld
</code>```

I opened the folder as a website and clicked start.  Has anyone else solved this?

The "Loading..." just runs forever.

答:
It looks like Steve Sanderson is working on integrating the CLI into the DotNet Angular template. Add new Angular CLI-based template

Check out this repo Angular-CSharp

This middleware from the repo excites me to no end.

```<code>public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
                app.UseHsts();
            }

            app.UseHttpsRedirection();
            app.UseStaticFiles();

            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller}/{action=Index}/{id?}");
            });

            app.UseSpa(spa =>
            {
                spa.Options.DefaultPage = "/dist/index.html";
                spa.Options.SourcePath = "ClientApp";

                /*
                // If you want to enable server-side rendering (SSR),
                // [1] In AngularSpa.csproj, change the <BuildServerSideRenderer> property
                //     value to 'true', so that the SSR bundle is built during publish
                // [2] Uncomment this code block
                spa.UseSpaPrerendering(options =>
                {
                    options.BootModulePath = $"{spa.Options.SourcePath}/dist-server/main.bundle.js";
                    options.BootModuleBuilder = env.IsDevelopment() ? new AngularCliBuilder(npmScript: "build:ssr") : null;
                    options.ExcludeUrls = new[] { "/sockjs-node" };
                });
                */

                if (env.IsDevelopment())
                {
                    spa.UseAngularCliServer(npmScript: "start");
                }
            });
        }
</code>```

Great job Steve!! Hopefully it will be ready soon.

Update: Looks like there is a preview available:
Microsoft.DotNet.Web.Spa.ProjectTemplates::2.0.0-preview1-final

Body:
Is it possible to run an Angular CLI generated project in Visual Studio 2017?

I tried generating a Hello World application and Visual Studio 2017 can't run it.

ng new HelloWorld

I opened the folder as a website and clicked start.  Has anyone else solved this?

The "Loading..." just runs forever.

Body:
It looks like Steve Sanderson is working on integrating the CLI into the DotNet Angular template. Add new Angular CLI-based template

Check out this repo Angular-CSharp

This middleware from the repo excites me to no end.

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
                app.UseHsts();
            }

            app.UseHttpsRedirection();
            app.UseStaticFiles();

            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller}/{action=Index}/{id?}");
            });

            app.UseSpa(spa =>
            {
                spa.Options.DefaultPage = "/dist/index.html";
                spa.Options.SourcePath = "ClientApp";

                /*
                // If you want to enable server-side rendering (SSR),
                // [1] In AngularSpa.csproj, change the <BuildServerSideRenderer> property
                //     value to 'true', so that the SSR bundle is built during publish
                // [2] Uncomment this code block
                spa.UseSpaPrerendering(options =>
                {
                    options.BootModulePath = $"{spa.Options.SourcePath}/dist-server/main.bundle.js";
                    options.BootModuleBuilder = env.IsDevelopment() ? new AngularCliBuilder(npmScript: "build:ssr") : null;
                    options.ExcludeUrls = new[] { "/sockjs-node" };
                });
                */

                if (env.IsDevelopment())
                {
                    spa.UseAngularCliServer(npmScript: "start");
                }
            });
        }

Great job Steve!! Hopefully it will be ready soon.

Update: Looks like there is a preview available:
Microsoft.DotNet.Web.Spa.ProjectTemplates::2.0.0-preview1-final


问:
python 3 find in list
I am creating a game and unable to detect turtle position in this list
I am using python3 and turtle.
the objective of this code is to create a filled shape when turtle intersect with its's own path

```<code>import turtle
t=turtle.Turtle()
t.fillcolor("red")
t.begin_fill()
s=turtle.Screen()
t.penup()
status=True
penstatus=False
t.speed(1)
x=[]

def go1():
    t.left(-(t.heading()))
    t.left(90)
def go2():
    t.left(-(t.heading()))
    # t.left(90)
def go3():
    t.left(-(t.heading()))
    t.left(270)
def go4():
    t.left(-(t.heading()))
    t.left(180)

def paint():
    global penstatus
    if penstatus==False:
        penstatus=True
        t.down()
    else:
        t.up()
def detect():
    global status
    a=t.position()
    if a in x:
        status=False
        print("yes")

while status:
    global x
    s.onkeypress(go1, "Up")
    s.onkeypress(go2, "Right")
    s.onkeypress(go3, "Down")
    s.onkeypress(go4, "Left")
    s.onkeypress(paint,"space")
    s.listen()
    x.append(t.position())
    t.fd(5)
    detect()

t.end_fill()
s.mainloop()
</code>```

it works sometimes but result of filling also gets wrong

答:
There are two reasons you're having trouble detecting if the current position is in your list of past positions.  The first is you "hop" five pixels at a time so you are potentially crossing the line at a "filled in" segment, not one you were actually positioned on.

The second is that turtle positions are floating point numbers and can be very slightly different when you come back to the same spot.  We can fix both problems by not comparing directly but asking if the distance between points is less than our "hop" distance.

My rework of your code below implements this approach.  It also changes how your keys work slightly; changes the logic to only include visible lines in the filled graphic; and is completely event-based.  It also has a reset, "r", key to start a new drawing.  You can back out any changes you don't like, the back position detection is still applicable:

```<code>from turtle import Turtle, Screen

DISTANCE = 3

def go_up():
    turtle.setheading(90)

def go_right():
    turtle.setheading(0)

def go_down():
    turtle.setheading(270)

def go_left():
    turtle.setheading(180)

def toggle_pen():
    if turtle.isdown():
        turtle.penup()
    else:
        turtle.pendown()
        turtle.begin_fill()  #  ignore pending begin_fill, start anew

def reset_drawing():
    global positions
    turtle.reset()
    turtle.fillcolor('red')
    turtle.speed('fastest')
    turtle.penup()
    positions = []

    move()

def move():
    for position in positions:
        if turtle.distance(position) < DISTANCE:
            turtle.end_fill()
            return

    if turtle.isdown():
        positions.append(turtle.position())

    turtle.forward(DISTANCE)

    screen.ontimer(move, 100)

screen = Screen()

screen.onkeypress(go_up, 'Up')
screen.onkeypress(go_right, 'Right')
screen.onkeypress(go_down, 'Down')
screen.onkeypress(go_left, 'Left')
screen.onkeypress(toggle_pen, 'space')
screen.onkeypress(reset_drawing, 'r')

screen.listen()

turtle = Turtle()

positions = None  # make sure global is defined

reset_drawing()

screen.mainloop()
</code>```

Title: python 3 find in list

Body:
I am creating a game and unable to detect turtle position in this list
I am using python3 and turtle.
the objective of this code is to create a filled shape when turtle intersect with its's own path

import turtle
t=turtle.Turtle()
t.fillcolor("red")
t.begin_fill()
s=turtle.Screen()
t.penup()
status=True
penstatus=False
t.speed(1)
x=[]

def go1():
    t.left(-(t.heading()))
    t.left(90)
def go2():
    t.left(-(t.heading()))
    # t.left(90)
def go3():
    t.left(-(t.heading()))
    t.left(270)
def go4():
    t.left(-(t.heading()))
    t.left(180)

def paint():
    global penstatus
    if penstatus==False:
        penstatus=True
        t.down()
    else:
        t.up()
def detect():
    global status
    a=t.position()
    if a in x:
        status=False
        print("yes")

while status:
    global x
    s.onkeypress(go1, "Up")
    s.onkeypress(go2, "Right")
    s.onkeypress(go3, "Down")
    s.onkeypress(go4, "Left")
    s.onkeypress(paint,"space")
    s.listen()
    x.append(t.position())
    t.fd(5)
    detect()

t.end_fill()
s.mainloop()

it works sometimes but result of filling also gets wrong

Body:
There are two reasons you're having trouble detecting if the current position is in your list of past positions.  The first is you "hop" five pixels at a time so you are potentially crossing the line at a "filled in" segment, not one you were actually positioned on.

The second is that turtle positions are floating point numbers and can be very slightly different when you come back to the same spot.  We can fix both problems by not comparing directly but asking if the distance between points is less than our "hop" distance.

My rework of your code below implements this approach.  It also changes how your keys work slightly; changes the logic to only include visible lines in the filled graphic; and is completely event-based.  It also has a reset, "r", key to start a new drawing.  You can back out any changes you don't like, the back position detection is still applicable:

from turtle import Turtle, Screen

DISTANCE = 3

def go_up():
    turtle.setheading(90)

def go_right():
    turtle.setheading(0)

def go_down():
    turtle.setheading(270)

def go_left():
    turtle.setheading(180)

def toggle_pen():
    if turtle.isdown():
        turtle.penup()
    else:
        turtle.pendown()
        turtle.begin_fill()  #  ignore pending begin_fill, start anew

def reset_drawing():
    global positions
    turtle.reset()
    turtle.fillcolor('red')
    turtle.speed('fastest')
    turtle.penup()
    positions = []

    move()

def move():
    for position in positions:
        if turtle.distance(position) < DISTANCE:
            turtle.end_fill()
            return

    if turtle.isdown():
        positions.append(turtle.position())

    turtle.forward(DISTANCE)

    screen.ontimer(move, 100)

screen = Screen()

screen.onkeypress(go_up, 'Up')
screen.onkeypress(go_right, 'Right')
screen.onkeypress(go_down, 'Down')
screen.onkeypress(go_left, 'Left')
screen.onkeypress(toggle_pen, 'space')
screen.onkeypress(reset_drawing, 'r')

screen.listen()

turtle = Turtle()

positions = None  # make sure global is defined

reset_drawing()

screen.mainloop()


问:
Email On Results Of Query On Condition
I have a query that gets the 2 newest datetime values. I need to get a diff of the datetime and email if the value is greater than 5 minutes. I have accomplished it using 3 tables but i would like to do it in a single query.

```<code>SELECT DATEDIFF(minute, T1, T2) + 10 As DIFF
FROM
(SELECT TOP 1 T1.DateAndTime As T1,  T2.DateAndTime AS T2

FROM [WIMS_SQL].[dbo].[FloatTable] as T1

Inner Join [WIMS_SQL].[dbo].[FloatTable] as T2

On T1.DateAndTime > T2.DateAndTime

Order By  T2.DateAndTime Desc)

IF DIFF > 5 "EMAIL FUNCTION"
</code>```

Im sure theres a better way to do this than i am using

答:
Here's the logic with a CTE.

```<code>declare @minutes int

;with cte as(
    select top 2 DateAndTime
    from [WIMS_SQL].[dbo].[FloatTable]
    order by DateAndTime desc)

select
    @minutes = datediff(minute, max(DateAndTime), min(DateAndTime)) + 10
from cte

if (@minutes > 5)
begin
    exec msdb..sp_send_dbmail
         @profile_name = 'Profile Name You Set Up'
        ,@recipients = 'someone@domain.com'
        ,@subject = 'some subject'
end
</code>```

ONLINE DEMO

This method will prevent you from making a cartesian product with that join condition and should be a lot faster.

Title: Email On Results Of Query On Condition

Body:
I have a query that gets the 2 newest datetime values. I need to get a diff of the datetime and email if the value is greater than 5 minutes. I have accomplished it using 3 tables but i would like to do it in a single query.

SELECT DATEDIFF(minute, T1, T2) + 10 As DIFF
FROM
(SELECT TOP 1 T1.DateAndTime As T1,  T2.DateAndTime AS T2

FROM [WIMS_SQL].[dbo].[FloatTable] as T1

Inner Join [WIMS_SQL].[dbo].[FloatTable] as T2

On T1.DateAndTime > T2.DateAndTime

Order By  T2.DateAndTime Desc)

IF DIFF > 5 "EMAIL FUNCTION"

Im sure theres a better way to do this than i am using

Body:
Here's the logic with a CTE.

declare @minutes int

;with cte as(
    select top 2 DateAndTime
    from [WIMS_SQL].[dbo].[FloatTable]
    order by DateAndTime desc)

select
    @minutes = datediff(minute, max(DateAndTime), min(DateAndTime)) + 10
from cte

if (@minutes > 5)
begin
    exec msdb..sp_send_dbmail
         @profile_name = 'Profile Name You Set Up'
        ,@recipients = 'someone@domain.com'
        ,@subject = 'some subject'
end

ONLINE DEMO

This method will prevent you from making a cartesian product with that join condition and should be a lot faster.


问:
select SQL query
I have a three tables

table 1 - key columns p1,  p2

table 2 - key columns  p1, STATUS

table 3 - key columns p2, STATUS

In table 1, if p1 is 0, then p2 will have value. but not the vice versa.
If p1 is there, then I need to check status in table 2, if not I need to check the status in table 3.

Now I need select find count of rows which are having pending status in any of table 2 and 3 from table 1.

Please help. thanks in advance

答:
```<code>SELECT  CASE p1 WHEN 0 THEN t2.status ELSE t3.status END
FROM    t1
LEFT JOIN
        t2
ON      t2.p1 = p1
LEFT JOIN
        t3
ON      t1.p1 = 0
        AND t3.p2 = t1.p2
</code>```

Title: select SQL query


问:
How to search only on certain region of window on SikuliX
I have monitor with 4k resolution, the animated window that need to be captured only 1024x768 (1/6 of the monitor screen), i want sikuli only search on that window only, not the whole screen because it's lagging. Is there function to do that?</p>

答: As Eugene has mentioned above, you need to create an object of Region with the bounds set. Once that is done, you can use click, find, etc for the region using the object and get it done.</p>


问:
How to Append text to static resource in Xamarin.Forms?
I have my resource like this.

```<code><ContentView.Resources>
    <ResourceDictionary>
        <x:String x:Key="LabelAutomationIdentifier">LBL_PD_L_PLV_LV_</x:String>
    </ResourceDictionary>
</ContentView.Resources>
</code>```

I need to use this resource in the AutomationId property of Label like this

```<code><Label AutomationId="{StaticResource LabelAutomationIdentifier} + LabelName" />
</code>```

But, this is not correct. I tried multiple ways but no luck.

I tried,

```<code><Label AutomationId="{Binding Source={StaticResource LabelAutomationIdentifier}, StringFormat='{}{0}LabelName'}" />
</code>```

also

```<code><Label AutomationId="{StaticResource LabelAutomationIdentifier, StringFormat='{0}LabelName'}" />
</code>```

答:
Had it been that the AutomationId was a bindable property -  would have worked just fine.

But it is not, and I believe that is the reason the Binding won't work in this case. Also, StaticResource doesn't have a StringFormat property to work with here, so the second option fails.

You can, however extend StaticResource extension to create a custom-markup extension to add formatting support.

```<code>[ContentProperty("StaticResourceKey")]
public class FormatExtension : IMarkupExtension
{
    public string StringFormat { get; set; }
    public string StaticResourceKey { get; set; }

    public object ProvideValue(IServiceProvider serviceProvider)
    {
        string toReturn = null;
        if (serviceProvider == null)
            throw new ArgumentNullException(nameof(serviceProvider));

        if (StaticResourceKey != null)
        {
            var staticResourceExtension = new StaticResourceExtension { Key = StaticResourceKey };

            toReturn = (string)staticResourceExtension.ProvideValue(serviceProvider);
            if (!string.IsNullOrEmpty(StringFormat))
                toReturn = string.Format(StringFormat, toReturn);
        }

        return toReturn;
    }
}
</code>```

Sample Usage

```<code><Label AutomationId="{local:Format LabelAutomationIdentifier, StringFormat='{0}_LabelName'}" />
</code>```

Body:
I have my resource like this.

<ContentView.Resources>
    <ResourceDictionary>
        <x:String x:Key="LabelAutomationIdentifier">LBL_PD_L_PLV_LV_</x:String>
    </ResourceDictionary>
</ContentView.Resources>

I need to use this resource in the AutomationId property of Label like this

But, this is not correct. I tried multiple ways but no luck.

I tried,

also

Body:
Had it been that the AutomationId was a bindable property - <Label AutomationId="{Binding Source={StaticResource LabelAutomationIdentifier}, StringFormat='{}{0}LabelName'}" /> would have worked just fine.

But it is not, and I believe that is the reason the Binding won't work in this case. Also, StaticResource doesn't have a StringFormat property to work with here, so the second option fails.

You can, however extend StaticResource extension to create a custom-markup extension to add formatting support.

[ContentProperty("StaticResourceKey")]
public class FormatExtension : IMarkupExtension
{
    public string StringFormat { get; set; }
    public string StaticResourceKey { get; set; }

    public object ProvideValue(IServiceProvider serviceProvider)
    {
        string toReturn = null;
        if (serviceProvider == null)
            throw new ArgumentNullException(nameof(serviceProvider));

        if (StaticResourceKey != null)
        {
            var staticResourceExtension = new StaticResourceExtension { Key = StaticResourceKey };

            toReturn = (string)staticResourceExtension.ProvideValue(serviceProvider);
            if (!string.IsNullOrEmpty(StringFormat))
                toReturn = string.Format(StringFormat, toReturn);
        }

        return toReturn;
    }
}

Sample Usage

<Label AutomationId="{local:Format LabelAutomationIdentifier, StringFormat='{0}_LabelName'}" />


问:
How does AudioKit's AKNodeOutputPlot pull it's data?
I'm very new to the AudioKit framework and I have been trying to understand a bit more about the DSP side to it.   Whilst rummaging around in the source code I realised that AKNodeOutputPlot does not pull data from the node the same way others would.

In the DSP code for the AKAmplitudeTracker an RMS value is calculated for each channel and the result is briefly written to the output buffer but at the end of the for loop the node is essentially bypassed by setting the output to the original input:

```<code>void process(AUAudioFrameCount frameCount, AUAudioFrameCount bufferOffset) override {

    for (int frameIndex = 0; frameIndex < frameCount; ++frameIndex) {

        int frameOffset = int(frameIndex + bufferOffset);

        for (int channel = 0; channel < channels; ++channel) {
            float *in  = (float *)inBufferListPtr->mBuffers[channel].mData  + frameOffset;
            float temp = *in;
            float *out = (float *)outBufferListPtr->mBuffers[channel].mData + frameOffset;
            if (channel == 0) {
                if (started) {
                    sp_rms_compute(sp, leftRMS, in, out);
                    leftAmplitude = *out;
                } else {
                    leftAmplitude = 0;
                }
            } else {
                if (started) {
                    sp_rms_compute(sp, rightRMS, in, out);
                    rightAmplitude = *out;
                } else {
                    rightAmplitude = 0;
                }
            }
            *out = temp;
        }
    }
}
</code>```

This makes sense since outputting the RMS value to the device speakers would sound terrible but when this node is used as the input to the AKNodeOutputPlot object RMS values are plotted.

I assumed that the leftAmplitude and rightAmplitude variables were being referenced somewhere but even if they are zeroed out the plot works just fine.  I'm interested in doing some work on the signal without effecting the output so I'd love it someone could help me figure how the AKPlot is grabbing this data.

Cheers

答:
AKNodeOutputPlot works with something called a "tap":

https://github.com/AudioKit/AudioKit/blob/master/AudioKit/Common/User%20Interface/AKNodeOutputPlot.swift

There are also a few other taps that are not necessarily just for user interface purposes:

https://github.com/AudioKit/AudioKit/tree/master/AudioKit/Common/Taps

Taps allow you to inspect the data being pulled through another node without being inserted into the signal chain itself.

Body:
I'm very new to the AudioKit framework and I have been trying to understand a bit more about the DSP side to it.   Whilst rummaging around in the source code I realised that AKNodeOutputPlot does not pull data from the node the same way others would.

In the DSP code for the AKAmplitudeTracker an RMS value is calculated for each channel and the result is briefly written to the output buffer but at the end of the for loop the node is essentially bypassed by setting the output to the original input:

void process(AUAudioFrameCount frameCount, AUAudioFrameCount bufferOffset) override {

    for (int frameIndex = 0; frameIndex < frameCount; ++frameIndex) {

        int frameOffset = int(frameIndex + bufferOffset);

        for (int channel = 0; channel < channels; ++channel) {
            float *in  = (float *)inBufferListPtr->mBuffers[channel].mData  + frameOffset;
            float temp = *in;
            float *out = (float *)outBufferListPtr->mBuffers[channel].mData + frameOffset;
            if (channel == 0) {
                if (started) {
                    sp_rms_compute(sp, leftRMS, in, out);
                    leftAmplitude = *out;
                } else {
                    leftAmplitude = 0;
                }
            } else {
                if (started) {
                    sp_rms_compute(sp, rightRMS, in, out);
                    rightAmplitude = *out;
                } else {
                    rightAmplitude = 0;
                }
            }
            *out = temp;
        }
    }
}

This makes sense since outputting the RMS value to the device speakers would sound terrible but when this node is used as the input to the AKNodeOutputPlot object RMS values are plotted.

I assumed that the leftAmplitude and rightAmplitude variables were being referenced somewhere but even if they are zeroed out the plot works just fine.  I'm interested in doing some work on the signal without effecting the output so I'd love it someone could help me figure how the AKPlot is grabbing this data.

Cheers


问:
cfftp : Copy and move file remotely?
I need to copy files from one folder to the another on the same sftp server. My code currently copies the files locally and reuploads them.

```<code><cfftp
  action  = "open"
  username = "#APPLICATION.intxml.SFTPUSERNAME#"
  password = "#APPLICATION.intxml.SFTPPASSWORD#"
  connection = "sftpcon"
  server  = "#APPLICATION.intxml.SFTPADDRESS#"
  port   = "#APPLICATION.intxml.SFTPPORT#"
  timeout  = "#APPLICATION.pageTimeout#"
  secure  = "#sftp#"/>

 <cfif cfftp.succeeded>

  <cfftp action = "LISTDIR" stopOnError = "No" name = "ListFiles" directory = "/#sfolder#" connection = "sftpcon"/>

     <cfloop query=getFiles>
      <cfftp  action    = "GETFILE"
        stopOnError  = "Yes"
        name    = "theFile"
        transferMode  = "binary"
        timeout   = 3600
        retrycount  = 10
        remoteFile  = "#sfolder##name#"
        localFile  = "#dfolder#/#name#"
        failIfExists = "no"
        connection   = "sftpcon">

      <cfftp  action    = "PUTFILE"
        stopOnError  = "Yes"
        name    = "theFile"
        transferMode  = "binary"
        timeout   = 3600
        retrycount  = 10
        localfile  = "#sfolder##name#"
        remoteFile  = "#dfolder#/#name#"
        failIfExists = "no"
        connection   = "sftpcon">

     </cfloop>

    </cfif>

 <cfftp action = "close"
      connection = "sftpcon"
      stopOnError = "Yes">
</code>```

Is there a better way to do this with coldfusion?

答: Found out that the ftp protocol does not provide a way to remotely copy a file into another folder and keep the original. That precludes coldfusion from providing a solution. Moving files on the other hand can be done with a rename. See the other answer and comments on the original question.</p>

Title: cfftp : Copy and move file remotely?

Body:
I need to copy files from one folder to the another on the same sftp server. My code currently copies the files locally and reuploads them.

<cfftp
  action  = "open"
  username = "#APPLICATION.intxml.SFTPUSERNAME#"
  password = "#APPLICATION.intxml.SFTPPASSWORD#"
  connection = "sftpcon"
  server  = "#APPLICATION.intxml.SFTPADDRESS#"
  port   = "#APPLICATION.intxml.SFTPPORT#"
  timeout  = "#APPLICATION.pageTimeout#"
  secure  = "#sftp#"/>

 <cfif cfftp.succeeded>

  <cfftp action = "LISTDIR" stopOnError = "No" name = "ListFiles" directory = "/#sfolder#" connection = "sftpcon"/>

     <cfloop query=getFiles>
      <cfftp  action    = "GETFILE"
        stopOnError  = "Yes"
        name    = "theFile"
        transferMode  = "binary"
        timeout   = 3600
        retrycount  = 10
        remoteFile  = "#sfolder##name#"
        localFile  = "#dfolder#/#name#"
        failIfExists = "no"
        connection   = "sftpcon">

      <cfftp  action    = "PUTFILE"
        stopOnError  = "Yes"
        name    = "theFile"
        transferMode  = "binary"
        timeout   = 3600
        retrycount  = 10
        localfile  = "#sfolder##name#"
        remoteFile  = "#dfolder#/#name#"
        failIfExists = "no"
        connection   = "sftpcon">

     </cfloop>

    </cfif>

 <cfftp action = "close"
      connection = "sftpcon"
      stopOnError = "Yes">

Is there a better way to do this with coldfusion?


问:
How to get record with like statement in c#
Hi I have get the record in dynamic created table in .cs page and I know how should I can get the record with specific id as below

```<code>string searchExpression = "ID = 5"
DataRow[] foundRows = YourDataTable.Select(searchExpression);
</code>```

Now you can loop through the results, like this:

```<code>foreach(DataRow dr in foundRows)
{

}
</code>```

But I don't know how can I write like statement on .cs page.

I had tried as below but not working

```<code>string searchExpression = "ID like'%5%'"
DataRow[] foundRows = YourDataTable.Select(searchExpression);
</code>```

答:
You will have to do:

```<code>string searchExpression = "ID like'*5*'";
</code>```

To make it more reusable, concat it. Like:

```<code>string searchExpression = "ID like '*" + fromParameter + "*'";
</code>```

I think it throws exception if you search for "*" itself, cant remember properly though. Please test that case.

Please refer to the article at: http://www.csharp-examples.net/dataview-rowfilter/
on how to write expression for filtering/selecting.

Copied from the link above:

If a column name contains any of these special characters ~ ( ) # \ / = > < + - * % & | ^ ' " [ ], you must enclose the column name within square brackets [ ]. If a column name contains right bracket ] or backslash \, escape it with backslash (] or \).

```<code>dataView.RowFilter = "Num = 10"             // number is equal to 10
dataView.RowFilter = "Date < #1/1/2008#"    // date is less than 1/1/2008
dataView.RowFilter = "Name <> 'John'"       // string is not equal to 'John'
dataView.RowFilter = "Id IN (1, 2, 3)"                    // integer values
dataView.RowFilter = "Price IN (1.0, 9.9, 11.5)"          // float values
dataView.RowFilter = "Name IN ('John', 'Jim', 'Tom')"     // string values
dataView.RowFilter = "Date IN (#12/31/2008#, #1/1/2009#)" // date time values
dataView.RowFilter = "Name LIKE 'j*'"       // values that start with 'j'
dataView.RowFilter = "Name LIKE '%jo%'"     // values that contain 'jo'
</code>```

Body:
Hi I have get the record in dynamic created table in .cs page and I know how should I can get the record with specific id as below

string searchExpression = "ID = 5"
DataRow[] foundRows = YourDataTable.Select(searchExpression);

Now you can loop through the results, like this:

foreach(DataRow dr in foundRows)
{

}

But I don't know how can I write like statement on .cs page.

I had tried as below but not working

string searchExpression = "ID like'%5%'"
DataRow[] foundRows = YourDataTable.Select(searchExpression);

Body:
You will have to do:

string searchExpression = "ID like'*5*'";

To make it more reusable, concat it. Like:

string searchExpression = "ID like '*" + fromParameter + "*'";

I think it throws exception if you search for "*" itself, cant remember properly though. Please test that case.

Please refer to the article at: http://www.csharp-examples.net/dataview-rowfilter/
on how to write expression for filtering/selecting.

Copied from the link above:

If a column name contains any of these special characters ~ ( ) # \ / = > < + - * % & | ^ ' " [ ], you must enclose the column name within square brackets [ ]. If a column name contains right bracket ] or backslash \, escape it with backslash (] or \).

dataView.RowFilter = "Num = 10"             // number is equal to 10
dataView.RowFilter = "Date < #1/1/2008#"    // date is less than 1/1/2008
dataView.RowFilter = "Name <> 'John'"       // string is not equal to 'John'
dataView.RowFilter = "Id IN (1, 2, 3)"                    // integer values
dataView.RowFilter = "Price IN (1.0, 9.9, 11.5)"          // float values
dataView.RowFilter = "Name IN ('John', 'Jim', 'Tom')"     // string values
dataView.RowFilter = "Date IN (#12/31/2008#, #1/1/2009#)" // date time values
dataView.RowFilter = "Name LIKE 'j*'"       // values that start with 'j'
dataView.RowFilter = "Name LIKE '%jo%'"     // values that contain 'jo'


问:
jQuery's closest doesn't work in IE8/9
I have this jQuery code:

```<code>$(this).closest('div:has(.FIND_ME)').find('.FIND_ME').hide();
</code>```

But element with class .FIND_ME doesn't hide in IE8 and 9.

This question is a continuation of Search for an item with a common ancestor

HTML:

```<code><div>
    <div><!-- all div without ID -->
        <span>some text</span>
        <div>
          <span id="listener1">click here</span>
          <span>sometext</span></div>
        <div>

        <span class="FIND_ME">Result Here</span></div>
    </div>

    <div>
        <span>some text</span>
        <div id="div1">
         <div id="div2">
          <span id="listener2">click here</span>
          <span>sometext</span></div>
         </div>
        <div>

        <span class="FIND_ME">Result Here</span></div>
    </div>
</div>
</code>```

答:
```<code>closest = function (target, tag) {
    if (target.parentElement == "undefined") {
        return null;
    }
    if (target.parentElement.localName == tag) {
        return target.parentElement;
    }
    return this.closest(target.parentElement, tag);
};
</code>```

Title: jQuery's closest doesn't work in IE8/9

Body:
I have this jQuery code:

$(this).closest('div:has(.FIND_ME)').find('.FIND_ME').hide();

But element with class .FIND_ME doesn't hide in IE8 and 9.

This question is a continuation of Search for an item with a common ancestor

HTML:

        some text

          click here
          sometext

        Result Here

        some text

          click here
          sometext

        Result Here


问:
how to execute count query in sqlite and gets int as number of rows
i want to retrieve counted number of rows saved in database with where clause , in SQlite, i am beginner and confused to execute this sql query

```<code>Select Count(*) From " + Table_Seekers + " where " + Uid + " = " + Table_Seekers
</code>```

i want to get number of counted rows in db where incoming Uid is same in db ? so any one please help.

```<code>public void getReqMade(String Uid) {
    SQLiteDatabase database = getReadableDatabase();
    database.execSQL("Select Count(*) From " + Table_Seekers + " where " + Uid + " = " + Table_Seekers);
}
</code>```

答:
If Table_Seekers is the name of the table and Uid is what you are searching then

```<code>Select Count(*) From Table_Seekers where Table_Seekers_field = Uid
</code>```

Also you should name the arguments of your methods starting by a lowercase.

Body:
i want to retrieve counted number of rows saved in database with where clause , in SQlite, i am beginner and confused to execute this sql query

Select Count(*) From " + Table_Seekers + " where " + Uid + " = " + Table_Seekers

i want to get number of counted rows in db where incoming Uid is same in db ? so any one please help.

public void getReqMade(String Uid) {
    SQLiteDatabase database = getReadableDatabase();
    database.execSQL("Select Count(*) From " + Table_Seekers + " where " + Uid + " = " + Table_Seekers);
}

Body:
If Table_Seekers is the name of the table and Uid is what you are searching then

Select Count(*) From Table_Seekers where Table_Seekers_field = Uid

Also you should name the arguments of your methods starting by a lowercase.


问:
theano GPU support: PTX JIT compiler library not found
I am installing libgpuarray v0.7.4. When I import theano, I got the following errors:
I am using the version of:

(1) Theano from github (rel-1.0.0rc1),

(2) CUDA 9.0
(I am sure CUDA / cusolver works, I installed pycuda, scikit-cuda and could run them successfully)

(3) cuDNN 7.0.3

(4) nvidia driver 384.90

```<code>Python 3.5.2 (default, Sep 14 2017, 22:51:06)
[GCC 5.4.0 20160609] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import theano
Using cuDNN version 7003 on context None
ERROR (theano.gpuarray): Could not initialize pygpu, support disabled
Traceback (most recent call last):
  File "/usr/local/lib/python3.5/dist-packages/Theano-1.0.0rc1-py3.5.egg/theano/gpuarray/__init__.py", line 220, in <module>
    use(config.device)
  File "/usr/local/lib/python3.5/dist-packages/Theano-1.0.0rc1-py3.5.egg/theano/gpuarray/__init__.py", line 207, in use
    init_dev(device, preallocate=preallocate)
  File "/usr/local/lib/python3.5/dist-packages/Theano-1.0.0rc1-py3.5.egg/theano/gpuarray/__init__.py", line 152, in init_dev
    pygpu.blas.gemm(0, tmp, tmp, 0, tmp, overwrite_c=True)
  File "pygpu/blas.pyx", line 149, in pygpu.blas.gemm
  File "pygpu/blas.pyx", line 47, in pygpu.blas.pygpu_blas_rgemm
pygpu.gpuarray.GpuArrayException: (b'cuLinkCreate: CUDA_ERROR_JIT_COMPILER_NOT_FOUND: PTX JIT compiler library not found', 3)
</code>```

Any idea on how to resolve it?
I want to make use of the GPU support of theano

EDIT (reply to talonmies)

I think pygpu could create a context over my GPU:

```<code>$ DEVICE=cuda python3
Python 3.5.2 (default, Sep 14 2017, 22:51:06)
[GCC 5.4.0 20160609] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import pygpu
>>> pygpu.test()
pygpu is installed in /usr/local/lib/python3.5/dist-packages/pygpu-0.7.4-py3.5-linux-x86_64.egg/pygpu
NumPy version 1.13.3
NumPy relaxed strides checking option: True
NumPy is installed in /usr/local/lib/python3.5/dist-packages/numpy-1.13.3-py3.5-linux-x86_64.egg/numpy
Python version 3.5.2 (default, Sep 14 2017, 22:51:06) [GCC 5.4.0 20160609]
nose version 1.3.7
*** Testing for GeForce GTX TITAN Black
mpi4py found: False
.EEEEEEEEEEEEEEEEEEEEEEEEEEE
</code>```

On the other hand, run nvidia-smi

```<code>Mon Nov 13 15:39:35 2017
+-----------------------------------------------------------------------------+
| NVIDIA-SMI 384.90                 Driver Version: 384.90                    |
|-------------------------------+----------------------+----------------------+
| GPU  Name        Persistence-M| Bus-Id        Disp.A | Volatile Uncorr. ECC |
| Fan  Temp  Perf  Pwr:Usage/Cap|         Memory-Usage | GPU-Util  Compute M. |
|===============================+======================+======================|
|   0  GeForce GTX TIT...  Off  | 00000000:01:00.0 Off |                  N/A |
| 28%   47C    P2    94W / 250W |    102MiB /  6082MiB |      0%      Default |
+-------------------------------+----------------------+----------------------+

+-----------------------------------------------------------------------------+
| Processes:                                                       GPU Memory |
|  GPU       PID   Type   Process name                             Usage      |
|=============================================================================|
|    0      5562      C   python3                                       91MiB |
+-----------------------------------------------------------------------------+
</code>```

I traced the code and found that the error appear from BLAS GEMM. I think there is no compiled code of my GPU and libgpuarray needs to compile on my machine. But somehow it cannot find the compiler.

END OF EDIT

答:
I was experiencing similar issues, but I needed to create symlinks

libnvidia-ptxjitcompiler.so.384.81

to point to

libnvidia-ptxjitcompiler.so.1
libnvidia-ptxjitcompiler.so

Body:
I am installing libgpuarray v0.7.4. When I import theano, I got the following errors:
I am using the version of:

(1) Theano from github (rel-1.0.0rc1),

(2) CUDA 9.0
(I am sure CUDA / cusolver works, I installed pycuda, scikit-cuda and could run them successfully)

(3) cuDNN 7.0.3

(4) nvidia driver 384.90

Python 3.5.2 (default, Sep 14 2017, 22:51:06)
[GCC 5.4.0 20160609] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import theano
Using cuDNN version 7003 on context None
ERROR (theano.gpuarray): Could not initialize pygpu, support disabled
Traceback (most recent call last):
  File "/usr/local/lib/python3.5/dist-packages/Theano-1.0.0rc1-py3.5.egg/theano/gpuarray/__init__.py", line 220, in <module>
    use(config.device)
  File "/usr/local/lib/python3.5/dist-packages/Theano-1.0.0rc1-py3.5.egg/theano/gpuarray/__init__.py", line 207, in use
    init_dev(device, preallocate=preallocate)
  File "/usr/local/lib/python3.5/dist-packages/Theano-1.0.0rc1-py3.5.egg/theano/gpuarray/__init__.py", line 152, in init_dev
    pygpu.blas.gemm(0, tmp, tmp, 0, tmp, overwrite_c=True)
  File "pygpu/blas.pyx", line 149, in pygpu.blas.gemm
  File "pygpu/blas.pyx", line 47, in pygpu.blas.pygpu_blas_rgemm
pygpu.gpuarray.GpuArrayException: (b'cuLinkCreate: CUDA_ERROR_JIT_COMPILER_NOT_FOUND: PTX JIT compiler library not found', 3)

Any idea on how to resolve it?
I want to make use of the GPU support of theano

EDIT (reply to talonmies)

I think pygpu could create a context over my GPU:

$ DEVICE=cuda python3
Python 3.5.2 (default, Sep 14 2017, 22:51:06)
[GCC 5.4.0 20160609] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import pygpu
>>> pygpu.test()
pygpu is installed in /usr/local/lib/python3.5/dist-packages/pygpu-0.7.4-py3.5-linux-x86_64.egg/pygpu
NumPy version 1.13.3
NumPy relaxed strides checking option: True
NumPy is installed in /usr/local/lib/python3.5/dist-packages/numpy-1.13.3-py3.5-linux-x86_64.egg/numpy
Python version 3.5.2 (default, Sep 14 2017, 22:51:06) [GCC 5.4.0 20160609]
nose version 1.3.7
*** Testing for GeForce GTX TITAN Black
mpi4py found: False
.EEEEEEEEEEEEEEEEEEEEEEEEEEE

On the other hand, run nvidia-smi

Mon Nov 13 15:39:35 2017
+-----------------------------------------------------------------------------+
| NVIDIA-SMI 384.90                 Driver Version: 384.90                    |
|-------------------------------+----------------------+----------------------+
| GPU  Name        Persistence-M| Bus-Id        Disp.A | Volatile Uncorr. ECC |
| Fan  Temp  Perf  Pwr:Usage/Cap|         Memory-Usage | GPU-Util  Compute M. |
|===============================+======================+======================|
|   0  GeForce GTX TIT...  Off  | 00000000:01:00.0 Off |                  N/A |
| 28%   47C    P2    94W / 250W |    102MiB /  6082MiB |      0%      Default |
+-------------------------------+----------------------+----------------------+

+-----------------------------------------------------------------------------+
| Processes:                                                       GPU Memory |
|  GPU       PID   Type   Process name                             Usage      |
|=============================================================================|
|    0      5562      C   python3                                       91MiB |
+-----------------------------------------------------------------------------+

I traced the code and found that the error appear from BLAS GEMM. I think there is no compiled code of my GPU and libgpuarray needs to compile on my machine. But somehow it cannot find the compiler.

END OF EDIT


问:
Is there a way to check for empty arrays returned from ActiveRecord queries?
I want to write an activerecord query that behaves something like this:

```<code>User.joins(:comment).where(comments: {replies: []})
</code>```

which returns Users where their comments have no replies.

```<code>User.first.comment.first.replies => [] returns an empty array
</code>```

I need this to be an activerecord relation only, so using ruby code won't work. Is there a way to check for empty arrays using activerecord?

Edit:
Example schema

```<code>create_table "users", force: :cascade do |t|
t.string "email",
t.string "password"
end

create_table "comments" do |t|
t.string "content"
end

create_table "replies" do |t|
t.string "content"
end
</code>```

User.rb

```<code>class User < ActiveRecord::Base
has_many :comments
end
</code>```

Comment.rb

```<code>class Comment < ActiveRecord::Base
belongs_to :user
has_many :replies
end
</code>```

Reply.rb

```<code>class Reply < ActiveRecord::Base
belongs_to :comment
belongs_to :user
end
</code>```

These are just example models but this should illustrate the problem with models associated this these.

So if a user(with id of 1) has made 3 comments, and only 1 of those 3 comments has a reply on it, how would I get the other 2 comments in an activerecord relation?

答:
You need to use a LEFT JOIN from comments to replies which will return all comments regardless of whether or not there was a reply for every comment.  The usual join in rails, i.e. join executed when you do @comment.replies or User.joins(comments: :replies) is an INNER JOIN.  ActiveRecord doesn't have a nifty DSL for writing left join queries, but does allow them in the following way:

```<code># Find all users who have at least one comment with no replies
User.joins(:comments)
  .joins("LEFT JOIN replies ON replies.comment_id = comments.id")
  .where("replies.id IS NULL")

# Find all comments for a user that don't have replies
@user.comments
  .joins("LEFT JOIN replies ON replies.comment_id = comments.id")
  .where("replies.id IS NULL")
</code>```

I included the two snippets because in your question it was unclear if you wanted to find the users or the comments for a certain user with no replies.

The where("replies.id IS NULL") is the filter which finds every comment in the LEFT JOIN with no  matching replies, and delivers the result you want.  This is a very common SQL trick worth keeping in mind for future data digging.

Body:
I want to write an activerecord query that behaves something like this:

User.joins(:comment).where(comments: {replies: []})

which returns Users where their comments have no replies.

User.first.comment.first.replies => [] returns an empty array

I need this to be an activerecord relation only, so using ruby code won't work. Is there a way to check for empty arrays using activerecord?

Edit:
Example schema

create_table "users", force: :cascade do |t|
t.string "email",
t.string "password"
end

create_table "comments" do |t|
t.string "content"
end

create_table "replies" do |t|
t.string "content"
end

User.rb

class User < ActiveRecord::Base
has_many :comments
end

Comment.rb

class Comment < ActiveRecord::Base
belongs_to :user
has_many :replies
end

Reply.rb

class Reply < ActiveRecord::Base
belongs_to :comment
belongs_to :user
end

These are just example models but this should illustrate the problem with models associated this these.

So if a user(with id of 1) has made 3 comments, and only 1 of those 3 comments has a reply on it, how would I get the other 2 comments in an activerecord relation?

Body:
You need to use a LEFT JOIN from comments to replies which will return all comments regardless of whether or not there was a reply for every comment.  The usual join in rails, i.e. join executed when you do @comment.replies or User.joins(comments: :replies) is an INNER JOIN.  ActiveRecord doesn't have a nifty DSL for writing left join queries, but does allow them in the following way:

# Find all users who have at least one comment with no replies
User.joins(:comments)
  .joins("LEFT JOIN replies ON replies.comment_id = comments.id")
  .where("replies.id IS NULL")

# Find all comments for a user that don't have replies
@user.comments
  .joins("LEFT JOIN replies ON replies.comment_id = comments.id")
  .where("replies.id IS NULL")

I included the two snippets because in your question it was unclear if you wanted to find the users or the comments for a certain user with no replies.

The where("replies.id IS NULL") is the filter which finds every comment in the LEFT JOIN with no  matching replies, and delivers the result you want.  This is a very common SQL trick worth keeping in mind for future data digging.


问:
Large eCommerce site: Is it time for HTML5?
I currently work for a large company and I design for their high-traffic ecommerce website. We support tens-of-thousands of users across a variety of browsers. Our current browser stats point to most people using either Firefox 3+ and IE8. There are about 5% of users still on IE6.

Is it time to start coding for the future and impliment HTML5 across the site? Is it a responsible thing to do or should I wait a year for people to upgrade to better supporting browsers?

Thank you.

答:
HTML5 isn't one specific thing. You can start using it even in browsers that have no idea what HTML5 is. If you just start using some of the extra tags or form types, they degrade perfectly into standard elements in older browsers. Video needs a Flash fallback anyway. The advanced scripting features all need fallbacks for non-supporting browsers anyway, or must only add non-essential functionality.

In short, sure, start using HTML5 techniques now to provide advantages for cutting-edge browsers, just make sure it all degrades nicely in older browsers.