问:
Disable back-page button in browser
I create auth app with routing in angular 2 with typescript. And now my task is disabled back button in browser from form localhost/form1 to localhost/login; how implement this?

答:
I solved this in my angular cordova app to prevent app from exiting as following. Contrary to most comments I've found I had to use the "document" object instead of the "window" object to capture the backbutton event

```<code>// Prevent from exiting app by hook into document backbutton
@HostListener('document:backbutton', ['$event'])
    onPopState(event) {
    alert('Start page');
}
</code>```

Usage in a component

```<code>import { Component, HostListener  } from '@angular/core';

export class myComponent {
    constructor() {}

    // Prevent from exiting app by hook into document backbutton
    @HostListener('document:backbutton', ['$event'])
       onPopState(event) {
       alert('Start page');
    }
}
</code>```

Title: Disable back-page button in browser

Body:
I solved this in my angular cordova app to prevent app from exiting as following. Contrary to most comments I've found I had to use the "document" object instead of the "window" object to capture the backbutton event

// Prevent from exiting app by hook into document backbutton
@HostListener('document:backbutton', ['$event'])
    onPopState(event) {
    alert('Start page');
}

Usage in a component

import { Component, HostListener  } from '@angular/core';

export class myComponent {
    constructor() {}

    // Prevent from exiting app by hook into document backbutton
    @HostListener('document:backbutton', ['$event'])
       onPopState(event) {
       alert('Start page');
    }
}


来源: stackexchange

问:
Appcelerator: Detect when user presses home button (iOS & Android)
I want to detect when the user presses the home button in Android and iOS and then logout from the session. Is there any way to do that?

On iOS I tried to use the Titanium.App.pause listener and it works when I press the home button, but the problem is that this listener is also triggered when I do other things inside the app, like opening the gallery or the camera from the app or even using the control center.

On Android I tried a similar thing. But I'm facing the same problem.

答:
There is subtle difference between pause and paused eventlisteners. Paused only detect when pressed home button on iPhone while pause always trigger when there is some interruptions into app like showing alert. Have a look into docs.
http://docs.appcelerator.com/platform/latest/#!/api/Titanium.App-event-pause
http://docs.appcelerator.com/platform/latest/#!/api/Titanium.App-event-paused

You can use whatever depending upon your requirement. For Android have look into this post that might be helpful for pause/resume Android.

http://www.tidev.io/2014/01/28/paused-resumed-events-on-android/

ContentLicense: CC BY-SA 3.0


问:
insert combined value into the database
I fetch total_amount value and insert into another table but i want to insert total_amount in one field and seperated by ",". How to do that?

I know Mysqli is latest version . but here mysql is working properly.

```<code><?php
include('database/db.php');
if ($_SERVER['REQUEST_METHOD'] == 'POST')
{
$sql1="Insert into test(`total_amount`) values ('{$_POST['i']}')";
$result1=mysql_query($sql1);
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Edit Page</title>
</head>
<body>
<form name="" action="<?php $_SERVER['PHP_SELF'] ?>" method="post">
<table>
<tr>
<td>Total Amount</td>
</tr>
<?php
$sql="Select * from tes1";
$result=mysql_query($sql);
while($dtset=mysql_fetch_array($result))
{
?>
<tr>
<td><input type="hidden" name="i" value="<?php echo $dtset['total_amount'];
?>"><?php echo $dtset['total_amount']; ?></td>
</tr>
<?php } ?>
</table>
<input type="submit" name="submit" value="submit">
</form>
</body>
</html>
</code>```

答:
```<code><?php
$sql="Select * from tes1";
$result=mysql_query($sql);
// Empty array
$amounts = [];
while($dtset=mysql_fetch_array($result))
{
    // Push the amounts to the array.
    $amounts[] = $dtset['total_amount'];
}
// Implode will create a string from your array and seperates it with
// the chosen character
$combined = implode(",",$amounts);
?>
<tr>
    <td>
        <input type="hidden" name="i" value="<?php echo
        $combined; ?>">
    <?php echo $combined; ?>
    </td>
</tr>
</code>```

The while loop is now not part of the table row, but instead creates the array with all values first and then you can add the string created by implode to your hidden form field.

Title: insert combined value into the database

Body:
I fetch total_amount value and insert into another table but i want to insert total_amount in one field and seperated by ",". How to do that?

I know Mysqli is latest version . but here mysql is working properly.

<?php
include('database/db.php');
if ($_SERVER['REQUEST_METHOD'] == 'POST')
{
$sql1="Insert into test(`total_amount`) values ('{$_POST['i']}')";
$result1=mysql_query($sql1);
}
?>
<!DOCTYPE html>

<title>Edit Page</title>

<form name="" action="<?php $_SERVER['PHP_SELF'] ?>" method="post">

Total Amount

<?php
$sql="Select * from tes1";
$result=mysql_query($sql);
while($dtset=mysql_fetch_array($result))
{
?>

<input type="hidden" name="i" value="<?php echo $dtset['total_amount'];
?>"><?php echo $dtset['total_amount']; ?>

<?php } ?>

<input type="submit" name="submit" value="submit">
</form>

Body:
<?php
$sql="Select * from tes1";
$result=mysql_query($sql);
// Empty array
$amounts = [];
while($dtset=mysql_fetch_array($result))
{
    // Push the amounts to the array.
    $amounts[] = $dtset['total_amount'];
}
// Implode will create a string from your array and seperates it with
// the chosen character
$combined = implode(",",$amounts);
?>
<tr>
    <td>
        <input type="hidden" name="i" value="<?php echo
        $combined; ?>">
    <?php echo $combined; ?>
    </td>
</tr>

The while loop is now not part of the table row, but instead creates the array with all values first and then you can add the string created by implode to your hidden form field.


问:
Access property after inheriting from an abstract class Java
I cannot access a field of a class that is a concrete type inheriting from an abstract class.

In Java I create a class of External student that extends Student

```<code> */
public class ExternalStudent extends Student  {
String currentSchool;

  public ExternalStudent(String name, Integer age, String studentIdentifier, String currentSchool) {
    super(name, age, studentIdentifier);
    this.currentSchool = currentSchool;
  }
}
</code>```

where student is

```<code>public abstract class Student {

    //Attributes
    String studentIdentifier;
    Integer age;
    String name;

    //Associations
    List<Subject> subject =  new ArrayList<Subject>();
    PersonalDetails personaldetails;

    //Methods
    public void setSubject () {
        this.subject.add(new Subject("Name"));
    }

    //Constructors
    public Student(String name, Integer age, String studentIdentifier){
       this.age = age;
       this.name = name;
       this.studentIdentifier = studentIdentifier;
    }
}
</code>```

and external student is set up by my class Application

```<code>public class ApplicationC {
    //Attributes
    private String personalStatement;
    private String applicationForm;

    //Associations
    Registration registration;
    Student student;
    ApplicationTest applicationtest;

    //Methods
    public void setApplicationResult(String result){
        this.applicationtest = new ApplicationTest(result);
    }

    //Constructor
    public ApplicationC (String personalStatement, String name){
        this.registration = new Registration();
        this.student = new ExternalStudent("Tom",16,"78954","DHS");
    }
}
</code>```

I've set up a simple test class

```<code>public void testPostCondition() throws ParseException{
 ApplicationC instance = new ApplicationC("test statement","test name");
    instance.setApplicationResult("pass");
    assertEquals("pass",instance.applicationtest.result);
         instance.student.age = 16;
     instance.student.studentIdentifier = "78954";
     instance.student.name = "Tom";
     instance.student.currentSchool = "test"; //Error as field does not exist
}
</code>```

But I cannot access the current school of the student instance (who must be an externalStudent). How can I access this field in order to test my code?

答:
Your instance is an AplicationC,

So, "instance.student" is a "Student".

"Student" does not have the "currentSchool" property.

to get to it

* add "currentSchool" property to "Student"

or

* cast your "instance.student" to "ExternalStudent"

note: you will need to handle all the exceptions and over-head of casting etc'

Hope this helps

Body:
I cannot access a field of a class that is a concrete type inheriting from an abstract class.

In Java I create a class of External student that extends Student

 */
public class ExternalStudent extends Student  {
String currentSchool;

  public ExternalStudent(String name, Integer age, String studentIdentifier, String currentSchool) {
    super(name, age, studentIdentifier);
    this.currentSchool = currentSchool;
  }
}

where student is

public abstract class Student {

    //Attributes
    String studentIdentifier;
    Integer age;
    String name;

    //Associations
    List<Subject> subject =  new ArrayList<Subject>();
    PersonalDetails personaldetails;

    //Methods
    public void setSubject () {
        this.subject.add(new Subject("Name"));
    }

    //Constructors
    public Student(String name, Integer age, String studentIdentifier){
       this.age = age;
       this.name = name;
       this.studentIdentifier = studentIdentifier;
    }
}

and external student is set up by my class Application

public class ApplicationC {
    //Attributes
    private String personalStatement;
    private String applicationForm;

    //Associations
    Registration registration;
    Student student;
    ApplicationTest applicationtest;

    //Methods
    public void setApplicationResult(String result){
        this.applicationtest = new ApplicationTest(result);
    }

    //Constructor
    public ApplicationC (String personalStatement, String name){
        this.registration = new Registration();
        this.student = new ExternalStudent("Tom",16,"78954","DHS");
    }
}

I've set up a simple test class

public void testPostCondition() throws ParseException{
 ApplicationC instance = new ApplicationC("test statement","test name");
    instance.setApplicationResult("pass");
    assertEquals("pass",instance.applicationtest.result);
         instance.student.age = 16;
     instance.student.studentIdentifier = "78954";
     instance.student.name = "Tom";
     instance.student.currentSchool = "test"; //Error as field does not exist
}

But I cannot access the current school of the student instance (who must be an externalStudent). How can I access this field in order to test my code?


问:
selenium grid for python error
i run selenium grid for python 3 on ubuntu virtualbox,
i setup a grid

java -jar selenium-server-standalone-3.4.0.jar -port 4444 -role hub

everything seems ok i get on terminal

INFO - Selenium Grid hub is up and running

i add a node

java -jar selenium-server-standalone-3.4.0.jar -role webdriver -browser "browserName=firefox,version=54,maxinstance=2,platform=LINUX" -hub http://localhost:4444/grid/register -port 5555

everything seems ok i get on terminal

INFO - The node is registered to the hub and ready to use

INFO - SessionCleaner initialized with insideBrowserTimeout 0 and clientGoneTimeout 1800000 polling every 180000

if i run this code with node address http://10.0.2.15:5555/wd/hub
everything works

```<code>PLATFORM = 'LINUX'
BROWSER = 'firefox'

     def setUp(self):
         desired_caps = {}
         desired_caps['platform'] = self.PLATFORM
        desired_caps['browserName'] = self.BROWSER
         self.driver = \
             webdriver.Remote('http://10.0.2.15:5555/wd/hub', desired_caps)
         self.driver.get("https://www.facebook.com/login/")
         self.driver.implicitly_wait(30)    self.driver.maximize_window()
</code>```

if i run the code above with the grid address http://10.0.2.15:4444/wd/hub  like it's supposed it has  to be i always get an error:

