问:
change url path using jquery
I have made a website for two different languages each being in two different folders en and bn. I want to switch between the folders on href element click using jquery.

```<code><a class="eng_link " style="" href="#"> English</a>
<a class=" link_active bangla_link " style="" href="#">বাংলা  /  </a>
</code>```

Say, I am currently on www.example.com/en/content?id=1. While clicking the link for english it will redirect to the url www.example.com/bn/content?id=1 and vice versa. Only the bn part of the url will change to en keeping other parts the same. How can I do this?

答:
This is how I have done it.
In the index page of bn:

```<code><a class="eng_link " style="" href="#" id='a' onClick="en_onClick()"> English</a>
<a class=" link_active bangla_link " style="" href="index" >বাংলা  /   </a>
</code>```

JS

```<code>    function en_onClick() {
     $(location).attr('href');
     var bn_pathname = window.location.href;
     var en_pathname = bn_pathname.replace("bn/", "en/");
     window.location.replace(en_pathname);
 }
</code>```

In the index page of en:

```<code> <a class=" bangla_link link_in" style="" href="#" onClick="bn_onClick()"> বাংলা</a>
 <a class=" link_active  eng_link" style="" href="#"> English  /   </a>
</code>```

JS

```<code>    function bn_onClick() {
     $(location).attr('href');
     var bn_pathname = window.location.href;
     var en_pathname = bn_pathname.replace("en/", "bn/");
     window.location.replace(en_pathname);
 }
</code>```

Title: change url path using jquery

Body:
I have made a website for two different languages each being in two different folders en and bn. I want to switch between the folders on href element click using jquery.

 English
বাংলা  /

Say, I am currently on www.example.com/en/content?id=1. While clicking the link for english it will redirect to the url www.example.com/bn/content?id=1 and vice versa. Only the bn part of the url will change to en keeping other parts the same. How can I do this?

Body:
This is how I have done it.
In the index page of bn:

<a class="eng_link " style="" href="#" id='a' onClick="en_onClick()"> English</a>
<a class=" link_active bangla_link " style="" href="index" >বাংলা &nbsp;/ &nbsp; </a>

JS

    function en_onClick() {
     $(location).attr('href');
     var bn_pathname = window.location.href;
     var en_pathname = bn_pathname.replace("bn/", "en/");
     window.location.replace(en_pathname);
 }

In the index page of en:

 <a class=" bangla_link link_in" style="" href="#" onClick="bn_onClick()"> বাংলা</a>
 <a class=" link_active  eng_link" style="" href="#"> English &nbsp;/ &nbsp; </a>

JS

    function bn_onClick() {
     $(location).attr('href');
     var bn_pathname = window.location.href;
     var en_pathname = bn_pathname.replace("en/", "bn/");
     window.location.replace(en_pathname);
 }


来源: stackexchange

问:
jquery update total based on checkboxes
I have a form where based on checkbox total value will be updated

Here is my form

```<code><label class="checkbox">
        <input type="checkbox" class="check" value="23">SEO
    </label>
    <label class="checkbox">
        <input type="checkbox" class="check" value="34">XYZ
    </label>
    <label class="checkbox">
            <input type="checkbox" class="check" value="45">Logo Design
    </label>

    <span class="product-price" id="total" >45</span>
</code>```

jQuery I have used

```<code>  $('input[type=checkbox]').change(function () {
        var val = parseFloat(this.value),
            totalVal = parseFloat($('#total').val());
        if (this.checked) {
            $('#total').val((totalVal + val).toFixed(2));
        } else {
            $('#total').val((totalVal - val).toFixed(2));
        }
    });
</code>```

But nothing get updated.What could be the possible Error?
Any solution please

答:
Span attribute doesn't have a val() property but text()

    $('input[type=checkbox]').change(function () {
            var val = parseFloat(this.value),
                totalVal = parseFloat($('#total').text());
            if (this.checked) {
                $('#total').text((totalVal + val).toFixed(2));
            } else {
                $('#total').text((totalVal - val).toFixed(2));
            }
        });```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label class="checkbox">
        <input type="checkbox" class="check" value="23">SEO
    </label>
    <label class="checkbox">
        <input type="checkbox" class="check" value="34">XYZ
    </label>
    <label class="checkbox">
            <input type="checkbox" class="check" value="45">Logo Design
    </label>

    <span class="product-price" id="total" >45</span></code>```

ContentLicense: CC BY-SA 3.0

Title: jquery update total based on checkboxes

Body:
I have a form where based on checkbox total value will be updated

Here is my form

        <input type="checkbox" class="check" value="23">SEO

        <input type="checkbox" class="check" value="34">XYZ

            <input type="checkbox" class="check" value="45">Logo Design

    45

jQuery I have used

  $('input[type=checkbox]').change(function () {
        var val = parseFloat(this.value),
            totalVal = parseFloat($('#total').val());
        if (this.checked) {
            $('#total').val((totalVal + val).toFixed(2));
        } else {
            $('#total').val((totalVal - val).toFixed(2));
        }
    });

But nothing get updated.What could be the possible Error?
Any solution please

Body:
Span attribute doesn't have a val() property but text()

    $('input[type=checkbox]').change(function () {
            var val = parseFloat(this.value),
                totalVal = parseFloat($('#total').text());
            if (this.checked) {
                $('#total').text((totalVal + val).toFixed(2));
            } else {
                $('#total').text((totalVal - val).toFixed(2));
            }
        });

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label class="checkbox">
        <input type="checkbox" class="check" value="23">SEO
    </label>
    <label class="checkbox">
        <input type="checkbox" class="check" value="34">XYZ
    </label>
    <label class="checkbox">
            <input type="checkbox" class="check" value="45">Logo Design
    </label>

    <span class="product-price" id="total" >45</span>


问:
How to convert normal string to datetime in Pandas
I have normal strings with more than millions data points from .csv file with format as below:

```<code>Datetime
22/12/2015  17:00:00
22/12/2015  18:00:00
</code>```

I loaded into pandas and tried to converted into datetime format by using pandas.to_datetime(df['Datetime']). However, the new time series data I got that is not correct. There are some new Datetime produced during converting process. For example, 2016-12-11 23:30:00 that does not contain in original data.

答:
It has been a while that I worked with panda, but in your example you have a different dateformat than in the example lines from csv:

```<code>yyyy-mm-dd hh:mm:ss
</code>```

instead of

```<code>mm/dd/yyyy hh:mm:ss
</code>```

the to_datetime function takes a parameter "format", this should help if that is the cause.

Body:
I have normal strings with more than millions data points from .csv file with format as below:

Datetime
22/12/2015  17:00:00
22/12/2015  18:00:00

I loaded into pandas and tried to converted into datetime format by using pandas.to_datetime(df['Datetime']). However, the new time series data I got that is not correct. There are some new Datetime produced during converting process. For example, 2016-12-11 23:30:00 that does not contain in original data.

Body:
It has been a while that I worked with panda, but in your example you have a different dateformat than in the example lines from csv:

yyyy-mm-dd hh:mm:ss

instead of

mm/dd/yyyy hh:mm:ss

the to_datetime function takes a parameter "format", this should help if that is the cause.


问:
Javascript: Nested Callbacks/MySQL Results
I am sure this is a basic question, but I have been searching google for awhile and can't find a satisfactory answer..

I am used to programming MySQL select queries in PHP and simply grabbing a result, looping through each row, and within the loop doing further queries based on the column values of each individual row.

However, I'm working with javascript server side code now that relies on a SQL object where you pass the query and then a callback function that will be invoked after the query is run.

I'm confused with some of the scoping issues and how to best cleanly do this. For example, I don't want to do something like:

```<code>SQL.query("select * from blah", function(result) {
  for(var i = 0; i < result.length; i++) {
    SQL.query("select * from blah2 where i =" + result[i].property, function(result2) {
      //now how do I access result from here? I know this isn't scoped correctly
    });
  }
});
</code>```

What is the standard way to write this style of nested SQL query and not have scoping issues/messy code? Thanks!

答:
Since you are using server-side Javascript, you can likely use forEach. Assuming that result instanceof Array == true:

```<code>SQL.query("select * from blah", function(result) {
  result.forEach(function(item, index) {
    SQL.query("select * from blah2 where i = " + item.property, function(result2) {
      console.log(item, index, result); //works as intended
    });
  });
});
</code>```

If result is merely array-like, then this

```<code>Array.prototype.forEach.call(result, function(item, index) { // etc...
</code>```

should do the trick.

ContentLicense: CC BY-SA 2.5

Body:
I am sure this is a basic question, but I have been searching google for awhile and can't find a satisfactory answer..

I am used to programming MySQL select queries in PHP and simply grabbing a result, looping through each row, and within the loop doing further queries based on the column values of each individual row.

However, I'm working with javascript server side code now that relies on a SQL object where you pass the query and then a callback function that will be invoked after the query is run.

I'm confused with some of the scoping issues and how to best cleanly do this. For example, I don't want to do something like:

SQL.query("select * from blah", function(result) {
  for(var i = 0; i < result.length; i++) {
    SQL.query("select * from blah2 where i =" + result[i].property, function(result2) {
      //now how do I access result from here? I know this isn't scoped correctly
    });
  }
});

What is the standard way to write this style of nested SQL query and not have scoping issues/messy code? Thanks!

Body:
Since you are using server-side Javascript, you can likely use forEach. Assuming that result instanceof Array == true:

SQL.query("select * from blah", function(result) {
  result.forEach(function(item, index) {
    SQL.query("select * from blah2 where i = " + item.property, function(result2) {
      console.log(item, index, result); //works as intended
    });
  });
});

If result is merely array-like, then this

