问:
How to check if a specific SPAN class content text
wanna check whether a specific SPAN class context text or not?
The SPAN class I want to check against is "distance" that has the kilometers numbers like (, 27 kilometers).

Tried the below code but still not working

if ($('.trip-summary-info').find('distance').length > 0) {
  alert("Working !!!");```
<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>
<div class="trip-summary-info">
  <h3>

      <span class="chevron-up"><i class="fa fa-chevron-up"></i></span> Booking Summary:
      <span class="date-time"></span>07-07-2017 09:05<span class="distance">, 99.84 kilometers</span><span class="duration">, 1 hrs 13 mins</span>

    <span class="custom-btn custom-btn-default edit back_first"><i class="fa fa-pencil"></i></span>
  </h3>
  <div class="trip_status custom-clearfix">
    <span class="location-form-marker"><i class="fa fa-map-marker"></i></span>
    <div class="location-form"></div>
    <div class="list-address-point" style="display:unset;"></div>
    <span class="location-to-marker"><i class="fa fa-map-marker"></i></span>
    <div class="location-to"></div>
  </div>

  <div class="additional_seats_wrapper editable-field">
    <strong>Additional Seats: </strong><span id="additional-seats" class="text-muted"></span>
    <!-- overlay-icon -->
    <div class="overlay-icon">
      <i class="fa fa-edit"></i>
    </div>
    <!-- /overlay-icon -->
  </div>
</div></code>```

答:
You are missing the . represent the class in find()

if ($('.trip-summary-info').find('.distance').length > 0) {
console.log($('.trip-summary-info').find('.distance').text())
  }```
<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>
<div class="trip-summary-info">
  <h3>

      <span class="chevron-up"><i class="fa fa-chevron-up"></i></span> Booking Summary:
      <span class="date-time"></span>07-07-2017 09:05<span class="distance">, 99.84 kilometers</span><span class="duration">, 1 hrs 13 mins</span>

    <span class="custom-btn custom-btn-default edit back_first"><i class="fa fa-pencil"></i></span>
  </h3>
  <div class="trip_status custom-clearfix">
    <span class="location-form-marker"><i class="fa fa-map-marker"></i></span>
    <div class="location-form"></div>
    <div class="list-address-point" style="display:unset;"></div>
    <span class="location-to-marker"><i class="fa fa-map-marker"></i></span>
    <div class="location-to"></div>
  </div>

  <div class="additional_seats_wrapper editable-field">
    <strong>Additional Seats: </strong><span id="additional-seats" class="text-muted"></span>
    <!-- overlay-icon -->
    <div class="overlay-icon">
      <i class="fa fa-edit"></i>
    </div>
    <!-- /overlay-icon -->
  </div>
</div></code>```

Body:
wanna check whether a specific SPAN class context text or not?
The SPAN class I want to check against is "distance" that has the kilometers numbers like (, 27 kilometers).

Tried the below code but still not working

if ($('.trip-summary-info').find('distance').length > 0) {
  alert("Working !!!");

       Booking Summary:
      07-07-2017 09:05, 99.84 kilometers, 1 hrs 13 mins

    Additional Seats:

Body:
You are missing the . represent the class in find()

if ($('.trip-summary-info').find('.distance').length > 0) {
console.log($('.trip-summary-info').find('.distance').text())
  }

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="trip-summary-info">
  <h3>
    <a href="javascript:void(0);" class="back_first">
      <span class="chevron-up"><i class="fa fa-chevron-up"></i></span> Booking Summary: &nbsp;
      <span class="date-time"></span>07-07-2017 09:05<span class="distance">, 99.84 kilometers</span><span class="duration">, 1 hrs 13 mins</span>
    </a>
    <span class="custom-btn custom-btn-default edit back_first"><a href="javascript:void(0);"><i class="fa fa-pencil"></i></a></span>
  </h3>
  <div class="trip_status custom-clearfix">
    <span class="location-form-marker"><i class="fa fa-map-marker"></i></span>
    <div class="location-form"></div>
    <div class="list-address-point" style="display:unset;"></div>
    <span class="location-to-marker"><i class="fa fa-map-marker"></i></span>
    <div class="location-to"></div>
  </div>

  <div class="additional_seats_wrapper editable-field">
    <strong>Additional Seats: </strong><span id="additional-seats" class="text-muted"></span>
    <!-- overlay-icon -->
    <div class="overlay-icon">
      <a class="btn-icon back_first" href="javascript:void(0);"><i class="fa fa-edit"></i></a>
    </div>
    <!-- /overlay-icon -->
  </div>
</div>


来源: stackexchange

问:
open on the same window form submit

var form = document.createElement("form");
form.setAttribute("hidden", "true");
form.setAttribute("method", "post");
form.setAttribute("target", "_blank");
form.setAttribute("action", "target.php");

document.body.appendChild(form); // Not entirely sure if this is necessary
form.submit();
return;```

I have the above code inside the success of an ajax succes. On success of saving data in the database I send back the said data to be print. I am using FPDF for printing and I have create a template in target.php and I am posting data into that page. So in order to send the data through post I create a form with target set as _blank expecting that when I save another set of data the and print the said data it will open on the previous tab. What is happening now is every time I save data it opens new tab.

What I expect is every time I save and print the data it will open to the previous tab that was opened on first print. Basically I dont want to open new tab every time I print. On first print open new tab then the rest will just load on that tab

答:
Is there such thing as _black

When I use this one I get the desired functionality I want

I tried a simple demo in w3school like below:

```<code><!DOCTYPE html>
<html>
<body>

<p>Open link in a new window or tab: <a href="https://www.w3schools.com" target="_black">Visit W3Schools!</a></p>

</body>
</html>
</code>```

I want to know if this is a valid target

ContentLicense: CC BY-SA 3.0

Title: open on the same window form submit

Body:
var form = document.createElement("form");
form.setAttribute("hidden", "true");
form.setAttribute("method", "post");
form.setAttribute("target", "_blank");
form.setAttribute("action", "target.php");

document.body.appendChild(form); // Not entirely sure if this is necessary
form.submit();
return;

I have the above code inside the success of an ajax succes. On success of saving data in the database I send back the said data to be print. I am using FPDF for printing and I have create a template in target.php and I am posting data into that page. So in order to send the data through post I create a form with target set as _blank expecting that when I save another set of data the and print the said data it will open on the previous tab. What is happening now is every time I save data it opens new tab.

What I expect is every time I save and print the data it will open to the previous tab that was opened on first print. Basically I dont want to open new tab every time I print. On first print open new tab then the rest will just load on that tab

Body:
Is there such thing as _black

When I use this one I get the desired functionality I want

I tried a simple demo in w3school like below:

<!DOCTYPE html>
<html>
<body>

<p>Open link in a new window or tab: <a href="https://www.w3schools.com" target="_black">Visit W3Schools!</a></p>

</body>
</html>

I want to know if this is a valid target


问:
Ionic 2 - Hide tabs on sub-pages
I have on my ionicbootstrap config:

```<code>{
   mode: 'md',
   tabsHideOnSubPages: true
}
</code>```

On my settings, but on some sub-pages the tabs are showing. This seems a random behaviour.
Is this the right way of doing this?

ionic : 2.0.0@beta.11

Thanks
Artur

#

EDIT:

I'm using this fix to make the tabs go away:

```<code>ionViewWillEnter() {
    let tabs = document.querySelectorAll('.show-tabbar');
    if (tabs !== null) {
        Object.keys(tabs).map((key) => {
            tabs[key].style.transform = 'translateY(56px)';
        });
    } // end if
}

ionViewDidLeave() {
    let tabs = document.querySelectorAll('.show-tabbar');
    if (tabs !== null) {
        Object.keys(tabs).map((key) => {
            tabs[key].style.transform = 'translateY(0)';
        });
    } // end if
}
</code>```

But have to be a bad way. Any simple way of doing this?

答:
2017 Answer

Based on the Ionic docs, you just simply need to add tabsHideOnSubPages: true to your app Ionic config like so:

app.module.ts

```<code>imports: [
  BrowserModule,
  IonicModule.forRoot(AppComponent, {
    tabsHideOnSubPages: true
  })
]
</code>```

Title: Ionic 2 - Hide tabs on sub-pages

Body:
I have on my ionicbootstrap config:

{
   mode: 'md',
   tabsHideOnSubPages: true
}

On my settings, but on some sub-pages the tabs are showing. This seems a random behaviour.
Is this the right way of doing this?

ionic : 2.0.0@beta.11

Thanks
Artur

#

EDIT:

I'm using this fix to make the tabs go away:

ionViewWillEnter() {
    let tabs = document.querySelectorAll('.show-tabbar');
    if (tabs !== null) {
        Object.keys(tabs).map((key) => {
            tabs[key].style.transform = 'translateY(56px)';
        });
    } // end if
}

ionViewDidLeave() {
    let tabs = document.querySelectorAll('.show-tabbar');
    if (tabs !== null) {
        Object.keys(tabs).map((key) => {
            tabs[key].style.transform = 'translateY(0)';
        });
    } // end if
}

But have to be a bad way. Any simple way of doing this?

Body:
2017 Answer

Based on the Ionic docs, you just simply need to add tabsHideOnSubPages: true to your app Ionic config like so:

app.module.ts

imports: [
  BrowserModule,
  IonicModule.forRoot(AppComponent, {
    tabsHideOnSubPages: true
  })
]


问:
How to fix this Dropdown in my Navigation bar?
My problem is that if I hover the dropdown it does not go over the size of the menu itself. I know I have this problem because of the fixed navbar, but I still want to keep it anyway. Any solutions?

My HTML NavBar and CSS:

ul {
    list-style-type: none;
    margin: 0;
    padding: 0;
    overflow: hidden;
    background-color: #333;
}

li {
    float: left;
}

li a, .dropbtn {
    display: inline-block;
    color: white;
    text-align: center;
    padding: 14px 16px;
    text-decoration: none;
}

li a:hover, .dropdown:hover .dropbtn {
    background-color: blue;
}

li.dropdown {
    display: inline-block !important;
}

.dropdown-content {
    display: none;
    position: absolute;
    background-color: #f9f9f9;
    min-width: 160px;
    box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
    z-index: 1;
}

.dropdown-content a {
    color: black;
    padding: 20px 20px;
    text-decoration: none;
    display: block;
    text-align: left;
}

.dropdown-content a:hover {background-color: #f1f1f1}

.dropdown:hover .dropdown-content {
    display: block;
}

body {
    margin:0;
    background-color: #f8f8f8;
    padding-top: 80px;
    position: center;
}

.navbar {
    overflow: hidden;
    background-color: white;
    position: fixed;
    top: 0px;
    width: 100%;
}

.navbar a {
    float: left;
    display: block;
    color: black;
    text-align: center;
    padding: 14px 16px;
    text-decoration: none;
    font-size: 18px;
    font-family: 'Lato', sans-serif;
}

.navbar a:hover {
    background-color: lightgrey;
}

.main {
    padding: 16px;
    margin-top: 30px;
    height: 1500px; /* Used in this example to enable scrolling */
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="navbar">
    <a><img src="Bilder/ITK_Logo.png" alt="Anscheinend gibt es ein Problem mit der Anzeige eines Bildes." width="100" height="16.6"></a>
    Home
    <li class="dropdown">
        Produkte
        <div class="dropdown-content">
            Amstweg
            Mach mit!
            Text
        </div>
    </li>
    Download
    Über uns
</div></code>```

Picture of the Problem itself

答:
```<code>ul {
    list-style-type: none;
    margin: 0;
    padding: 0;
    background-color: #333;
}

li {
    float: left;
}

li a, .dropbtn {
    display: inline-block;
    color: white;
    text-align: center;
    padding: 14px 16px;
    text-decoration: none;
}

li a:hover, .dropdown:hover .dropbtn {
    background-color: blue;
}

li.dropdown {
    display: inline-block !important;
}

.dropdown-content {
    display: none;
    position: absolute;
    background-color: #f9f9f9;
    min-width: 160px;
    box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
    z-index: 1;
  top:100%;
}

.dropdown-content a {
    color: black;
    padding: 20px 20px;
    text-decoration: none;
    display: block;
    text-align: left;
}

.dropdown-content a:hover {background-color: #f1f1f1}

.dropdown:hover .dropdown-content {
    display: block;
}

body {
    margin:0;
    background-color: #f8f8f8;
    padding-top: 80px;
    position: center;
}

.navbar {
    background-color: white;
    position: fixed;
    top: 0px;
    width: 100%;
}

.navbar a {
    float: left;
    display: block;
    color: black;
    text-align: center;
    padding: 14px 16px;
    text-decoration: none;
    font-size: 18px;
    font-family: 'Lato', sans-serif;
}

.navbar a:hover {
    background-color: lightgrey;
}

.dropdown-content a {
    width: 100%;
    text-align: left;
}
.main {
    padding: 16px;
    margin-top: 30px;
    height: 1500px; /* Used in this example to enable scrolling */
}
</code>```

The above code should work for your dropdown.
Try it works.
This must be what you are looking for. Thank you

Body:
My problem is that if I hover the dropdown it does not go over the size of the menu itself. I know I have this problem because of the fixed navbar, but I still want to keep it anyway. Any solutions?

My HTML NavBar and CSS:

ul {
    list-style-type: none;
    margin: 0;
    padding: 0;
    overflow: hidden;
    background-color: #333;
}

li {
    float: left;
}

li a, .dropbtn {
    display: inline-block;
    color: white;
    text-align: center;
    padding: 14px 16px;
    text-decoration: none;
}

li a:hover, .dropdown:hover .dropbtn {
    background-color: blue;
}

li.dropdown {
    display: inline-block !important;
}

.dropdown-content {
    display: none;
    position: absolute;
    background-color: #f9f9f9;
    min-width: 160px;
    box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
    z-index: 1;
}

.dropdown-content a {
    color: black;
    padding: 20px 20px;
    text-decoration: none;
    display: block;
    text-align: left;
}

.dropdown-content a:hover {background-color: #f1f1f1}

.dropdown:hover .dropdown-content {
    display: block;
}

body {
    margin:0;
    background-color: #f8f8f8;
    padding-top: 80px;
    position: center;
}

.navbar {
    overflow: hidden;
    background-color: white;
    position: fixed;
    top: 0px;
    width: 100%;
}

.navbar a {
    float: left;
    display: block;
    color: black;
    text-align: center;
    padding: 14px 16px;
    text-decoration: none;
    font-size: 18px;
    font-family: 'Lato', sans-serif;
}

.navbar a:hover {
    background-color: lightgrey;
}

.main {
    padding: 16px;
    margin-top: 30px;
    height: 1500px; /* Used in this example to enable scrolling */
}

    Home

        Produkte

            Amstweg
            Mach mit!
            Text

    Download
    Über uns

Picture of the Problem itself

Body:
ul {
    list-style-type: none;
    margin: 0;
    padding: 0;
    background-color: #333;
}

li {
    float: left;
}

li a, .dropbtn {
    display: inline-block;
    color: white;
    text-align: center;
    padding: 14px 16px;
    text-decoration: none;
}

li a:hover, .dropdown:hover .dropbtn {
    background-color: blue;
}

li.dropdown {
    display: inline-block !important;
}

.dropdown-content {
    display: none;
    position: absolute;
    background-color: #f9f9f9;
    min-width: 160px;
    box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
    z-index: 1;
  top:100%;
}

.dropdown-content a {
    color: black;
    padding: 20px 20px;
    text-decoration: none;
    display: block;
    text-align: left;
}

.dropdown-content a:hover {background-color: #f1f1f1}

.dropdown:hover .dropdown-content {
    display: block;
}

body {
    margin:0;
    background-color: #f8f8f8;
    padding-top: 80px;
    position: center;
}

.navbar {
    background-color: white;
    position: fixed;
    top: 0px;
    width: 100%;
}

.navbar a {
    float: left;
    display: block;
    color: black;
    text-align: center;
    padding: 14px 16px;
    text-decoration: none;
    font-size: 18px;
    font-family: 'Lato', sans-serif;
}

.navbar a:hover {
    background-color: lightgrey;
}

.dropdown-content a {
    width: 100%;
    text-align: left;
}
.main {
    padding: 16px;
    margin-top: 30px;
    height: 1500px; /* Used in this example to enable scrolling */
}

The above code should work for your dropdown.
Try it works.
This must be what you are looking for. Thank you


问:
jQuery ui close button is not shown but it works properly
I am using the jQuery-ui dialog and I have added the libraries:

```<code><link rel="stylesheet" href="../css/bootstrap.min.css">
<link rel="stylesheet" href="../css/jquery-ui.css">

<script src="../js/jquery-3.2.1.min.js"></script>
<script src="../js/tether.min.js"></script>
<script src="../js/bootstrap.min.js"></script>
<script src="../js/jquery-ui.js"></script>
</code>```

But when the dialog box appears, you can not see the close button X.

I can see it as this:

And I have these errors at the console:

Failed to load resource: the server responded with a status of 404
  (Not Found)

答:
image file is not its original place kindly download required image of plugin and retry below code </p>

```<code>  <link rel="stylesheet" href="../css/bootstrap.min.css">
<link rel="stylesheet" href="../css/jquery-ui.css">

<script src="../js/jquery-3.2.1.min.js"></script>
<script src="../js/tether.min.js"></script>
<script src="../js/bootstrap.min.js"></script>
<script src="../js/jquery-ui.js"></script>
</code>```

Body:
I am using the jQuery-ui dialog and I have added the libraries:

<link rel="stylesheet" href="../css/bootstrap.min.css">
<link rel="stylesheet" href="../css/jquery-ui.css">

But when the dialog box appears, you can not see the close button X.

I can see it as this:

And I have these errors at the console:

Failed to load resource: the server responded with a status of 404
  (Not Found)

Body:
image file is not its original place kindly download required image of plugin and retry below code

  <link rel="stylesheet" href="../css/bootstrap.min.css">
<link rel="stylesheet" href="../css/jquery-ui.css">

<script src="../js/jquery-3.2.1.min.js"></script>
<script src="../js/tether.min.js"></script>
<script src="../js/bootstrap.min.js"></script>
<script src="../js/jquery-ui.js"></script>


答:
you need to add . before distance to find class.

       Booking Summary:
        07-07-2017 09:05, 99.84 kilometers, 1 hrs 13 mins

   Additional Seats:

```

Title: How to check if a specific SPAN class content text

Body:
you need to add . before distance to find class.

<div class="trip-summary-info">
      <h3>
   <a href="javascript:void(0);" class="back_first">
       <span class="chevron-up"><i class="fa fa-chevron-up"></i></span>
       Booking Summary:
       &nbsp;<span class="date-time"></span>07-07-2017 09:05<span class="distance">, 99.84 kilometers</span><span class="duration">, 1 hrs 13 mins</span>
   </a>
   <span class="custom-btn custom-btn-default edit back_first"><a href="javascript:void(0);"><i class="fa fa-pencil"></i></a></span>
      </h3>
      <div class="trip_status custom-clearfix">
       <span class="location-form-marker"><i class="fa fa-map-marker"></i></span><div class="location-form"></div>
       <div class="list-address-point" style="display:unset;"></div>
       <span class="location-to-marker"><i class="fa fa-map-marker"></i></span><div class="location-to"></div>
      </div>

      <div class="additional_seats_wrapper editable-field">
   <strong>Additional Seats: </strong><span id="additional-seats" class="text-muted"></span>
   <!-- overlay-icon -->
   <div class="overlay-icon">
    <a class="btn-icon back_first" href="javascript:void(0);"><i class="fa fa-edit"></i></a>
   </div>
   <!-- /overlay-icon -->
      </div>
  </div>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>

if($('.trip-summary-info').find('.distance').length > 0){
    alert("Working !!!");
}
</script>


问:
Creating an array of Images and display one at random on Apple Watch
I'm trying to add my first ever extension for Apple Watch but having issues with creating an array for the app. When I run the app it crashes and I get this error show up at my array:

Thread 1: EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0)

Below is my code, all I want is my image to change to a random image from the array every time the button is tapped:

```<code>import WatchKit
import Foundation

class InterfaceController: WKInterfaceController {

    let runeArray = [UIImage(named: ("Fehu.png"))!, UIImage(named: ("Uruz.png"))!, UIImage(named: ("Thurisaz.png"))!]

    @IBOutlet var runeImage: WKInterfaceImage!

    override func awake(withContext context: Any?) {
        super.awake(withContext: context)

        // Configure interface objects here.
    }

    override func willActivate() {
        // This method is called when watch view controller is about to be visible to user
        super.willActivate()
    }

    override func didDeactivate() {
        // This method is called when watch view controller is no longer visible
        super.didDeactivate()
    }

    @IBAction func castRuneButton() {

        let randomRune = runeArray[Int(arc4random_uniform(UInt32(runeArray.count)))]
        runeImage.setImage(randomRune)
    }
}
</code>```

答: Make sure you have selected both the iOS and watch extension targets for your asset catalog. </p>

Body:
I'm trying to add my first ever extension for Apple Watch but having issues with creating an array for the app. When I run the app it crashes and I get this error show up at my array:

Thread 1: EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0)

Below is my code, all I want is my image to change to a random image from the array every time the button is tapped:

import WatchKit
import Foundation

class InterfaceController: WKInterfaceController {

    let runeArray = [UIImage(named: ("Fehu.png"))!, UIImage(named: ("Uruz.png"))!, UIImage(named: ("Thurisaz.png"))!]

    @IBOutlet var runeImage: WKInterfaceImage!

    override func awake(withContext context: Any?) {
        super.awake(withContext: context)

        // Configure interface objects here.
    }

    override func willActivate() {
        // This method is called when watch view controller is about to be visible to user
        super.willActivate()
    }

    override func didDeactivate() {
        // This method is called when watch view controller is no longer visible
        super.didDeactivate()
    }

    @IBAction func castRuneButton() {

        let randomRune = runeArray[Int(arc4random_uniform(UInt32(runeArray.count)))]
        runeImage.setImage(randomRune)
    }
}


问:
Binding Combobox SelectedItem by a field's value
Combobox bind to a set of Provinces, Village object has ProvinceID field and i want to bind SelectedItem of Combobox to a Province with Village's ProvinceID.

My code is:

```<code><ComboBox ItemsSource="{Binding ProvincesList}"
          DisplayMemberPath="ProvinceName"
          SelectedValuePath="ProvinceID"
          SelectedValue="{Binding Village.ProvinceID}" />
</code>```

But SelectedItem is anything.

答:
First thing I notice is that that is not the correct syntax for binding to a control.

```<code>   SelectedValue="{Binding Village.ProvinceID}"
</code>```

Should be

```<code>   SelectedValue="<%# Village.ProvinceID %>"
</code>```

ContentLicense: CC BY-SA 2.5

Body:
Combobox bind to a set of Provinces, Village object has ProvinceID field and i want to bind SelectedItem of Combobox to a Province with Village's ProvinceID.

My code is:

<ComboBox ItemsSource="{Binding ProvincesList}"
          DisplayMemberPath="ProvinceName"
          SelectedValuePath="ProvinceID"
          SelectedValue="{Binding Village.ProvinceID}" />

But SelectedItem is anything.

Body:
First thing I notice is that that is not the correct syntax for binding to a control.

   SelectedValue="{Binding Village.ProvinceID}"

Should be

   SelectedValue="<%# Village.ProvinceID %>"


问:
K-Means Clustering Performance Benchmarking
I have data that is 157-dimensional with 688 data-points. With the data I would like to perform clustering.

Since K-Means is the simplest algorithm, I have decided to begin with this method.

Here is the Sklearn function call:

KMeans(init='k-means++', n_clusters=4, n_init=10), name="k-means++", data=sales)

Here are some output metrics:

```<code>init                  time    inertia   homo   compl  v-meas     ARI     AMI  num_clusters
k-means++             0.06s    38967   0.262   0.816   0.397   0.297   0.250      4
k-means++             0.05s    29825   0.321   0.847   0.466   0.338   0.306      6
k-means++             0.07s    23131   0.411   0.836   0.551   0.430   0.393      8
k-means++             0.09s    20566   0.636   0.817   0.715   0.788   0.621     10
k-means++             0.09s    18695   0.534   0.794   0.638   0.568   0.513     12
k-means++             0.11s    16805   0.773   0.852   0.810   0.916   0.760     14
k-means++             0.11s    15297   0.822   0.775   0.798   0.811   0.761     16
</code>```

Can someone, please, help me interpret them?

I know that it is good to have a low inertia and high homogeneity score, but I do not know what a good threshold for these is.

For example, 15297 is the lowest inertia I have received, but that happens when the K-clusters is set to 16. Is this good or bad?

Available abbreviations:

homo = homogeneity score;

compl = completeness score;

v_meas = v-measure score;

ARI = adjusted Rand score;

AMI = adjusted mutual info.

答:
The more centroids you have, the lower inertia you will get.
Having more centroids (num_clusters = centroids) means more ways for inputs to be classified to a center, lowering the magnitude of inertia overall in a multi-dimensional space. However, having more centroids also means that it may be more complicated for a machine to reach convergence for a defined number of max_iter in each n_init (by default, max_iter is set to 300). So, you should understand that for each random initialisation of centroids (each start of n_init), your machine computes KMeans algorithm at maximum 300 times, trying to reach a state, where no reclassification of inputs is possible. Of course, if it reaches convergence earlier, then it proceeds to the next n_init. Equally, if your machine does not find a solution for a defined number of iterations (300 in your case), then it still does a next step with another random placement of centroids. After 10 initialisations, the best output in terms of inertia is taken. You may try to increase both max_iter and num_clusters to see that it takes longer to find a solution.

There are no universal thresholds for homo and inertia due to the fact that there are different datasets. The amount of centroids should be chosen empirically, judging from the structure of data and the amount of clusters these inputs should have.

compl is the completeness metrics that reaches its upper bound (1.0) if all inputs of a given class are assigned to the same cluster. Given that its interval is [0.0, 1.0], you may interpret it as a proportion. homo is the homogeneity metrics which interval is equal to compl. It reaches 1.0 if each cluster contains inputs of a single class. v_meas is simply a harmonic mean of those two metrics.

ARI is actually the adjusted Rand score. You can read more about ARI and AMI.

More general information about completeness score and homogeneity measure is here.

Also, you should consider reducing the dimension size with PCA, because performing KMeans on largely multi-dimensional data may give less satisfying results.

Body:
I have data that is 157-dimensional with 688 data-points. With the data I would like to perform clustering.

Since K-Means is the simplest algorithm, I have decided to begin with this method.

Here is the Sklearn function call:

KMeans(init='k-means++', n_clusters=4, n_init=10), name="k-means++", data=sales)

Here are some output metrics:

init                  time    inertia   homo   compl  v-meas     ARI     AMI  num_clusters
k-means++             0.06s    38967   0.262   0.816   0.397   0.297   0.250      4
k-means++             0.05s    29825   0.321   0.847   0.466   0.338   0.306      6
k-means++             0.07s    23131   0.411   0.836   0.551   0.430   0.393      8
k-means++             0.09s    20566   0.636   0.817   0.715   0.788   0.621     10
k-means++             0.09s    18695   0.534   0.794   0.638   0.568   0.513     12
k-means++             0.11s    16805   0.773   0.852   0.810   0.916   0.760     14
k-means++             0.11s    15297   0.822   0.775   0.798   0.811   0.761     16

Can someone, please, help me interpret them?

I know that it is good to have a low inertia and high homogeneity score, but I do not know what a good threshold for these is.

For example, 15297 is the lowest inertia I have received, but that happens when the K-clusters is set to 16. Is this good or bad?

Available abbreviations:

homo = homogeneity score;

compl = completeness score;

v_meas = v-measure score;

ARI = adjusted Rand score;

AMI = adjusted mutual info.


问:
How to create custom queries with spring data, hibernate, for mapped entities?
What I want is a query similar to :

```<code>SELECT s FROM First s WHERE s.x = :x and s.secondId.thirdId.id = :id;
</code>```

I am trying to migrate this to spring data.
I can't figure out what should be the methodname in my repository.

My entities :

```<code>First{
    int x;
    @JoinColumn(name = "second_id", referencedColumnName = "id")
    @ManyToOne(optional = false)
    private Second secondId;
}

Second{
    int id;
    @JoinColumn(name = "third_id", referencedColumnName = "id")
    @ManyToOne(optional = false)
    private Third thirdId;
    int c;
}

Third {
    int id;
    // more data here
    int b;
    int c;
}
</code>```

I tried : findByThirdIdAndX(int id, xval);
getting :

Invalid derived query! No property thirdId found for type First

How can I achieve this?

答:
thirdId is a property of secondId that is a property of First. This is how you would specify that:

```<code>findBySecondIdThirdIdIdAndX(int id, int xval);
</code>```

Here is the relevant doc for nested properties.

Body:
What I want is a query similar to :

SELECT s FROM First s WHERE s.x = :x and s.secondId.thirdId.id = :id;

I am trying to migrate this to spring data.
I can't figure out what should be the methodname in my repository.

My entities :

First{
    int x;
    @JoinColumn(name = "second_id", referencedColumnName = "id")
    @ManyToOne(optional = false)
    private Second secondId;
}

Second{
    int id;
    @JoinColumn(name = "third_id", referencedColumnName = "id")
    @ManyToOne(optional = false)
    private Third thirdId;
    int c;
}

Third {
    int id;
    // more data here
    int b;
    int c;
}

I tried : findByThirdIdAndX(int id, xval);
getting :

Invalid derived query! No property thirdId found for type First

How can I achieve this?

Body:
thirdId is a property of secondId that is a property of First. This is how you would specify that:

findBySecondIdThirdIdIdAndX(int id, int xval);

Here is the relevant doc for nested properties.


问:
How do we check Twitter Bootstrap radio buttons using Laravel Dusk?
According to twitter bootstrap, this is how we do a radio:

```<code><div class="radio">
  <label>
    <input type="radio" name="optionsRadios" id="optionsRadios1" value="option1" checked>
    Option one is this and that—be sure to include why it's great
  </label>
</div>
</code>```

And this is my code:

```<code>$browser->click('#menu-reports')
        ->waitForText('Users')
        ->click('#menu-reports-users')
        ->radio('sitesActive', '2')
        ->radio('includeDisabled', '2')
        ->radio('includeNonCertifiable', '2')
        ->press('Apply')
        ->waitForText('Showing 0 to 0 of 0 entries')
;
</code>```

With the input inside the label tag. But the problem is that Dusk (actually Facebook Webdriver) is not able to find it this way. It keeps raising:

```<code>Facebook\WebDriver\Exception\ElementNotVisibleException: element not visible
</code>```

To make it work I have put the input outside the label, but then, of course, the boostrap radio does not show as it should anymore.

```<code><div class="radio">
  <input type="radio" name="optionsRadios" id="optionsRadios1" value="option1" checked>
  <label>
    Option one is this and that—be sure to include why it's great
  </label>
</div>
</code>```

Does not work using IDs either:

Not even setting an ID to the input:

```<code><input
   type="radio"
   name="sitesActive"
   id="sitesActive3"
   value="2"
>
</code>```

And trying to select it this way:

```<code>->radio('#sitesActive3', '2')
</code>```

The problem is that Dusk (Webdriver) cannot even see the element in the page, as this simple like fails the exact same way:

```<code>$browser->waitFor('#sitesActive3');
</code>```

Resulting in:

```<code>Facebook\WebDriver\Exception\TimeOutException: Waited 5 seconds for selector [#sitesActive3].
</code>```

And that happens every time I have a form with an input with a label surrounding it, if I take the input out of the label, it works. But that's not as simple with radios, as it was with some other inputs, radios.

This is a properly coded radio:

This is a radio with the input outside the label tag:

So, how are you doing this?

答:
You may not be happy to edit your views for the sake of your test script but if you are open to that, what about adding a class to the

```<code><input type="radio" ... >
</code>```

and then using

```<code>        ->click('.yourClass')
</code>```

in your Dusk test?

Body:
According to twitter bootstrap, this is how we do a radio:

    <input type="radio" name="optionsRadios" id="optionsRadios1" value="option1" checked>
    Option one is this and that—be sure to include why it's great

And this is my code:

$browser->click('#menu-reports')
        ->waitForText('Users')
        ->click('#menu-reports-users')
        ->radio('sitesActive', '2')
        ->radio('includeDisabled', '2')
        ->radio('includeNonCertifiable', '2')
        ->press('Apply')
        ->waitForText('Showing 0 to 0 of 0 entries')
;

With the input inside the label tag. But the problem is that Dusk (actually Facebook Webdriver) is not able to find it this way. It keeps raising:

Facebook\WebDriver\Exception\ElementNotVisibleException: element not visible

To make it work I have put the input outside the label, but then, of course, the boostrap radio does not show as it should anymore.

  <input type="radio" name="optionsRadios" id="optionsRadios1" value="option1" checked>

    Option one is this and that—be sure to include why it's great

Does not work using IDs either:

Not even setting an ID to the input:

<input
   type="radio"
   name="sitesActive"
   id="sitesActive3"
   value="2"
>

And trying to select it this way:

->radio('#sitesActive3', '2')

The problem is that Dusk (Webdriver) cannot even see the element in the page, as this simple like fails the exact same way:

$browser->waitFor('#sitesActive3');

Resulting in:

Facebook\WebDriver\Exception\TimeOutException: Waited 5 seconds for selector [#sitesActive3].

And that happens every time I have a form with an input with a label surrounding it, if I take the input out of the label, it works. But that's not as simple with radios, as it was with some other inputs, radios.

This is a properly coded radio:

This is a radio with the input outside the label tag:

So, how are you doing this?

Body:
You may not be happy to edit your views for the sake of your test script but if you are open to that, what about adding a class to the

<input type="radio" ... >

and then using

        ->click('.yourClass')

in your Dusk test?


问:
Unable to locate element 'Add to Cart ' on Ted Baker ecommerce site
enter image description hereI am not able to locate web Element Add to cart using Xpath as well as classname.
Steps:trying to add product in cart /wishlist but button is not clickable.
 Can anyone please help me to resolve this issue.

    ===========================================================================
    Code>>>

```<code>    package Test;
    import java.util.HashMap;
    import java.util.Map;
    import org.openqa.selenium.By;
    import org.openqa.selenium.JavascriptExecutor;
    import org.openqa.selenium.WebDriver;
    import org.openqa.selenium.WebElement;
    import org.openqa.selenium.chrome.ChromeDriver;
    import org.openqa.selenium.chrome.ChromeOptions;
    import org.openqa.selenium.interactions.Actions;
    import org.openqa.selenium.support.ui.ExpectedConditions;
    import org.openqa.selenium.support.ui.Select;
    import org.openqa.selenium.support.ui.WebDriverWait;

    public class tedbak {

        public static void main(String[] args) throws InterruptedException {
            // TODO Auto-generated method stub
            WebDriver driver;

                System.setProperty("webdriver.chrome.driver","C:\\Chrome\\chromedriver_win32\\chromedriver.exe");
                //System.setProperty("org.apache.commons.logging.Log", "org.apache.commons.logging.impl.Jdk14Logger");
             Thread.sleep(2000);
            ChromeOptions options = new ChromeOptions();
            Map<String, Object> prefs = new HashMap<String, Object>();
            prefs.put("credentials_enable_service", false);
            prefs.put("password_manager_enabled", false);
              options.setExperimentalOption("prefs", prefs);
            options.addArguments("start-maximized");
            options.addArguments("disable-infobars");
            driver = new ChromeDriver(options);

                driver.get("http://www.tedbaker.com/");

                WebDriverWait wait = new WebDriverWait(driver, 40);
                wait.until(ExpectedConditions.presenceOfElementLocated(By.xpath("html/body/div[3]/div[2]/div/div/ul/li[1]/a")));
                        if(driver.findElement(By.xpath("html/body/div[3]/div[2]/div/div/ul/li[1]/a")).isDisplayed())
                            {

                            driver.findElement(By.xpath("html/body/div[3]/div[2]/div/div/ul/li[1]/a")).click();

                            WebElement Search_Item=driver.findElement(By.xpath("html/body/div[2]/header/div/nav[2]/section/ul[2]/li[1]/a/span[1]"));
                            Search_Item.click();
                            WebElement Seacrh_item_message=driver.findElement(By.id("search"));
                            WebElement Search_textbox=driver.findElement(By.xpath("html/body/div[2]/header/div/form/div[1]/ol/li[1]/input"));

                            Search_textbox.sendKeys("Watches");
                            driver.findElement(By.xpath("html/body/div[2]/header/div/form/div[1]/ol/li[2]/input")).click();
                            WebElement SearchResult_pagemessage=driver.findElement(By.xpath("html/body/div[2]/div/div/div[1]/div/h1"));
                            driver.findElement(By.xpath("html/body/div[2]/div/div/div[1]/div/div/div/span[1]")).click();

 WebElement Item_Tobuy = driver.findElement(By.xpath("html/body/div[2]/div/div/div[2]/div[2]/div[1]/article/div[2]/header/div/h4/a"));
                            JavascriptExecutor jse1= (JavascriptExecutor)driver;
                            jse1.executeScript("window.scrollBy(0,400)", "");
                            Item_Tobuy.click();
                                                         driver.findElement(By.xpath("html/body/div[2]/div/div/div[2]/div[1]/section[2]/form/ol/li[2]/span/span/select")).click();
                           Select dropdown1=new Select(driver.findElement(By.id("qty")));
                           dropdown1.selectByVisibleText("5");
                           driver.findElement(By.id("qty")).click();
                           driver.findElement(By.xpath("html/body/div[2]/div/div/div[2]/div[1]/section[2]/form/div[3]/div[2]/a/span[1]/span[1]")).click();
                                                                            }

    }
    }
===========================================================================
    error>>>

    Starting ChromeDriver 2.30.477700 (0057494ad8732195794a7b32078424f92a5fce41) on port 17869
    Only local connections are allowed.
    Exception in thread "main" org.openqa.selenium.NoSuchElementException: no such element: Unable to locate element: {"method":"xpath","selector":"html/body/div[2]/div/div/div[2]/div[1]/section[2]/form/div[3]/div[2]/a/span[1]/span[1]"}
      (Session info: chrome=59.0.3071.86)
      (Driver info: chromedriver=2.30.477700 (0057494ad8732195794a7b32078424f92a5fce41),platform=Windows NT 10.0.14393 x86_64) (WARNING: The server did not provide any stacktrace information)
    Command duration or timeout: 52 milliseconds
    For documentation on this error, please visit: http://seleniumhq.org/exceptions/no_such_element.html
    Build info: version: '2.53.0', revision: '35ae25b', time: '2016-03-15 17:00:58'
    System info: host: 'D90ZC6Q1', ip: '192.168.163.235', os.name: 'Windows 10', os.arch: 'amd64', os.version: '10.0', java.version: '1.8.0_92'
    Driver info: org.openqa.selenium.chrome.ChromeDriver
    Capabilities [{applicationCacheEnabled=false, rotatable=false, mobileEmulationEnabled=false, networkConnectionEnabled=false, chrome={chromedriverVersion=2.30.477700 (0057494ad8732195794a7b32078424f92a5fce41), userDataDir=C:\Users\DAHIBH~1\AppData\Local\Temp\scoped_dir8284_18567}, takesHeapSnapshot=true, pageLoadStrategy=normal, databaseEnabled=false, handlesAlerts=true, hasTouchScreen=false, version=59.0.3071.86, platform=XP, browserConnectionEnabled=false, nativeEvents=true, acceptSslCerts=true, locationContextEnabled=true, webStorageEnabled=true, browserName=chrome, takesScreenshot=true, javascriptEnabled=true, cssSelectorsEnabled=true, unexpectedAlertBehaviour=}]
    Session ID: b48bc601ec61113cfada0c7c2f5f77b8
    *** Element info: {Using=xpath, value=html/body/div[2]/div/div/div[2]/div[1]/section[2]/form/div[3]/div[2]/a/span[1]/span[1]}
        at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
        at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
        at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
        at java.lang.reflect.Constructor.newInstance(Unknown Source)
        at org.openqa.selenium.remote.ErrorHandler.createThrowable(ErrorHandler.java:206)
        at org.openqa.selenium.remote.ErrorHandler.throwIfResponseFailed(ErrorHandler.java:158)
        at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:678)
        at org.openqa.selenium.remote.RemoteWebDriver.findElement(RemoteWebDriver.java:363)
        at org.openqa.selenium.remote.RemoteWebDriver.findElementByXPath(RemoteWebDriver.java:500)
        at org.openqa.selenium.By$ByXPath.findElement(By.java:361)
        at org.openqa.selenium.remote.RemoteWebDriver.findElement(RemoteWebDriver.java:355)
        at Test.tedbak.main(tedbak.java:70)
</code>```

答:
First of all, please try not to use absolute xpath locators. This is a very bad strategy of locating elements. Try to have at least relative locators or not have xpaths at all. Please see this post, and this post about using a good Selenium selector.

Secondly, you can use the following selectors, for your given case

```<code>driver.findElement(By.cssSelector("div.product_add.ng-scope")).click()
</code>```

does it successfully.

or even this,

```<code>driver.findElement(By.cssSelector("div.button_success.major")).click()
</code>```

does the same job.

Body:
enter image description hereI am not able to locate web Element Add to cart using Xpath as well as classname.
Steps:trying to add product in cart /wishlist but button is not clickable.
 Can anyone please help me to resolve this issue.

    ===========================================================================
    Code>>>

    package Test;
    import java.util.HashMap;
    import java.util.Map;
    import org.openqa.selenium.By;
    import org.openqa.selenium.JavascriptExecutor;
    import org.openqa.selenium.WebDriver;
    import org.openqa.selenium.WebElement;
    import org.openqa.selenium.chrome.ChromeDriver;
    import org.openqa.selenium.chrome.ChromeOptions;
    import org.openqa.selenium.interactions.Actions;
    import org.openqa.selenium.support.ui.ExpectedConditions;
    import org.openqa.selenium.support.ui.Select;
    import org.openqa.selenium.support.ui.WebDriverWait;

    public class tedbak {

        public static void main(String[] args) throws InterruptedException {
            // TODO Auto-generated method stub
            WebDriver driver;

                System.setProperty("webdriver.chrome.driver","C:\\Chrome\\chromedriver_win32\\chromedriver.exe");
                //System.setProperty("org.apache.commons.logging.Log", "org.apache.commons.logging.impl.Jdk14Logger");
             Thread.sleep(2000);
            ChromeOptions options = new ChromeOptions();
            Map<String, Object> prefs = new HashMap<String, Object>();
            prefs.put("credentials_enable_service", false);
            prefs.put("password_manager_enabled", false);
              options.setExperimentalOption("prefs", prefs);
            options.addArguments("start-maximized");
            options.addArguments("disable-infobars");
            driver = new ChromeDriver(options);

                driver.get("http://www.tedbaker.com/");

                WebDriverWait wait = new WebDriverWait(driver, 40);
                wait.until(ExpectedConditions.presenceOfElementLocated(By.xpath("html/body/div[3]/div[2]/div/div/ul/li[1]/a")));
                        if(driver.findElement(By.xpath("html/body/div[3]/div[2]/div/div/ul/li[1]/a")).isDisplayed())
                            {

                            driver.findElement(By.xpath("html/body/div[3]/div[2]/div/div/ul/li[1]/a")).click();

                            WebElement Search_Item=driver.findElement(By.xpath("html/body/div[2]/header/div/nav[2]/section/ul[2]/li[1]/a/span[1]"));
                            Search_Item.click();
                            WebElement Seacrh_item_message=driver.findElement(By.id("search"));
                            WebElement Search_textbox=driver.findElement(By.xpath("html/body/div[2]/header/div/form/div[1]/ol/li[1]/input"));

                            Search_textbox.sendKeys("Watches");
                            driver.findElement(By.xpath("html/body/div[2]/header/div/form/div[1]/ol/li[2]/input")).click();
                            WebElement SearchResult_pagemessage=driver.findElement(By.xpath("html/body/div[2]/div/div/div[1]/div/h1"));
                            driver.findElement(By.xpath("html/body/div[2]/div/div/div[1]/div/div/div/span[1]")).click();

 WebElement Item_Tobuy = driver.findElement(By.xpath("html/body/div[2]/div/div/div[2]/div[2]/div[1]/article/div[2]/header/div/h4/a"));
                            JavascriptExecutor jse1= (JavascriptExecutor)driver;
                            jse1.executeScript("window.scrollBy(0,400)", "");
                            Item_Tobuy.click();
                                                         driver.findElement(By.xpath("html/body/div[2]/div/div/div[2]/div[1]/section[2]/form/ol/li[2]/span/span/select")).click();
                           Select dropdown1=new Select(driver.findElement(By.id("qty")));
                           dropdown1.selectByVisibleText("5");
                           driver.findElement(By.id("qty")).click();
                           driver.findElement(By.xpath("html/body/div[2]/div/div/div[2]/div[1]/section[2]/form/div[3]/div[2]/a/span[1]/span[1]")).click();
                                                                            }

    }
    }
===========================================================================
    error>>>

    Starting ChromeDriver 2.30.477700 (0057494ad8732195794a7b32078424f92a5fce41) on port 17869
    Only local connections are allowed.
    Exception in thread "main" org.openqa.selenium.NoSuchElementException: no such element: Unable to locate element: {"method":"xpath","selector":"html/body/div[2]/div/div/div[2]/div[1]/section[2]/form/div[3]/div[2]/a/span[1]/span[1]"}
      (Session info: chrome=59.0.3071.86)
      (Driver info: chromedriver=2.30.477700 (0057494ad8732195794a7b32078424f92a5fce41),platform=Windows NT 10.0.14393 x86_64) (WARNING: The server did not provide any stacktrace information)
    Command duration or timeout: 52 milliseconds
    For documentation on this error, please visit: http://seleniumhq.org/exceptions/no_such_element.html
    Build info: version: '2.53.0', revision: '35ae25b', time: '2016-03-15 17:00:58'
    System info: host: 'D90ZC6Q1', ip: '192.168.163.235', os.name: 'Windows 10', os.arch: 'amd64', os.version: '10.0', java.version: '1.8.0_92'
    Driver info: org.openqa.selenium.chrome.ChromeDriver
    Capabilities [{applicationCacheEnabled=false, rotatable=false, mobileEmulationEnabled=false, networkConnectionEnabled=false, chrome={chromedriverVersion=2.30.477700 (0057494ad8732195794a7b32078424f92a5fce41), userDataDir=C:\Users\DAHIBH~1\AppData\Local\Temp\scoped_dir8284_18567}, takesHeapSnapshot=true, pageLoadStrategy=normal, databaseEnabled=false, handlesAlerts=true, hasTouchScreen=false, version=59.0.3071.86, platform=XP, browserConnectionEnabled=false, nativeEvents=true, acceptSslCerts=true, locationContextEnabled=true, webStorageEnabled=true, browserName=chrome, takesScreenshot=true, javascriptEnabled=true, cssSelectorsEnabled=true, unexpectedAlertBehaviour=}]
    Session ID: b48bc601ec61113cfada0c7c2f5f77b8
    *** Element info: {Using=xpath, value=html/body/div[2]/div/div/div[2]/div[1]/section[2]/form/div[3]/div[2]/a/span[1]/span[1]}
        at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
        at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
        at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
        at java.lang.reflect.Constructor.newInstance(Unknown Source)
        at org.openqa.selenium.remote.ErrorHandler.createThrowable(ErrorHandler.java:206)
        at org.openqa.selenium.remote.ErrorHandler.throwIfResponseFailed(ErrorHandler.java:158)
        at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:678)
        at org.openqa.selenium.remote.RemoteWebDriver.findElement(RemoteWebDriver.java:363)
        at org.openqa.selenium.remote.RemoteWebDriver.findElementByXPath(RemoteWebDriver.java:500)
        at org.openqa.selenium.By$ByXPath.findElement(By.java:361)
        at org.openqa.selenium.remote.RemoteWebDriver.findElement(RemoteWebDriver.java:355)
        at Test.tedbak.main(tedbak.java:70)

Body:
First of all, please try not to use absolute xpath locators. This is a very bad strategy of locating elements. Try to have at least relative locators or not have xpaths at all. Please see this post, and this post about using a good Selenium selector.

Secondly, you can use the following selectors, for your given case

driver.findElement(By.cssSelector("div.product_add.ng-scope")).click()

does it successfully.

or even this,

driver.findElement(By.cssSelector("div.button_success.major")).click()

does the same job.


问:
How to classify my array of object compared to my table?
I want to reorder my array of object, I want it follows (const quote) the theme position (const themeOrder).

```<code>const quote = [{
  theme: 'spirituality'
}, {
  theme: 'politic'
}, {
  theme: 'military'
}, {
  theme: 'politic'
}, {
  theme: 'tech'
}];
const themeOrder = ['tech', 'politic', 'military', 'spirituality'];
</code>```

I want a result like

```<code>newQuote = [{
  theme: 'tech'
}, {
  theme: 'politic'
}, {
  theme: 'military'
}, {
  theme: 'spirituality'
}]
</code>```

答:
You can sort your array objects with Array.prototype.sort by comparing the theme properties' index positions in the themeOrder array:

const quote = [{
  theme: 'spirituality'
}, {
  theme: 'politic'
}, {
  theme: 'military'
}, {
  theme: 'politic'
}, {
  theme: 'tech'
}];
const themeOrder = ['tech', 'politic', 'military', 'spirituality'];

quote.sort((a, b) => themeOrder.indexOf(a.theme) - themeOrder.indexOf(b.theme));

console.log(quote);```

Body:
I want to reorder my array of object, I want it follows (const quote) the theme position (const themeOrder).

const quote = [{
  theme: 'spirituality'
}, {
  theme: 'politic'
}, {
  theme: 'military'
}, {
  theme: 'politic'
}, {
  theme: 'tech'
}];
const themeOrder = ['tech', 'politic', 'military', 'spirituality'];

I want a result like

newQuote = [{
  theme: 'tech'
}, {
  theme: 'politic'
}, {
  theme: 'military'
}, {
  theme: 'spirituality'
}]


问:
How to update key value in talend with tmysqloutput component
My scenario is like, I have the tMysqlOutput component is like as follows

tMysqlOutput ---> Basic settings ---> Action on table is Default  and Action on Data is Update

tMysqlOutput ---> Advanced settings -----> Use field options

I want to update indicator (indicator is key column also), but i am unable to update the indicator

Thanks in Advance

答:
When updating a field value, Talend/MySQL needs a primary key field to find the correct record.

Since it is looking up the field with the primary key, it might not be possible to update the very field which has been used for looking up the row.

You might be able to achieve what you want with an additional autoincrementing id field.

This id field would be the Update Key and nothing else is selected. Then indicator would be Updateable.

Source


问:
Printing garbage information in R
I am facing some wired problem in R. When I try to print values from column named 'who' from CSV file it prints extra information (probably garbage) which is even not present in the file. Here is the information I am reading from file

```<code>bug_id  who
1141327 dtownsend
1141327 dtownsend
1142623 wkocher
1142623 wkocher
1143179 jorge
1143179 jorge
1144222 dtownsend
1144222 dtownsend
1144493 markh
1144493 ryanvm
1144493 ryanvm
1144493 twalker
1145049 wkocher
</code>```

The code is:

```<code>dataframe <- read.csv("try.csv", header = TRUE)
 i <- 1
while(i < nrow(dataframe)) {
   print(dataframe$who[i])
     i <- i + 1
 }
</code>```

Output is

```<code>[1] dtownsend
Levels: dtownsend jorge markh ryanvm twalker wkocher
[1] dtownsend
Levels: dtownsend jorge markh ryanvm twalker wkocher
[1] wkocher
Levels: dtownsend jorge markh ryanvm twalker wkocher
[1] wkocher
Levels: dtownsend jorge markh ryanvm twalker wkocher
[1] jorge
Levels: dtownsend jorge markh ryanvm twalker wkocher
</code>```

答:
R has a data type called factor (read more here) which is causing this behavior.  The "levels" are allowable values, and are the default data type for strings.  The solution is relatively simple:

```<code>dataframe <- read.csv("try.csv", header = TRUE, stringsAsFactors=FALSE)
## show datatypes
lapply(dataframe,class)

 i <- 1
while(i < nrow(dataframe)) {
   print(dataframe$who[i])
     i <- i + 1
 }
</code>```

The other solution is to use a package like readr that avoids the use of factors by default.

EDIT: If you need factors, you can always print with print(as.character()) to make things look nicer.

Title: Printing garbage information in R

Body:
I am facing some wired problem in R. When I try to print values from column named 'who' from CSV file it prints extra information (probably garbage) which is even not present in the file. Here is the information I am reading from file

bug_id  who
1141327 dtownsend
1141327 dtownsend
1142623 wkocher
1142623 wkocher
1143179 jorge
1143179 jorge
1144222 dtownsend
1144222 dtownsend
1144493 markh
1144493 ryanvm
1144493 ryanvm
1144493 twalker
1145049 wkocher

The code is:

dataframe <- read.csv("try.csv", header = TRUE)
 i <- 1
while(i < nrow(dataframe)) {
   print(dataframe$who[i])
     i <- i + 1
 }

Output is

[1] dtownsend
Levels: dtownsend jorge markh ryanvm twalker wkocher
[1] dtownsend
Levels: dtownsend jorge markh ryanvm twalker wkocher
[1] wkocher
Levels: dtownsend jorge markh ryanvm twalker wkocher
[1] wkocher
Levels: dtownsend jorge markh ryanvm twalker wkocher
[1] jorge
Levels: dtownsend jorge markh ryanvm twalker wkocher

Body:
R has a data type called factor (read more here) which is causing this behavior.  The "levels" are allowable values, and are the default data type for strings.  The solution is relatively simple:

dataframe <- read.csv("try.csv", header = TRUE, stringsAsFactors=FALSE)
## show datatypes
lapply(dataframe,class)

 i <- 1
while(i < nrow(dataframe)) {
   print(dataframe$who[i])
     i <- i + 1
 }

The other solution is to use a package like readr that avoids the use of factors by default.

EDIT: If you need factors, you can always print with print(as.character()) to make things look nicer.


问:
Highchart - Add dynamic data to the bar
I am using the bar chart. I want to add the new bar in the existing bar chart which is already drawn.

How to do that?
I have used the following

```<code>chartObject.series[i].addPoint(99, true);
</code>```

But didn't get the result. It's automatically add the value with the default label name.

I want to insert the E bar with the value under A. How can I do that?

```<code>chartObject = Highcharts.chart('chartContainer', {
            chart: {
                type: 'bar'
            },
            title: {
                text: ''
            },
            xAxis: {
                categories: ["A", "B", "C", "D"],
                title: {
                    text: null
                }
            },
            yAxis: {
                min: 0,
            },

            plotOptions: {
                bar: {
                    dataLabels: {
                        enabled: true
                    }
                },
                series: {
                    cursor: 'pointer',
                    point: {
                        events: {
                            click: function () {
                                debugger

                                for (var i = 0; i < chartObject.series.length; i++) {
                                    chartObject.series[i].addPoint(99, true);

                                }

                                alert('Category: ' + this.category + ', value: ' + this.y);
                            }
                        }
                    }
                },
                showInLegend: false
            },
            legend: {
                enabled: false
            },
            credits: {
                enabled: false
            },
            tooltip: {
                enabled: false

            },
            series: [{
                showInLegend: false,
                data: [
                    50,
                    35,
                    25,
                    80
                ]
            }]
        });
</code>```

答:
Please refer to this jsfiddle: http://jsfiddle.net/kkulig/rhneon2q/

I think that one of the convenient ways to do this is to move categories definitions to name properties of points:

```<code>data: [
   {y: 50, name: 'A'},
   {y: 35, name: 'B'}
]
</code>```

and change xAxis type to category:

```<code>type: 'category'
</code>```

It's explained here: http://api.highcharts.com/highcharts/xAxis.categories

Then you can update chart with new point just like that:

UPDATE:

Code:

```<code>chartObject.series[i].addPoint({y: this.y, name: 'E'}, true);
</code>```

Adds new point with category on the end of a serie.

If you wan't new point with category to appear after the clicked one, you can use this code:

```<code>var data = chartObject.userOptions.series[i].data.slice(); // clone original userOptions
data.splice(this.index + 1, 0, {
  y: 10,
  name: "New cat. " + (chartObject.series[i].data.length - 2) // 2 - initial categories number
});
chartObject.series[i].update({
  data: data
});
</code>```

END OF UPDATE

Unfortunately if you set categories like you did before:

```<code>categories: ["A", "B", "C", "D"]
</code>```

name property of added point won't be used as category.

Title: Highchart - Add dynamic data to the bar

Body:
I am using the bar chart. I want to add the new bar in the existing bar chart which is already drawn.

How to do that?
I have used the following

chartObject.series[i].addPoint(99, true);

But didn't get the result. It's automatically add the value with the default label name.

I want to insert the E bar with the value under A. How can I do that?

chartObject = Highcharts.chart('chartContainer', {
            chart: {
                type: 'bar'
            },
            title: {
                text: ''
            },
            xAxis: {
                categories: ["A", "B", "C", "D"],
                title: {
                    text: null
                }
            },
            yAxis: {
                min: 0,
            },

            plotOptions: {
                bar: {
                    dataLabels: {
                        enabled: true
                    }
                },
                series: {
                    cursor: 'pointer',
                    point: {
                        events: {
                            click: function () {
                                debugger

                                for (var i = 0; i < chartObject.series.length; i++) {
                                    chartObject.series[i].addPoint(99, true);

                                }

                                alert('Category: ' + this.category + ', value: ' + this.y);
                            }
                        }
                    }
                },
                showInLegend: false
            },
            legend: {
                enabled: false
            },
            credits: {
                enabled: false
            },
            tooltip: {
                enabled: false

            },
            series: [{
                showInLegend: false,
                data: [
                    50,
                    35,
                    25,
                    80
                ]
            }]
        });

Body:
Please refer to this jsfiddle: http://jsfiddle.net/kkulig/rhneon2q/

I think that one of the convenient ways to do this is to move categories definitions to name properties of points:

data: [
   {y: 50, name: 'A'},
   {y: 35, name: 'B'}
]

and change xAxis type to category:

type: 'category'

It's explained here: http://api.highcharts.com/highcharts/xAxis.categories

Then you can update chart with new point just like that:

UPDATE:

Code:

chartObject.series[i].addPoint({y: this.y, name: 'E'}, true);

Adds new point with category on the end of a serie.

If you wan't new point with category to appear after the clicked one, you can use this code:

var data = chartObject.userOptions.series[i].data.slice(); // clone original userOptions
data.splice(this.index + 1, 0, {
  y: 10,
  name: "New cat. " + (chartObject.series[i].data.length - 2) // 2 - initial categories number
});
chartObject.series[i].update({
  data: data
});

END OF UPDATE

Unfortunately if you set categories like you did before:

categories: ["A", "B", "C", "D"]

name property of added point won't be used as category.


问:
What's the difference between 'isset()' and '!empty()' in PHP?
I don't understand the difference between isset() and !empty().

Because if a variable has been set, isn't it the same as not being empty?

答:
And one more remark. empty() checks if the variable exists as well. I.e. if we perform empty() to the variable that wasn't declared, we don't receive an error, empty() returns 'true'. Therefore we may avoid isset() if next we need to check if the variable empty.

So

```<code>isset($var) && !empty($var)
</code>```

will be equals to

```<code>!empty($var)
</code>```

Body:
And one more remark. empty() checks if the variable exists as well. I.e. if we perform empty() to the variable that wasn't declared, we don't receive an error, empty() returns 'true'. Therefore we may avoid isset() if next we need to check if the variable empty.

So

isset($var) && !empty($var)

will be equals to

!empty($var)


问:
regular expression to add characters before and after numbers
I have a list of numbers between square brackets, and I need to add words before and after the exact numbers (i.e. keep the same numbers).  I use notepad++ to replace, but if you have a solution with other program please advise.

Example:

```<code>text [121] othertext
moretext [16] othertextmore
andtext [5940] othertextplus
</code>```

outcome:

```<code>text xxxxxxxxx [121] xxxxxxxxx othertext
moretext xxxxxxxxx [16] xxxxxxxxx othertextmore
andtext xxxxxxxxx [5940] xxxxxxxxx othertextplus
</code>```

The numbers are of course \d+ but I want to tell it to keep the same numbers when looking.

答:
Regular expression:

```<code>Find regex = \[\d+\]
Replace regex = xxxxxxxxx$&xxxxxxxxx
</code>```

Refer: regexr

Body:
I have a list of numbers between square brackets, and I need to add words before and after the exact numbers (i.e. keep the same numbers).  I use notepad++ to replace, but if you have a solution with other program please advise.

Example:

text [121] othertext
moretext [16] othertextmore
andtext [5940] othertextplus

outcome:

text xxxxxxxxx [121] xxxxxxxxx othertext
moretext xxxxxxxxx [16] xxxxxxxxx othertextmore
andtext xxxxxxxxx [5940] xxxxxxxxx othertextplus

The numbers are of course \d+ but I want to tell it to keep the same numbers when looking.

Body:
Regular expression:

Find regex = \[\d+\]
Replace regex = xxxxxxxxx$&xxxxxxxxx

Refer: regexr


问:
How to build and install rails application dependencies on different hosts
I have a rails 3 application that I'd like to deploy. My deployment environment does not have build tools installed and cannot then install dependencies with native extensions.

I have a build host configured with build tools that can build the native extensions.

How can I deploy the native extensions from my build host ?

I have tried doing bundle package on the build host and bundle install --local on the remote host. It correctly installs gems without native extensions but it still tries to build native extensions on the production host.

答:
It is bad practice to build on your production servers.

When I deploy Django or Rails I always build a toolchain for whatever the OS package management system doesn't cover.  I then develop and deploy with that toolchain.  This assures everyone uses the same versions of the tools.

To create the toolchain you need to install the packages and supporting executables in that directory.  You also need to make sure that they are relocatable.

For example I currently use Django on RedHat.  RedHat doesn't use the latest version of python, and many of the python libs I use rev more often than the repository maintainers pick them up.  As a result there are often no RPMs for the latest software.  I create a toolchain directory, compiled python on all the libs I needed into that directory.  I then bundle it up into an RPM for deployment.

toolchain/

bin/

python

...

lib/

python2.7/

...

site-packages/

...

include/

...


问:
How can I add together the values of an array in CoffeeScript?
I have an array of numbers.
How can I add them together the easiest way in CoffeeScript?</p>

答:
```<code>numbers = [1, 2, 3]
sum = 0
(sum += num for num in numbers) # add each number in array to sum
</code>```


问:
How to check if a specific SPAN class content text
wanna check whether a specific SPAN class context text or not?
The SPAN class I want to check against is "distance" that has the kilometers numbers like (, 27 kilometers).

Tried the below code but still not working

if ($('.trip-summary-info').find('distance').length > 0) {
  alert("Working !!!");```
<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>
<div class="trip-summary-info">
  <h3>

      <span class="chevron-up"><i class="fa fa-chevron-up"></i></span> Booking Summary:
      <span class="date-time"></span>07-07-2017 09:05<span class="distance">, 99.84 kilometers</span><span class="duration">, 1 hrs 13 mins</span>

    <span class="custom-btn custom-btn-default edit back_first"><i class="fa fa-pencil"></i></span>
  </h3>
  <div class="trip_status custom-clearfix">
    <span class="location-form-marker"><i class="fa fa-map-marker"></i></span>
    <div class="location-form"></div>
    <div class="list-address-point" style="display:unset;"></div>
    <span class="location-to-marker"><i class="fa fa-map-marker"></i></span>
    <div class="location-to"></div>
  </div>

  <div class="additional_seats_wrapper editable-field">
    <strong>Additional Seats: </strong><span id="additional-seats" class="text-muted"></span>
    <!-- overlay-icon -->
    <div class="overlay-icon">
      <i class="fa fa-edit"></i>
    </div>
    <!-- /overlay-icon -->
  </div>
</div></code>```

答:
You could try the following:</p>

```<code>var $distance = $('.trip-summary-info .distance');
if ($distance.text() === ""){
   // There is no text, so handle that
}
else {
   // There is text, so you could do something different
}
</code>```

Body:
wanna check whether a specific SPAN class context text or not?
The SPAN class I want to check against is "distance" that has the kilometers numbers like (, 27 kilometers).

Tried the below code but still not working

if ($('.trip-summary-info').find('distance').length > 0) {
  alert("Working !!!");

       Booking Summary:
      07-07-2017 09:05, 99.84 kilometers, 1 hrs 13 mins

    Additional Seats:

Body:
You could try the following:

var $distance = $('.trip-summary-info .distance');
if ($distance.text() === ""){
   // There is no text, so handle that
}
else {
   // There is text, so you could do something different
}


问:
Can I change my android application style at runtime?
I want to change the manifest style when the user chooses a setting in the preferences file or settings. I have a setting in my apk which includes a list of preferences with three entries {Style_1, Style_2, Style_3}. I want to change the style color, like primaryColor, when the user clicks a style. How can I do this?

答:
Yes you can do this easily, I do it all the time.

Just call this method before setContentView like this:

```<code> setTheme(R.style.Theme);
 setContentView(R.layout.activity_layout);
</code>```

Now what I do is that i take a static int variable in the app constants and change it according to my theme. Then i do something like this

```<code> //This is in my constants file
 public static int CURRENT_THEME = R.style.AppTheme;

 //This is in my onCreate of every Activity.
 setTheme(Constants.CURRENT_THEME);
 setContentView(R.layout.activity_layout);
</code>```

Hope this helps.

Body:
Yes you can do this easily, I do it all the time.

Just call this method before setContentView like this:

 setTheme(R.style.Theme);
 setContentView(R.layout.activity_layout);

Now what I do is that i take a static int variable in the app constants and change it according to my theme. Then i do something like this

 //This is in my constants file
 public static int CURRENT_THEME = R.style.AppTheme;

 //This is in my onCreate of every Activity.
 setTheme(Constants.CURRENT_THEME);
 setContentView(R.layout.activity_layout);

Hope this helps.


问:
CasperJS scraping result from the terminal
Let's say I've got one main url stored in a variable.

var google = 'http://www.google.com';

If I wanna search the word dog from the google var for example, from the terminal and scrape all the results how can I do this? For example:

casperjs test.js dog

答:
Here is a documentation regarding App Arguments in NodeJS.

Read this and start writing your app.
After that you might need regular expressions. Here is an example how to get all occurrences of a dog in a string

```<code>var str = 'red dog jumps over brown dog';
var regexp = /dog/gi;
var matches_array = str.match(regexp);

console.log(matches_array);
</code>```

These are only hints on how to achieve this.

If you have any other question regarding this, create a new question with Minimal, Complete, and Verifiable example for a specific problem

Body:
Here is a documentation regarding App Arguments in NodeJS.

Read this and start writing your app.
After that you might need regular expressions. Here is an example how to get all occurrences of a dog in a string

var str = 'red dog jumps over brown dog';
var regexp = /dog/gi;
var matches_array = str.match(regexp);

console.log(matches_array);

These are only hints on how to achieve this.

If you have any other question regarding this, create a new question with Minimal, Complete, and Verifiable example for a specific problem


问:
adal angular app reloading - by design?
I have built a simple angular app and for authentication, I authenticate against AzureAD using use the npm package adal-angular4

When authentication happens, the user gets sent to https://login.microsoftonline.com they login and get sent back to the agulare app which causes a reload/recompile which will cause a load time delay, only short but the overall load time experience is doubled.

As you can see above :

login is loaded (localhost)

app is compiled

user taken to login screen (azuread)

user logs in and user is taken back to login (localhost)

app is complied

The load gap between main.bundle.js and background' is a simple way to show the compile time, its only a VERY TIME but I have a VERY FAST PC.

What can be done to avoid the recompile? My thoughts are

Do all the auth in the index.html (eg, pre first load of APP) and just save the JWT token to the session storage

Find an angular packages do this via an IFRAME

Anyone got any thoughts on this? maybe adal-angular4 should use an IFRAME?

Some more details

Example of adal-angular4

Microsofts anglurejs example which uses this javascrit maybe this is a good starting place for a pure JavaScript solutoon thats executed from the index.html.

答:
You need to use adal.js directly not via the angular application.

In the main index.html add the following code

```<code><script src="https://secure.aadcdn.microsoftonline-p.com/lib/1.0.0/js/adal.min.js"></script>
<script>
window.config = {
  instance: 'https://login.microsoftonline.com/',
  tenant: 'yourtenant.co.uk',
  clientId: '11111111-1111-1111-1111-1111111111',
  postLogoutRedirectUri: window.location.origin,
  cacheLocation: 'localStorage',
};
// Check For & Handle Redirect From AAD After Login
var authContext = new AuthenticationContext(config);
var isCallback = authContext.isCallback(window.location.hash);
authContext.handleWindowCallback();
if (isCallback && !authContext.getLoginError()) {
    window.location = authContext._getItem(authContext.CONSTANTS.STORAGE.LOGIN_REQUEST);
}
var user = authContext.getCachedUser();
if (!user) {
  authContext.login();
}
</script>
</code>```

The index.html can still load all the javascript for the angular app, the above code will execute.

Within my angular app I use angular2-jwt which expects the token to be in token so I needed to move the token with the following code :

```<code>localStorage.setItem('token', localStorage.getItem( 'adal.access.token.key' + config.clientId));
</code>```

I added a message in the app AppComponent you can see this in the debug console.

Old way, you can see the re-load..

Pure JavaScript way, as you see, just one app load.

Title: adal angular app reloading - by design?

Body:
You need to use adal.js directly not via the angular application.

In the main index.html add the following code

<script src="https://secure.aadcdn.microsoftonline-p.com/lib/1.0.0/js/adal.min.js"></script>
<script>
window.config = {
  instance: 'https://login.microsoftonline.com/',
  tenant: 'yourtenant.co.uk',
  clientId: '11111111-1111-1111-1111-1111111111',
  postLogoutRedirectUri: window.location.origin,
  cacheLocation: 'localStorage',
};
// Check For & Handle Redirect From AAD After Login
var authContext = new AuthenticationContext(config);
var isCallback = authContext.isCallback(window.location.hash);
authContext.handleWindowCallback();
if (isCallback && !authContext.getLoginError()) {
    window.location = authContext._getItem(authContext.CONSTANTS.STORAGE.LOGIN_REQUEST);
}
var user = authContext.getCachedUser();
if (!user) {
  authContext.login();
}
</script>

The index.html can still load all the javascript for the angular app, the above code will execute.

Within my angular app I use angular2-jwt which expects the token to be in token so I needed to move the token with the following code :

localStorage.setItem('token', localStorage.getItem( 'adal.access.token.key' + config.clientId));

I added a message in the app AppComponent you can see this in the debug console.

Old way, you can see the re-load..

Pure JavaScript way, as you see, just one app load.


问:
.NET Billboard Control
I still can't seem to get this to work.  If anyone else has any ideas I would really appreciate it.  The two websites whose controls I am trying to duplicate is mtv.com and nba.com.  I couldn't get jCarousel or the adrotator to have four images that rotate.  One large image and three small images.  If anyone has any ideas please let me know.

Hello,

Does anyone know where I can find a billboard control?  I'm not sure what it's really called but I'm going to call it a billboard control.  Examples of these are at the three below websites.  Basically what I'm talking about is anywhere from 3 to 5 images or html files that rotate every couple of seconds with a preview of these images/html files to the side or below.  I am looking for something I can use with C# .net.  Any help would be much appreciated.

espn.go.com
mtv.com
nba.com

Thanks

答: ASP.NET WebForms comes with that control. It is called AdRotator.

Title: .NET Billboard Control


问:
Jupyter notebook display two pandas tables side by side
I have two pandas dataframes and I would like to display them in Jupyter notebook.

Doing something like:

```<code>display(df1)
display(df2)
</code>```

Shows them one below another:

I would like to have a second dataframe on the right of the first one. There is a similar question, but it looks like there a person is satisfied either with merging them in one dataframe of showing the difference between them.

This will not work for me. In my case dataframes can represent completely different (non-comparable elements) and the size of them can be different. Thus my main goal is to save space.

答:
I have ended up writing a function that can do this:
[update: added titles based on suggestions (thnx @Antony_Hatchkins et al.)]

```<code>from IPython.display import display_html
from itertools import chain,cycle
def display_side_by_side(*args,titles=cycle([''])):
    html_str=''
    for df,title in zip(args, chain(titles,cycle(['</br>'])) ):
        html_str+='<th style="text-align:center"><td style="vertical-align:top">'
        html_str+=f'<h2 style="text-align: center;">{title}</h2>'
        html_str+=df.to_html().replace('table','table style="display:inline"')
        html_str+='</td></th>'
    display_html(html_str,raw=True)

</code>```

Example usage:

```<code>df1 = pd.DataFrame(np.arange(12).reshape((3,4)),columns=['A','B','C','D',])
df2 = pd.DataFrame(np.arange(16).reshape((4,4)),columns=['A','B','C','D',])
display_side_by_side(df1,df2,df1, titles=['Foo','Foo Bar']) #we left 3rd empty...
</code>```

Body:
I have two pandas dataframes and I would like to display them in Jupyter notebook.

Doing something like:

display(df1)
display(df2)

Shows them one below another:

I would like to have a second dataframe on the right of the first one. There is a similar question, but it looks like there a person is satisfied either with merging them in one dataframe of showing the difference between them.

This will not work for me. In my case dataframes can represent completely different (non-comparable elements) and the size of them can be different. Thus my main goal is to save space.

Body:
I have ended up writing a function that can do this:
[update: added titles based on suggestions (thnx @Antony_Hatchkins et al.)]

from IPython.display import display_html
from itertools import chain,cycle
def display_side_by_side(*args,titles=cycle([''])):
    html_str=''
    for df,title in zip(args, chain(titles,cycle(['</br>'])) ):
        html_str+='<th style="text-align:center"><td style="vertical-align:top">'
        html_str+=f'<h2 style="text-align: center;">{title}</h2>'
        html_str+=df.to_html().replace('table','table style="display:inline"')
        html_str+='</td></th>'
    display_html(html_str,raw=True)

Example usage:

df1 = pd.DataFrame(np.arange(12).reshape((3,4)),columns=['A','B','C','D',])
df2 = pd.DataFrame(np.arange(16).reshape((4,4)),columns=['A','B','C','D',])
display_side_by_side(df1,df2,df1, titles=['Foo','Foo Bar']) #we left 3rd empty...

ContentLicense: CC BY-SA 4.0


问:
PHP: Pull all images from a specified directory using relative image path
I am trying to create a gallery where images are automatically pulled from a images directory.

When I foreach() each image it returns however it pulls the entire root path as the image src

/home/dev/public_html/assets/images/

this causes the images not to show and shows dead linked images on screen. I need the relative path like this:

/assets/images/imagename.jpg

How would I set a base path/URL?

```<code>$dirname = "/home/dev/public_html/assets/images/";

$images = glob($dirname."*.jpg");

foreach($images as $image) {
    echo '<img src="'.$image.'" /><br />';
}
</code>```

I tried setting $dirname to this

```<code>$dirname = "/assets/images/";
</code>```

But I get no result and nothing pulls through at all.

The file i am creating this in, is located outside the public_html folder, i believe this could be casing the issue but the file cannot be relocated.

答:
You could may make use of scandir() http://php.net/manual/en/function.scandir.php

Somethink like:

Edit: Changed the code a bit, so scandir only take files, otherwise the first two placed in the array are folders for the parent folders.

```<code>$dir = "assets/images/";
$images = scandir($dir);

foreach($images as $image) {
     if($image != '.' && $image != '..') {
          echo ' <img src="assets/images/'.$image.'"><br>';
     }
}
</code>```

Hope this helped. If not, let me know, so I can change my answer. But I think it should be fine, as far as I understood what you're trying.

Body:
I am trying to create a gallery where images are automatically pulled from a images directory.

When I foreach() each image it returns however it pulls the entire root path as the image src

/home/dev/public_html/assets/images/

this causes the images not to show and shows dead linked images on screen. I need the relative path like this:

/assets/images/imagename.jpg

How would I set a base path/URL?

$dirname = "/home/dev/public_html/assets/images/";

$images = glob($dirname."*.jpg");

foreach($images as $image) {
    echo '
';
}

I tried setting $dirname to this

$dirname = "/assets/images/";

But I get no result and nothing pulls through at all.

The file i am creating this in, is located outside the public_html folder, i believe this could be casing the issue but the file cannot be relocated.

Body:
You could may make use of scandir() http://php.net/manual/en/function.scandir.php

Somethink like:

Edit: Changed the code a bit, so scandir only take files, otherwise the first two placed in the array are folders for the parent folders.

$dir = "assets/images/";
$images = scandir($dir);

foreach($images as $image) {
     if($image != '.' && $image != '..') {
          echo ' <img src="assets/images/'.$image.'"><br>';
     }
}

Hope this helped. If not, let me know, so I can change my answer. But I think it should be fine, as far as I understood what you're trying.


问:
A persist insert all data from OneToMany ArrayCollection variable
I have a bug when I try to persist a data, and I did not found help about someone having exactly the same problem....

I have two linked entities score(ManyToOne)/player(OneToMany) and when I persist the score, doctrine insert all the scores stored in the array collection $scores of the player corresponding to the score I want to store.
For information, I store each score of a round, so an user have more than one score (so the manyToOne/OneToMany relation).

I have a list of players with all their scores. I only want to insert the last one, like the others are already in the db. But for each solutions I tried, doctrine insert all the scores... even if I only put the last score in the player score.
Then, I delete the persist cascade on each entities, doctrine throw an exception about a link on entities...

Here is the Score entity

```<code>/**
 * Score
 *
 * @ORM\Table(name="score")
 * @ORM\Entity(repositoryClass="AppBundle\Entity\Repository\ScoreRepository")
 */
class Score
{
/**
 * @var int
 *
 * @ORM\Column(name="id", type="integer")
 * @ORM\Id
 * @ORM\GeneratedValue(strategy="AUTO")
 */
protected $id;

/**
 * @ORM\ManyToOne(targetEntity="AppBundle\Entity\Player", inversedBy="scores", cascade={"persist"})
 * @ORM\JoinColumn(name="player", referencedColumnName="id")
 *
 * @var Player
 */
private $player;

/**
 * @var DateTime
 *
 * @ORM\Column(name="played_at", type="datetime")
 */
private $playedAt;

/**
 * @var int
 *
 * @ORM\Column(name="value", type="integer")
 */
private $value;
</code>```

Here is the Player entity :

```<code>/**
 * Player
 *
 * @ORM\Table(name="player")
 * @ORM\Entity(repositoryClass="AppBundle\Entity\Repository\PlayerRepository")
 */
class Player extends BaseUser
{
/**
 * @var int
 *
 * @ORM\Column(name="id", type="integer")
 * @ORM\Id
 * @ORM\GeneratedValue(strategy="AUTO")
 */
protected $id;

/**
 * @var string
 *
 * @ORM\Column(name="firstname", type="string", length=255)
 */
private $firstname;

/**
 * @var string
 *
 * @ORM\Column(name="lastname", type="string", length=255)
 */
private $lastname;

/**
 * @var string
 *
 * @ORM\Column(name="job", type="string", length=255)
 */
private $job;

 /**
 * @ORM\OneToMany(targetEntity="AppBundle\Entity\Score", mappedBy="player", cascade={"persist"})
 *
 * @var ArrayCollection|Score[]
 */
private $scores;
</code>```

Here is now, my controller where I want to persist the score

```<code>$content = $request->getContent();
    $scoresParams = [];
    if (!empty($content))
    {
        $scoresParams = json_decode($content, true); // 2nd param to get as array
    }
    $players = array();

    $transformer = $this->get('app.transformer.score');
    foreach($scoresParams as $k=>$v) {
        $players[] = $transformer->reverseTransform($v);
    }
    foreach($players as $k=>$p) {
        $index = count($p->getScores()) - 1;
        $s = $p->getScores()[$index];
        $p->setScores(array($s));
        $this->get('app.repository.score')->persist($s);
    }
</code>```

I setted the player score with just the score I want to save... Because, like i have a persist on cascad, and all the others scores of the users are not retrieve from doctrine, hit will try to insert them...
So, for the first player, ok, but for the second, $s has already an ID when i persist it, and it persist all the data of the player (not only the last one).

The transformer is a bundle (League\Fractal\Transformer) which creates an array of players from a array of data

```<code>public function reverseTransform(array $data)
{
    $this->checkRequiredFields($data);

    $player = $this->playerRepository->find($data[self::KEY_ID]);

    if (!$player) {
        throw new NotFoundException('User not found');
    }

    $scoresRaw = $data[self::KEY_ENC_SCORES];
    $scores = array();

    foreach($scoresRaw as $k => $s) {
        $score = new Score($player);
        if($s[self::KEY_ENC_SCORE_ID] != 0) {
            $score->setId($s[self::KEY_ENC_SCORE_ID]);
        }
        $score->setPlayedAt( ( new \DateTime() )->setTimestamp( $s[self::KEY_ENC_SCORE_DATE] ) );
        $score->setValue($s[self::KEY_ENC_SCORE_VALUE]);
        $scores[] = $score;
    }

    $player->setScores($scores);

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

Can you see what's wrong here ?

Here is the solution
-> controller

```<code>        $content = $request->getContent();
    $scoresParams = [];
    if (!empty($content))
    {
        $scoresParams = json_decode($content, true); // 2nd param to get as array
    }
    $players = array();

    $transformer = $this->get('app.transformer.score');
    // For each players
    foreach($scoresParams as $i=>$player) {
        $scores = $player['scores'];
        foreach($scores as $j=>$s) {
            $score = $transformer->reverseTransform($s['data']);
            $this->get('app.repository.score')->merge($score);
        }
    }

    $response = new JsonResponse(array('data' => ''));
    $response->setStatusCode(201);

    return $response;
</code>```

And the function that reverse the score array to an object

```<code>    $player = $this->playerRepository->find($data[self::KEY_USER]);

    if (!$player) {
        throw new NotFoundException('User not found');
    }

    $score = new Score($player);
    if($data[self::KEY_ID] != 0) {
        $score->setId($data[self::KEY_ID]);
    }
    $score->setPlayedAt( ( new \DateTime() )->setTimestamp( $data[self::KEY_DATE] ) );
    $score->setValue($data[self::KEY_VALUE]);

    return $score;
</code>```

答:
As your entity comes from a json, it is not linked to the entity manager.

I think you should use merge() method to link it.

http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/reference/working-with-objects.html#merging-entities

```<code>    $score->setValue($s[self::KEY_ENC_SCORE_VALUE]);
    $this->get('app.repository.score')->merge($score);
    $scores[] = $score;
}
$player->setScores($scores);
</code>```

Body:
I have a bug when I try to persist a data, and I did not found help about someone having exactly the same problem....

I have two linked entities score(ManyToOne)/player(OneToMany) and when I persist the score, doctrine insert all the scores stored in the array collection $scores of the player corresponding to the score I want to store.
For information, I store each score of a round, so an user have more than one score (so the manyToOne/OneToMany relation).

I have a list of players with all their scores. I only want to insert the last one, like the others are already in the db. But for each solutions I tried, doctrine insert all the scores... even if I only put the last score in the player score.
Then, I delete the persist cascade on each entities, doctrine throw an exception about a link on entities...

Here is the Score entity

/**
 * Score
 *
 * @ORM\Table(name="score")
 * @ORM\Entity(repositoryClass="AppBundle\Entity\Repository\ScoreRepository")
 */
class Score
{
/**
 * @var int
 *
 * @ORM\Column(name="id", type="integer")
 * @ORM\Id
 * @ORM\GeneratedValue(strategy="AUTO")
 */
protected $id;

/**
 * @ORM\ManyToOne(targetEntity="AppBundle\Entity\Player", inversedBy="scores", cascade={"persist"})
 * @ORM\JoinColumn(name="player", referencedColumnName="id")
 *
 * @var Player
 */
private $player;

/**
 * @var DateTime
 *
 * @ORM\Column(name="played_at", type="datetime")
 */
private $playedAt;

/**
 * @var int
 *
 * @ORM\Column(name="value", type="integer")
 */
private $value;

Here is the Player entity :

/**
 * Player
 *
 * @ORM\Table(name="player")
 * @ORM\Entity(repositoryClass="AppBundle\Entity\Repository\PlayerRepository")
 */
class Player extends BaseUser
{
/**
 * @var int
 *
 * @ORM\Column(name="id", type="integer")
 * @ORM\Id
 * @ORM\GeneratedValue(strategy="AUTO")
 */
protected $id;

/**
 * @var string
 *
 * @ORM\Column(name="firstname", type="string", length=255)
 */
private $firstname;

/**
 * @var string
 *
 * @ORM\Column(name="lastname", type="string", length=255)
 */
private $lastname;

/**
 * @var string
 *
 * @ORM\Column(name="job", type="string", length=255)
 */
private $job;

 /**
 * @ORM\OneToMany(targetEntity="AppBundle\Entity\Score", mappedBy="player", cascade={"persist"})
 *
 * @var ArrayCollection|Score[]
 */
private $scores;

Here is now, my controller where I want to persist the score

$content = $request->getContent();
    $scoresParams = [];
    if (!empty($content))
    {
        $scoresParams = json_decode($content, true); // 2nd param to get as array
    }
    $players = array();

    $transformer = $this->get('app.transformer.score');
    foreach($scoresParams as $k=>$v) {
        $players[] = $transformer->reverseTransform($v);
    }
    foreach($players as $k=>$p) {
        $index = count($p->getScores()) - 1;
        $s = $p->getScores()[$index];
        $p->setScores(array($s));
        $this->get('app.repository.score')->persist($s);
    }

I setted the player score with just the score I want to save... Because, like i have a persist on cascad, and all the others scores of the users are not retrieve from doctrine, hit will try to insert them...
So, for the first player, ok, but for the second, $s has already an ID when i persist it, and it persist all the data of the player (not only the last one).

The transformer is a bundle (League\Fractal\Transformer) which creates an array of players from a array of data

public function reverseTransform(array $data)
{
    $this->checkRequiredFields($data);

    $player = $this->playerRepository->find($data[self::KEY_ID]);

    if (!$player) {
        throw new NotFoundException('User not found');
    }

    $scoresRaw = $data[self::KEY_ENC_SCORES];
    $scores = array();

    foreach($scoresRaw as $k => $s) {
        $score = new Score($player);
        if($s[self::KEY_ENC_SCORE_ID] != 0) {
            $score->setId($s[self::KEY_ENC_SCORE_ID]);
        }
        $score->setPlayedAt( ( new \DateTime() )->setTimestamp( $s[self::KEY_ENC_SCORE_DATE] ) );
        $score->setValue($s[self::KEY_ENC_SCORE_VALUE]);
        $scores[] = $score;
    }

    $player->setScores($scores);

    return $player;
}

Can you see what's wrong here ?

Here is the solution
-> controller

        $content = $request->getContent();
    $scoresParams = [];
    if (!empty($content))
    {
        $scoresParams = json_decode($content, true); // 2nd param to get as array
    }
    $players = array();

    $transformer = $this->get('app.transformer.score');
    // For each players
    foreach($scoresParams as $i=>$player) {
        $scores = $player['scores'];
        foreach($scores as $j=>$s) {
            $score = $transformer->reverseTransform($s['data']);
            $this->get('app.repository.score')->merge($score);
        }
    }

    $response = new JsonResponse(array('data' => ''));
    $response->setStatusCode(201);

    return $response;

And the function that reverse the score array to an object

    $player = $this->playerRepository->find($data[self::KEY_USER]);

    if (!$player) {
        throw new NotFoundException('User not found');
    }

    $score = new Score($player);
    if($data[self::KEY_ID] != 0) {
        $score->setId($data[self::KEY_ID]);
    }
    $score->setPlayedAt( ( new \DateTime() )->setTimestamp( $data[self::KEY_DATE] ) );
    $score->setValue($data[self::KEY_VALUE]);

    return $score;

Body:
As your entity comes from a json, it is not linked to the entity manager.

I think you should use merge() method to link it.

http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/reference/working-with-objects.html#merging-entities

    $score->setValue($s[self::KEY_ENC_SCORE_VALUE]);
    $this->get('app.repository.score')->merge($score);
    $scores[] = $score;
}
$player->setScores($scores);


答:
You can access it through this:</p>

```<code>if($(".trip-summary-info").find('h3').find('.distance').length > 0){
   alert('working!!').
}
</code>```

Body:
You can access it through this:

if($(".trip-summary-info").find('h3').find('.distance').length > 0){
   alert('working!!').
}


问:
3 Unicode Vulgar fractions - 1/7, 1/9 and 1/10 became box
Unicode provides us the code for printing few pre-defined vulgar fractions. When using the corresponding code for HTML, for 3 fractions they become box. They are 1/7, 1/9 and 1/10 [see attached screen shot]. This is seen on the sites also who are providing this code themselves. like: http://unicodefractions.com/

Can anyone help me out how to print them successfully on the web page?

答:
These three characters:

VULGAR FRACTION ONE SEVENTH (U+2150)

VULGAR FRACTION ONE NINTH (U+2151)

VULGAR FRACTION ONE TENTH (U+2152)

...have been introduced in Unicode version 5.2 (2009). This differentiates them from most other "vulgar fractions", which have been introduced in Unicode version 1.1 (1993).

In my browser, these characters in your link display correctly. So, I guess that your browser does not yet support Unicode version 5.2, and thus doesn't know the Unicode code points belonging to these characters.

I would suggest to update/reinstall your browser, or try with a different browser that supports Unicode version 5.2 and higher.

OwnerDisplayName: Plymouth Rock


答:
Are you looking for the .NET AdRotator control ? That supports the most basic use cases, and it shouldn't be too much hassle to extend it and add functionality if needed. It is the closest to what you need, that is built into the framework.

Another solution would be to use the jCarousel with jQuery. Depending on your specific needs, it could be a better choice.

Title: .NET Billboard Control

Body:
I still can't seem to get this to work.  If anyone else has any ideas I would really appreciate it.  The two websites whose controls I am trying to duplicate is mtv.com and nba.com.  I couldn't get jCarousel or the adrotator to have four images that rotate.  One large image and three small images.  If anyone has any ideas please let me know.

Hello,

Does anyone know where I can find a billboard control?  I'm not sure what it's really called but I'm going to call it a billboard control.  Examples of these are at the three below websites.  Basically what I'm talking about is anywhere from 3 to 5 images or html files that rotate every couple of seconds with a preview of these images/html files to the side or below.  I am looking for something I can use with C# .net.  Any help would be much appreciated.

espn.go.com
mtv.com
nba.com

Thanks