```<code>Error
Traceback (most recent call last):
  File "/home/thorbuntu/PycharmProjects/seletests/grid_test.py", line 21, in setUp
    webdriver.Remote('http://10.0.2.15:4444/wd/hub', desired_caps)
  File "/usr/local/lib/python3.5/dist-packages/selenium/webdriver/remote/webdriver.py", line 98, in __init__
    self.start_session(desired_capabilities, browser_profile)
  File "/usr/local/lib/python3.5/dist-packages/selenium/webdriver/remote/webdriver.py", line 188, in start_session
    response = self.execute(Command.NEW_SESSION, parameters)
  File "/usr/local/lib/python3.5/dist-packages/selenium/webdriver/remote/webdriver.py", line 256, in execute
    self.error_handler.check_response(response)
  File "/usr/local/lib/python3.5/dist-packages/selenium/webdriver/remote/errorhandler.py", line 194, in check_response
    raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.WebDriverException: Message: None
Stacktrace:
    at java.util.HashMap.putMapEntries (HashMap.java:500)
    at java.util.HashMap.putAll (HashMap.java:784)
    at org.openqa.selenium.remote.DesiredCapabilities.<init> (DesiredCapabilities.java:55)
    at org.openqa.grid.web.servlet.handler.RequestHandler.process (RequestHandler.java:104)
    at org.openqa.grid.web.servlet.DriverServlet.process (DriverServlet.java:83)
    at org.openqa.grid.web.servlet.DriverServlet.doPost (DriverServlet.java:67)
    at javax.servlet.http.HttpServlet.service (HttpServlet.java:707)
    at javax.servlet.http.HttpServlet.service (HttpServlet.java:790)
    at org.seleniumhq.jetty9.servlet.ServletHolder.handle (ServletHolder.java:841)
    at org.seleniumhq.jetty9.servlet.ServletHandler.doHandle (ServletHandler.java:543)
    at org.seleniumhq.jetty9.server.handler.ScopedHandler.nextHandle (ScopedHandler.java:188)
    at org.seleniumhq.jetty9.server.session.SessionHandler.doHandle (SessionHandler.java:1584)
    at org.seleniumhq.jetty9.server.handler.ScopedHandler.nextHandle (ScopedHandler.java:188)
    at org.seleniumhq.jetty9.server.handler.ContextHandler.doHandle (ContextHandler.java:1228)
    at org.seleniumhq.jetty9.server.handler.ScopedHandler.nextScope (ScopedHandler.java:168)
    at org.seleniumhq.jetty9.servlet.ServletHandler.doScope (ServletHandler.java:481)
    at org.seleniumhq.jetty9.server.session.SessionHandler.doScope (SessionHandler.java:1553)
    at org.seleniumhq.jetty9.server.handler.ScopedHandler.nextScope (ScopedHandler.java:166)
    at org.seleniumhq.jetty9.server.handler.ContextHandler.doScope (ContextHandler.java:1130)
    at org.seleniumhq.jetty9.server.handler.ScopedHandler.handle (ScopedHandler.java:141)
    at org.seleniumhq.jetty9.server.handler.HandlerWrapper.handle (HandlerWrapper.java:132)
    at org.seleniumhq.jetty9.server.Server.handle (Server.java:564)
    at org.seleniumhq.jetty9.server.HttpChannel.handle (HttpChannel.java:320)
    at org.seleniumhq.jetty9.server.HttpConnection.onFillable (HttpConnection.java:251)
    at org.seleniumhq.jetty9.io.AbstractConnection$ReadCallback.succeeded (AbstractConnection.java:279)
    at org.seleniumhq.jetty9.io.FillInterest.fillable (FillInterest.java:112)
    at org.seleniumhq.jetty9.io.ChannelEndPoint$2.run (ChannelEndPoint.java:124)
    at org.seleniumhq.jetty9.util.thread.QueuedThreadPool.runJob (QueuedThreadPool.java:672)
    at org.seleniumhq.jetty9.util.thread.QueuedThreadPool$2.run (QueuedThreadPool.java:590)
    at java.lang.Thread.run (Thread.java:748)
</code>```

where can be the problem i'm rinning ubuntu on virtualbox and selenium python

thanks a lot

答:
You may have actually stumbled into a bug in the Grid side (which has been fixed already but pending a release)

When your python client code instantiates a new Remote WebDriver via the below lines

```<code>desired_caps = {}
desired_caps['platform'] = self.PLATFORM
desired_caps['browserName'] = self.BROWSER

self.driver = webdriver.Remote('http://10.0.2.15:4444/wd/hub', desired_caps)
</code>```

This gets translated into a JSON payload of the below form

```<code>{
    "capabilities": {
        "alwaysMatch": {
            "browserName": "chrome"
        },
        "firstMatch": [

        ]
    },
    "desiredCapabilities": {
        "browserName": "chrome"
    }
}
</code>```

On the grid side (Selenium Grid v.3.4.0), the hub attempts at parsing this JSON into a desired capability using the below logic in org.openqa.grid.web.servlet.handler.WebDriverRequest#extractDesiredCapability:

```<code>public Map<String, Object> extractDesiredCapability() {
    String json = getBody();
    try {
      JsonObject map = new JsonParser().parse(json).getAsJsonObject();
      // Current W3C has required / desired capabilities wrapped in a 'capabilites' object.
      // This will need to be updated if/when https://github.com/w3c/webdriver/pull/327 gets merged
      if (map.has("capabilities")) {
        return new JsonToBeanConverter().convert(Map.class, map.getAsJsonObject("capabilities").getAsJsonObject("desiredCapabilities"));
      }
      JsonObject dc = map.get("desiredCapabilities").getAsJsonObject();
      return new JsonToBeanConverter().convert(Map.class, dc);

    } catch (Exception e) {
      throw new GridException("Cannot extract a capabilities from the request: " + json, e);
    }
}
</code>```

As you can see, this logic ends up returning a NULL value for the desired capabilities because :

In the JSON Payload, the element capabilities was found but
Within the JSON sub element capabilities, there was no sub element called desiredCapabilities

This causes a NULL map to be returned via extractDesiredCapability() and eventually triggers a NullPointerException.

I know that this has now been fixed in the Selenium Grid codebase as part of this commit which adds a Null Check guard before instantiating a HashMap and this commit ensures that the Grid basically checks if :

The JSON payload has a key called capabilities and

Within the key capabilities there's a subkey called desiredCapabilities before it attempts at extracting the capabilities as a map and if not just look for the key desiredCapabilities.

If on the other hand you point your test code directly to the node, it works fine, because none of this above mentioned parsing is involved when a test is routed to the node.

So for now I would suggest that you please roll back to using Selenium 2.53.1 of Grid till the next version (which contains both the above cited commits) is released.

Hope that helps.

Title: selenium grid for python error

Body:
i run selenium grid for python 3 on ubuntu virtualbox,
i setup a grid

java -jar selenium-server-standalone-3.4.0.jar -port 4444 -role hub

everything seems ok i get on terminal

INFO - Selenium Grid hub is up and running

i add a node

java -jar selenium-server-standalone-3.4.0.jar -role webdriver -browser "browserName=firefox,version=54,maxinstance=2,platform=LINUX" -hub http://localhost:4444/grid/register -port 5555

everything seems ok i get on terminal

INFO - The node is registered to the hub and ready to use

INFO - SessionCleaner initialized with insideBrowserTimeout 0 and clientGoneTimeout 1800000 polling every 180000

if i run this code with node address http://10.0.2.15:5555/wd/hub
everything works

PLATFORM = 'LINUX'
BROWSER = 'firefox'

     def setUp(self):
         desired_caps = {}
         desired_caps['platform'] = self.PLATFORM
        desired_caps['browserName'] = self.BROWSER
         self.driver = \
             webdriver.Remote('http://10.0.2.15:5555/wd/hub', desired_caps)
         self.driver.get("https://www.facebook.com/login/")
         self.driver.implicitly_wait(30)    self.driver.maximize_window()

if i run the code above with the grid address http://10.0.2.15:4444/wd/hub  like it's supposed it has  to be i always get an error:

Error
Traceback (most recent call last):
  File "/home/thorbuntu/PycharmProjects/seletests/grid_test.py", line 21, in setUp
    webdriver.Remote('http://10.0.2.15:4444/wd/hub', desired_caps)
  File "/usr/local/lib/python3.5/dist-packages/selenium/webdriver/remote/webdriver.py", line 98, in __init__
    self.start_session(desired_capabilities, browser_profile)
  File "/usr/local/lib/python3.5/dist-packages/selenium/webdriver/remote/webdriver.py", line 188, in start_session
    response = self.execute(Command.NEW_SESSION, parameters)
  File "/usr/local/lib/python3.5/dist-packages/selenium/webdriver/remote/webdriver.py", line 256, in execute
    self.error_handler.check_response(response)
  File "/usr/local/lib/python3.5/dist-packages/selenium/webdriver/remote/errorhandler.py", line 194, in check_response
    raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.WebDriverException: Message: None
Stacktrace:
    at java.util.HashMap.putMapEntries (HashMap.java:500)
    at java.util.HashMap.putAll (HashMap.java:784)
    at org.openqa.selenium.remote.DesiredCapabilities.<init> (DesiredCapabilities.java:55)
    at org.openqa.grid.web.servlet.handler.RequestHandler.process (RequestHandler.java:104)
    at org.openqa.grid.web.servlet.DriverServlet.process (DriverServlet.java:83)
    at org.openqa.grid.web.servlet.DriverServlet.doPost (DriverServlet.java:67)
    at javax.servlet.http.HttpServlet.service (HttpServlet.java:707)
    at javax.servlet.http.HttpServlet.service (HttpServlet.java:790)
    at org.seleniumhq.jetty9.servlet.ServletHolder.handle (ServletHolder.java:841)
    at org.seleniumhq.jetty9.servlet.ServletHandler.doHandle (ServletHandler.java:543)
    at org.seleniumhq.jetty9.server.handler.ScopedHandler.nextHandle (ScopedHandler.java:188)
    at org.seleniumhq.jetty9.server.session.SessionHandler.doHandle (SessionHandler.java:1584)
    at org.seleniumhq.jetty9.server.handler.ScopedHandler.nextHandle (ScopedHandler.java:188)
    at org.seleniumhq.jetty9.server.handler.ContextHandler.doHandle (ContextHandler.java:1228)
    at org.seleniumhq.jetty9.server.handler.ScopedHandler.nextScope (ScopedHandler.java:168)
    at org.seleniumhq.jetty9.servlet.ServletHandler.doScope (ServletHandler.java:481)
    at org.seleniumhq.jetty9.server.session.SessionHandler.doScope (SessionHandler.java:1553)
    at org.seleniumhq.jetty9.server.handler.ScopedHandler.nextScope (ScopedHandler.java:166)
    at org.seleniumhq.jetty9.server.handler.ContextHandler.doScope (ContextHandler.java:1130)
    at org.seleniumhq.jetty9.server.handler.ScopedHandler.handle (ScopedHandler.java:141)
    at org.seleniumhq.jetty9.server.handler.HandlerWrapper.handle (HandlerWrapper.java:132)
    at org.seleniumhq.jetty9.server.Server.handle (Server.java:564)
    at org.seleniumhq.jetty9.server.HttpChannel.handle (HttpChannel.java:320)
    at org.seleniumhq.jetty9.server.HttpConnection.onFillable (HttpConnection.java:251)
    at org.seleniumhq.jetty9.io.AbstractConnection$ReadCallback.succeeded (AbstractConnection.java:279)
    at org.seleniumhq.jetty9.io.FillInterest.fillable (FillInterest.java:112)
    at org.seleniumhq.jetty9.io.ChannelEndPoint$2.run (ChannelEndPoint.java:124)
    at org.seleniumhq.jetty9.util.thread.QueuedThreadPool.runJob (QueuedThreadPool.java:672)
    at org.seleniumhq.jetty9.util.thread.QueuedThreadPool$2.run (QueuedThreadPool.java:590)
    at java.lang.Thread.run (Thread.java:748)