Array.prototype.forEach.call(result, function(item, index) { // etc...

should do the trick.


问:
How to use collapse menu bar only in bootstrap mobile mode
https://s11.postimg.org/a5wieqgkj/navbar.png

Hi,
For bootstrap navigation bar how to make it show only collapse menu(without brand name and background bar) in small screen devices. That is it should show only following.
https://s8.postimg.org/4npr7uxvp/navbar.png

Thanks.

答:
You could solve it by using media query. Here you go. Feel free to ask me. Hope this answer yours.

@media (max-width: 700px) {
  .navbar-header {
    background-color: white;
  }
  nav.navbar {
    border: 0px;
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<nav class="navbar navbar-default">
  <div class="container-fluid">
    <!-- Brand and toggle get grouped for better mobile display -->
    <div class="navbar-header">
      <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
        <span class="sr-only">Toggle navigation</span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
      </button>
    </div>

    <!-- Collect the nav links, forms, and other content for toggling -->
    <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
      <ul class="nav navbar-nav">
        <li class="active">Home <span class="sr-only">(current)</span></li>
        <li>About Us</li>
      </ul>
    </div><!-- /.navbar-collapse -->
  </div><!-- /.container-fluid -->
</nav>
<script
  src="https://code.jquery.com/jquery-3.2.1.js"
  integrity="sha256-DZAnKJ/6XZ9si04Hgrsxu/8s717jcIzLy3oi35EouyE="
  crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script></code>```

Body:
You could solve it by using media query. Here you go. Feel free to ask me. Hope this answer yours.

@media (max-width: 700px) {
  .navbar-header {
    background-color: white;
  }
  nav.navbar {
    border: 0px;
  }
}

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<nav class="navbar navbar-default">
  <div class="container-fluid">
    <!-- Brand and toggle get grouped for better mobile display -->
    <div class="navbar-header">
      <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
        <span class="sr-only">Toggle navigation</span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
      </button>
    </div>

    <!-- Collect the nav links, forms, and other content for toggling -->
    <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
      <ul class="nav navbar-nav">
        <li class="active"><a href="#">Home <span class="sr-only">(current)</span></a></li>
        <li><a href="#">About Us</a></li>
      </ul>
    </div><!-- /.navbar-collapse -->
  </div><!-- /.container-fluid -->
</nav>
<script
  src="https://code.jquery.com/jquery-3.2.1.js"
  integrity="sha256-DZAnKJ/6XZ9si04Hgrsxu/8s717jcIzLy3oi35EouyE="
  crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>


问:
Android Firebase database: how to retrieve multiple rows?
This is my database structure:

What i am trying to do, is to fill a listView with all the elements in the database, in a custom layout with 3 textView for each line:

Title

Date

Text

Title

Date

Text

Title

Date

Text

I tried custom adapter, extending FirebaseListAdapter<>,with a class to store the data, but i can't solve this problem.

Can you help me, please?

答:
```<code>FirebaseDatabase database = FirebaseDatabase.getInstance();
        DatabaseReference myRef = database.getReference();
        myRef.addListenerForSingleValueEvent(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                if (dataSnapshot.hasChildren()) {
                    for (DataSnapshot dataSnapshot1 : dataSnapshot.getChildren()) {
                     your_module_obj=   dataSnapshot1.getValue(Your_module_class_name.class);
                    }
                }
            }
        @Override
        public void onCancelled(DatabaseError error) {
            Log.w("dd", "Failed to read value.", error.toException());
        }
    });
</code>```


问:
getting scheme java.lang.NullPointerException: scheme while trying to fake a server call in my service
I have a service class in my project and I want to test one of its methods that is performing an api call, so I want to catch this call and return something fake so I can test my method, it looks like this:

```<code>class MyService @Inject()(implicit config: Configuration, wsClient: WSClient) {

  def methodToTest(list: List[String]): Future[Either[BadRequestResponse, Unit]] = {
    wsClient.url(url).withHeaders(("Content-Type", "application/json")).post(write(list)).map { response =>
      response.status match {
        case Status.OK =>
          Right(logger.debug("Everything is OK!"))
        case Status.BAD_REQUEST =>
          Left(parse(response.body).extract[BadRequestResponse])
        case _ =>
          val ex = new RuntimeException(s"Failed with status: ${response.status} body: ${response.body}")
          logger.error(s"Service failed: ", ex)
          throw ex
      }
    }
  }
}
</code>```

and now in my test class I go:

```<code>class MyServiceTest extends FreeSpec with ShouldMatchers with OneAppPerSuite with ScalaFutures with WsScalaTestClient {

  implicit lazy val materializer: Materializer = app.materializer
  lazy val config: Configuration = app.injector.instanceOf[Configuration]
  lazy val myService = app.injector.instanceOf[MyService]

  "My Service Tests" - {

    "Should behave as im expecting" in {
      Server.withRouter() {
        case POST(p"/fake/api/in/conf") => Action { request =>
          Results.Ok
        }
      } { implicit port =>
        WsTestClient.withClient { implicit client =>

          whenReady(myService.methodToTest(List("1","2","3"))) { res =>
            res.isRight shouldBe true
          }
        }
      }
    }
  }
}
</code>```

and I get this error:

```<code>scheme java.lang.NullPointerException: scheme
</code>```

also tried put under client => :

```<code>val myService = new MyService {
         implicit val config: Configuration = configuration
         implicit val ws: WSClient = client
      }
</code>```

but got some other error that I dont have enough arguments in the constructor...

why is it not working?

if there is a better nd simpler way to fake this api call i will love to hear it :)

thanks!

答:
Server.withRouter may not be exactly what you want. It creates a server and bound it to a random port, per instance (unless you specify the port). It also creates its own instance of application which will be disconnected from the app you used to instantiate the service.

Another thing is that the injected WSClient do not works relative to your application. You need to use the client which is passed to WsTestClient.withClient block instead. So, you should do something like:

```<code>class MyServiceTest extends FreeSpec with ShouldMatchers with OneAppPerSuite with ScalaFutures with WsScalaTestClient {

  implicit lazy val materializer: Materializer = app.materializer
  lazy val config: Configuration = app.injector.instanceOf[Configuration]

  "My Service Tests" - {

    "Should behave as im expecting" in {
      Server.withRouter() {
        case POST(p"/fake/api/in/conf") => Action { request =>
          Results.Ok
        }
      } { implicit port =>
        WsTestClient.withClient { implicit client =>

          // Use the client "instrumented" by Play. It will
          // handle the relative aspect of the url.
          val myService = new MyService(client, config)

          whenReady(myService.methodToTest(List("1","2","3"))) { res =>
            res.isRight shouldBe true
          }
        }
      }
    }
  }
}
</code>```

Body:
I have a service class in my project and I want to test one of its methods that is performing an api call, so I want to catch this call and return something fake so I can test my method, it looks like this:

class MyService @Inject()(implicit config: Configuration, wsClient: WSClient) {

  def methodToTest(list: List[String]): Future[Either[BadRequestResponse, Unit]] = {
    wsClient.url(url).withHeaders(("Content-Type", "application/json")).post(write(list)).map { response =>
      response.status match {
        case Status.OK =>
          Right(logger.debug("Everything is OK!"))
        case Status.BAD_REQUEST =>
          Left(parse(response.body).extract[BadRequestResponse])
        case _ =>
          val ex = new RuntimeException(s"Failed with status: ${response.status} body: ${response.body}")
          logger.error(s"Service failed: ", ex)
          throw ex
      }
    }
  }
}

and now in my test class I go:

class MyServiceTest extends FreeSpec with ShouldMatchers with OneAppPerSuite with ScalaFutures with WsScalaTestClient {

  implicit lazy val materializer: Materializer = app.materializer
  lazy val config: Configuration = app.injector.instanceOf[Configuration]
  lazy val myService = app.injector.instanceOf[MyService]

  "My Service Tests" - {

    "Should behave as im expecting" in {
      Server.withRouter() {
        case POST(p"/fake/api/in/conf") => Action { request =>
          Results.Ok
        }
      } { implicit port =>
        WsTestClient.withClient { implicit client =>

          whenReady(myService.methodToTest(List("1","2","3"))) { res =>
            res.isRight shouldBe true
          }
        }
      }
    }
  }
}

and I get this error:

scheme java.lang.NullPointerException: scheme

also tried put under client => :

val myService = new MyService {
         implicit val config: Configuration = configuration
         implicit val ws: WSClient = client
      }

but got some other error that I dont have enough arguments in the constructor...

why is it not working?

if there is a better nd simpler way to fake this api call i will love to hear it :)

thanks!

Body:
Server.withRouter may not be exactly what you want. It creates a server and bound it to a random port, per instance (unless you specify the port). It also creates its own instance of application which will be disconnected from the app you used to instantiate the service.

Another thing is that the injected WSClient do not works relative to your application. You need to use the client which is passed to WsTestClient.withClient block instead. So, you should do something like:

class MyServiceTest extends FreeSpec with ShouldMatchers with OneAppPerSuite with ScalaFutures with WsScalaTestClient {

  implicit lazy val materializer: Materializer = app.materializer
  lazy val config: Configuration = app.injector.instanceOf[Configuration]

  "My Service Tests" - {

    "Should behave as im expecting" in {
      Server.withRouter() {
        case POST(p"/fake/api/in/conf") => Action { request =>
          Results.Ok
        }
      } { implicit port =>
        WsTestClient.withClient { implicit client =>

          // Use the client "instrumented" by Play. It will
          // handle the relative aspect of the url.
          val myService = new MyService(client, config)

          whenReady(myService.methodToTest(List("1","2","3"))) { res =>
            res.isRight shouldBe true
          }
        }
      }
    }
  }
}


问:
'Access-Control-Allow-Origin' error in request js
I'm writing an angular 2 app which uses a module called github-trend. I have a service which calls some functions from the module

```<code> scraper.scrapeTrendingRepos("").then(function(repos) {
 repos.forEach(function(repo) {
    //more code here
});
}).catch(function(err) {
  console.log(err.message);
});
</code>```

For now I'm testing my angular app with Chrome(56.0.2924.87) on http://localhost:3000/ and its giving me an Access-Control-Allow-Origin, here is full message:

Fetch API cannot load https://github.com/trending. No
  'Access-Control-Allow-Origin' header is present on the requested
  resource. Origin 'http://localhost:3000' is therefore not allowed
  access. If an opaque response serves your needs, set the request's
  mode to 'no-cors' to fetch the resource with CORS disabled.

data.service.ts:43 Failed to fetch

I've searched around and know that this might be happening because get request and server are working on differnt ports? Looking at the repo, the github-trend module using requestjs to make http requests but I'm not sure how to fix this. Is there a way I can make it work on chrome? What should I modify in the module code so as to make it work?

答: Solved the problem by using an Allow-Control-Allow-Origin extension for chrome.

Body:
I'm writing an angular 2 app which uses a module called github-trend. I have a service which calls some functions from the module

 scraper.scrapeTrendingRepos("").then(function(repos) {
 repos.forEach(function(repo) {
    //more code here
});
}).catch(function(err) {
  console.log(err.message);
});

For now I'm testing my angular app with Chrome(56.0.2924.87) on http://localhost:3000/ and its giving me an Access-Control-Allow-Origin, here is full message:

Fetch API cannot load https://github.com/trending. No
  'Access-Control-Allow-Origin' header is present on the requested
  resource. Origin 'http://localhost:3000' is therefore not allowed
  access. If an opaque response serves your needs, set the request's
  mode to 'no-cors' to fetch the resource with CORS disabled.

data.service.ts:43 Failed to fetch

I've searched around and know that this might be happening because get request and server are working on differnt ports? Looking at the repo, the github-trend module using requestjs to make http requests but I'm not sure how to fix this. Is there a way I can make it work on chrome? What should I modify in the module code so as to make it work?


问:
How to handle white spaces in dataframe column names in spark
I registered a tmp table from a df that has white spaces in the column header.how can i extract the column while using sql query via sqlContext.
I tried to use back-tick but it is not working</p>

```<code>df1 =  sqlContext.sql("""select Company, Sector, Industry, `Altman Z-score as Z_Score` from tmp1 """)
</code>```

答:
You have to place only the column name within back-ticks, not its alias:

Without Alias:

```<code>df1 =  sqlContext.sql("""select Company, Sector, Industry, `Altman Z-score` as Z_Score from tmp1""")
</code>```

With Alias:

```<code>df1 =  sqlContext.sql("""select t1.Company, t1.Sector, t1.Industry, t1.`Altman Z-score` as Z_Score from tmp1 t1""")
</code>```

Body:
I registered a tmp table from a df that has white spaces in the column header.how can i extract the column while using sql query via sqlContext.
I tried to use back-tick but it is not working

df1 =  sqlContext.sql("""select Company, Sector, Industry, `Altman Z-score as Z_Score` from tmp1 """)

Body:
You have to place only the column name within back-ticks, not its alias:

Without Alias:

df1 =  sqlContext.sql("""select Company, Sector, Industry, `Altman Z-score` as Z_Score from tmp1""")

With Alias:

df1 =  sqlContext.sql("""select t1.Company, t1.Sector, t1.Industry, t1.`Altman Z-score` as Z_Score from tmp1 t1""")


问:
Cannot find class in classpath when trying to run TestNG from the main method
I run my Selenium Testng tests using Maven, but I am trying to create executable jars, so other team members can simply run an automation suite from their desktop with minimal setup.

So I have added a main "runner" method to create an executable jar.

```<code>public class LaunchTests {

public static void main(String[] args) {
    TestListenerAdapter tla = new TestListenerAdapter();
    TestNG testng = new TestNG();
    List<String> suites = new ArrayList();
    suites.add("testng.xml");//path to xml..
    testng.setTestSuites(suites);
    testng.run();

}
</code>```

}

My best guess is that something needs to be added to the POM.xml?

When running the testng tests manually from eclipse, or with mvn clean test (Surefire plugin), they run flawlessly. But I get this error when trying to run as a Java program.

```<code>    Exception in thread "main" org.testng.TestNGException:
Cannot find class in classpath: package.TestOne
    at org.testng.xml.XmlClass.loadClass(XmlClass.java:81)
    at org.testng.xml.XmlClass.init(XmlClass.java:73)
    at org.testng.xml.XmlClass.<init>(XmlClass.java:59)
    at org.testng.xml.TestNGContentHandler.startElement(TestNGContentHandler.java:548)
    at com.sun.org.apache.xerces.internal.parsers.AbstractSAXParser.startElement(Unknown Source)
    at com.sun.org.apache.xerces.internal.parsers.AbstractXMLDocumentParser.emptyElement(Unknown Source)
    at com.sun.org.apache.xerces.internal.impl.dtd.XMLDTDValidator.emptyElement(Unknown Source)
    at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl.scanStartElement(Unknown Source)
    at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl$FragmentContentDriver.next(Unknown Source)
    at com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl.next(Unknown Source)
    at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl.scanDocument(Unknown Source)
    at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(Unknown Source)
    at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(Unknown Source)
    at com.sun.org.apache.xerces.internal.parsers.XMLParser.parse(Unknown Source)
    at com.sun.org.apache.xerces.internal.parsers.AbstractSAXParser.parse(Unknown Source)
    at com.sun.org.apache.xerces.internal.jaxp.SAXParserImpl$JAXPSAXParser.parse(Unknown Source)
    at com.sun.org.apache.xerces.internal.jaxp.SAXParserImpl.parse(Unknown Source)
    at javax.xml.parsers.SAXParser.parse(Unknown Source)
    at org.testng.xml.XMLParser.parse(XMLParser.java:38)
    at org.testng.xml.SuiteXmlParser.parse(SuiteXmlParser.java:16)
    at org.testng.xml.SuiteXmlParser.parse(SuiteXmlParser.java:9)
    at org.testng.xml.Parser.parse(Parser.java:172)
    at org.testng.TestNG.initializeSuitesAndJarFile(TestNG.java:302)
    at org.testng.TestNG.run(TestNG.java:991)
    at util.LaunchTests.main(LaunchTests.java:17)
</code>```

Testng.xml

```<code><?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<suite name="Suite1" parallel="methods" thread-count="1">

    <test name="Chrome Adviser Portal" allow-return-values="true"
        thread-count="1">
        <parameters>
            <parameter name="browser" value="chrome" />
            <parameter name="loginType" value="adviser" />
        </parameters>
        <classes>
            <class name="adviserPortal.AdviserLogin" />
        </classes>
    </test>
</suite>
</code>```

答:
You mentioned that you are able to run the tests from within eclipse via maven surefire plugin and you are not able to run it only when executing your main method.

This can only happen when you class LaunchTests resides in src/main/java and your suite xml file testng.xml is referring to classes within src/test/java. Java classes within src/main/java donot have visibility into java classes that reside within src/test/java. That explains why TestNG throws the exception Cannot find class in classpath

And if your LaunchTests moves into src/test/java then by default it wont be included in the uber jar (executable jar) that you are building because test classes are omitted.

So if you really want to be able to do this, you have two options

Move all your test classes from src/test/java into src/main/java and then work with it (Surefire plugin configuration in your pom file may need some tweaks to let it know that your test sources is not src/test/java but src/main/java.

You make use of something like maven jar plugin to create a jar of test classes by referring to here.

Body:
I run my Selenium Testng tests using Maven, but I am trying to create executable jars, so other team members can simply run an automation suite from their desktop with minimal setup.

So I have added a main "runner" method to create an executable jar.

public class LaunchTests {

public static void main(String[] args) {
    TestListenerAdapter tla = new TestListenerAdapter();
    TestNG testng = new TestNG();
    List<String> suites = new ArrayList();
    suites.add("testng.xml");//path to xml..
    testng.setTestSuites(suites);
    testng.run();

}

}

My best guess is that something needs to be added to the POM.xml?

When running the testng tests manually from eclipse, or with mvn clean test (Surefire plugin), they run flawlessly. But I get this error when trying to run as a Java program.

    Exception in thread "main" org.testng.TestNGException:
Cannot find class in classpath: package.TestOne
    at org.testng.xml.XmlClass.loadClass(XmlClass.java:81)
    at org.testng.xml.XmlClass.init(XmlClass.java:73)
    at org.testng.xml.XmlClass.<init>(XmlClass.java:59)
    at org.testng.xml.TestNGContentHandler.startElement(TestNGContentHandler.java:548)
    at com.sun.org.apache.xerces.internal.parsers.AbstractSAXParser.startElement(Unknown Source)
    at com.sun.org.apache.xerces.internal.parsers.AbstractXMLDocumentParser.emptyElement(Unknown Source)
    at com.sun.org.apache.xerces.internal.impl.dtd.XMLDTDValidator.emptyElement(Unknown Source)
    at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl.scanStartElement(Unknown Source)
    at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl$FragmentContentDriver.next(Unknown Source)
    at com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl.next(Unknown Source)
    at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl.scanDocument(Unknown Source)
    at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(Unknown Source)
    at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(Unknown Source)
    at com.sun.org.apache.xerces.internal.parsers.XMLParser.parse(Unknown Source)
    at com.sun.org.apache.xerces.internal.parsers.AbstractSAXParser.parse(Unknown Source)
    at com.sun.org.apache.xerces.internal.jaxp.SAXParserImpl$JAXPSAXParser.parse(Unknown Source)
    at com.sun.org.apache.xerces.internal.jaxp.SAXParserImpl.parse(Unknown Source)
    at javax.xml.parsers.SAXParser.parse(Unknown Source)
    at org.testng.xml.XMLParser.parse(XMLParser.java:38)
    at org.testng.xml.SuiteXmlParser.parse(SuiteXmlParser.java:16)
    at org.testng.xml.SuiteXmlParser.parse(SuiteXmlParser.java:9)
    at org.testng.xml.Parser.parse(Parser.java:172)
    at org.testng.TestNG.initializeSuitesAndJarFile(TestNG.java:302)
    at org.testng.TestNG.run(TestNG.java:991)
    at util.LaunchTests.main(LaunchTests.java:17)

Testng.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<suite name="Suite1" parallel="methods" thread-count="1">

    <test name="Chrome Adviser Portal" allow-return-values="true"
        thread-count="1">
        <parameters>
            <parameter name="browser" value="chrome" />
            <parameter name="loginType" value="adviser" />
        </parameters>
        <classes>
            <class name="adviserPortal.AdviserLogin" />
        </classes>
    </test>
</suite>


问:
Cannot implicitly convert type 'string' to 'byte' in c#
For example consider the following code:

```<code>Properties.Settings.Default.startUp = cmbStart.SelectedIndex.ToString();
</code>```

in vb.net the same approach works fine but in c# it's not. Here startUp is user defined setting which is type byte and cmbStart is a ComboBox. What can I do to fix this error?

答:
The difference is that VB.Net allow string to be implicitly converted into byte, and throw an exception if the value cannot be converted, but c# doesn't allow string to be implicitly converted.

SelectedIndex is of type integer, try casting it to byte instead of using ToString() method,use the following code:

```<code>Properties.Settings.Default.startUp = (byte)cmbStart.SelectedIndex;
</code>```

Useful Links

Option Explicit and Option Strict in Visual Basic .NET and in Visual Basic

Option Strict Statement

Implicit and Explicit Conversions (Visual Basic)

Conversions Between Strings and Other Types (Visual Basic)

Cannot implicitly convert type 'string' to 'int'

Casting and Type Conversions (C# Programming Guide)

How to: Convert a String to a Number (C# Programming Guide)

Body:
For example consider the following code:

Properties.Settings.Default.startUp = cmbStart.SelectedIndex.ToString();

in vb.net the same approach works fine but in c# it's not. Here startUp is user defined setting which is type byte and cmbStart is a ComboBox. What can I do to fix this error?

Body:
The difference is that VB.Net allow string to be implicitly converted into byte, and throw an exception if the value cannot be converted, but c# doesn't allow string to be implicitly converted.

SelectedIndex is of type integer, try casting it to byte instead of using ToString() method,use the following code:

Properties.Settings.Default.startUp = (byte)cmbStart.SelectedIndex;

Useful Links

Option Explicit and Option Strict in Visual Basic .NET and in Visual Basic

Option Strict Statement

Implicit and Explicit Conversions (Visual Basic)

Conversions Between Strings and Other Types (Visual Basic)

Cannot implicitly convert type 'string' to 'int'

Casting and Type Conversions (C# Programming Guide)

How to: Convert a String to a Number (C# Programming Guide)


答:
You cann't. String type contain multiple byte
you can choose maybe one of it's character

```<code>cmbStart.SelectedIndex.ToString()[0]
</code>```

this will return first character of the converted index to string (probably not what you want).
but if you combo box doesn't has more than 256 item to select from,
you can convert the returned value for selected item to byte and store it in startup.

```<code>(byte)cmbStart.SelectedIndex
</code>```

Title: Cannot implicitly convert type 'string' to 'byte' in c#

Body:
You cann't. String type contain multiple byte
you can choose maybe one of it's character

cmbStart.SelectedIndex.ToString()[0]

this will return first character of the converted index to string (probably not what you want).
but if you combo box doesn't has more than 256 item to select from,
you can convert the returned value for selected item to byte and store it in startup.

(byte)cmbStart.SelectedIndex


问:
Retrieving a element with multiple xpaths
This isn't much of a coding question but one about what options should I take next. I've just started using selenium about a week ago and started to get the hang of most of its function.

I was working on a work project to login into various websites until I ran into a issue where I was getting this error when I tried to find the password field

Exception in thread "main" org.openqa.selenium.ElementNotVisibleException: element not visible

I went ahead and double checked the name & id  but I couldn't find the field using locators like .id, name, and xpath. I inspected the xpath with Firebug and noticed that it returned two results instead of one.

Current Xpath looks like this

```<code>.//*[@id='password']
</code>```

I was wondering if anyone could point me to the right direct when  dealing with something like this.

答:
In cases like this you need to use another unique DOM element (parent, ancestor, sibling, child) with connection to the element you are looking for. For example In those html snippets

```<code><div id='a'>
  <div id='password'></div>
</div>
</code>```

And

```<code><div id='b'>
  <div id='password'></div>
</div>
</code>```

.//*[@id='password'] will have two results

However

```<code>.//*[@id='b']/[@id='password']
</code>```

Will have only one result

Body:
This isn't much of a coding question but one about what options should I take next. I've just started using selenium about a week ago and started to get the hang of most of its function.

I was working on a work project to login into various websites until I ran into a issue where I was getting this error when I tried to find the password field

Exception in thread "main" org.openqa.selenium.ElementNotVisibleException: element not visible

I went ahead and double checked the name & id  but I couldn't find the field using locators like .id, name, and xpath. I inspected the xpath with Firebug and noticed that it returned two results instead of one.

Current Xpath looks like this

.//*[@id='password']

I was wondering if anyone could point me to the right direct when  dealing with something like this.

Body:
In cases like this you need to use another unique DOM element (parent, ancestor, sibling, child) with connection to the element you are looking for. For example In those html snippets

<div id='a'>
  <div id='password'></div>
</div>

And

<div id='b'>
  <div id='password'></div>
</div>

.//*[@id='password'] will have two results

However

.//*[@id='b']/[@id='password']

Will have only one result


问:
Conversion of Video background to colored background
I am using a video as background after the completion of video I would like to change the video background to colour background like red green or some any colour. I am trying in HTML5 but got stuck. Can anyone please help me with this.</p>

答:
try this code, as per my understanding may be this is what you are searching for, here after completion of video in the background, i have changed body background color to red.

  $(document).ready(function(){
    $('video').on('ended',function(){
    $("video").first().attr('src','')
         $('html, body').css('background','red');
    });
  });```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#header {
  border-bottom: 0px;
  margin-bottom: 0px;
}
.featured-area {
  margin-top: 0px;
  margin-bottom: 0px;
}
#recent-posts {
  margin-top: 27px;
}
#blurb {
  margin-bottom: 27px;
  width: 75%;
}
.recent-post-box {
  background-color: #f2f2f2;
  padding-top: 4px;
  margin-top: 40px;
}
#logo {
  display: none;
}
#hero {
  position: relative;
  z-index: 1;
  height: 600px;
  width: 100%;
  margin-bottom: 40px;
  vertical-align: middle;
  text-align: center;
}
#hero #bg {
  position: absolute;
  z-index: -1;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  background: url("http://www.makemeapro.org/wp-content/uploads/2015/07/hero-cover-modified.jpg");
  opacity: .4;
  max-width:100%;
  height:auto;
  background-size:cover;
    overflow:hidden;
}
#outerDiv {
  width: 100%;
  height: 100%;
}
.btn {
  background: #3498db;
  background-image: -webkit-linear-gradient(top, #3498db, #2980b9);
  background-image: -moz-linear-gradient(top, #3498db, #2980b9);
  background-image: -ms-linear-gradient(top, #3498db, #2980b9);
  background-image: -o-linear-gradient(top, #3498db, #2980b9);
  background-image: linear-gradient(to bottom, #3498db, #2980b9);
  -webkit-border-radius: 28;
  -moz-border-radius: 28;
  border-radius: 28px;
  color: #ffffff;
  font-size: 20px;
  padding: 10px 20px 10px 20px;
  text-decoration: none;
  border: 0px;
  outline: none;
}

.btn:hover {
  background: #3cb0fd;
  background-image: -webkit-linear-gradient(top, #3cb0fd, #3498db);
  background-image: -moz-linear-gradient(top, #3cb0fd, #3498db);
  background-image: -ms-linear-gradient(top, #3cb0fd, #3498db);
  background-image: -o-linear-gradient(top, #3cb0fd, #3498db);
  background-image: linear-gradient(to bottom, #3cb0fd, #3498db);
  text-decoration: none;
  cursor: pointer;
}

#hero video {
    width:100%;
    height:100%;
    object-fit:cover;
}</code>```

<!DOCTYPE html>

     <video autoplay>
        <source src="http://www.w3schools.com/html/mov_bbb.mp4" type="video/mp4"/>
        <source src="http://www.w3schools.com/html/mov_bbb.ogg" type="video/ogg"/>
      </video>

Helping young professionals navigate the world of work.

<button class="btn">JOIN THE REVOLUTION</button>

```

Body:
try this code, as per my understanding may be this is what you are searching for, here after completion of video in the background, i have changed body background color to red.

  $(document).ready(function(){
    $('video').on('ended',function(){
    $("video").first().attr('src','')
         $('html, body').css('background','red');
    });
  });

#header {
  border-bottom: 0px;
  margin-bottom: 0px;
}
.featured-area {
  margin-top: 0px;
  margin-bottom: 0px;
}
#recent-posts {
  margin-top: 27px;
}
#blurb {
  margin-bottom: 27px;
  width: 75%;
}
.recent-post-box {
  background-color: #f2f2f2;
  padding-top: 4px;
  margin-top: 40px;
}
#logo {
  display: none;
}
#hero {
  position: relative;
  z-index: 1;
  height: 600px;
  width: 100%;
  margin-bottom: 40px;
  vertical-align: middle;
  text-align: center;
}
#hero #bg {
  position: absolute;
  z-index: -1;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  background: url("http://www.makemeapro.org/wp-content/uploads/2015/07/hero-cover-modified.jpg");
  opacity: .4;
  max-width:100%;
  height:auto;
  background-size:cover;
    overflow:hidden;
}
#outerDiv {
  width: 100%;
  height: 100%;
}
.btn {
  background: #3498db;
  background-image: -webkit-linear-gradient(top, #3498db, #2980b9);
  background-image: -moz-linear-gradient(top, #3498db, #2980b9);
  background-image: -ms-linear-gradient(top, #3498db, #2980b9);
  background-image: -o-linear-gradient(top, #3498db, #2980b9);
  background-image: linear-gradient(to bottom, #3498db, #2980b9);
  -webkit-border-radius: 28;
  -moz-border-radius: 28;
  border-radius: 28px;
  color: #ffffff;
  font-size: 20px;
  padding: 10px 20px 10px 20px;
  text-decoration: none;
  border: 0px;
  outline: none;
}

.btn:hover {
  background: #3cb0fd;
  background-image: -webkit-linear-gradient(top, #3cb0fd, #3498db);
  background-image: -moz-linear-gradient(top, #3cb0fd, #3498db);
  background-image: -ms-linear-gradient(top, #3cb0fd, #3498db);
  background-image: -o-linear-gradient(top, #3cb0fd, #3498db);
  background-image: linear-gradient(to bottom, #3cb0fd, #3498db);
  text-decoration: none;
  cursor: pointer;
}

#hero video {
    width:100%;
    height:100%;
    object-fit:cover;
}

<!DOCTYPE html>
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
</head>
<body>
<div id="hero">
<div id="bg">
     <video autoplay>
        <source src="http://www.w3schools.com/html/mov_bbb.mp4" type="video/mp4"/>
        <source src="http://www.w3schools.com/html/mov_bbb.ogg" type="video/ogg"/>
      </video>

</div>
<table id="outerDiv" cellpadding="0" cellspacing="0" border="0">
    <tr>
        <td valign="middle" id="innerDiv">
<div class="post-header"><h1 style="color: #383838;">Helping young professionals navigate the world of work.</h1></div>
<div align="center"><button class="btn">JOIN THE REVOLUTION</button></div>
        </td>
    </tr>
</table>
</div>

</body>
</html>


问:
Inconsistency between $ and ^ in regex when using start/end arguments to re.search?
From what I've read, ^ should match the start of a string, and $ the end. However, with re.search(), it looks like the behavior of ^ continues to work fine, while $ 'breaks'. Example:

```<code>>>> a = re.compile( "^a" )
>>> print a.search( "cat", 1, 3 )
None
</code>```

This seems correct to me -- 'a' is not at the start of the string, even if it is at the start of the search.

```<code>>>> a = re.compile( "a$" )
>>> print a.search( "cat", 0, 2 )
<_sre.SRE_Match object at 0x7f41df2334a8>
</code>```

This seems wrong to me, or inconsistent at least.

The documentation on the re module explicitly mentions that the behavior of ^ does not change due to start/end arguments to re.search, but no change in behavior is mentioned for $ (that I've seen).

Can anyone explain why things were designed this way, and/or suggest a convenient workaround?

By workaround, I would like to compose a regex which always matches the end of the string, even when someone uses the end argument to re.search.

And why was re.search designed such that:

```<code>s.search( string, endPos=len(string) - 1 )
</code>```

is the same as

```<code>s.search( string[:-1] )
</code>```

when

```<code>s.search( string, startPos=1 )
</code>```

is explicitly and intentionally not the same as

```<code>s.search( string[1:] )
</code>```

It seems to be less an issue of inconsistency between ^ and $, and more of an inconsistency within the re.search function.

答:
This seems wrong to me, or inconsistent at least.

No, the endpos interpretation is consistent with the rest of Python, it's the starting pos position that's inconsistent as the documentation explains:

parameter pos gives an index in the string where the search is to
  start; it defaults to 0. This is not completely equivalent to slicing
  the string; the '^' pattern character matches at the real beginning of
  the string

Body:
From what I've read, ^ should match the start of a string, and $ the end. However, with re.search(), it looks like the behavior of ^ continues to work fine, while $ 'breaks'. Example:

>>> a = re.compile( "^a" )
>>> print a.search( "cat", 1, 3 )
None

This seems correct to me -- 'a' is not at the start of the string, even if it is at the start of the search.

>>> a = re.compile( "a$" )
>>> print a.search( "cat", 0, 2 )
<_sre.SRE_Match object at 0x7f41df2334a8>

This seems wrong to me, or inconsistent at least.

The documentation on the re module explicitly mentions that the behavior of ^ does not change due to start/end arguments to re.search, but no change in behavior is mentioned for $ (that I've seen).

Can anyone explain why things were designed this way, and/or suggest a convenient workaround?

By workaround, I would like to compose a regex which always matches the end of the string, even when someone uses the end argument to re.search.

And why was re.search designed such that:

s.search( string, endPos=len(string) - 1 )

is the same as

s.search( string[:-1] )

when

s.search( string, startPos=1 )

is explicitly and intentionally not the same as

s.search( string[1:] )

It seems to be less an issue of inconsistency between ^ and $, and more of an inconsistency within the re.search function.


问:
Regex for links in html text
I hope this question is not a RTFM one.
I am trying to write a Python script that extracts links from a standard HTML webpage (the <link href... tags).
I have searched the web for matching regexen and found many different patterns. Is there any agreed, standard regex to match links?

Adam

UPDATE:
I am actually looking for two different answers:

What's the library solution for parsing HTML links. Beautiful Soup seems to be a good solution (thanks, Igal Serban and cletus!)

Can a link be defined using a regex?

答:
Shoudln't a link be a well-defined regex?

No, [X]HTML is not in the general case parseable with regex. Consider examples like:

```<code><link title='hello">world' href="x">link</link>
<!-- <link href="x">not a link</link> -->
<![CDATA[ ><link href="x">not a link</link> ]]>
<script>document.write('<link href="x">not a link</link>')</script>
</code>```

and that's just a few random valid examples; if you have to cope with real-world tag-soup HTML there are a million malformed possibilities.

If you know and can rely on the exact output format of the target page you can get away with regex. Otherwise it is completely the wrong choice for scraping web pages.

OwnerDisplayName: Udi Pasmon

Title: Regex for links in html text

LastEditorDisplayName: Udi Pasmon

Body:
Shoudln't a link be a well-defined regex?

No, [X]HTML is not in the general case parseable with regex. Consider examples like:

<link title='hello">world' href="x">link</link>
<!-- <link href="x">not a link</link> -->
<![CDATA[ ><link href="x">not a link</link> ]]>
<script>document.write('<link href="x">not a link</link>')</script>

and that's just a few random valid examples; if you have to cope with real-world tag-soup HTML there are a million malformed possibilities.

If you know and can rely on the exact output format of the target page you can get away with regex. Otherwise it is completely the wrong choice for scraping web pages.

OwnerDisplayName: bobince


问:
How do I use JQuery to add an event to a textbox when the user pushes enter?
And please don't submit the form when the user pushes enter on THAT SPECIFIC textbox.</p>

答:
Check enter key on keyup event,</p>

```<code>$j("#idOfSpecificBox").bind("keyup",function(e1){
       if(e1.keyCode==13){
          return false;
       }
});
</code>```

Body:
Check enter key on keyup event,

$j("#idOfSpecificBox").bind("keyup",function(e1){
       if(e1.keyCode==13){
          return false;
       }
});


问:
I'm getting NoSuchElement exception error
I have shared the below code please let me know the correction

```<code>import org.openqa.selenium.By;
import org.openqa.selenium.ie.InternetExplorerDriver;

public class MyClass {

    public static void main(String[] args) throws InterruptedException {
        // TODO Auto-generated method stub
        /*System.setProperty("webdriver.ie.driver","D:\\Backup\\Documents\\Automation\\drivers\\IEDriverServer.exe");
        InternetExplorerDriver driver = new InternetExplorerDriver();
        driver.get("https://www.google.com");

        WebDriverWait driverWait = new WebDriverWait(driver,50);

        driverWait.until(ExpectedConditions.elementToBeClickable(By.xpath("//*[@id='lst-ib']"))).click();
        driver.findElementByXPath("//*[@id='lst-ib']").sendKeys("Make My Trip");
        driver.findElementById("_fZl").click();
        driverWait.until(ExpectedConditions.elementToBeClickable(By.linkText("MakeMyTrip, India's No 1 Travel Site | Book Hotels, Flights, Holiday ..."))).click();
        Screenshot S1 = new Screenshot();
        S1.Takescreen();*/
        String username = null;
        String password = null;
        MyClass C1 = new MyClass();
        C1.URLs(username, password);
    }

    public void URLs  (String username, String password) throws InterruptedException
    {

        System.setProperty("webdriver.ie.driver","D:\\Backup\\Documents\\Automation\\drivers\\IEDriverServer.exe");
        InternetExplorerDriver driver = new InternetExplorerDriver();
        driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
        driver.get("https://google.com");
        driver.findElement(By.className("lst lst-tbb sbibps")).sendKeys("irctc");
        driver.findElement(By.id("_fZl")).click();
        Thread.sleep(10000);
        driver.findElement(By.linkText("IRCTC Next Generation eTicketing System")).click();
        username = driver.findElement(By.id("usernameId")).getTagName();
        password = driver.findElement(By.className("loginPassword")).getTagName();
        System.out.println(username);
        System.out.println(password);
    }
}
</code>```

Error :

Exception in thread "main" org.openqa.selenium.NoSuchElementException:
  Unable to find element with class name == lst lst-tbb sbibps (WARNING:
  The server did not provide any stacktrace information) Command
  duration or timeout: 10.45 seconds

答:
In Google.com , there is normally three input tags available for search , However 2 of them have property of hidden =true

```<code><div id="gs_sc0" class="gsfi" style="background: transparent none repeat scroll 0% 0%; color: transparent; padding: 0px; position: absolute; z-index: 2; white-space: pre; visibility: hidden;"/>

<input id="gs_taif0" class="gsfi" disabled="" autocomplete="off" aria-**hidden="true"** style="border: medium none; padding: 0px; margin: 0px; height: auto; width: 100%; position: absolute; z-index: 1; background-color: transparent; color: silver; left: 0px; visibility: hidden;" dir="ltr"/>

<input id="gs_htif0" class="gsfi" disabled="" autocomplete="off" aria-hidden="true" style="border: medium none; padding: 0px; margin: 0px; height: auto; width: 100%; position: absolute; z-index: 1; background-color: transparent; color: silver; transition: all 0.218s ease 0s; opacity: 0; text-align: left; left: 0px;" dir="ltr"/>
</code>```

So we have to use the input which is not hidden , in this case use

```<code>driver.findElement(By.id("lst-ib")).sendKeys("irctc");
</code>```

Body:
I have shared the below code please let me know the correction

import org.openqa.selenium.By;
import org.openqa.selenium.ie.InternetExplorerDriver;

public class MyClass {

    public static void main(String[] args) throws InterruptedException {
        // TODO Auto-generated method stub
        /*System.setProperty("webdriver.ie.driver","D:\\Backup\\Documents\\Automation\\drivers\\IEDriverServer.exe");
        InternetExplorerDriver driver = new InternetExplorerDriver();
        driver.get("https://www.google.com");

        WebDriverWait driverWait = new WebDriverWait(driver,50);

        driverWait.until(ExpectedConditions.elementToBeClickable(By.xpath("//*[@id='lst-ib']"))).click();
        driver.findElementByXPath("//*[@id='lst-ib']").sendKeys("Make My Trip");
        driver.findElementById("_fZl").click();
        driverWait.until(ExpectedConditions.elementToBeClickable(By.linkText("MakeMyTrip, India's No 1 Travel Site | Book Hotels, Flights, Holiday ..."))).click();
        Screenshot S1 = new Screenshot();
        S1.Takescreen();*/
        String username = null;
        String password = null;
        MyClass C1 = new MyClass();
        C1.URLs(username, password);
    }

    public void URLs  (String username, String password) throws InterruptedException
    {

        System.setProperty("webdriver.ie.driver","D:\\Backup\\Documents\\Automation\\drivers\\IEDriverServer.exe");
        InternetExplorerDriver driver = new InternetExplorerDriver();
        driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
        driver.get("https://google.com");
        driver.findElement(By.className("lst lst-tbb sbibps")).sendKeys("irctc");
        driver.findElement(By.id("_fZl")).click();
        Thread.sleep(10000);
        driver.findElement(By.linkText("IRCTC Next Generation eTicketing System")).click();
        username = driver.findElement(By.id("usernameId")).getTagName();
        password = driver.findElement(By.className("loginPassword")).getTagName();
        System.out.println(username);
        System.out.println(password);
    }
}

Error :

Exception in thread "main" org.openqa.selenium.NoSuchElementException:
  Unable to find element with class name == lst lst-tbb sbibps (WARNING:
  The server did not provide any stacktrace information) Command
  duration or timeout: 10.45 seconds

Body:
In Google.com , there is normally three input tags available for search , However 2 of them have property of hidden =true

<div id="gs_sc0" class="gsfi" style="background: transparent none repeat scroll 0% 0%; color: transparent; padding: 0px; position: absolute; z-index: 2; white-space: pre; visibility: hidden;"/>

<input id="gs_taif0" class="gsfi" disabled="" autocomplete="off" aria-**hidden="true"** style="border: medium none; padding: 0px; margin: 0px; height: auto; width: 100%; position: absolute; z-index: 1; background-color: transparent; color: silver; left: 0px; visibility: hidden;" dir="ltr"/>

<input id="gs_htif0" class="gsfi" disabled="" autocomplete="off" aria-hidden="true" style="border: medium none; padding: 0px; margin: 0px; height: auto; width: 100%; position: absolute; z-index: 1; background-color: transparent; color: silver; transition: all 0.218s ease 0s; opacity: 0; text-align: left; left: 0px;" dir="ltr"/>

So we have to use the input which is not hidden , in this case use

driver.findElement(By.id("lst-ib")).sendKeys("irctc");


问:
one to many relation in django
I have two table user and address. User has many requests.

```<code>class User(models.Model):
    user_id=models.AutoField(primary_key = True)
    catcher_fname = models.CharField(max_length = 128, blank = True)
    catcher_lname = models.CharField(max_length = 128, blank = True)
    api_key = models.CharField(max_length = 100, blank = False)

class Address (models.Model):
    address_id=models.AutoField(primary_key = True)
    address = models.CharField(max_length = 150)
    city = models.CharField(max_length = 255)
    user = models.ForeignKey(User)
</code>```

When I hit a user table, I want his address also and return as JSON.

user = User.obejcts.get(pk=2)

it's return me only user data not address :(

答:
models.py-

```<code>class User(models.Model):
    catcher_fname = models.CharField(max_length = 128, blank = True)
    catcher_lname = models.CharField(max_length = 128, blank = True)
    api_key = models.CharField(max_length = 100, blank = False)

class Address (models.Model):
    address = models.CharField(max_length = 150)
    city = models.CharField(max_length = 255)
    user = models.ForeignKey(User,on_delete=models.CASCADE)
</code>```

Note - id field is autoincrementing and in-built in django, you don't need to specify it directly.
Following is a demonstration how should you link your user obj and address obj.

```<code>>> from .models import User,Address
>> user_obj = User.objects.get(pk=pk)
>> address_obj = Address.objects.get(pk=address_pk)
>> user_obj.address = address_obj
>> user_obj.save()
</code>```

Later you can access the address from the user object as -

```<code>>> from .models import User
>> user_obj = User.objects.get(pk=pk)
>> user_obj.address_set.all() (will give the data)
</code>```

Title: one to many relation in django

Body:
I have two table user and address. User has many requests.

class User(models.Model):
    user_id=models.AutoField(primary_key = True)
    catcher_fname = models.CharField(max_length = 128, blank = True)
    catcher_lname = models.CharField(max_length = 128, blank = True)
    api_key = models.CharField(max_length = 100, blank = False)

class Address (models.Model):
    address_id=models.AutoField(primary_key = True)
    address = models.CharField(max_length = 150)
    city = models.CharField(max_length = 255)
    user = models.ForeignKey(User)

When I hit a user table, I want his address also and return as JSON.

user = User.obejcts.get(pk=2)

it's return me only user data not address :(

Body:
models.py-

class User(models.Model):
    catcher_fname = models.CharField(max_length = 128, blank = True)
    catcher_lname = models.CharField(max_length = 128, blank = True)
    api_key = models.CharField(max_length = 100, blank = False)

class Address (models.Model):
    address = models.CharField(max_length = 150)
    city = models.CharField(max_length = 255)
    user = models.ForeignKey(User,on_delete=models.CASCADE)

Note - id field is autoincrementing and in-built in django, you don't need to specify it directly.
Following is a demonstration how should you link your user obj and address obj.

>> from .models import User,Address
>> user_obj = User.objects.get(pk=pk)
>> address_obj = Address.objects.get(pk=address_pk)
>> user_obj.address = address_obj
>> user_obj.save()

Later you can access the address from the user object as -

>> from .models import User
>> user_obj = User.objects.get(pk=pk)
>> user_obj.address_set.all() (will give the data)


问:
Why won't my changes in git go through?
All I wanted to do was to add all files.

Now I got directories that are just icons and I never saw something like that before.

I just wanted to add all files. I did

```<code>git add *
git commit -m "added"
git push
</code>```

And now I got this incomprehensible mess.

How can you explain this state?

答:
Those gray folders are gitlinks (special entry in the index).

They represent nested git repos: the parent repo only records their SHA1 (that you see beside the grey icons)

You need to decide if you want to:

record them properly as submodules

ignore them completely

add their content in your repo (removing their inner .git folder)

Note: don't use git add *: the * is expanded by the shell.

Use git add .

Title: Why won't my changes in git go through?

Body:
All I wanted to do was to add all files.

Now I got directories that are just icons and I never saw something like that before.

I just wanted to add all files. I did

git add *
git commit -m "added"
git push

And now I got this incomprehensible mess.

How can you explain this state?


问:
Can SpannableString be Serializable?
I want post an object with SpannableString by Intent. I let the object implement Serializable, but it will throw

java.io.NotSerializableException: android.text.SpannableString

So I let SpannableString implement Serializable.

```<code>private class MySpannableString extends SpannableString implements Serializable{
    public MySpannableString(CharSequence source) {
        super(source);
    }
}
</code>```

But I can't get the object in the next Activity.

答:
As per the documentation for SpannableString, it does not implement the Serializable interface, hence you got the "java.io.NotSerializableException" exception.

Doc - https://developer.android.com/reference/android/text/SpannableString.html

Your approach to workaround this by extending SpannableString and implementing the Serializable interface will not work. The reason for this being that in order to make a non-serializable Class serializable by extending it, it needs to have an accessible no-argument constructor. The SpannableString class does not have that, the only accessible constructor that is has takes a CharacterSequence as an argument.

As per the documentation for the Serializable interface -

"To allow subtypes of non-serializable classes to be serialized, the subtype may assume responsibility for saving and restoring the state of the supertype's public, protected, and (if accessible) package fields. The subtype may assume this responsibility only if the class it extends has an accessible no-arg constructor to initialize the class's state. It is an error to declare a class Serializable if this is not the case. The error will be detected at runtime."

Doc - https://docs.oracle.com/javase/7/docs/api/java/io/Serializable.html

Title: Can SpannableString be Serializable?

Body:
I want post an object with SpannableString by Intent. I let the object implement Serializable, but it will throw

java.io.NotSerializableException: android.text.SpannableString

So I let SpannableString implement Serializable.

private class MySpannableString extends SpannableString implements Serializable{
    public MySpannableString(CharSequence source) {
        super(source);
    }
}

But I can't get the object in the next Activity.


问:
Escaping values with apostrophes for MySQL insert
I am trying to create some SQL insert statements and a few variables have names like the following:

"Aamma's Pastries"

I want to escape the quote (') as I am adding the value into the MySQL database. How do I do that with PHP?

答:
You've already accepted an answer, but I'd like to suggest a better approach to you.  Using an approach like mysql_real_escape_string requires you to consistently remember to apply it every single time in every single query; it's tedious and error prone.

A more simple approach, which also ensures consistency is to use parameterised statements.  This ensures that everything is correctly escaped, and also avoids you having to embed variables in your queries.

In PHP, this can be used with the newer PDO or MySQLi libraries. Of these, I prefer PDO for the flexibility it provides (e.g. I'm currently stuck with MySQL, but I don't intend to keep my app running that way forever, and with PDO the migration will be massively simplified), but there are plenty of questions here on SO that cover the pros and cons of each.


问:
$http.post not working in AngularJS
When I use $http.get my code works, but if I use $http.post, I never get the parameters to the request .php file.

This is Service function:

```<code>    TestPanel.service('MySampleService', function ($http, $q) {
    this.getAllPosts = function () {

        var def = $q.defer();
        $http.post('/data/AJAXRequest.php', 'mydata=1&abcd=2').success(function (data) {
            if (data == null)
                def.reject('ERROR: DATA IS NULL');
            else if (data.HasError)
                def.reject('ERROR: ' + data.Message);
            else
                def.resolve(data);
        }).error(function () {
            def.reject('ERROR: Sorry, unable to complete your request.');
        });

        return def.promise;
    }
});
</code>```

And Controller function:

```<code> TestController.controller('PostCtrl', ['$scope', '$http', 'MySampleService',
    function ($scope, $http, MySampleService) {

        function FetchPostsList() {
            MySampleService.getAllPosts().then(function (data) {
                $scope.lstPosts = data.ResponseData;
                $scope.totalRecords = data.totalRecords;
                console.info('DATA=' + $scope.lstPosts);
            },
            function (err) {
                console.info('err=' + err);
            });
        }

        FetchPostsList();
    }
]);
</code>```

and
My AJAXRequest.php file

```<code><?php
   var_dump($_POST)
?>
</code>```

if I use $http.post()

Output:

```<code> array (size=0)
  empty
</code>```

If i use $http.get()

my output is :

```<code>array (size=2)
  'mydata' => string '1' (length=1)
  'abcd' => string '2' (length=1)
</code>```

I checked the post in FireBug tool, that its sending data to my php file. but php file getting no params.

If I use $.ajax or $.post my code work and it gives the response.

答:
```<code>$http({
    method: 'POST',
    url: 'http://mtapi.azurewebsites.net/api/sectiontype',
    dataType: 'json',
    data: {SectionTypeId:0, Name: $scope.message},
    headers: { 'Content-Type': 'application/json; charset=UTF-8' }
}).success(function (data) {
    alert(data);
}).error(function (data) {
    alert(data);
});
</code>```

headers must be added in the end of the array otherwise it won't work.

Title: $http.post not working in AngularJS

Body:
When I use $http.get my code works, but if I use $http.post, I never get the parameters to the request .php file.

This is Service function:

    TestPanel.service('MySampleService', function ($http, $q) {
    this.getAllPosts = function () {

        var def = $q.defer();
        $http.post('/data/AJAXRequest.php', 'mydata=1&abcd=2').success(function (data) {
            if (data == null)
                def.reject('ERROR: DATA IS NULL');
            else if (data.HasError)
                def.reject('ERROR: ' + data.Message);
            else
                def.resolve(data);
        }).error(function () {
            def.reject('ERROR: Sorry, unable to complete your request.');
        });

        return def.promise;
    }
});

And Controller function:

 TestController.controller('PostCtrl', ['$scope', '$http', 'MySampleService',
    function ($scope, $http, MySampleService) {

        function FetchPostsList() {
            MySampleService.getAllPosts().then(function (data) {
                $scope.lstPosts = data.ResponseData;
                $scope.totalRecords = data.totalRecords;
                console.info('DATA=' + $scope.lstPosts);
            },
            function (err) {
                console.info('err=' + err);
            });
        }

        FetchPostsList();
    }
]);

and
My AJAXRequest.php file

<?php
   var_dump($_POST)
?>

if I use $http.post()

Output:

 array (size=0)
  empty

If i use $http.get()

my output is :

array (size=2)
  'mydata' => string '1' (length=1)
  'abcd' => string '2' (length=1)

I checked the post in FireBug tool, that its sending data to my php file. but php file getting no params.

If I use $.ajax or $.post my code work and it gives the response.

Body:
$http({
    method: 'POST',
    url: 'http://mtapi.azurewebsites.net/api/sectiontype',
    dataType: 'json',
    data: {SectionTypeId:0, Name: $scope.message},
    headers: { 'Content-Type': 'application/json; charset=UTF-8' }
}).success(function (data) {
    alert(data);
}).error(function (data) {
    alert(data);
});

headers must be added in the end of the array otherwise it won't work.


问:
select grandparent in css
i have an html code like this

```<code><div class="main-container">
   <div class="main">
     <div class="col-main">
        <div class="category-products">
           <div class="toolbar"> </div>
        </div>
     </div>
   </div>
</div>
</code>```

i've tried to change the main-container background if it has toolbar descendant, ive tried like this :

```<code> .main-container > .main .col-main .category-products .toolbar{
  background-color: #f5f5f5;
  padding-top: 0;
}

.main-container >  .toolbar{
  background-color: #f5f5f5;
  padding-top: 0;
}
</code>```

but nothing works

答:
.main-container{
  background-color: #f5f5f5;
  padding-top: 0;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="main-container">
   <div class="main">
     <div class="col-main">
        <div class="category-products">
           <div class="toolbar">CSS set background color</div>
        </div>
     </div>
   </div>
</div></code>```

Title: select grandparent in css

Body:
i have an html code like this

i've tried to change the main-container background if it has toolbar descendant, ive tried like this :

 .main-container > .main .col-main .category-products .toolbar{
  background-color: #f5f5f5;
  padding-top: 0;
}

.main-container >  .toolbar{
  background-color: #f5f5f5;
  padding-top: 0;
}

but nothing works

Body:
.main-container{
  background-color: #f5f5f5;
  padding-top: 0;
}

<div class="main-container">
   <div class="main">
     <div class="col-main">
        <div class="category-products">
           <div class="toolbar">CSS set background color</div>
        </div>
     </div>
   </div>
</div>


问:
How to show a frame of a video file (image) with tkinter in python
I am trying to show video frames (not from a stream) with tkinter. The next step are buttons which allow the user to get a frame backward or forward in the video. I have to say that I am quite new in programming with python.
So first I read the following articles:

Python snippets: Converting video to images http://srand.fr/blog/python%20import%20video.html

The Tkinter PhotoImage Class: http://effbot.org/tkinterbook/photoimage.htm

The problem is that I can’t use the image converted with imageio or VideoFileClip to show it with tkinter photoimage. I get the following error:

```<code>_tkinter.TclError: image "[[  …(some numbers)…   ]]" doesn't exist
</code>```

Here is my simple code. I hope you can help me :)

```<code>from moviepy.editor import VideoFileClip
from tkinter import *
import pylab

vid =VideoFileClip("example.mp4")

window = Tk()
window.title("Choose Frame")
window.geometry ("900x600")

count =20

photo = vid.get_frame(count)
label =Label(window, image = photo)
label.pack()
</code>```

Other Code, same problem:

```<code>import imageio
from tkinter import *
import pylab

filename = './example.mp4'
vid = imageio.get_reader(filename,  'ffmpeg')

window = Tk()
window.title("Choose Frame")
window.geometry ("900x600")

count =20

photo = vid.get_data(count)
label =Label(window, image = photo)
label.pack()
</code>```

答:
And here is another nice working example of a player that I was trying to make with Tkinter and some sample code with Opencv module.
This is a just an example idea, not finish code by any means.</p>

```<code>import cv2
from Tkinter import *
from PIL import Image, ImageTk
import io
import threading
import os, sys

def resize(image):
    im = image
    new_siz = siz
    im.thumbnail(new_siz, Image.ANTIALIAS)
    return im

def size(event):
    global siz
    if siz == screenWH:
        siz = (200, 200)
    else:
        siz = screenWH
        win.state('zoomed')
    print 'size is: ', siz

def view_frame_video():
    vc = cv2.VideoCapture('test_video.flv')
    if vc.isOpened():
        rval , frame = vc.read()
    else:
        rval = False

    while rval:
        rval, frame = vc.read()
        img =Image.fromarray(frame)
        img = resize(img)
        imgtk = ImageTk.PhotoImage(img)
        lbl.config(image=imgtk)
        lbl.img = imgtk
        if stop == True:
            vc.release()
            break      #stop the loop thus stops updating the label and reading imagge frames
        cv2.waitKey(1)
    vc.release()

def stop_():
    global stop
    stop = True

def play():
    stop = False
    t = threading.Thread(target=view_frame_video)
    t.start()

win = Tk()

stop = None
screenWH = (win.winfo_screenwidth(), win.winfo_screenheight())
siz = (200, 200)

Label(text='Press Play Button').pack()
frm_ = Frame(bg='black')
frm_.pack()
lbl = Label(frm_, bg='black')
lbl.pack(expand=True)
lbl.bind('<Double-Button-1>', size)

frm = Frame()
frm.pack()
Button(text='Play', command = play).pack(side=LEFT)
Button(text='Stop', command = stop_).pack(side=LEFT)

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

Body:
I am trying to show video frames (not from a stream) with tkinter. The next step are buttons which allow the user to get a frame backward or forward in the video. I have to say that I am quite new in programming with python.
So first I read the following articles:

Python snippets: Converting video to images http://srand.fr/blog/python%20import%20video.html

The Tkinter PhotoImage Class: http://effbot.org/tkinterbook/photoimage.htm

The problem is that I can’t use the image converted with imageio or VideoFileClip to show it with tkinter photoimage. I get the following error:

_tkinter.TclError: image "[[  …(some numbers)…   ]]" doesn't exist

Here is my simple code. I hope you can help me :)

from moviepy.editor import VideoFileClip
from tkinter import *
import pylab

vid =VideoFileClip("example.mp4")

window = Tk()
window.title("Choose Frame")
window.geometry ("900x600")

count =20

photo = vid.get_frame(count)
label =Label(window, image = photo)
label.pack()

Other Code, same problem:

import imageio
from tkinter import *
import pylab

filename = './example.mp4'
vid = imageio.get_reader(filename,  'ffmpeg')

window = Tk()
window.title("Choose Frame")
window.geometry ("900x600")

count =20

photo = vid.get_data(count)
label =Label(window, image = photo)
label.pack()

Body:
And here is another nice working example of a player that I was trying to make with Tkinter and some sample code with Opencv module.
This is a just an example idea, not finish code by any means.

import cv2
from Tkinter import *
from PIL import Image, ImageTk
import io
import threading
import os, sys

def resize(image):
    im = image
    new_siz = siz
    im.thumbnail(new_siz, Image.ANTIALIAS)
    return im

def size(event):
    global siz
    if siz == screenWH:
        siz = (200, 200)
    else:
        siz = screenWH
        win.state('zoomed')
    print 'size is: ', siz

def view_frame_video():
    vc = cv2.VideoCapture('test_video.flv')
    if vc.isOpened():
        rval , frame = vc.read()
    else:
        rval = False

    while rval:
        rval, frame = vc.read()
        img =Image.fromarray(frame)
        img = resize(img)
        imgtk = ImageTk.PhotoImage(img)
        lbl.config(image=imgtk)
        lbl.img = imgtk
        if stop == True:
            vc.release()
            break      #stop the loop thus stops updating the label and reading imagge frames
        cv2.waitKey(1)
    vc.release()

def stop_():
    global stop
    stop = True

def play():
    stop = False
    t = threading.Thread(target=view_frame_video)
    t.start()

win = Tk()

stop = None
screenWH = (win.winfo_screenwidth(), win.winfo_screenheight())
siz = (200, 200)

Label(text='Press Play Button').pack()
frm_ = Frame(bg='black')
frm_.pack()
lbl = Label(frm_, bg='black')
lbl.pack(expand=True)
lbl.bind('<Double-Button-1>', size)

frm = Frame()
frm.pack()
Button(text='Play', command = play).pack(side=LEFT)
Button(text='Stop', command = stop_).pack(side=LEFT)

win.mainloop()


问:
Arduino WDT timer value after external interrupt
I am counting pulses using an external interrupt, but I put the processor to sleep in between pulses using wdt_enable, using the 8-second interval.

When the interrupt occurs and the processor wakes up to service the interrupt, is it possible to find out how long into the 8-second period I am? That is, can I read the wdt timer to see how long it has been running (or how long it has to go)?

答: The ATMEL328p Datasheet Page 51 shows the architecture of the Watchdog. There does not seem to be a method to read back the Watchdog Prescaler. The answer assumes you are using an Arduino with a 328p.</p>


问:
How can I rotate a 2d array in php by 90 degrees
I want to rotate a matrix 90 degrees clockwise. This amounts to making the first column in the input the first row of the output, the second column of the input the 2nd row of the output, and the 3rd column of the input the 3rd row of the output. Note that the bottom of the column=the beginning of the row, because of the 90 degree rotation.

For example:

```<code>$matrix=    [[1, 2, 3]
             [4, 5, 6],
             [7, 8, 9]];

rotate90degrees($matrix)=      [[7, 4, 1],
                                [8, 5, 2],
                                [9, 6, 3]]
</code>```

What I know is I have first transpose the matrix and then swap the columns to rotate the matrix by 90 degrees. How can this be applied to php?

答:
Another reliable option:

```<code>function rotateMatrix90( $matrix )
{
    $matrix = array_values( $matrix );
    $matrix90 = array();

    // make each new row = reversed old column
    foreach( array_keys( $matrix[0] ) as $column ){
        $matrix90[] = array_reverse( array_column( $matrix, $column ) );
    }

    return $matrix90;
}
</code>```

Less clever than @mark-baker's by far. Maybe more clear.

Body:
I want to rotate a matrix 90 degrees clockwise. This amounts to making the first column in the input the first row of the output, the second column of the input the 2nd row of the output, and the 3rd column of the input the 3rd row of the output. Note that the bottom of the column=the beginning of the row, because of the 90 degree rotation.

For example:

$matrix=    [[1, 2, 3]
             [4, 5, 6],
             [7, 8, 9]];

rotate90degrees($matrix)=      [[7, 4, 1],
                                [8, 5, 2],
                                [9, 6, 3]]

What I know is I have first transpose the matrix and then swap the columns to rotate the matrix by 90 degrees. How can this be applied to php?

Body:
Another reliable option:

function rotateMatrix90( $matrix )
{
    $matrix = array_values( $matrix );
    $matrix90 = array();

    // make each new row = reversed old column
    foreach( array_keys( $matrix[0] ) as $column ){
        $matrix90[] = array_reverse( array_column( $matrix, $column ) );
    }

    return $matrix90;
}

Less clever than @mark-baker's by far. Maybe more clear.


问:
.htaccess dynamic subdomain files
here is my code in my .htaccess file:

```<code>RewriteCond %{HTTP_HOST} !^www\.domain\.com
RewriteCond %{HTTP_HOST} ([^.]+)\.domain\.com [NC]
RewriteRule ^/?$ /user/profile.php?name=%1 [L]
</code>```

here is what it does:

if i visit test.domain.com, it will show the contents (not redirect) of domain.com/profile.php?name=test.

but if i type: test.domain.com/login, it will show the contents of the page: domain.com/login.

Question: why is that? how can i turn that off? thanks

答:
Hope this will work, working fine on my end.</p>

```<code>RewriteCond %{HTTP_HOST} !^www\.domain\.in
RewriteCond %{HTTP_HOST} ^test\.dmmain\.in [NC]
RewriteRule ^$ http://test.domain.in/user/profile.php [L,QSA]
</code>```

Title: .htaccess dynamic subdomain files

Body:
here is my code in my .htaccess file:

RewriteCond %{HTTP_HOST} !^www\.domain\.com
RewriteCond %{HTTP_HOST} ([^.]+)\.domain\.com [NC]
RewriteRule ^/?$ /user/profile.php?name=%1 [L]

here is what it does:

if i visit test.domain.com, it will show the contents (not redirect) of domain.com/profile.php?name=test.

but if i type: test.domain.com/login, it will show the contents of the page: domain.com/login.

Question: why is that? how can i turn that off? thanks

Body:
Hope this will work, working fine on my end.

RewriteCond %{HTTP_HOST} !^www\.domain\.in
RewriteCond %{HTTP_HOST} ^test\.dmmain\.in [NC]
RewriteRule ^$ http://test.domain.in/user/profile.php [L,QSA]


问:
Below java code runs, not sure if this kind of code is allowed by java compiler
Hi I am not sure but below code compiles and runs but below line of code looks weird.

```<code>public int Integer = new Integer(1);
</code>```

Is this some special syntax?

```<code>public class HelloWorld {
    public int Integer = new Integer(1);

    public static void main(String[] args) {
        System.out.println("Hello World");
    }
}
</code>```

答:
Integer is not a reserved word, so it can be used as an attribute name. So basically public int Integer is an attribute called Integer using the int primitive.

The Integer attribute will create a new Integer object and the java compiler will autoboxing it to the integer primitive. Give a look here for more details.

What you did is equivalent to this:

```<code>Integer Integer = new Integer(1);
</code>```

And is also equivalente to this:

```<code>int Integer = 1;
</code>```

Body:
Hi I am not sure but below code compiles and runs but below line of code looks weird.

public int Integer = new Integer(1);

Is this some special syntax?

public class HelloWorld {
    public int Integer = new Integer(1);

    public static void main(String[] args) {
        System.out.println("Hello World");
    }
}

Body:
Integer is not a reserved word, so it can be used as an attribute name. So basically public int Integer is an attribute called Integer using the int primitive.

The Integer attribute will create a new Integer object and the java compiler will autoboxing it to the integer primitive. Give a look here for more details.

What you did is equivalent to this:

Integer Integer = new Integer(1);

And is also equivalente to this:

int Integer = 1;


问:
What's the difference/compatibility between aiohttp and websockets?
What's the difference between aiohttp's websocket support (i.e. WebSocketResponse) and websockets   (both offer an async support)? Can they be mixed?

答:
They are two different libraries maintained by different people. Both are built on top of asyncio.

websockets aims to be a simple easy to use library to implement websockets clients and servers and is maintained mostly by a single developer. On the other hand, aiohttp is a quite bigger library maintained by bigger team, offering not only websockets but, as the name suggests, HTTP functionality as well. Some of its functionality overlaps that of flask and requests, but in a async fashion.

In terms of size, websockets is about 4k LOC, while aiohttp is about 40k LOC. If you just need a simple and easy to use websockets client, go for websockets. If you are already using aiohttp and need websockets functionality, use what aiohttp has to offer. I don't see a point in mixing them.

ContentLicense: CC BY-SA 4.0


问:
How to handle white spaces in dataframe column names in spark
I registered a tmp table from a df that has white spaces in the column header.how can i extract the column while using sql query via sqlContext.
I tried to use back-tick but it is not working</p>

```<code>df1 =  sqlContext.sql("""select Company, Sector, Industry, `Altman Z-score as Z_Score` from tmp1 """)
</code>```

答:
There is problem in query, Corrected query is below (wrapped as Z_Score in ``) :-

```<code>df1 =  sqlContext.sql("""select Company, Sector, Industry, `Altman Z-score` as Z_Score from tmp1 """)
</code>```

One more Alternate:-

```<code>import pyspark.sql.functions as F
df1 =  sqlContext.sql("""select * from tmp1 """)
df1.select(F.col("Altman Z-score").alias("Z_Score")).show()
</code>```

Body:
I registered a tmp table from a df that has white spaces in the column header.how can i extract the column while using sql query via sqlContext.
I tried to use back-tick but it is not working

df1 =  sqlContext.sql("""select Company, Sector, Industry, `Altman Z-score as Z_Score` from tmp1 """)

Body:
There is problem in query, Corrected query is below (wrapped as Z_Score in ``) :-

df1 =  sqlContext.sql("""select Company, Sector, Industry, `Altman Z-score` as Z_Score from tmp1 """)

One more Alternate:-

import pyspark.sql.functions as F
df1 =  sqlContext.sql("""select * from tmp1 """)
df1.select(F.col("Altman Z-score").alias("Z_Score")).show()