where can be the problem i'm rinning ubuntu on virtualbox and selenium python

thanks a lot

Body:
You may have actually stumbled into a bug in the Grid side (which has been fixed already but pending a release)

When your python client code instantiates a new Remote WebDriver via the below lines

desired_caps = {}
desired_caps['platform'] = self.PLATFORM
desired_caps['browserName'] = self.BROWSER

self.driver = webdriver.Remote('http://10.0.2.15:4444/wd/hub', desired_caps)

This gets translated into a JSON payload of the below form

{
    "capabilities": {
        "alwaysMatch": {
            "browserName": "chrome"
        },
        "firstMatch": [

        ]
    },
    "desiredCapabilities": {
        "browserName": "chrome"
    }
}

On the grid side (Selenium Grid v.3.4.0), the hub attempts at parsing this JSON into a desired capability using the below logic in org.openqa.grid.web.servlet.handler.WebDriverRequest#extractDesiredCapability:

public Map<String, Object> extractDesiredCapability() {
    String json = getBody();
    try {
      JsonObject map = new JsonParser().parse(json).getAsJsonObject();
      // Current W3C has required / desired capabilities wrapped in a 'capabilites' object.
      // This will need to be updated if/when https://github.com/w3c/webdriver/pull/327 gets merged
      if (map.has("capabilities")) {
        return new JsonToBeanConverter().convert(Map.class, map.getAsJsonObject("capabilities").getAsJsonObject("desiredCapabilities"));
      }
      JsonObject dc = map.get("desiredCapabilities").getAsJsonObject();
      return new JsonToBeanConverter().convert(Map.class, dc);

    } catch (Exception e) {
      throw new GridException("Cannot extract a capabilities from the request: " + json, e);
    }
}

As you can see, this logic ends up returning a NULL value for the desired capabilities because :

In the JSON Payload, the element capabilities was found but
Within the JSON sub element capabilities, there was no sub element called desiredCapabilities

This causes a NULL map to be returned via extractDesiredCapability() and eventually triggers a NullPointerException.

I know that this has now been fixed in the Selenium Grid codebase as part of this commit which adds a Null Check guard before instantiating a HashMap and this commit ensures that the Grid basically checks if :

The JSON payload has a key called capabilities and

Within the key capabilities there's a subkey called desiredCapabilities before it attempts at extracting the capabilities as a map and if not just look for the key desiredCapabilities.

If on the other hand you point your test code directly to the node, it works fine, because none of this above mentioned parsing is involved when a test is routed to the node.

So for now I would suggest that you please roll back to using Selenium 2.53.1 of Grid till the next version (which contains both the above cited commits) is released.

Hope that helps.


问:
Stripe landing page setting not working
I'm currently taking an online course to make an airbnb like web application with ruby on rails. It utilizes Stripe for the payment and I want to make the landing page from my app to the Stripe a register page instead of a login page.

I'm completely following the tutorial that successfully makes the register page as the landing page with the below code.

stripe_landing: 'register'

But my landing page is still the login page. I googled the above code but all I could find was pages from 2-4 years ago. I wonder if Stripe changed it recently. (but hpar replied saying nothing has changed)

I put the whole code here... When I click the link to Stripe, it goes to stripe#oauth.

```<code>    class StripeController < ApplicationController
      # Connect yourself to a Stripe account.
      # Only works on the currently logged in user.
      # See app/services/stripe_oauth.rb for #oauth_url details.

      def oauth
        connector = StripeOauth.new( current_user )
        url, error = connector.oauth_url( redirect_uri: stripe_confirm_url )

        if url.nil?
          flash[:error] = error
          redirect_to manage_listing_payment_path( session[:listing_id] )
        else
          redirect_to url
        end
      end

    end
</code>```

then,

```<code>    class StripeOauth < Struct.new( :user )

      def oauth_url( params )
        url = client.authorize_url( {
          scope: 'read_write',
          stripe_landing: 'register',
          stripe_user: {
            email: user.email
          }
        }.merge( params ) )

        [ url, nil ]
      end

      # A simple OAuth2 client we can use to generate a URL
      # to redirect the user to as well as get an access token.
      # Used in #oauth_url and #verify!
      # see this docs https://github.com/intridea/oauth2
      def client
        @client ||= OAuth2::Client.new(
          ENV['STRIPE_CONNECT_CLIENT_ID'],
          Stripe.api_key,
          {
            site: 'https://connect.stripe.com',
            authorize_url: '/oauth/authorize',
            token_url: '/oauth/token'
          }
        ).auth_code
      end

    end
</code>```

The terminal says;

Started GET "/connect/oauth" for ::1 at 2017-07-09 00:37:55 +0800
Processing by StripeController#oauth as HTML
  User Load (0.1ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = ?  ORDER BY "users"."id" ASC LIMIT 1  [["id", 1]]
Redirected to https://connect.stripe.com/oauth/authorize?client_id=ca_AuidWGx68TXWlWO3d3UbWcRcuPqfSeNH&redirect_uri=http%3A%2F%2Flocalhost%3A3000%2Fconnect%2Fconfirm&response_type=code&scope=read_write&stripe_landing=register&stripe_user%5Bemail%5D=aaa%40gmail.com

so I think I get the right url here (same as the tutorial video gets). However, in Chrome, it actually goes to;

https://connect.stripe.com/login?redirect=%2Foauth%2Fauthorize%3Fclient_id%3Dca_AuidWGx68TXWlWO3d3UbWcRcuPqfSeNH%26redirect_uri%3Dhttp%253A%252F%252Flocalhost%253A3000%252Fconnect%252Fconfirm%26response_type%3Dcode%26scope%3Dread_write%26stripe_landing%3Dregister%26stripe_user%255Bemail%255D%3Daaa%2540gmail.com&force_login=true

Sorry for the poor explanation but it would be great if anyone can solve this mystery. Thanks a lot!

答: I tried on safari and it worked properly so I deleted related cookies on chrome and it worked.</p>

Title: Stripe landing page setting not working

Body:
I'm currently taking an online course to make an airbnb like web application with ruby on rails. It utilizes Stripe for the payment and I want to make the landing page from my app to the Stripe a register page instead of a login page.

I'm completely following the tutorial that successfully makes the register page as the landing page with the below code.

stripe_landing: 'register'

But my landing page is still the login page. I googled the above code but all I could find was pages from 2-4 years ago. I wonder if Stripe changed it recently. (but hpar replied saying nothing has changed)

I put the whole code here... When I click the link to Stripe, it goes to stripe#oauth.

    class StripeController < ApplicationController
      # Connect yourself to a Stripe account.
      # Only works on the currently logged in user.
      # See app/services/stripe_oauth.rb for #oauth_url details.

      def oauth
        connector = StripeOauth.new( current_user )
        url, error = connector.oauth_url( redirect_uri: stripe_confirm_url )

        if url.nil?
          flash[:error] = error
          redirect_to manage_listing_payment_path( session[:listing_id] )
        else
          redirect_to url
        end
      end

    end

then,

    class StripeOauth < Struct.new( :user )

      def oauth_url( params )
        url = client.authorize_url( {
          scope: 'read_write',
          stripe_landing: 'register',
          stripe_user: {
            email: user.email
          }
        }.merge( params ) )

        [ url, nil ]
      end

      # A simple OAuth2 client we can use to generate a URL
      # to redirect the user to as well as get an access token.
      # Used in #oauth_url and #verify!
      # see this docs https://github.com/intridea/oauth2
      def client
        @client ||= OAuth2::Client.new(
          ENV['STRIPE_CONNECT_CLIENT_ID'],
          Stripe.api_key,
          {
            site: 'https://connect.stripe.com',
            authorize_url: '/oauth/authorize',
            token_url: '/oauth/token'
          }
        ).auth_code
      end

    end

The terminal says;

Started GET "/connect/oauth" for ::1 at 2017-07-09 00:37:55 +0800
Processing by StripeController#oauth as HTML
  User Load (0.1ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = ?  ORDER BY "users"."id" ASC LIMIT 1  [["id", 1]]
Redirected to https://connect.stripe.com/oauth/authorize?client_id=ca_AuidWGx68TXWlWO3d3UbWcRcuPqfSeNH&redirect_uri=http%3A%2F%2Flocalhost%3A3000%2Fconnect%2Fconfirm&response_type=code&scope=read_write&stripe_landing=register&stripe_user%5Bemail%5D=aaa%40gmail.com

so I think I get the right url here (same as the tutorial video gets). However, in Chrome, it actually goes to;

https://connect.stripe.com/login?redirect=%2Foauth%2Fauthorize%3Fclient_id%3Dca_AuidWGx68TXWlWO3d3UbWcRcuPqfSeNH%26redirect_uri%3Dhttp%253A%252F%252Flocalhost%253A3000%252Fconnect%252Fconfirm%26response_type%3Dcode%26scope%3Dread_write%26stripe_landing%3Dregister%26stripe_user%255Bemail%255D%3Daaa%2540gmail.com&force_login=true

Sorry for the poor explanation but it would be great if anyone can solve this mystery. Thanks a lot!


问:
Best way to create instance of child object from parent object
I'm creating a child object from a parent object. So the scenario is that I have an object and a child object which adds a distance property for scenarios where I want to search. I've chosen to use inheritance as my UI works equivalently with either a search object or a list of objects not the result of a location search. So in this case inheritance seems a sensible choice.

As present I need to generate a new object MyObjectSearch from an instance of MyObject. At present I'm doing this in the constructor manually by setting properties one by one. I could use reflection but this would be slow. Is there a better way of achieving this kind of object enhancement?

Hopefully my code below illustrates the scenario.

```<code>public class MyObject {

    // Some properties and a location.
}

public class MyObjectSearch : MyObject {

    public double Distance { get; set; }

    public MyObjectSearch(MyObject obj) {
         base.Prop1 = obj.Prop1;
         base.Prop2 = obj.Prop2;
    }
}
</code>```

And my search function:

```<code>public List<MyObjectSearch> DoSearch(Location loc) {
  var myObjectSearchList = new List<MyObjectSearch>();

   foreach (var object in myObjectList) {
       var distance = getDistance();
       var myObjectSearch = new MyObjectSearch(object);
       myObjectSearch.Distance = distance;
       myObjectSearchList.add(myObjectSearch);
   }
   return myObjectSearchList;
}
</code>```

答:
There are libraries to handle this; but if you just want a quick implementation in a few places, I would definitely go for a "copy constructor" as previously suggested.

One interesting point not mentioned is that if an object is a subclass, then it can access the child's private variables from the within the parent!

So, on the parent add a CloneIntoChild method. In my example:

Order is the parent class

OrderSnapshot is the child class

_bestPrice is a non-readonly private member on Order. But Order can set it for OrderSnapshot.

Example:

```<code>public OrderSnapshot CloneIntoChild()
{
    OrderSnapshot sn = new OrderSnapshot()
    {
        _bestPrice = this._bestPrice,
        _closed = this._closed,
        _opened = this._opened,
        _state = this._state
    };
    return sn;
}
</code>```

NOTE: Readonly member variables MUST be set in the constructor, so you will have to use the child constructor to set these...

Although I don't like "up-sizing" generally, I use this approach a lot for analytic snapshots...

ContentLicense: CC BY-SA 4.0

Body:
I'm creating a child object from a parent object. So the scenario is that I have an object and a child object which adds a distance property for scenarios where I want to search. I've chosen to use inheritance as my UI works equivalently with either a search object or a list of objects not the result of a location search. So in this case inheritance seems a sensible choice.

As present I need to generate a new object MyObjectSearch from an instance of MyObject. At present I'm doing this in the constructor manually by setting properties one by one. I could use reflection but this would be slow. Is there a better way of achieving this kind of object enhancement?

Hopefully my code below illustrates the scenario.

public class MyObject {

    // Some properties and a location.
}

public class MyObjectSearch : MyObject {

    public double Distance { get; set; }

    public MyObjectSearch(MyObject obj) {
         base.Prop1 = obj.Prop1;
         base.Prop2 = obj.Prop2;
    }
}

And my search function:

public List<MyObjectSearch> DoSearch(Location loc) {
  var myObjectSearchList = new List<MyObjectSearch>();

   foreach (var object in myObjectList) {
       var distance = getDistance();
       var myObjectSearch = new MyObjectSearch(object);
       myObjectSearch.Distance = distance;
       myObjectSearchList.add(myObjectSearch);
   }
   return myObjectSearchList;
}

Body:
There are libraries to handle this; but if you just want a quick implementation in a few places, I would definitely go for a "copy constructor" as previously suggested.

One interesting point not mentioned is that if an object is a subclass, then it can access the child's private variables from the within the parent!

So, on the parent add a CloneIntoChild method. In my example:

Order is the parent class

OrderSnapshot is the child class

_bestPrice is a non-readonly private member on Order. But Order can set it for OrderSnapshot.

Example:

public OrderSnapshot CloneIntoChild()
{
    OrderSnapshot sn = new OrderSnapshot()
    {
        _bestPrice = this._bestPrice,
        _closed = this._closed,
        _opened = this._opened,
        _state = this._state
    };
    return sn;
}

NOTE: Readonly member variables MUST be set in the constructor, so you will have to use the child constructor to set these...

Although I don't like "up-sizing" generally, I use this approach a lot for analytic snapshots...


问:
The properties expression is not valid. The expression should represent a property
I have these two entities

```<code>public class Song : IPathHavingEntity
    {
        public int Id { get; set; }
        [Required]
        public string Path { get; set; }
        [Required]
        public virtual Album Album { get; set; }
        [Required]
        public int TrackNumber { get; set; }
    }

public class Album : IPathHavingEntity
    {
        public int Id { get; set; }
        [Required]
        public string Path { get; set; }
        public virtual IEnumerable<Song> Songs { get; set; }
        [Required]
        public int AlbumNumber { get; set; }
    }
</code>```

Path is defined in the IPathHavingEntity interface.

In my Seed method I want to add a song to the Songs table only if it doesn't exist.  For this reason I check that the album path and song path combination don't exist already before adding it thus

```<code>context.Songs.AddOrUpdate(
    s => new { FilePath = s.Path, AlbumPath = s.Album.Path },
    new Song { TrackNumber = 1, Path = "01 Intro.mp3", Album = one });
</code>```

The problem is I get this error

The properties expression 's => new <>f__AnonymousType0``2(FilePath =
s.Path, AlbumPath = s.Album.Path)' is not valid. The expression should
represent a   property: C#: 't => t.MyProperty'  VB.Net: 'Function(t) t.MyProperty'. When specifying multiple properties use an anonymous type: C#: 't => new { t.MyProperty1, t.MyProperty2 }'  VB.Net: 'Function(t) New With { t.MyProperty1, t.MyProperty2 }'.

What's the problem?

答:
In my case, The Only modification I did that on the Model Classes forget to put {get; set;} with the property declaration, Thus ...It's solved my problem.

Like this:

Before:

```<code> public int Supplier_ID;
 public String Supplier_Code;
</code>```

After:

```<code> public int Supplier_ID { get; set; }
 public String Supplier_Code { get; set; }
</code>```

Kindly Check your Model Classes should have the Get/Set property

Body:
I have these two entities

public class Song : IPathHavingEntity
    {
        public int Id { get; set; }
        [Required]
        public string Path { get; set; }
        [Required]
        public virtual Album Album { get; set; }
        [Required]
        public int TrackNumber { get; set; }
    }

public class Album : IPathHavingEntity
    {
        public int Id { get; set; }
        [Required]
        public string Path { get; set; }
        public virtual IEnumerable<Song> Songs { get; set; }
        [Required]
        public int AlbumNumber { get; set; }
    }

Path is defined in the IPathHavingEntity interface.

In my Seed method I want to add a song to the Songs table only if it doesn't exist.  For this reason I check that the album path and song path combination don't exist already before adding it thus

context.Songs.AddOrUpdate(
    s => new { FilePath = s.Path, AlbumPath = s.Album.Path },
    new Song { TrackNumber = 1, Path = "01 Intro.mp3", Album = one });

The problem is I get this error

The properties expression 's => new <>f__AnonymousType0``2(FilePath =
s.Path, AlbumPath = s.Album.Path)' is not valid. The expression should
represent a   property: C#: 't => t.MyProperty'  VB.Net: 'Function(t) t.MyProperty'. When specifying multiple properties use an anonymous type: C#: 't => new { t.MyProperty1, t.MyProperty2 }'  VB.Net: 'Function(t) New With { t.MyProperty1, t.MyProperty2 }'.

What's the problem?

Body:
In my case, The Only modification I did that on the Model Classes forget to put {get; set;} with the property declaration, Thus ...It's solved my problem.

Like this:

Before:

 public int Supplier_ID;
 public String Supplier_Code;

After:

 public int Supplier_ID { get; set; }
 public String Supplier_Code { get; set; }

Kindly Check your Model Classes should have the Get/Set property


问:
CELERY WindowsError: [Error 6] The handle is invalid
I am new with celery and i am following the tutorial given on their site i got this error

```<code> from celery import Celery
 app = Celery('tasks', broker='pyamqp://guest@localhost//')

 @app.task
 def add(x, y):
     return x + y
</code>```

and cmd shows error like this

```<code>-------------- celery@DESKTOP-O90R45G v4.0.2 (latentcall)
---- **** -----
--- * ***  * -- Windows-10-10.0.14393 2016-12-16 20:05:48
-- * - **** ---
- ** ---------- [config]
- ** ---------- .> app:         tasks:0x4591950
- ** ---------- .> transport:   amqp://guest:**@localhost:5672//
- ** ---------- .> results:     disabled://
- *** --- * --- .> concurrency: 4 (prefork)
-- ******* ---- .> task events: OFF (enable -E to monitor tasks in this worker)
--- ***** -----  -------------- [queues]
                .> celery           exchange=celery(direct) key=celery

[tasks]   . tasks.add

[2016-12-16 20:05:49,029: CRITICAL/MainProcess] Unrecoverable error:
TypeError('argument 1 must be an integer, not _subprocess_handle',)
Traceback (most recent call last):   File
"c:\python27\lib\site-packages\celery\worker\worker.py", line 203, in
start
    self.blueprint.start(self)   File "c:\python27\lib\site-packages\celery\bootsteps.py", line 119, in
start
    step.start(parent)   File "c:\python27\lib\site-packages\celery\bootsteps.py", line 370, in
start
    return self.obj.start()   File "c:\python27\lib\site-packages\celery\concurrency\base.py", line 131,
in start
    self.on_start()   File "c:\python27\lib\site-packages\celery\concurrency\prefork.py", line
112, in on_start
    **self.options)   File "c:\python27\lib\site-packages\billiard\pool.py", line 1008, in
__init__
    self._create_worker_process(i)   File "c:\python27\lib\site-packages\billiard\pool.py", line 1117, in
_create_worker_process
    w.start()   File "c:\python27\lib\site-packages\billiard\process.py", line 122, in
start
    self._popen = self._Popen(self)   File "c:\python27\lib\site-packages\billiard\context.py", line 383, in
_Popen
    return Popen(process_obj)   File "c:\python27\lib\site-packages\billiard\popen_spawn_win32.py", line
64, in __init__
    _winapi.CloseHandle(ht) TypeError: argument 1 must be an integer, not _subprocess_handle Traceback (most recent call last):   File
"<string>", line 1, in <module>   File
"c:\python27\lib\site-packages\billiard\spawn.py", line 159, in
spawn_main
    new_handle = steal_handle(parent_pid, pipe_handle)   File "c:\python27\lib\site-packages\billiard\reduction.py", line 126, in
steal_handle
    _winapi.DUPLICATE_SAME_ACCESS | _winapi.DUPLICATE_CLOSE_SOURCE) >WindowsError: [Error 6] The handle is invalid
</code>```

答:
Looks like your rabbitmq server is not running. Did you run install and start rabbimq server?

You can checkout rabbitmq docs and install it. Start rabbitmq server and then start your celery worker with your app

```<code>celery worker -l info -A tasks
</code>```

Body:
I am new with celery and i am following the tutorial given on their site i got this error

 from celery import Celery
 app = Celery('tasks', broker='pyamqp://guest@localhost//')

 @app.task
 def add(x, y):
     return x + y

and cmd shows error like this

-------------- celery@DESKTOP-O90R45G v4.0.2 (latentcall)
---- **** -----
--- * ***  * -- Windows-10-10.0.14393 2016-12-16 20:05:48
-- * - **** ---
- ** ---------- [config]
- ** ---------- .> app:         tasks:0x4591950
- ** ---------- .> transport:   amqp://guest:**@localhost:5672//
- ** ---------- .> results:     disabled://
- *** --- * --- .> concurrency: 4 (prefork)
-- ******* ---- .> task events: OFF (enable -E to monitor tasks in this worker)
--- ***** -----  -------------- [queues]
                .> celery           exchange=celery(direct) key=celery

[tasks]   . tasks.add

[2016-12-16 20:05:49,029: CRITICAL/MainProcess] Unrecoverable error:
TypeError('argument 1 must be an integer, not _subprocess_handle',)
Traceback (most recent call last):   File
"c:\python27\lib\site-packages\celery\worker\worker.py", line 203, in
start
    self.blueprint.start(self)   File "c:\python27\lib\site-packages\celery\bootsteps.py", line 119, in
start
    step.start(parent)   File "c:\python27\lib\site-packages\celery\bootsteps.py", line 370, in
start
    return self.obj.start()   File "c:\python27\lib\site-packages\celery\concurrency\base.py", line 131,
in start
    self.on_start()   File "c:\python27\lib\site-packages\celery\concurrency\prefork.py", line
112, in on_start
    **self.options)   File "c:\python27\lib\site-packages\billiard\pool.py", line 1008, in
__init__
    self._create_worker_process(i)   File "c:\python27\lib\site-packages\billiard\pool.py", line 1117, in
_create_worker_process
    w.start()   File "c:\python27\lib\site-packages\billiard\process.py", line 122, in
start
    self._popen = self._Popen(self)   File "c:\python27\lib\site-packages\billiard\context.py", line 383, in
_Popen
    return Popen(process_obj)   File "c:\python27\lib\site-packages\billiard\popen_spawn_win32.py", line
64, in __init__
    _winapi.CloseHandle(ht) TypeError: argument 1 must be an integer, not _subprocess_handle Traceback (most recent call last):   File
"<string>", line 1, in <module>   File
"c:\python27\lib\site-packages\billiard\spawn.py", line 159, in
spawn_main
    new_handle = steal_handle(parent_pid, pipe_handle)   File "c:\python27\lib\site-packages\billiard\reduction.py", line 126, in
steal_handle
    _winapi.DUPLICATE_SAME_ACCESS | _winapi.DUPLICATE_CLOSE_SOURCE) >WindowsError: [Error 6] The handle is invalid

Body:
Looks like your rabbitmq server is not running. Did you run install and start rabbimq server?

You can checkout rabbitmq docs and install it. Start rabbitmq server and then start your celery worker with your app

celery worker -l info -A tasks


问:
count the number of zero group bits in a number
How do you count the number of zero group bits in a number? group bits
is any consecutive zero or one bits, for example, 2 is represented
as ....0000000000000000010 has two zero bits groups the least
significant bit and the group starts after one.
Also, I am in a bad need for algorithms on bits manipulation if any
one has a reference, please share</p>

答:
Try this code
Didnt test it.. so do let me know if you find some bug

num is the input.

```<code>int main()
{
    int count = 0;

    int num = 0xF0000000, mask = 1; /*size of mask and num should be same. */

    int i;
    int flag= 1;

    i = sizeof(num) * 8;

    while(--i) {
         if(flag && !(num & mask)) {
            count++;
            flag = 0;
        }
        else if(num & mask)
            flag = 1;

    mask = mask<<1;
 }

 printf("\n%d\n",count);
 }

Thanks
cexpert
http://learnwithtechies.com
</code>```

ContentLicense: CC BY-SA 2.5

Body:
Try this code
Didnt test it.. so do let me know if you find some bug

num is the input.

int main()
{
    int count = 0;

    int num = 0xF0000000, mask = 1; /*size of mask and num should be same. */

    int i;
    int flag= 1;

    i = sizeof(num) * 8;

    while(--i) {
         if(flag && !(num & mask)) {
            count++;
            flag = 0;
        }
        else if(num & mask)
            flag = 1;

    mask = mask<<1;
 }

 printf("\n%d\n",count);
 }

Thanks
cexpert
http://learnwithtechies.com


问:
How to declare component props on html <template> tag on Vue.js
I'm using Vue. Instead of declaring my templates on my javascript, I prefer to do the html way for readability and code detection on sublime, so I'm using this:

```<code><template id="test-component">
  <h1>Testing</h1>
</template>

Vue.component('test', {
  template: '#test-component'
});

<test></test>
</code>```

Works well.. but I want to pass some data to the template, like this:

```<code><template id="test-component">
  <h1>{{text}}</h1>
</template>

Vue.component('test', {
  template: '#test-component',
  props: ['text']
});

<test text="asd"></test>
</code>```

Also works well, but.. I want to declare the props on the template tag for easier readability on my project, not on the javascript component function, is there any way I could do that? Something like this (doesn't work):

```<code><template id="test-component" props="['text]">
  <h1>{{text}}</h1>
</template>
</code>```

答:
You can't declare props on the template tag like you have suggested, the only way is to declare them in JavaScript as per the documentation.

I'm not really sure why you would want to do that, or how it would improve readability. Props are a part of the component definition itself, not the template. Not all props might be rendered in the template either. Do you think that computed properties should be specified on the template tag too?

Body:
I'm using Vue. Instead of declaring my templates on my javascript, I prefer to do the html way for readability and code detection on sublime, so I'm using this:

<template id="test-component">

Testing

</template>

Vue.component('test', {
  template: '#test-component'
});

<test></test>

Works well.. but I want to pass some data to the template, like this:

<template id="test-component">

{{text}}

</template>

Vue.component('test', {
  template: '#test-component',
  props: ['text']
});

<test text="asd"></test>

Also works well, but.. I want to declare the props on the template tag for easier readability on my project, not on the javascript component function, is there any way I could do that? Something like this (doesn't work):

<template id="test-component" props="['text]">

{{text}}

</template>


问:
Problems with installing tensorf flow on ubuntu
I installed tensorflow on Linux, but when I try to import it in the python shell it cannot find the module. I cannot find the error massage on the tensorflow website. Does anyone have any ideas on how I can fix it?

Whenever I give the command:

```<code>import tensorflow as tf
</code>```

I get as a return:

```<code>Traceback (most recent call last):
     File "<stdin>", line 1, in <module>
  File "/home/beheerder/anaconda2/lib/python2.7/site-packages/tensorflow/__init__.py", line 24, in <module>
    from tensorflow.python import *
  File "/home/beheerder/anaconda2/lib/python2.7/site-packages/tensorflow/python/__init__.py", line 51, in <module>
    from tensorflow.python import pywrap_tensorflow
  File "/home/beheerder/anaconda2/lib/python2.7/site-packages/tensorflow/python/pywrap_tensorflow.py", line 52, in <module>
    raise ImportError(msg)
ImportError: Traceback (most recent call last):
  File "/home/beheerder/anaconda2/lib/python2.7/site-packages/tensorflow/python/pywrap_tensorflow.py", line 41, in <module>
    from tensorflow.python.pywrap_tensorflow_internal import *
  File "/home/beheerder/anaconda2/lib/python2.7/site-packages/tensorflow/python/pywrap_tensorflow_internal.py", line 28, in <module>
    _pywrap_tensorflow_internal = swig_import_helper()
  File "/home/beheerder/anaconda2/lib/python2.7/site-packages/tensorflow/python/pywrap_tensorflow_internal.py", line 24, in swig_import_helper
    _mod = imp.load_module('_pywrap_tensorflow_internal', fp, pathname, description)
ImportError: libcublas.so.8.0: cannot open shared object file: No such file or directory

Failed to load the native TensorFlow runtime.

See https://www.tensorflow.org/install/install_sources#common_installation_problems

for some common reasons and solutions.  Include the entire stack trace
above this error message when asking for help.
</code>```

答:
Going through your error seems like you're using anaconda for your tensorflow. I have got this error and it seems that tensorflow-gpu for anacoda is still under development and does not work properly.

I suggest you to installed the tensorflow-gpu version out of the anaconda environment. The cpu version works fine though.

After clean installing it again without anacoda for python 2.7. DO:

```<code>cd /opt/DL/tensorflow/bin/
source tensorflow-activate
</code>```

Follow this as it is similar

Body:
I installed tensorflow on Linux, but when I try to import it in the python shell it cannot find the module. I cannot find the error massage on the tensorflow website. Does anyone have any ideas on how I can fix it?

Whenever I give the command:

import tensorflow as tf

I get as a return:

Traceback (most recent call last):
     File "<stdin>", line 1, in <module>
  File "/home/beheerder/anaconda2/lib/python2.7/site-packages/tensorflow/__init__.py", line 24, in <module>
    from tensorflow.python import *
  File "/home/beheerder/anaconda2/lib/python2.7/site-packages/tensorflow/python/__init__.py", line 51, in <module>
    from tensorflow.python import pywrap_tensorflow
  File "/home/beheerder/anaconda2/lib/python2.7/site-packages/tensorflow/python/pywrap_tensorflow.py", line 52, in <module>
    raise ImportError(msg)
ImportError: Traceback (most recent call last):
  File "/home/beheerder/anaconda2/lib/python2.7/site-packages/tensorflow/python/pywrap_tensorflow.py", line 41, in <module>
    from tensorflow.python.pywrap_tensorflow_internal import *
  File "/home/beheerder/anaconda2/lib/python2.7/site-packages/tensorflow/python/pywrap_tensorflow_internal.py", line 28, in <module>
    _pywrap_tensorflow_internal = swig_import_helper()
  File "/home/beheerder/anaconda2/lib/python2.7/site-packages/tensorflow/python/pywrap_tensorflow_internal.py", line 24, in swig_import_helper
    _mod = imp.load_module('_pywrap_tensorflow_internal', fp, pathname, description)
ImportError: libcublas.so.8.0: cannot open shared object file: No such file or directory

Failed to load the native TensorFlow runtime.

See https://www.tensorflow.org/install/install_sources#common_installation_problems

for some common reasons and solutions.  Include the entire stack trace
above this error message when asking for help.

Body:
Going through your error seems like you're using anaconda for your tensorflow. I have got this error and it seems that tensorflow-gpu for anacoda is still under development and does not work properly.

I suggest you to installed the tensorflow-gpu version out of the anaconda environment. The cpu version works fine though.

After clean installing it again without anacoda for python 2.7. DO:

cd /opt/DL/tensorflow/bin/
source tensorflow-activate

Follow this as it is similar


问:
Replacing strings in a 2d python list
I am reading in a text file as lines and then splitting those lines by white space, giving me a 2d list. Some of the strings in the embedded arrays contain junk that I'm trying to filter out using str.replace, but it's not working.

```<code>import os

infile = 'CMULEX.txt'

data = []
with open(infile, 'r') as f:
    read_data = f.readlines()

    for row in read_data[:5]:
        split_line = (row.split())
        data.append(split_line)

for line in data[:5]:
    for wd in line:
        wd = wd.replace('Coda', '')
</code>```

答:
```<code>For line in data[:5]:
   line[:] = [ '' if x == 'Coda' else x for x in line]
</code>```

Title: Replacing strings in a 2d python list

Body:
I am reading in a text file as lines and then splitting those lines by white space, giving me a 2d list. Some of the strings in the embedded arrays contain junk that I'm trying to filter out using str.replace, but it's not working.

import os

infile = 'CMULEX.txt'

data = []
with open(infile, 'r') as f:
    read_data = f.readlines()

    for row in read_data[:5]:
        split_line = (row.split())
        data.append(split_line)

for line in data[:5]:
    for wd in line:
        wd = wd.replace('Coda', '')


问:
Why does the higher resolution BufferedImage get wrapped and compressed within Canvas?
I have a JFrame GUI that is capturing raw video stream live from a LAN connected camera. I'm setting the RBG value (camera streams the pixel values, but just as white and black colors) for each coordinate in the BufferedImage (img1) and drawing the image on a standard Java extended Canvas (MyCanvas canvas1).

Code snippet for drawing in threaded environment which works fine except for the resolution 1280x960.

```<code>while (true) {
                synchronized (this) {
                    if (shouldrun == false) {
                        System.out.println("Quiting Thread.....\n");
                        break;
                    }
                }
                if (in.read(ch) < 0) {
                    break;
                }
                /* Mono */
                pixelvalue = 0x00000000 | (ch[0] << 16)
                        | (ch[0] << 8) | (ch[0]);
                img1.setRGB(x, y, pixelvalue);
                x++;
                //resWidth = 1280
                if (x >= resWidth) {
                    x = 0;
                    y++;
                }
                framedata[pixelcount] = (byte) ch[0];
                pixelcount++;
                //resHeight = 960
                if (pixelcount >= resWidth * resHeight) {
                    System.out.println("pixelcount = " + pixelcount);
                    if (record == true) {
                        System.out.println("Recording Frame...");

                        if (fo != null) {
                            fo.write(framedata);
                        }
                    }
                    synchronized (canvas1) {
                        canvas1.DrawImage(img1);
                        canvas1.repaint();
                    }
                    Thread.sleep(33);
                    pixelcount = 0;
                    x = 0;
                    y = 0;
                }

            }
</code>```

Code snippet of Canvas class for canvas1 object:

```<code>class MyCanvas extends Canvas {
    int startAngle = 0;
    int extent = 45;
    boolean filled = false;
    Image disimg = null;

    public void DrawImage(Image img) {
        disimg = img;
    }

    public void paint(Graphics g) {
        g.setColor(Color.pink);
         g.drawImage(disimg, 0, 0, null);
    }

    public void redraw(boolean filled, int start, int extent) {
        this.filled = filled;
        this.startAngle = start;
        this.extent = extent;
        repaint();
    }

}
</code>```

The Java GUI app was successfully able to draw the image in 640x480 (resWidth=640 & resHeight=480) resolution image from the camera as shown below

I'm simply setting the resWidth variable to 640 and resHeight variable to 480 for coordinate increment limits and the canvas dimension.

However when doing the same for 1280x960 resolution the result shows 2 duplicate images and compressed/squashed vertically:

Why would this occur? Can I not simply vary the width and height variables in the code? Could it be the Jpanel layout? Or the way the camera streams the pixel values in that resolution?

答:
When you say width and height, I assume you are not referring to the input resolution that comes from the camera but you are wanting to change how it is rendered on your canvas. Because the input resolution cannot be change and will depend on the input device. I mean, you just can't simply change the input resolution to 1920x1080 for example since the actual resolution comes from the camera itself, however you can change the way it is rendered to your display (output resolution).

So from 640x480 input resolution camera input, you want to render it to a 1280x960 display resolution. Scaling it twice.
I would revert your code to the original width and height of 640x480 and I would look at your MyCanvas class extension for rendering to the screen.

The original code

```<code>public void paint(Graphics g) {
    g.setColor(Color.pink);
    g.drawImage(disimg, 0, 0, null);
}
</code>```

I would change it to

```<code>public void paint(Graphics g) {
    g.setColor(Color.pink);
    g.drawImage(disimg, 0, 0, desiredWidth, desiredHeight, null);
}
</code>```

where the desiredWidth and desiredHeight can be (640x480) or (1280x960) or anything you desire since this is something you can control, not the input resolution.

You can even draw the image to fill the entire size of the canvas something like

```<code>public void paint(Graphics g) {
    g.setColor(Color.pink);
    g.drawImage(disimg, 0, 0, this.getWidth(), this.getHeight(), null);
}
</code>```

This is the API you would be looking into.
https://docs.oracle.com/javase/7/docs/api/java/awt/Graphics.html#drawImage(java.awt.Image,%20int,%20int,%20int,%20int,%20java.awt.image.ImageObserver)

Hope it helps, Happy Coding!

Body:
I have a JFrame GUI that is capturing raw video stream live from a LAN connected camera. I'm setting the RBG value (camera streams the pixel values, but just as white and black colors) for each coordinate in the BufferedImage (img1) and drawing the image on a standard Java extended Canvas (MyCanvas canvas1).

Code snippet for drawing in threaded environment which works fine except for the resolution 1280x960.

while (true) {
                synchronized (this) {
                    if (shouldrun == false) {
                        System.out.println("Quiting Thread.....\n");
                        break;
                    }
                }
                if (in.read(ch) < 0) {
                    break;
                }
                /* Mono */
                pixelvalue = 0x00000000 | (ch[0] << 16)
                        | (ch[0] << 8) | (ch[0]);
                img1.setRGB(x, y, pixelvalue);
                x++;
                //resWidth = 1280
                if (x >= resWidth) {
                    x = 0;
                    y++;
                }
                framedata[pixelcount] = (byte) ch[0];
                pixelcount++;
                //resHeight = 960
                if (pixelcount >= resWidth * resHeight) {
                    System.out.println("pixelcount = " + pixelcount);
                    if (record == true) {
                        System.out.println("Recording Frame...");

                        if (fo != null) {
                            fo.write(framedata);
                        }
                    }
                    synchronized (canvas1) {
                        canvas1.DrawImage(img1);
                        canvas1.repaint();
                    }
                    Thread.sleep(33);
                    pixelcount = 0;
                    x = 0;
                    y = 0;
                }

            }

Code snippet of Canvas class for canvas1 object:

class MyCanvas extends Canvas {
    int startAngle = 0;
    int extent = 45;
    boolean filled = false;
    Image disimg = null;

    public void DrawImage(Image img) {
        disimg = img;
    }

    public void paint(Graphics g) {
        g.setColor(Color.pink);
         g.drawImage(disimg, 0, 0, null);
    }

    public void redraw(boolean filled, int start, int extent) {
        this.filled = filled;
        this.startAngle = start;
        this.extent = extent;
        repaint();
    }

}

The Java GUI app was successfully able to draw the image in 640x480 (resWidth=640 & resHeight=480) resolution image from the camera as shown below

I'm simply setting the resWidth variable to 640 and resHeight variable to 480 for coordinate increment limits and the canvas dimension.

However when doing the same for 1280x960 resolution the result shows 2 duplicate images and compressed/squashed vertically:

Why would this occur? Can I not simply vary the width and height variables in the code? Could it be the Jpanel layout? Or the way the camera streams the pixel values in that resolution?

Body:
When you say width and height, I assume you are not referring to the input resolution that comes from the camera but you are wanting to change how it is rendered on your canvas. Because the input resolution cannot be change and will depend on the input device. I mean, you just can't simply change the input resolution to 1920x1080 for example since the actual resolution comes from the camera itself, however you can change the way it is rendered to your display (output resolution).

So from 640x480 input resolution camera input, you want to render it to a 1280x960 display resolution. Scaling it twice.
I would revert your code to the original width and height of 640x480 and I would look at your MyCanvas class extension for rendering to the screen.

The original code

public void paint(Graphics g) {
    g.setColor(Color.pink);
    g.drawImage(disimg, 0, 0, null);
}

I would change it to

public void paint(Graphics g) {
    g.setColor(Color.pink);
    g.drawImage(disimg, 0, 0, desiredWidth, desiredHeight, null);
}

where the desiredWidth and desiredHeight can be (640x480) or (1280x960) or anything you desire since this is something you can control, not the input resolution.

You can even draw the image to fill the entire size of the canvas something like

public void paint(Graphics g) {
    g.setColor(Color.pink);
    g.drawImage(disimg, 0, 0, this.getWidth(), this.getHeight(), null);
}

This is the API you would be looking into.
https://docs.oracle.com/javase/7/docs/api/java/awt/Graphics.html#drawImage(java.awt.Image,%20int,%20int,%20int,%20int,%20java.awt.image.ImageObserver)

Hope it helps, Happy Coding!


问:
Share image and text using android share dialog
is it possible to share image and text to facebook, instagram and whatsapp using android share dialog? i am trying for 2 weeks to do this with no success. the only thing i can do is to write some code foreach media without using the share dialog. this is some code that work with whatsapp but not with insta and facebook</p>

```<code>String DishImage = listDishes.get(selectedDish).getDishImage();
            Picasso.with(this).load(DishImage).into(new Target() {
                @Override
                public void onBitmapLoaded(Bitmap bm, Picasso.LoadedFrom from) {
                    OutputStream fOut = null;
                    Uri outputFileUri;
                    try {
                        File root = new File(Environment.getExternalStorageDirectory() + File.separator + "FoodMana" + File.separator);
                        root.mkdirs();
                        File sdImageMainDirectory = new File(root, "myPicName.jpg");
                        fOut = new FileOutputStream(sdImageMainDirectory);
                    } catch (Exception e) {Toast.makeText(getApplicationContext(), "Error occured. Please try again later.", Toast.LENGTH_SHORT).show();}

                    try {
                        bm.compress(Bitmap.CompressFormat.PNG, 100, fOut);
                        fOut.flush();
                        fOut.close();
                    } catch (Exception e) {
                    }

                        Intent waIntent = new Intent(android.content.Intent.ACTION_SEND);
                        waIntent.setType("image/*");
                        waIntent.putExtra(Intent.EXTRA_STREAM, Uri.parse(Environment.getExternalStorageDirectory()
                                + File.separator + "FoodMana" + File.separator + "myPicName.jpg"));
                        waIntent.putExtra(Intent.EXTRA_TEXT, "I am going to eat that dish!!!!!" + "\n" + "what do you think? check out");
                        startActivity(Intent.createChooser(waIntent, "Share with"));

                }

                @Override
                public void onBitmapFailed(Drawable errorDrawable) {
                    Log.d("TAG","error");
                }

                @Override
                public void onPrepareLoad(Drawable placeHolderDrawable) {
                    Log.d("TAG","prepared");

                }
            });
</code>```

答:
I  am using this to share a link everwhere
I am getting my link from  al_details.get(getLayoutPosition()).get(URL_WEB).toString()

```<code>share.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                    Intent shareintent = new Intent(Intent.ACTION_SEND);
                    shareintent.setType("text/plain");
                    shareintent.putExtra(Intent.EXTRA_TEXT,al_details.get(getLayoutPosition()).get(URL_WEB).toString());
                    mContext.startActivity(Intent.createChooser(shareintent,"Share Via"));
                    }
                });
</code>```

I tried many things from internet but at the end i did this. So you can try it once .

Body:
is it possible to share image and text to facebook, instagram and whatsapp using android share dialog? i am trying for 2 weeks to do this with no success. the only thing i can do is to write some code foreach media without using the share dialog. this is some code that work with whatsapp but not with insta and facebook

String DishImage = listDishes.get(selectedDish).getDishImage();
            Picasso.with(this).load(DishImage).into(new Target() {
                @Override
                public void onBitmapLoaded(Bitmap bm, Picasso.LoadedFrom from) {
                    OutputStream fOut = null;
                    Uri outputFileUri;
                    try {
                        File root = new File(Environment.getExternalStorageDirectory() + File.separator + "FoodMana" + File.separator);
                        root.mkdirs();
                        File sdImageMainDirectory = new File(root, "myPicName.jpg");
                        fOut = new FileOutputStream(sdImageMainDirectory);
                    } catch (Exception e) {Toast.makeText(getApplicationContext(), "Error occured. Please try again later.", Toast.LENGTH_SHORT).show();}

                    try {
                        bm.compress(Bitmap.CompressFormat.PNG, 100, fOut);
                        fOut.flush();
                        fOut.close();
                    } catch (Exception e) {
                    }

                        Intent waIntent = new Intent(android.content.Intent.ACTION_SEND);
                        waIntent.setType("image/*");
                        waIntent.putExtra(Intent.EXTRA_STREAM, Uri.parse(Environment.getExternalStorageDirectory()
                                + File.separator + "FoodMana" + File.separator + "myPicName.jpg"));
                        waIntent.putExtra(Intent.EXTRA_TEXT, "I am going to eat that dish!!!!!" + "\n" + "what do you think? check out");
                        startActivity(Intent.createChooser(waIntent, "Share with"));

                }

                @Override
                public void onBitmapFailed(Drawable errorDrawable) {
                    Log.d("TAG","error");
                }

                @Override
                public void onPrepareLoad(Drawable placeHolderDrawable) {
                    Log.d("TAG","prepared");

                }
            });

Body:
I  am using this to share a link everwhere
I am getting my link from  al_details.get(getLayoutPosition()).get(URL_WEB).toString()

share.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                    Intent shareintent = new Intent(Intent.ACTION_SEND);
                    shareintent.setType("text/plain");
                    shareintent.putExtra(Intent.EXTRA_TEXT,al_details.get(getLayoutPosition()).get(URL_WEB).toString());
                    mContext.startActivity(Intent.createChooser(shareintent,"Share Via"));
                    }
                });

I tried many things from internet but at the end i did this. So you can try it once .


问:
How to tell if my Java component is in an Applet?
I have a Component which I am using both in a standalone Java application as well as in a Java applet. How can I figure out from within the Component whether my component is in an applet?

Also, once I figure out that I'm running in an Applet, how can I get access to the Applet?

答:
I think you should be able to do it by repeatedly calling Component.getParent() until you get to the top of the container tree, and then checking whether that container is an instanceof Applet.

The code below is completely untested:

```<code>boolean isInAnApplet(Component c)
{
    Component p = c.getParent();
    if (p != null) {
         return isInAnApplet(p);
    } else {
         return (c instanceof Applet);
    }
}
</code>```

OwnerDisplayName: Epaga

Body:
I think you should be able to do it by repeatedly calling Component.getParent() until you get to the top of the container tree, and then checking whether that container is an instanceof Applet.

The code below is completely untested:

boolean isInAnApplet(Component c)
{
    Component p = c.getParent();
    if (p != null) {
         return isInAnApplet(p);
    } else {
         return (c instanceof Applet);
    }
}

OwnerDisplayName: Alnitak

LastEditorDisplayName: Alnitak


问:
prepare a json object in view to pass the controller
i have a tree that has a ul li HTML structure .

In every li there is a span that contains the node name of the tree.

I have to make a json object after reading the tree it should look like some thing in this manner

```<code>        this.orgStructureId = null;
        this.name = null;
        this.nodeList = null;
        this.parent = null;
        this.list = null;
</code>```

i am not sure that it will be the structure but some thing similar.so how can i make this object do you need any more inputs for making the json object.

http://i.stack.imgur.com/9itqx.jpg
Tree sample snap shot

答:
Tree is generated on the server

If your tree is generated on the server side, you could as well add its JSON string to your HTML and use that preprepared JSON data instead of generating in on the client side...

```<code><ul id="TreeRoot" data="{ name: 'Some name', ... }">
    <li>...</li>
    ...
</ul>
</code>```

Then just call

```<code>var data = $.parseJSON($("#TreeRoot").attr("data"));
</code>```

and you'll get your JSON data to send to the server. But there will be another obstacle... passing that data to controller action.

I suggest you read this blog post about sending JSON data, that will make your life even easier...

Tree is generated on the client

In case your tree is generated/edited on the client by users you will have no other option but either:

traverse DOM elements of your hierarchy data and generate JSON

generate JSON data while user creates the tree and have it prepared on the go and use the end result

I'd probably go with the second one, because you'll be manipulating data already anyway. So why not generate HTML nodes and populate variables as well.

Body:
i have a tree that has a ul li HTML structure .

In every li there is a span that contains the node name of the tree.

I have to make a json object after reading the tree it should look like some thing in this manner

        this.orgStructureId = null;
        this.name = null;
        this.nodeList = null;
        this.parent = null;
        this.list = null;

i am not sure that it will be the structure but some thing similar.so how can i make this object do you need any more inputs for making the json object.

http://i.stack.imgur.com/9itqx.jpg
Tree sample snap shot

Body:
Tree is generated on the server

If your tree is generated on the server side, you could as well add its JSON string to your HTML and use that preprepared JSON data instead of generating in on the client side...

<ul id="TreeRoot" data="{ name: 'Some name', ... }">
    <li>...</li>
    ...
</ul>

Then just call

var data = $.parseJSON($("#TreeRoot").attr("data"));

and you'll get your JSON data to send to the server. But there will be another obstacle... passing that data to controller action.

I suggest you read this blog post about sending JSON data, that will make your life even easier...

Tree is generated on the client

In case your tree is generated/edited on the client by users you will have no other option but either:

traverse DOM elements of your hierarchy data and generate JSON

generate JSON data while user creates the tree and have it prepared on the go and use the end result

I'd probably go with the second one, because you'll be manipulating data already anyway. So why not generate HTML nodes and populate variables as well.


问:
how can i find the sum of all integers given in the string by using JavaScript?
How do I calculate the sum of all the numbers in a string by using the JavaScript ? In the example below, the expected result would be 2+0+1+5. My attempt is below. </p>

```<code>var a = "weare20boysand15girls";
    var i;
    for(i=0; i<a.length; i++){
        var b = Number(a[i]);
        var c=0;
        c += b;
        console.log(c);
</code>```

答:
//Try this:  You have to split the string to an array and then test each character for addition.</p>

```<code>function sumNumbers_in_a_String() {

  var strName = "weare20boysand15girls";
  var strArray = strName.split("");
  var c = 0;
  var l = strArray.length;
  for (var i = 0; i < l; i++){
      if (parseInt(strArray[i])){
         var b = Number(strArray[i]);
         var c = c + b;
      }
 }
}
</code>```

Body:
How do I calculate the sum of all the numbers in a string by using the JavaScript ? In the example below, the expected result would be 2+0+1+5. My attempt is below.

var a = "weare20boysand15girls";
    var i;
    for(i=0; i<a.length; i++){
        var b = Number(a[i]);
        var c=0;
        c += b;
        console.log(c);

Body:
//Try this:  You have to split the string to an array and then test each character for addition.

function sumNumbers_in_a_String() {

  var strName = "weare20boysand15girls";
  var strArray = strName.split("");
  var c = 0;
  var l = strArray.length;
  for (var i = 0; i < l; i++){
      if (parseInt(strArray[i])){
         var b = Number(strArray[i]);
         var c = c + b;
      }
 }
}


问:
PHP - Cookies are being removed, but are regenerated on the next page
I have an option for users to select a "Remember me" option on my site that saves certain information to cookies so that they can be authenticated without needing to log in.

However, when users want to log out, it seems that these cookies are being deleted, but are for some reason being created again when they are sent to the next page.

The following is an example of my log out script. Before this exact code is called, the user is authenticated via a different file included in the log out file and cookies are set if the user has specified that they wish to be remembered.

// -- FROM THE AUTH FILE -- //

setcookie("username", "bob240", time() + (86400 * 30), "/", ".domain.com");
setcookie("password", "password123", time() + (86400 * 30), "/", ".domain.com");

// -- END FROM THE AUTH FILE -- //

// Clear cookies by setting them to a past date.
setcookie("username", "", time() - (86400 * 30), "/", ".domain.com");
setcookie("password", "", time() - (86400 * 30), "/", ".domain.com");

// Check if the session was destroyed.
if(session_destroy()) {

    // Redirect the user.
    header('Location: /next/page/'); die("Redirecting...");

}
```

This means that the same cookies are set twice on the same page. However, because these cookies are set in the order from which they are listed, there should not be any conflicts.

However, to test this theory, I tracked the header requests and responses from my browser and I could see that the cookies were being set when the user was authenticated and deleted when the user logged out.

To check further, I printed $_SESSION and $_COOKIE multiple times on the log out page and the page the user was redirected to. I could see that the cookies were being removed, as $_COOKIE was empty. However, $_SESSION still contained the necessary information to authenticate the user. Because of this, I thought that the sessions were somehow causing the problem. However, I threw away this thought when I tested logging out without the cookies being set from the "Remember me" option, and everything worked fine.

I also want to note that when visiting the log out page from a sub-domain, going from sub-domain.domain.com -> www.domain.com/log-out-page/, I was able to successfully log out even with cookies set.

I am also able to sometimes successfully log out after visiting the log out page multiple times.

I use the same code (AFAIK) on two others sites, which are both on the same web servers, and everything is working fine. I even tried using the files from the other two sites, but the problem still persists. All of these sites use CloudFlare and have the same settings set.

Since this is a very vague issue, you can use the demo account on my site to log in and test anything yourself.

Site that isn't working: https://theartex.net/system/login/,
site that is working: https://mathhulk.me/system/login/

Account:
username - demo,
password - demo

答: The constant pinging of /cloud/api/ to get the alerts for the user sets the cookies at the same time as /system/logout removes them. If you keep /cloud/api from setting the two cookies then it should all work again.

Body:
I have an option for users to select a "Remember me" option on my site that saves certain information to cookies so that they can be authenticated without needing to log in.

However, when users want to log out, it seems that these cookies are being deleted, but are for some reason being created again when they are sent to the next page.

The following is an example of my log out script. Before this exact code is called, the user is authenticated via a different file included in the log out file and cookies are set if the user has specified that they wish to be remembered.

// -- FROM THE AUTH FILE -- //

setcookie("username", "bob240", time() + (86400 * 30), "/", ".domain.com");
setcookie("password", "password123", time() + (86400 * 30), "/", ".domain.com");

// -- END FROM THE AUTH FILE -- //

// Clear cookies by setting them to a past date.
setcookie("username", "", time() - (86400 * 30), "/", ".domain.com");
setcookie("password", "", time() - (86400 * 30), "/", ".domain.com");

// Check if the session was destroyed.
if(session_destroy()) {

    // Redirect the user.
    header('Location: /next/page/'); die("Redirecting...");

}

This means that the same cookies are set twice on the same page. However, because these cookies are set in the order from which they are listed, there should not be any conflicts.

However, to test this theory, I tracked the header requests and responses from my browser and I could see that the cookies were being set when the user was authenticated and deleted when the user logged out.

To check further, I printed $_SESSION and $_COOKIE multiple times on the log out page and the page the user was redirected to. I could see that the cookies were being removed, as $_COOKIE was empty. However, $_SESSION still contained the necessary information to authenticate the user. Because of this, I thought that the sessions were somehow causing the problem. However, I threw away this thought when I tested logging out without the cookies being set from the "Remember me" option, and everything worked fine.

I also want to note that when visiting the log out page from a sub-domain, going from sub-domain.domain.com -> www.domain.com/log-out-page/, I was able to successfully log out even with cookies set.

I am also able to sometimes successfully log out after visiting the log out page multiple times.

I use the same code (AFAIK) on two others sites, which are both on the same web servers, and everything is working fine. I even tried using the files from the other two sites, but the problem still persists. All of these sites use CloudFlare and have the same settings set.

Since this is a very vague issue, you can use the demo account on my site to log in and test anything yourself.

Site that isn't working: https://theartex.net/system/login/,
site that is working: https://mathhulk.me/system/login/

Account:
username - demo,
password - demo


问:
Ember app cannot load json data from local file
I have been following the ember quick start guide to create an app that displays some data (https://guides.emberjs.com/v2.13.0/getting-started/quick-start/) but instead of displaying just a javascript array with scientists names, I want to display the products from the following json.

I have placed the json file in the public folder.

It looks like:

```<code>{
  "products": [
    {
      "_id": "58ff60ffcd082f040072305a",
      "slug": "apple-tree-printed-linen-butterfly-bow-tie",
      "name": "Apple Tree Printed Linen Butterfly Bow Tie ",
      "description": "This fun 40 Colori Apple Tree Printed Linen Butterfly Bow Tie features a design of various apple trees built from tiny polka dots. The back of this bow tie features a polka dot print in complementing colours which when the bow tie is tied will pop out from behind making for a subtle yet unique detail. The playful design, stand out natural linen texture, and colourful combinations make this bow tie a perfect accessory for any outfit!\n",
      "standard_manufacturer": "58cbafc55491430300c422ff",
      "details": "Size: Untied (self-tie) bow tie with an easily adjustable neck strap from 13-3/4'' to 19'' (35 to 48 cm)\nHeight: 6 cm\nMaterial: Printed 100% linen\nCare: Dry clean\nMade in Italy",
      "sizes": [
        {
          "value": "Violet",
          "size": "57722c80c8595b0300a11e61",
          "_id": "58ff60ffcd082f0400723070",
          "marked_as_oos_at": null,
          "quantity": -1,
          "stock": true,
          "id": "58ff60ffcd082f0400723070"
        },
</code>```

and so on.

My code for the model of the route for displaying the list is as follows

```<code>import Ember from 'ember';

export default Ember.Route.extend({
    model() {
        //return ['Marie Curie', 'Mae Jemison', 'Albert Hofmann'];
        return Ember.$.getJSON("/products.json");
    }
});
</code>```

I have followed the tutorial exactly except for the

```<code>return Ember.$.getJSON("/products.json");
</code>```

line in scientists.js. My data is not being displayed and the error i get in the ember inspector is

```<code>compiled.js:2 Uncaught TypeError: Failed to execute 'getComputedStyle' on 'Window': parameter 1 is not of type 'Element'.
    at E (compiled.js:2)
    at Object.u (compiled.js:25)
    at compiled.js:25
E   @   compiled.js:2
u   @   compiled.js:25
(anonymous) @   compiled.js:25
</code>```

I am very new with ember and fairly new with js. Any help appreciated! Thanks!

答:
What about placing the JSON in the app folder and importing it?

```<code>import Ember from 'ember';
import yourData from 'your-app/json-file-name.js';

export default Ember.Route.extend({
  model() {
    return yourData;
  }
});
</code>```

https://ember-twiddle.com/afb9d71933322860938b3936d617a776 - you can use this to try and get a .json working...

There is a thread here too:
https://discuss.emberjs.com/t/how-to-import-data-from-json-file-to-ember-app

BUT... don't expect it to properly be in the ember-data store - and function like you'd expect in many situations.

Body:
I have been following the ember quick start guide to create an app that displays some data (https://guides.emberjs.com/v2.13.0/getting-started/quick-start/) but instead of displaying just a javascript array with scientists names, I want to display the products from the following json.

I have placed the json file in the public folder.

It looks like:

{
  "products": [
    {
      "_id": "58ff60ffcd082f040072305a",
      "slug": "apple-tree-printed-linen-butterfly-bow-tie",
      "name": "Apple Tree Printed Linen Butterfly Bow Tie ",
      "description": "This fun 40 Colori Apple Tree Printed Linen Butterfly Bow Tie features a design of various apple trees built from tiny polka dots. The back of this bow tie features a polka dot print in complementing colours which when the bow tie is tied will pop out from behind making for a subtle yet unique detail. The playful design, stand out natural linen texture, and colourful combinations make this bow tie a perfect accessory for any outfit!\n",
      "standard_manufacturer": "58cbafc55491430300c422ff",
      "details": "Size: Untied (self-tie) bow tie with an easily adjustable neck strap from 13-3/4'' to 19'' (35 to 48 cm)\nHeight: 6 cm\nMaterial: Printed 100% linen\nCare: Dry clean\nMade in Italy",
      "sizes": [
        {
          "value": "Violet",
          "size": "57722c80c8595b0300a11e61",
          "_id": "58ff60ffcd082f0400723070",
          "marked_as_oos_at": null,
          "quantity": -1,
          "stock": true,
          "id": "58ff60ffcd082f0400723070"
        },

and so on.

My code for the model of the route for displaying the list is as follows

import Ember from 'ember';

export default Ember.Route.extend({
    model() {
        //return ['Marie Curie', 'Mae Jemison', 'Albert Hofmann'];
        return Ember.$.getJSON("/products.json");
    }
});

I have followed the tutorial exactly except for the

return Ember.$.getJSON("/products.json");

line in scientists.js. My data is not being displayed and the error i get in the ember inspector is

compiled.js:2 Uncaught TypeError: Failed to execute 'getComputedStyle' on 'Window': parameter 1 is not of type 'Element'.
    at E (compiled.js:2)
    at Object.u (compiled.js:25)
    at compiled.js:25
E   @   compiled.js:2
u   @   compiled.js:25
(anonymous) @   compiled.js:25

I am very new with ember and fairly new with js. Any help appreciated! Thanks!

Body:
What about placing the JSON in the app folder and importing it?

import Ember from 'ember';
import yourData from 'your-app/json-file-name.js';

export default Ember.Route.extend({
  model() {
    return yourData;
  }
});

https://ember-twiddle.com/afb9d71933322860938b3936d617a776 - you can use this to try and get a .json working...

There is a thread here too:
https://discuss.emberjs.com/t/how-to-import-data-from-json-file-to-ember-app

BUT... don't expect it to properly be in the ember-data store - and function like you'd expect in many situations.


问:
nothing to repeat error using Scrapy when crawling geographic.org/streetview
My start URL is http://www.geographic.org/streetview/usa/index.html.

I am using the following code:

```<code>import scrapy
from scrapy.spiders import CrawlSpider, Rule
from scrapy.linkextractors import LinkExtractor
from urlparse import urljoin

class StreetViewSpider(CrawlSpider):
    name = "streetview"
    allowed_domains = ["geographic.org"]
    start_urls = ["http://www.geographic.org/streetview/usa/index.html"]
    rules = (
        Rule(LinkExtractor(restrict_xpaths="*.html"), follow=True),
        Rule(LinkExtractor(allow=('*.html',)), callback='parse_item')
    )

    def parse_item(self, response):
        self.logger.info('Hi, this is an item page! %s', response.url)
        item = scrapy.Item()
        sub_urls = response.xpath("descendant-or-self::li/descendant-or-self::*/a/@href").extract()
        item['urls'] = map(lambda x: urljoin(response.url, x), sub_urls)
        return item
</code>```

I only need the links and text of all a tags that have *.html in their URL and are with in the domain www.geographic.org. The crawler should go will the time we find view.php in href extracted.

I run the crawler using scrapy crawl streetview and I get:

```<code>> scrapy crawl streetview
Traceback (most recent call last):
  File "e:\miniconda2\lib\runpy.py", line 174, in _run_module_as_main
    "__main__", fname, loader, pkg_name)
  File "e:\miniconda2\lib\runpy.py", line 72, in _run_code
    exec code in run_globals
  File "E:\Miniconda2\Scripts\scrapy.exe\__main__.py", line 9, in <module>
  File "e:\miniconda2\lib\site-packages\scrapy\cmdline.py", line 148, in execute
    cmd.crawler_process = CrawlerProcess(settings)
  File "e:\miniconda2\lib\site-packages\scrapy\crawler.py", line 243, in __init__
    super(CrawlerProcess, self).__init__(settings)
  File "e:\miniconda2\lib\site-packages\scrapy\crawler.py", line 134, in __init__
    self.spider_loader = _get_spider_loader(settings)
  File "e:\miniconda2\lib\site-packages\scrapy\crawler.py", line 330, in _get_spider_loader
    return loader_cls.from_settings(settings.frozencopy())
  File "e:\miniconda2\lib\site-packages\scrapy\spiderloader.py", line 61, in from_settings
    return cls(settings)
  File "e:\miniconda2\lib\site-packages\scrapy\spiderloader.py", line 25, in __init__
    self._load_all_spiders()
  File "e:\miniconda2\lib\site-packages\scrapy\spiderloader.py", line 47, in _load_all_spiders
    for module in walk_modules(name):
  File "e:\miniconda2\lib\site-packages\scrapy\utils\misc.py", line 71, in walk_modules
    submod = import_module(fullpath)
  File "e:\miniconda2\lib\importlib\__init__.py", line 37, in import_module
    __import__(name)
  File "F:\PyCharmProjects\streetview\streetview\spiders\collector.py", line 7, in <module>
    class StreetViewSpider(CrawlSpider):
  File "F:\PyCharmProjects\streetview\streetview\spiders\collector.py", line 13, in StreetViewSpider
    Rule(LinkExtractor(allow=('*.html',)), callback='parse_item')
  File "e:\miniconda2\lib\site-packages\scrapy\linkextractors\lxmlhtml.py", line 116, in __init__
    canonicalize=canonicalize, deny_extensions=deny_extensions)
  File "e:\miniconda2\lib\site-packages\scrapy\linkextractors\__init__.py", line 57, in __init__
    for x in arg_to_iter(allow)]
  File "e:\miniconda2\lib\re.py", line 194, in compile
    return _compile(pattern, flags)
  File "e:\miniconda2\lib\re.py", line 251, in _compile
    raise error, v # invalid expression
sre_constants.error: nothing to repeat
</code>```

答:
You are getting the error because you are not supplying valid regular expression for allow attribute of LinkExtractor in the second rule. Also the restrict_xpaths attribute of LinkExtractor in the first rule won't work. Try going with these rules:

```<code>rules = (
    Rule(LinkExtractor(restrict_xpaths="//a[contains(@href,'.html')]"), follow=True),
    Rule(LinkExtractor(allow=('.*\.html',)), callback='parse_item')
)
</code>```

Body:
My start URL is http://www.geographic.org/streetview/usa/index.html.

I am using the following code:

import scrapy
from scrapy.spiders import CrawlSpider, Rule
from scrapy.linkextractors import LinkExtractor
from urlparse import urljoin

class StreetViewSpider(CrawlSpider):
    name = "streetview"
    allowed_domains = ["geographic.org"]
    start_urls = ["http://www.geographic.org/streetview/usa/index.html"]
    rules = (
        Rule(LinkExtractor(restrict_xpaths="*.html"), follow=True),
        Rule(LinkExtractor(allow=('*.html',)), callback='parse_item')
    )

    def parse_item(self, response):
        self.logger.info('Hi, this is an item page! %s', response.url)
        item = scrapy.Item()
        sub_urls = response.xpath("descendant-or-self::li/descendant-or-self::*/a/@href").extract()
        item['urls'] = map(lambda x: urljoin(response.url, x), sub_urls)
        return item

I only need the links and text of all a tags that have *.html in their URL and are with in the domain www.geographic.org. The crawler should go will the time we find view.php in href extracted.

I run the crawler using scrapy crawl streetview and I get:

> scrapy crawl streetview
Traceback (most recent call last):
  File "e:\miniconda2\lib\runpy.py", line 174, in _run_module_as_main
    "__main__", fname, loader, pkg_name)
  File "e:\miniconda2\lib\runpy.py", line 72, in _run_code
    exec code in run_globals
  File "E:\Miniconda2\Scripts\scrapy.exe\__main__.py", line 9, in <module>
  File "e:\miniconda2\lib\site-packages\scrapy\cmdline.py", line 148, in execute
    cmd.crawler_process = CrawlerProcess(settings)
  File "e:\miniconda2\lib\site-packages\scrapy\crawler.py", line 243, in __init__
    super(CrawlerProcess, self).__init__(settings)
  File "e:\miniconda2\lib\site-packages\scrapy\crawler.py", line 134, in __init__
    self.spider_loader = _get_spider_loader(settings)
  File "e:\miniconda2\lib\site-packages\scrapy\crawler.py", line 330, in _get_spider_loader
    return loader_cls.from_settings(settings.frozencopy())
  File "e:\miniconda2\lib\site-packages\scrapy\spiderloader.py", line 61, in from_settings
    return cls(settings)
  File "e:\miniconda2\lib\site-packages\scrapy\spiderloader.py", line 25, in __init__
    self._load_all_spiders()
  File "e:\miniconda2\lib\site-packages\scrapy\spiderloader.py", line 47, in _load_all_spiders
    for module in walk_modules(name):
  File "e:\miniconda2\lib\site-packages\scrapy\utils\misc.py", line 71, in walk_modules
    submod = import_module(fullpath)
  File "e:\miniconda2\lib\importlib\__init__.py", line 37, in import_module
    __import__(name)
  File "F:\PyCharmProjects\streetview\streetview\spiders\collector.py", line 7, in <module>
    class StreetViewSpider(CrawlSpider):
  File "F:\PyCharmProjects\streetview\streetview\spiders\collector.py", line 13, in StreetViewSpider
    Rule(LinkExtractor(allow=('*.html',)), callback='parse_item')
  File "e:\miniconda2\lib\site-packages\scrapy\linkextractors\lxmlhtml.py", line 116, in __init__
    canonicalize=canonicalize, deny_extensions=deny_extensions)
  File "e:\miniconda2\lib\site-packages\scrapy\linkextractors\__init__.py", line 57, in __init__
    for x in arg_to_iter(allow)]
  File "e:\miniconda2\lib\re.py", line 194, in compile
    return _compile(pattern, flags)
  File "e:\miniconda2\lib\re.py", line 251, in _compile
    raise error, v # invalid expression
sre_constants.error: nothing to repeat

Body:
You are getting the error because you are not supplying valid regular expression for allow attribute of LinkExtractor in the second rule. Also the restrict_xpaths attribute of LinkExtractor in the first rule won't work. Try going with these rules:

rules = (
    Rule(LinkExtractor(restrict_xpaths="//a[contains(@href,'.html')]"), follow=True),
    Rule(LinkExtractor(allow=('.*\.html',)), callback='parse_item')
)