问:
Javascript dom manipulation by data object
I have HTML like this

```<code><div class="fruits">[ Banana Apple Orange Melon Papaya ][ Avocado Coconut Strawberry ]</div>
</code>```

I want to convert it become like this

```<code><div class="fruits">
<p id="pid_0" data-show="wid_0">
    <span id="wid_0" data-price="100" data-code="1">Banana</span>
    <span id="wid_1" data-price="200" data-code="2">Apple</span>
    <span id="wid_2" data-price="300" data-code="3">Orange</span>
    <span id="wid_3" data-price="400" data-code="4">Melon</span>
    <span id="wid_4" data-price="500" data-code="5">Papaya</span>
</p>
<p id="pid_5" data-show="wid_5">
    <span id="wid_5" data-price="600" data-code="6">Avocado</span>
    <span id="wid_6" data-price="700" data-code="7">Coconut</span>
    <span id="wid_7" data-price="800" data-code="8">Strawberry</span>
</p>
</code>```

This is how I got so far

```<code><script>
var price_arr = [100, 200, 300, 400, 500, 600, 700, 800];
var code_arr = [1, 2, 3, 4, 5, 6, 7, 8];

$(".fruits").each(function() {
    $(this).text($(this).text().replace(/\w+/g, "<span>$&</span>"));
    $(this).text($(this).text().replace(/\[/g, "<p> "));
    $(this).text($(this).text().replace(/\]/g, "</p>"));
});

var str = $(".fruits").text();
var words = str.split(" ");
var result = [];
var obj = {};

for (var i = 0; i < words.length - 1; i++) {
    // words
    words[i] += " ";

    var w = "wid_"+i;
    var p = "pid_"+i;

    var price = price_arr[i];
    var code = code_arr[i];
    var name = words[i] += " ";

    obj = {get_price:price, get_code:code, display:name};
    result.push(obj);
}
</script>
</code>```

I'm want to use data object(obj) and store it to each html attribute, but I'm getting stuck. Anyone please help me, I will be highly appreciate.

答:
You can parse the .textContent of .fruits element to create an array using .replace(), JSON.parse(); use $.map() to create html from array elements, set .innerHTML of .fruits using .html().

Increment variables storing 0, 0, 1, 0 for id of p elements, id of span elements, "code" and "price" data-* attributes set with data at jQuery(html, attributes)

var fruit = $(".fruits");
var data = fruit.text()
           .replace(/(\w+)/g, "\"$1\",")
           .replace(/,(?=\s])/g, "")
           .replace(/\]\[/, "],[");
var id = 0;
var s = 0;
var w = 1;
var n = 0;

var html = $.map(JSON.parse("[" + data + "]"), function(el) {
  var p = $("
", {
            id: "pid_" + id,
            html: $.map(el, function(_fruit) {
                    return $("", {
                             id:"wid_"+ (s++),
                             text: _fruit + "\n"
                           })
                           .attr({
                             "data-price": (n += 100),
                             "data-code": w++
                           })
          })
  }).attr("data-show", "wid_" + id);

  id += 5;
  return p;
});

fruit.html(html);```
<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="fruits">[ Banana Apple Orange Melon Papaya ][ Avocado Coconut Strawberry ]</div></code>```

Body:
I have HTML like this

[ Banana Apple Orange Melon Papaya ][ Avocado Coconut Strawberry ]

I want to convert it become like this

    Banana
    Apple
    Orange
    Melon
    Papaya

    Avocado
    Coconut
    Strawberry

This is how I got so far

I'm want to use data object(obj) and store it to each html attribute, but I'm getting stuck. Anyone please help me, I will be highly appreciate.

Body:
You can parse the .textContent of .fruits element to create an array using .replace(), JSON.parse(); use $.map() to create html from array elements, set .innerHTML of .fruits using .html().

Increment variables storing 0, 0, 1, 0 for id of p elements, id of span elements, "code" and "price" data-* attributes set with data at jQuery(html, attributes)

var fruit = $(".fruits");
var data = fruit.text()
           .replace(/(\w+)/g, "\"$1\",")
           .replace(/,(?=\s])/g, "")
           .replace(/\]\[/, "],[");
var id = 0;
var s = 0;
var w = 1;
var n = 0;

var html = $.map(JSON.parse("[" + data + "]"), function(el) {
  var p = $("<p>", {
            id: "pid_" + id,
            html: $.map(el, function(_fruit) {
                    return $("<span>", {
                             id:"wid_"+ (s++),
                             text: _fruit + "\n"
                           })
                           .attr({
                             "data-price": (n += 100),
                             "data-code": w++
                           })
          })
  }).attr("data-show", "wid_" + id);

  id += 5;
  return p;
});

fruit.html(html);

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="fruits">[ Banana Apple Orange Melon Papaya ][ Avocado Coconut Strawberry ]</div>


来源: stackexchange

问:
Get current number of partitions of a DataFrame
Is there any way to get the current number of partitions of a DataFrame?
I checked the DataFrame javadoc (spark 1.6) and didn't found a method for that, or am I just missed it?
(In case of JavaRDD there's a getNumPartitions() method.) </p>

答:
convert to RDD then get the partitions length</p>

```<code>DF.rdd.partitions.length
</code>```

ContentLicense: CC BY-SA 3.0

Body:
convert to RDD then get the partitions length

DF.rdd.partitions.length


问:
Visual Studio Code push automatically
Is it possible to make git push after commit automatically?
Now I need to click on push after commit manually and this is not very comfortable.</p>

答:
There doesn't seem to be something like that built-in to VSCode's Git front-end, but there is an option to remove the safety check.  "git.confirmSync": false will remove the confirmation dialog when using VSCode's built-in Push/remote sync.

@Mistermatt's link looks like what you asked for though, I've had too many problems with blindly pushing myself :).

Title: Visual Studio Code push automatically


问:
How to add a space between images in a CSS image slideshow?
EDIT:

Good progress... By updating the following code, I almost get exactly what I want to achieve, but I don't understand exactly why it almost works. Spacing both sides during transition, spacing hidden after transition, but with a slight amount of clipping of image: https://codepen.io/anon/pen/LWqPJB

```<code>body {
     margin: -6%;
}
div#slider {
     overflow: hidden;
}
div#slider figure img {
     width: 18%;
     float: left;
     padding-left: 1%;
     padding-right: 1%;
}
</code>```

Although, it's not a perfect solution, the second alternative that seems to do the job is:

```<code>div#slider {
    margin-left: -6%;
    margin-right: -6%;
    overflow: hidden;
}
div#slider figure img {
    width: 18%;
    margin-left: 1%;
    margin-right: 1%;
    float: left;
}
</code>```

Problem

I'm implementing a simple image slideshow in a webpage using only HTML and CSS. The code I am starting with is below and at https://codepen.io/anon/pen/wJRVwP

Currently each slide follows the next with no space between images (image 1). However, I'm trying to add a 100px space between each image that is only visible during the transition. So attempting to add a gap, I change the CSS code below;

from:

```<code>div#slider figure img { width: 20%; float: left;}
</code>```

(demo 1: https://codepen.io/anon/pen/wJRVwP)

to:

```<code>div#slider figure img { width: 20%; float: left; padding-left: 100px;}
</code>```

(demo 2: https://codepen.io/anon/pen/vxvoNy)

The result of changing the code adds a 100px space between all images, but, the code change introduces a new problem — images no longer align and progressively get worse after each slide change (image 2).

Question

How can I achieve a space between images and fix this? In code, how
  can I change the CSS code to add a 100px space between each image, and keep
  all images aligned during and after transition?

Images

demo 1 during transition.

demo 1 after transition.

required outcome.

Code

https://codepen.io/anon/pen/wJRVwP

@keyframes slidy {
  0% {
    left: 0%;
  }
  20% {
    left: 0%;
  }
  25% {
    left: -100%;
  }
  45% {
    left: -100%;
  }
  50% {
    left: -200%;
  }
  70% {
    left: -200%;
  }
  75% {
    left: -300%;
  }
  95% {
    left: -300%;
  }
  100% {
    left: -400%;
  }
}

body {
  margin: 0;
}

div#slider {
  overflow: hidden;
}

div#slider figure img {
  width: 20%;
  float: left;
}

div#slider figure {
  position: relative;
  width: 500%;
  margin: 0;
  left: 0;
  text-align: left;
  font-size: 0;
  animation: 20s slidy infinite;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><base href="https://s3-us-west-2.amazonaws.com/s.cdpn.io/4273/">
<div id="slider">
  <figure>
    <img src="austin-fireworks.jpg" alt>
    <img src="taj-mahal_copy.jpg" alt>
    <img src="austin-fireworks.jpg" alt>
    <img src="ankor-wat.jpg" alt>
    <img src="austin-fireworks.jpg" alt>
  </figure>
</div></code>```

答:
apply a box-sizing:border-box property to all img. Add padding left and right (it look somewhat odd if you don't pad both sides).

These are the css adjustments

```<code>div#slider figure img {
    width: 20%;
    float: left;
    padding-right: 50px;
    padding-left: 50px;
    box-sizing:border-box
}
</code>```

Snippet below

@keyframes slidy {
  0% {
    left: 0%;
  }
  20% {
    left: 0%;
  }
  25% {
    left: -100%;
  }
  45% {
    left: -100%;
  }
  50% {
    left: -200%;
  }
  70% {
    left: -200%;
  }
  75% {
    left: -300%;
  }
  95% {
    left: -300%;
  }
  100% {
    left: -400%;
  }
}

body {
  margin: 0;
}

div#slider {
  overflow: hidden;
}

div#slider figure img {
  width: 20%;
  float: left;
  padding-right: 50px;
  padding-left: 50px;
  box-sizing: border-box
}

div#slider figure {
  position: relative;
  width: 500%;
  margin: 0;
  left: 0;
  text-align: left;
  font-size: 0;
  animation: 20s slidy infinite;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><base href="https://s3-us-west-2.amazonaws.com/s.cdpn.io/4273/">
<div id="slider">
  <figure>
    <img src="austin-fireworks.jpg" alt>
    <img src="taj-mahal_copy.jpg" alt>
    <img src="austin-fireworks.jpg" alt>
    <img src="ankor-wat.jpg" alt>
    <img src="austin-fireworks.jpg" alt>
  </figure>
</div></code>```

Body:
EDIT:

Good progress... By updating the following code, I almost get exactly what I want to achieve, but I don't understand exactly why it almost works. Spacing both sides during transition, spacing hidden after transition, but with a slight amount of clipping of image: https://codepen.io/anon/pen/LWqPJB

body {
     margin: -6%;
}
div#slider {
     overflow: hidden;
}
div#slider figure img {
     width: 18%;
     float: left;
     padding-left: 1%;
     padding-right: 1%;
}

Although, it's not a perfect solution, the second alternative that seems to do the job is:

div#slider {
    margin-left: -6%;
    margin-right: -6%;
    overflow: hidden;
}
div#slider figure img {
    width: 18%;
    margin-left: 1%;
    margin-right: 1%;
    float: left;
}

Problem

I'm implementing a simple image slideshow in a webpage using only HTML and CSS. The code I am starting with is below and at https://codepen.io/anon/pen/wJRVwP

Currently each slide follows the next with no space between images (image 1). However, I'm trying to add a 100px space between each image that is only visible during the transition. So attempting to add a gap, I change the CSS code below;

from:

div#slider figure img { width: 20%; float: left;}

(demo 1: https://codepen.io/anon/pen/wJRVwP)

to:

div#slider figure img { width: 20%; float: left; padding-left: 100px;}

(demo 2: https://codepen.io/anon/pen/vxvoNy)

The result of changing the code adds a 100px space between all images, but, the code change introduces a new problem — images no longer align and progressively get worse after each slide change (image 2).

Question

How can I achieve a space between images and fix this? In code, how
  can I change the CSS code to add a 100px space between each image, and keep
  all images aligned during and after transition?

Images

demo 1 during transition.

demo 1 after transition.

required outcome.

Code

https://codepen.io/anon/pen/wJRVwP

@keyframes slidy {
  0% {
    left: 0%;
  }
  20% {
    left: 0%;
  }
  25% {
    left: -100%;
  }
  45% {
    left: -100%;
  }
  50% {
    left: -200%;
  }
  70% {
    left: -200%;
  }
  75% {
    left: -300%;
  }
  95% {
    left: -300%;
  }
  100% {
    left: -400%;
  }
}

body {
  margin: 0;
}

div#slider {
  overflow: hidden;
}

div#slider figure img {
  width: 20%;
  float: left;
}

div#slider figure {
  position: relative;
  width: 500%;
  margin: 0;
  left: 0;
  text-align: left;
  font-size: 0;
  animation: 20s slidy infinite;
}

<base href="https://s3-us-west-2.amazonaws.com/s.cdpn.io/4273/">

Body:
apply a box-sizing:border-box property to all img. Add padding left and right (it look somewhat odd if you don't pad both sides).

These are the css adjustments

div#slider figure img {
    width: 20%;
    float: left;
    padding-right: 50px;
    padding-left: 50px;
    box-sizing:border-box
}

Snippet below

@keyframes slidy {
  0% {
    left: 0%;
  }
  20% {
    left: 0%;
  }
  25% {
    left: -100%;
  }
  45% {
    left: -100%;
  }
  50% {
    left: -200%;
  }
  70% {
    left: -200%;
  }
  75% {
    left: -300%;
  }
  95% {
    left: -300%;
  }
  100% {
    left: -400%;
  }
}

body {
  margin: 0;
}

div#slider {
  overflow: hidden;
}

div#slider figure img {
  width: 20%;
  float: left;
  padding-right: 50px;
  padding-left: 50px;
  box-sizing: border-box
}

div#slider figure {
  position: relative;
  width: 500%;
  margin: 0;
  left: 0;
  text-align: left;
  font-size: 0;
  animation: 20s slidy infinite;
}

<base href="https://s3-us-west-2.amazonaws.com/s.cdpn.io/4273/">
<div id="slider">
  <figure>
    <img src="austin-fireworks.jpg" alt>
    <img src="taj-mahal_copy.jpg" alt>
    <img src="austin-fireworks.jpg" alt>
    <img src="ankor-wat.jpg" alt>
    <img src="austin-fireworks.jpg" alt>
  </figure>
</div>


问:
Image not inserting in folder using PHP and MYSQL

Iam trying to insert image in folder using php and mysql but the image is not storing in folder as well as in database
  This is my PHP Code

```<code> if(isset($name)) {
$pass = base64_encode($pass);
$cpass = base64_encode($cpass);
$image_name = $_FILES['image']['name'];
$image_temp = $_FILES['image']['tmp_name'];
$image_type = $_FILES['image']['type'];
if ($image_type == 'image/png' || $image_type == 'image/jpg' || $image_type == 'image/iso' || $image_type = 'image/gif') {
    $upload = move_uploaded_file('uploads1/' . $_FILES['image']['name']);
      if($upload) {
          $reg_query = mysqli_query($conn, "INSERT INTO `quiz_register`(`name`, `email`, `mobile`, `password`, `cpassword`, `image`) VALUES ('$name','$mail','$cell','$pass','$cpass','$image_name')");
          if ($reg_query) {
              echo 'success';
          } else {
              echo 'fail';
          }
      }
  }
}
</code>```

This is my HTML code

```<code>      <form method="post" action="" enctype="multipart/form-data">
      <input type="text" name="name" placeholder="name" class="form-control" id="name"> <br>
      <input type="email" name="mail" placeholder="mailid@domain" class="form-control" id="mail"> <br>
      <input type="text" name="mobile" placeholder="Mobile" class="form-control" id="mobile"> <br>
      <input type="password" name="password" placeholder="password" class="form-control" id="password"> <br>
      <input type="password" name="cpassword" placeholder="confirm-password" class="form-control" id="cpassword"> <br>
      <input type="file" name="image" id="file" class="form-control" required> <br>
 </form>
</code>```

答:
I have recently done this. here is what i used and it worked like a charm</p>

```<code>$binary=base64_decode($file);
$file = fopen('../newSite/profileImages/'.$filename, 'wb');
// Create File
$is_written = fwrite($file, $binary);
fclose($file);

if($is_written > 0) {

    $connection = mysqli_connect('localhost', 'username', 'pass','db name');

            $query = "UPDATE users SET image = '$filename' WHERE id = '$user_id';";

    $result = mysqli_query($connection, $query) ;

    if($result){
        echo "success";
    }else{
        echo "failed";
    }

    mysqli_close($connection);
}
</code>```

Body:
Iam trying to insert image in folder using php and mysql but the image is not storing in folder as well as in database
  This is my PHP Code

 if(isset($name)) {
$pass = base64_encode($pass);
$cpass = base64_encode($cpass);
$image_name = $_FILES['image']['name'];
$image_temp = $_FILES['image']['tmp_name'];
$image_type = $_FILES['image']['type'];
if ($image_type == 'image/png' || $image_type == 'image/jpg' || $image_type == 'image/iso' || $image_type = 'image/gif') {
    $upload = move_uploaded_file('uploads1/' . $_FILES['image']['name']);
      if($upload) {
          $reg_query = mysqli_query($conn, "INSERT INTO `quiz_register`(`name`, `email`, `mobile`, `password`, `cpassword`, `image`) VALUES ('$name','$mail','$cell','$pass','$cpass','$image_name')");
          if ($reg_query) {
              echo 'success';
          } else {
              echo 'fail';
          }
      }
  }
}

This is my HTML code

      <form method="post" action="" enctype="multipart/form-data">
      <input type="text" name="name" placeholder="name" class="form-control" id="name">

      <input type="email" name="mail" placeholder="mailid@domain" class="form-control" id="mail">

      <input type="text" name="mobile" placeholder="Mobile" class="form-control" id="mobile">

      <input type="password" name="password" placeholder="password" class="form-control" id="password">

      <input type="password" name="cpassword" placeholder="confirm-password" class="form-control" id="cpassword">

      <input type="file" name="image" id="file" class="form-control" required>

 </form>

Body:
I have recently done this. here is what i used and it worked like a charm

$binary=base64_decode($file);
$file = fopen('../newSite/profileImages/'.$filename, 'wb');
// Create File
$is_written = fwrite($file, $binary);
fclose($file);

if($is_written > 0) {

    $connection = mysqli_connect('localhost', 'username', 'pass','db name');

            $query = "UPDATE users SET image = '$filename' WHERE id = '$user_id';";

    $result = mysqli_query($connection, $query) ;

    if($result){
        echo "success";
    }else{
        echo "failed";
    }

    mysqli_close($connection);
}


问:
Find volume defined by irregular data points - python
I am trying to find the volume given a set of data points (x,y,z) using python. These data points are samples collected from an experiment (so the plotted surface can be quite irregular). I have worked out how to create a 3D plot but not how to calculate the volume using python.

```<code>X, Y = np.meshgrid(x, y)
Z = griddata(xpts, ypts, zpts, x, y)
fig = plt.figure()
ax = fig.gca(projection='3d')
surf = ax.plot_surface(X, Y, Z,
                       rstride=5,
                       cstride=5,
                       cmap=cm.jet,
                       linewidth=0,
                       antialiased=True,
                       vmin=np.nanmin(Z),
                       vmax = np.nanmax(Z))
</code>```

Here's a similar question to find the area under an irregular surface using python,  Volume under "plane" defined by data points - python. Could this be adapted to find the volume?
Any help is appreciated.
Thanks.

答:
I would be lazy and use ConvexHull like a black box:

```<code>import scipy.spatial as ss
import numpy as np
npoints = 6
ndimensions = 3
points = np.random.rand(npoints, ndimensions)
hull = ss.ConvexHull(points)
print('volume inside points is: ',hull.volume)
</code>```

though this is probably not CPU-optimized since ConvexHull computes a bunch of things.

Hope this helps.

Body:
I am trying to find the volume given a set of data points (x,y,z) using python. These data points are samples collected from an experiment (so the plotted surface can be quite irregular). I have worked out how to create a 3D plot but not how to calculate the volume using python.

X, Y = np.meshgrid(x, y)
Z = griddata(xpts, ypts, zpts, x, y)
fig = plt.figure()
ax = fig.gca(projection='3d')
surf = ax.plot_surface(X, Y, Z,
                       rstride=5,
                       cstride=5,
                       cmap=cm.jet,
                       linewidth=0,
                       antialiased=True,
                       vmin=np.nanmin(Z),
                       vmax = np.nanmax(Z))

Here's a similar question to find the area under an irregular surface using python,  Volume under "plane" defined by data points - python. Could this be adapted to find the volume?
Any help is appreciated.
Thanks.

Body:
I would be lazy and use ConvexHull like a black box:

import scipy.spatial as ss
import numpy as np
npoints = 6
ndimensions = 3
points = np.random.rand(npoints, ndimensions)
hull = ss.ConvexHull(points)
print('volume inside points is: ',hull.volume)

though this is probably not CPU-optimized since ConvexHull computes a bunch of things.

Hope this helps.


问:
What attribute shows that a native app element is disabled?
I have a button that, when disabled, has a disabled attribute on web. However, when I view that same button on iOS or Android native, not only does it not have a disabled attribute, but it has an enabled attribute marked as true. Why don't native elements have the disabled attribute, or why do they always have an enabled one that is true?

答:
Try the below code

```<code>driver.findElement("your locator").isEnabled();
</code>```

This will return true if element is enabled otherwise false.

Body:
Try the below code

driver.findElement("your locator").isEnabled();

This will return true if element is enabled otherwise false.


问:
GridView Template Binding (C# UWP)
I was getting trough the questions about binding but so far didn't find solution to my problem ( that might be stupid one, but I'm really new to the UWP thing ).
I'm trying to add "projects" that my application makes, inside GridView object, so I made template for it:

```<code><GridView x:Name="GV_Seznam_Projektov" Grid.Column="2" Margin="0,10,0,0" Grid.Row="2">
        <GridView.ItemTemplate>
            <DataTemplate x:DataType="x:String">
                <Grid Background="#19162D50" HorizontalAlignment="Left" Width="200" Height="300" VerticalAlignment="Top">
                    <Rectangle Fill="{StaticResource cl_main_back}" HorizontalAlignment="Left" Height="40" VerticalAlignment="Top" Width="200"/>
                    <TextBlock HorizontalAlignment="Left" Height="60" Margin="0,40,0,0" TextWrapping="Wrap" Text="{x:Bind}" VerticalAlignment="Top" Width="200" TextAlignment="Center" Padding="0,15,0,0" FontSize="20" FontWeight="Light"/>
                    <TextBlock HorizontalAlignment="Left" Height="20" Margin="0,80,0,0" TextWrapping="Wrap" Text="by Laurent Resman" VerticalAlignment="Top" Width="200" TextAlignment="Center" Padding="0" FontSize="12" FontWeight="Light"/>
                </Grid>
            </DataTemplate>
        </GridView.ItemTemplate>
    </GridView>
</code>```

and add objects like this:

```<code>GV_Seznam_Projektov.Items.Add("fublisher.io");
</code>```

I found all documentation about it on msdn network, but then I cam across a problem, I wish that every object would have different "top bar" and background color, so does anyone know how to bind, in my example three different variables inside template? I'm guessing I should make an object, right? but I have no idea how to bind it properly.

Thanks for reading all this :)

答:
An ItemsControl object can serve two roles. It can be used to present a fixed set of items, or it can be used to display a list obtained from data binding to a data source. Using an ItemsControl for data is more common. To display data, specify the binding to the data as the ItemsSource value (or use the data context) and don't populate Items. If you want to display a fixed list, populate Items with one or more FrameworkElement child objects, and don't specify ItemsSource.

ItemsSource typically references a list of items. This can be a fixed list from a business object, or a list that's designed to fire notifications if the underlying data changes. The list might be a generic interface (for example IList) or a practical class that implements the collection interfaces that Windows Runtime data binding supports. When you display items in an ItemsControl, you can use the ItemTemplate property, the ItemsPanel property, or both to specify the appearance of the items.

For more info, see For more info, see Remarks of the ItemsControl.

In your code, you set the "fublisher.io" to the Items of the GridView. You should be able to add it to the list and set the list to the ItemsSource of the GridView.

For example:

```<code><GridView x:Name="GV_Seznam_Projektov" Grid.Column="2" Margin="0,10,0,0" Grid.Row="2" ItemsSource="{x:Bind Items}">
    <GridView.ItemTemplate>
        <DataTemplate x:DataType="x:String">
            <Grid Background="#19162D50" HorizontalAlignment="Left" Width="200" Height="300" VerticalAlignment="Top">
                <Rectangle Fill="{StaticResource cl_main_back}" HorizontalAlignment="Left" Height="40" VerticalAlignment="Top" Width="200" />
                <TextBlock HorizontalAlignment="Left" Height="60" Margin="0,40,0,0" TextWrapping="Wrap" Text="{x:Bind}" VerticalAlignment="Top" Width="200" TextAlignment="Center" Padding="0,15,0,0" FontSize="20" FontWeight="Light" />
                <TextBlock HorizontalAlignment="Left" Height="20" Margin="0,80,0,0" TextWrapping="Wrap" Text="by Laurent Resman" VerticalAlignment="Top" Width="200" TextAlignment="Center" Padding="0" FontSize="12" FontWeight="Light" />
            </Grid>
        </DataTemplate>
    </GridView.ItemTemplate>
</GridView>
</code>```

Code behind:

```<code>private ObservableCollection<string> Items;

public MainPage()
{
    this.InitializeComponent();
    Items = new ObservableCollection<string>();
    Items.Add("fublisher.io");
}
</code>```

Title: GridView Template Binding (C# UWP)

Body:
I was getting trough the questions about binding but so far didn't find solution to my problem ( that might be stupid one, but I'm really new to the UWP thing ).
I'm trying to add "projects" that my application makes, inside GridView object, so I made template for it:

<GridView x:Name="GV_Seznam_Projektov" Grid.Column="2" Margin="0,10,0,0" Grid.Row="2">
        <GridView.ItemTemplate>
            <DataTemplate x:DataType="x:String">
                <Grid Background="#19162D50" HorizontalAlignment="Left" Width="200" Height="300" VerticalAlignment="Top">
                    <Rectangle Fill="{StaticResource cl_main_back}" HorizontalAlignment="Left" Height="40" VerticalAlignment="Top" Width="200"/>
                    <TextBlock HorizontalAlignment="Left" Height="60" Margin="0,40,0,0" TextWrapping="Wrap" Text="{x:Bind}" VerticalAlignment="Top" Width="200" TextAlignment="Center" Padding="0,15,0,0" FontSize="20" FontWeight="Light"/>
                    <TextBlock HorizontalAlignment="Left" Height="20" Margin="0,80,0,0" TextWrapping="Wrap" Text="by Laurent Resman" VerticalAlignment="Top" Width="200" TextAlignment="Center" Padding="0" FontSize="12" FontWeight="Light"/>
                </Grid>
            </DataTemplate>
        </GridView.ItemTemplate>
    </GridView>

and add objects like this:

GV_Seznam_Projektov.Items.Add("fublisher.io");

I found all documentation about it on msdn network, but then I cam across a problem, I wish that every object would have different "top bar" and background color, so does anyone know how to bind, in my example three different variables inside template? I'm guessing I should make an object, right? but I have no idea how to bind it properly.

Thanks for reading all this :)

Body:
An ItemsControl object can serve two roles. It can be used to present a fixed set of items, or it can be used to display a list obtained from data binding to a data source. Using an ItemsControl for data is more common. To display data, specify the binding to the data as the ItemsSource value (or use the data context) and don't populate Items. If you want to display a fixed list, populate Items with one or more FrameworkElement child objects, and don't specify ItemsSource.

ItemsSource typically references a list of items. This can be a fixed list from a business object, or a list that's designed to fire notifications if the underlying data changes. The list might be a generic interface (for example IList) or a practical class that implements the collection interfaces that Windows Runtime data binding supports. When you display items in an ItemsControl, you can use the ItemTemplate property, the ItemsPanel property, or both to specify the appearance of the items.

For more info, see For more info, see Remarks of the ItemsControl.

In your code, you set the "fublisher.io" to the Items of the GridView. You should be able to add it to the list and set the list to the ItemsSource of the GridView.

For example:

<GridView x:Name="GV_Seznam_Projektov" Grid.Column="2" Margin="0,10,0,0" Grid.Row="2" ItemsSource="{x:Bind Items}">
    <GridView.ItemTemplate>
        <DataTemplate x:DataType="x:String">
            <Grid Background="#19162D50" HorizontalAlignment="Left" Width="200" Height="300" VerticalAlignment="Top">
                <Rectangle Fill="{StaticResource cl_main_back}" HorizontalAlignment="Left" Height="40" VerticalAlignment="Top" Width="200" />
                <TextBlock HorizontalAlignment="Left" Height="60" Margin="0,40,0,0" TextWrapping="Wrap" Text="{x:Bind}" VerticalAlignment="Top" Width="200" TextAlignment="Center" Padding="0,15,0,0" FontSize="20" FontWeight="Light" />
                <TextBlock HorizontalAlignment="Left" Height="20" Margin="0,80,0,0" TextWrapping="Wrap" Text="by Laurent Resman" VerticalAlignment="Top" Width="200" TextAlignment="Center" Padding="0" FontSize="12" FontWeight="Light" />
            </Grid>
        </DataTemplate>
    </GridView.ItemTemplate>
</GridView>

Code behind:

private ObservableCollection<string> Items;

public MainPage()
{
    this.InitializeComponent();
    Items = new ObservableCollection<string>();
    Items.Add("fublisher.io");
}


问:
Android EditText delete(backspace) key event
How can I detect delete (backspace) key event for a editText? I've tried using TextWatcher, but when the editText is empty, when I press delete key, nothing happens. I want to detect delete key press foe an editText even if it has no text. </p>

答:
This seems to be working for me :</p>

```<code>public void onTextChanged(CharSequence s, int start, int before, int count) {
    if (before - count == 1) {
        onBackSpace();
    } else if (s.subSequence(start, start + count).toString().equals("\n")) {
        onNewLine();
    }
}
</code>```

Body:
This seems to be working for me :

public void onTextChanged(CharSequence s, int start, int before, int count) {
    if (before - count == 1) {
        onBackSpace();
    } else if (s.subSequence(start, start + count).toString().equals("\n")) {
        onNewLine();
    }
}


问:
Ionic serve show this error Ionic2
in this typescript code i define public currentLocation : {lat: number, lng: number}; and i get value of currentLocation inside  this.geolocation method in console.log(this.currentLocation). but outside of this block in console.log(this.currentLocation)  i got undefine. How can i get value in global variable?

```<code>export class DetailsPage {

  typeDetails: {};

  public currentLocation : {lat: number, lng: number};

   posOptions = {
  enableHighAccuracy: true,
  timeout: 20000,
  maximumAge: 0
};

  constructor(public navCtrl: NavController,
          public navParams: NavParams,
          private typeApi : TypeApi,
          public geolocation : Geolocation) {}

  ionViewDidLoad() {
  let baseUrl  ='https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=21.2150756,72.8880545&radius=500&type=hospital&key=AIzaSyBldIefF25dfjjtMZq1hjUxrj4T4hK66Mg';
    this.geolocation.getCurrentPosition().then((resp) => {

      this.currentLocation ={
          lat :resp.coords.latitude,
          lng :resp.coords.longitude

      };

 console.log(this.currentLocation);

    }).catch((error) => {
      console.log('Error getting location', error);
    });

  console.log(this.currentLocation);

console.log('ionViewDidLoad DetailsPage');

     //this.typeDetails = this.typeApi.getTypeDetails();
     //console.log(this.typeDetails);

    this.typeApi.getTypeDetails().then(data => {
    this.typeDetails = data;
    console.log(this.typeDetails);
  });
  }

}
</code>```

答:
Hence it is a promise you have to use console.log(this.currentLocation); inside the resolve method as shown below.Due to the async nature, you cannot log it outside the promise.B'cose you don't know which moment it'll have a value.

```<code>this.geolocation.getCurrentPosition().then((resp) => {

      this.currentLocation ={
          lat :resp.coords.latitude,
          lng :resp.coords.longitude

      };

    console.log(this.currentLocation);//here you have to use log method

    }).catch((error) => {
      console.log('Error getting location', error);
    });
</code>```

Title: Ionic serve show this error Ionic2

Body:
in this typescript code i define public currentLocation : {lat: number, lng: number}; and i get value of currentLocation inside  this.geolocation method in console.log(this.currentLocation). but outside of this block in console.log(this.currentLocation)  i got undefine. How can i get value in global variable?

export class DetailsPage {

  typeDetails: {};

  public currentLocation : {lat: number, lng: number};

   posOptions = {
  enableHighAccuracy: true,
  timeout: 20000,
  maximumAge: 0
};

  constructor(public navCtrl: NavController,
          public navParams: NavParams,
          private typeApi : TypeApi,
          public geolocation : Geolocation) {}

  ionViewDidLoad() {
  let baseUrl  ='https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=21.2150756,72.8880545&radius=500&type=hospital&key=AIzaSyBldIefF25dfjjtMZq1hjUxrj4T4hK66Mg';
    this.geolocation.getCurrentPosition().then((resp) => {

      this.currentLocation ={
          lat :resp.coords.latitude,
          lng :resp.coords.longitude

      };

 console.log(this.currentLocation);

    }).catch((error) => {
      console.log('Error getting location', error);
    });

  console.log(this.currentLocation);

console.log('ionViewDidLoad DetailsPage');

     //this.typeDetails = this.typeApi.getTypeDetails();
     //console.log(this.typeDetails);

    this.typeApi.getTypeDetails().then(data => {
    this.typeDetails = data;
    console.log(this.typeDetails);
  });
  }

}

Body:
Hence it is a promise you have to use console.log(this.currentLocation); inside the resolve method as shown below.Due to the async nature, you cannot log it outside the promise.B'cose you don't know which moment it'll have a value.

this.geolocation.getCurrentPosition().then((resp) => {

      this.currentLocation ={
          lat :resp.coords.latitude,
          lng :resp.coords.longitude

      };

    console.log(this.currentLocation);//here you have to use log method

    }).catch((error) => {
      console.log('Error getting location', error);
    });


问:
Could someone explain this for me - for (i = 0; i=10; i++)
I know this below statement works

```<code>for ($i= 0; $i=<10; $i++)
</code>```

will output till 0 to 10
but when I write this code

```<code>for ($i=0; $i=10; $i++)
</code>```

it print 10 for unlimited times... why  why it not print 0 to 10...
what error I have done to get the result 0 to 10 for it....

答: because i=10 always be true i==10 will be good</p>

Body:
I know this below statement works

for ($i= 0; $i=<10; $i++)

will output till 0 to 10
but when I write this code

for ($i=0; $i=10; $i++)

it print 10 for unlimited times... why  why it not print 0 to 10...
what error I have done to get the result 0 to 10 for it....


问:
Detect element content changes with jQuery
change() function works and detects changes on form elements, but is there a way of detecting when a DOM element's content was changed?

This does not work, unless #content is a form element

```<code>$("#content").change( function(){
    // do something
});
</code>```

I want this to trigger when doing something like:

```<code>$("#content").html('something');
</code>```

Also html() or append() function don't have a callback.

Any suggestions?

答:
We can achieve this by using Mutation Events. According to www.w3.org, The mutation event module is designed to allow notification of any changes to the structure of a document, including attr and text modifications. For more detail MUTATION EVENTS

For Example :

```<code>$("body").on('DOMSubtreeModified', "#content", function() {
    alert('Content Modified'); // do something
});
</code>```

Body:
change() function works and detects changes on form elements, but is there a way of detecting when a DOM element's content was changed?

This does not work, unless #content is a form element

$("#content").change( function(){
    // do something
});

I want this to trigger when doing something like:

$("#content").html('something');

Also html() or append() function don't have a callback.

Any suggestions?

Body:
We can achieve this by using Mutation Events. According to www.w3.org, The mutation event module is designed to allow notification of any changes to the structure of a document, including attr and text modifications. For more detail MUTATION EVENTS

For Example :

$("body").on('DOMSubtreeModified', "#content", function() {
    alert('Content Modified'); // do something
});


答: The middle term in a for loop is the condition that says whether the loop should continue running.  i=10 assigns 10 to i, and it also evaluates to the number 10, which is not zero, so it's considered true.  Since the loop's condition is always true, it never stops running.

Title: Could someone explain this for me - for (i = 0; i=10; i++)


问:
how can i implemented cloud computing in my application?
i have a problem that i am using web services and want that for example i have implemented facebook in my application and want that all the notification that arise in my facebook will get notified in my android phone even if application is installed but not opened in phone. So, to implement this into my application i think i have to use cloud computing but how can i do this i dont know. Can anyone help me out of this problem?

Thanks

答:
I don't know what kind of application you have already written, but you need the implement a backend that checks the Facebook notifications, which can (probably) be done using the Facebook API: http://developers.facebook.com/blog/post/291

To send the notifications to the phone, you can use push notifications. Since 2.2 this can be done with Cloud To Device Messaging:
http://android-developers.blogspot.com/2010/05/android-cloud-to-device-messaging.html
and
http://blog.boxedice.com/2010/10/07/android-push-notifications-tutorial/

ContentLicense: CC BY-SA 2.5


问:
Access Denied when opening phpMyAdmin
What could be the problem of my MySQL database server in WAMP.

I can't open it. The error says:

MySQL said: Documentation
#2002 - No connection could be made because the target machine actively refused it.

The server is not responding (or the local server's socket is not correctly configured).
```
<p>I checked the ports, but no other apps are using port 3306 which is dedicated to mysqld.</p>
<p>Here's what <code>mysql.log</code> says:</p>
<pre class="lang-none prettyprint-override"><code>120728 22:34:40 [Note] Plugin 'FEDERATED' is disabled.
120728 22:34:42 InnoDB: The InnoDB memory heap is disabled
120728 22:34:42 InnoDB: Mutexes and rw_locks use Windows interlocked functions
120728 22:34:42 InnoDB: Compressed tables use zlib 1.2.3
120728 22:34:43 InnoDB: Initializing buffer pool, size = 128.0M
120728 22:34:43 InnoDB: Completed initialization of buffer pool
120728 22:34:44 InnoDB: highest supported file format is Barracuda.
120728 22:34:52  InnoDB: Waiting for the background threads to start
120728 22:34:53 InnoDB: 1.1.8 started; log sequence number 74876578
wampmysqld: File '.\mysql-bin.000025' not found (Errcode: 2)
120728 22:34:53 [ERROR] Failed to open log (file '.\mysql-bin.000025', errno 2)
120728 22:34:53 [ERROR] Could not open log file
120728 22:34:53 [ERROR] Can't init tc log
120728 22:34:53 [ERROR] Aborting

120728 22:34:53  InnoDB: Starting shutdown...
120728 22:34:53  InnoDB: Shutdown completed; log sequence number 74876578
120728 22:34:53 [Note] wampmysqld: Shutdown complete

120728 22:35:16 [Note] Plugin 'FEDERATED' is disabled.
120728 22:35:16 InnoDB: The InnoDB memory heap is disabled
120728 22:35:16 InnoDB: Mutexes and rw_locks use Windows interlocked functions
120728 22:35:16 InnoDB: Compressed tables use zlib 1.2.3
120728 22:35:16 InnoDB: Initializing buffer pool, size = 128.0M
120728 22:35:16 InnoDB: Completed initialization of buffer pool
120728 22:35:16 InnoDB: highest supported file format is Barracuda.
120728 22:35:32  InnoDB: Waiting for the background threads to start
120728 22:35:33 InnoDB: 1.1.8 started; log sequence number 74876578
wampmysqld: File '.\mysql-bin.000025' not found (Errcode: 2)
120728 22:35:33 [ERROR] Failed to open log (file '.\mysql-bin.000025', errno 2)
120728 22:35:33 [ERROR] Could not open log file
120728 22:35:33 [ERROR] Can't init tc log
120728 22:35:33 [ERROR] Aborting

120728 22:35:33  InnoDB: Starting shutdown...
120728 22:35:34  InnoDB: Shutdown completed; log sequence number 74876578
120728 22:35:34 [Note] wampmysqld: Shutdown complete

120728 22:35:42 [Note] Plugin 'FEDERATED' is disabled.
120728 22:35:42 InnoDB: The InnoDB memory heap is disabled
120728 22:35:42 InnoDB: Mutexes and rw_locks use Windows interlocked functions
120728 22:35:42 InnoDB: Compressed tables use zlib 1.2.3
120728 22:35:42 InnoDB: Initializing buffer pool, size = 128.0M
120728 22:35:42 InnoDB: Completed initialization of buffer pool
120728 22:35:44 InnoDB: highest supported file format is Barracuda.
120728 22:35:59  InnoDB: Waiting for the background threads to start
120728 22:36:00 InnoDB: 1.1.8 started; log sequence number 74876578
wampmysqld: File '.\mysql-bin.000025' not found (Errcode: 2)
120728 22:36:00 [ERROR] Failed to open log (file '.\mysql-bin.000025', errno 2)
120728 22:36:00 [ERROR] Could not open log file
120728 22:36:00 [ERROR] Can't init tc log
120728 22:36:00 [ERROR] Aborting

120728 22:36:00  InnoDB: Starting shutdown...
120728 22:36:01  InnoDB: Shutdown completed; log sequence number 74876578
120728 22:36:01 [Note] wampmysqld: Shutdown complete
</code>```

PS: I don't have a Skype. So I think it's not the conflict.

答:
I installed MySQL stand-alone (not using any XAMPP/WAMP stack) and got this problem some time ago. I just ran the following command in windows command prompt:

```<code>C:\>"C:\mysql\bin\mysqld" --console
</code>```

where "C:\mysql\" is the installation directory (adjust the path according to your own case). The

```<code>  --console
</code>```

displays the process for debugging purposes.

After startup, you should see something like:

```<code>C:\mysql\bin\mysqld: ready for connections
Version: '5.7.10'  socket: ''  port: 3306
</code>```

For moore, see Starting MySQL Server

ContentLicense: CC BY-SA 4.0

Title: Access Denied when opening phpMyAdmin

Body:
What could be the problem of my MySQL database server in WAMP.

I can't open it. The error says:

MySQL said: Documentation
#2002 - No connection could be made because the target machine actively refused it.

The server is not responding (or the local server's socket is not correctly configured).

I checked the ports, but no other apps are using port 3306 which is dedicated to mysqld.

Here's what mysql.log says:

120728 22:34:40 [Note] Plugin 'FEDERATED' is disabled.
120728 22:34:42 InnoDB: The InnoDB memory heap is disabled
120728 22:34:42 InnoDB: Mutexes and rw_locks use Windows interlocked functions
120728 22:34:42 InnoDB: Compressed tables use zlib 1.2.3
120728 22:34:43 InnoDB: Initializing buffer pool, size = 128.0M
120728 22:34:43 InnoDB: Completed initialization of buffer pool
120728 22:34:44 InnoDB: highest supported file format is Barracuda.
120728 22:34:52  InnoDB: Waiting for the background threads to start
120728 22:34:53 InnoDB: 1.1.8 started; log sequence number 74876578
wampmysqld: File '.\mysql-bin.000025' not found (Errcode: 2)
120728 22:34:53 [ERROR] Failed to open log (file '.\mysql-bin.000025', errno 2)
120728 22:34:53 [ERROR] Could not open log file
120728 22:34:53 [ERROR] Can't init tc log
120728 22:34:53 [ERROR] Aborting

120728 22:34:53  InnoDB: Starting shutdown...
120728 22:34:53  InnoDB: Shutdown completed; log sequence number 74876578
120728 22:34:53 [Note] wampmysqld: Shutdown complete

120728 22:35:16 [Note] Plugin 'FEDERATED' is disabled.
120728 22:35:16 InnoDB: The InnoDB memory heap is disabled
120728 22:35:16 InnoDB: Mutexes and rw_locks use Windows interlocked functions
120728 22:35:16 InnoDB: Compressed tables use zlib 1.2.3
120728 22:35:16 InnoDB: Initializing buffer pool, size = 128.0M
120728 22:35:16 InnoDB: Completed initialization of buffer pool
120728 22:35:16 InnoDB: highest supported file format is Barracuda.
120728 22:35:32  InnoDB: Waiting for the background threads to start
120728 22:35:33 InnoDB: 1.1.8 started; log sequence number 74876578
wampmysqld: File '.\mysql-bin.000025' not found (Errcode: 2)
120728 22:35:33 [ERROR] Failed to open log (file '.\mysql-bin.000025', errno 2)
120728 22:35:33 [ERROR] Could not open log file
120728 22:35:33 [ERROR] Can't init tc log
120728 22:35:33 [ERROR] Aborting

120728 22:35:33  InnoDB: Starting shutdown...
120728 22:35:34  InnoDB: Shutdown completed; log sequence number 74876578
120728 22:35:34 [Note] wampmysqld: Shutdown complete

120728 22:35:42 [Note] Plugin 'FEDERATED' is disabled.
120728 22:35:42 InnoDB: The InnoDB memory heap is disabled
120728 22:35:42 InnoDB: Mutexes and rw_locks use Windows interlocked functions
120728 22:35:42 InnoDB: Compressed tables use zlib 1.2.3
120728 22:35:42 InnoDB: Initializing buffer pool, size = 128.0M
120728 22:35:42 InnoDB: Completed initialization of buffer pool
120728 22:35:44 InnoDB: highest supported file format is Barracuda.
120728 22:35:59  InnoDB: Waiting for the background threads to start
120728 22:36:00 InnoDB: 1.1.8 started; log sequence number 74876578
wampmysqld: File '.\mysql-bin.000025' not found (Errcode: 2)
120728 22:36:00 [ERROR] Failed to open log (file '.\mysql-bin.000025', errno 2)
120728 22:36:00 [ERROR] Could not open log file
120728 22:36:00 [ERROR] Can't init tc log
120728 22:36:00 [ERROR] Aborting

120728 22:36:00  InnoDB: Starting shutdown...
120728 22:36:01  InnoDB: Shutdown completed; log sequence number 74876578
120728 22:36:01 [Note] wampmysqld: Shutdown complete

PS: I don't have a Skype. So I think it's not the conflict.

Body:
I installed MySQL stand-alone (not using any XAMPP/WAMP stack) and got this problem some time ago. I just ran the following command in windows command prompt:

C:\>"C:\mysql\bin\mysqld" --console

where "C:\mysql\" is the installation directory (adjust the path according to your own case). The

  --console

displays the process for debugging purposes.

After startup, you should see something like:

C:\mysql\bin\mysqld: ready for connections
Version: '5.7.10'  socket: ''  port: 3306

For moore, see Starting MySQL Server


答:
```<code><?php

        if(isset($_POST['submit']))
        {
        $filename=$_FILES['image']['name'];
        $filetempname=$_FILES['image']['tmp_name'];
        $fname=md5($_SERVER['REMOTE_ADDR'].rand()).$filename;
        $filepath="uploads/uploads1/".$fname;
        $upload=move_uploaded_file($filetempname,$filepath1);
if($upload) {
          $reg_query = mysqli_query($conn, "INSERT INTO `quiz_register`(`name`, `email`, `mobile`, `password`, `cpassword`, `image`) VALUES ('$name','$mail','$cell','$pass','$cpass','$filepath')");
          if ($reg_query) {
              echo 'success';
          } else {
              echo 'fail';
          }
      }
?>
</code>```

You check this code it may be helpful to you .

Title: Image not inserting in folder using PHP and MYSQL

Body:
<?php

        if(isset($_POST['submit']))
        {
        $filename=$_FILES['image']['name'];
        $filetempname=$_FILES['image']['tmp_name'];
        $fname=md5($_SERVER['REMOTE_ADDR'].rand()).$filename;
        $filepath="uploads/uploads1/".$fname;
        $upload=move_uploaded_file($filetempname,$filepath1);
if($upload) {
          $reg_query = mysqli_query($conn, "INSERT INTO `quiz_register`(`name`, `email`, `mobile`, `password`, `cpassword`, `image`) VALUES ('$name','$mail','$cell','$pass','$cpass','$filepath')");
          if ($reg_query) {
              echo 'success';
          } else {
              echo 'fail';
          }
      }
?>

You check this code it may be helpful to you .


答: The second statement in the for loop is the condition. When its not true it will leave the loop. i=10 is not a comparator. i will be set to 10 every round that loop goes and because it "works" its resulting in true. i == 10 would be a comparator but i would never be 10 in its first round.</p>


问:
How to refresh registry value
I am uninstalling some application and reading the software installation enumeration value from registry.

The problem is after uninstallation it is not changing the registry value untill unless the screen or regedit is not refreshed. after refreshing only i am getting the correct value.

Could some one help me out to refresh the regedit in python codes.

Regards,
upendra

答:
I assume that by "refreshing" the "screen," you mean restarting the computer? Regardless, you can be sure that whatever registry keys you've modified will be correctly updated after the system is restarted. The registry is updated with lazy flush and writer threads, so my guess is that the changes you're making aren't flushed back to the registry immediately, but your question doesn't provide enough information about how you're modifying these registry values for me to be able to propose an alternative solution.

Perhaps more importantly, what are you trying to do here? Are you trying to get your uninstaller to verify that your application has been uninstalled? Why is this necessary? I feel like there has to be a better way than expecting registry edits to be committed and then read back out immediately.

Title: How to refresh registry value


问:
How to save text from the ListBox?
Can I use the "StreamWriter" function to save the text in the ListBox?</p>

```<code>private void button3_Click(object sender, EventArgs e)
        {

            SaveFileDialog saveFile1 = new SaveFileDialog();
            saveFile1.DefaultExt = "*.txt";
            saveFile1.Filter = "Text files|*.txt";
            if (saveFile1.ShowDialog() == System.Windows.Forms.DialogResult.OK &&
            saveFile1.FileName.Length > 0)
            {
                using (StreamWriter sw = new StreamWriter(saveFile1.FileName, true))

                {
                    sw.WriteLine(listBox1.Text);
                    sw.Close();
                }
</code>```

答:
If you want to save all items on your Listbox using StreamWriter, loop through all items and pass it on a string, or stringbuilder then write it on your file:

```<code>using (StreamWriter sw = new StreamWriter(saveFile1.FileName, true))
   {
      string text = "";
      foreach (var item in listBox1.Items)
       {
         text += item.ToString() + Environment.NewLine; //I added new line per list.
       }
    sw.WriteLine(text);
    sw.Close();
   }
</code>```

If you want the selected text instead, you can just use the SelectedItem:

```<code>using (StreamWriter sw = new StreamWriter(saveFile1.FileName, true))
      {
         sw.WriteLine(listBox1.SelectedItem);
         sw.Close();
      }
</code>```

Title: How to save text from the ListBox?

Body:
Can I use the "StreamWriter" function to save the text in the ListBox?

private void button3_Click(object sender, EventArgs e)
        {

            SaveFileDialog saveFile1 = new SaveFileDialog();
            saveFile1.DefaultExt = "*.txt";
            saveFile1.Filter = "Text files|*.txt";
            if (saveFile1.ShowDialog() == System.Windows.Forms.DialogResult.OK &&
            saveFile1.FileName.Length > 0)
            {
                using (StreamWriter sw = new StreamWriter(saveFile1.FileName, true))

                {
                    sw.WriteLine(listBox1.Text);
                    sw.Close();
                }

Body:
If you want to save all items on your Listbox using StreamWriter, loop through all items and pass it on a string, or stringbuilder then write it on your file:

using (StreamWriter sw = new StreamWriter(saveFile1.FileName, true))
   {
      string text = "";
      foreach (var item in listBox1.Items)
       {
         text += item.ToString() + Environment.NewLine; //I added new line per list.
       }
    sw.WriteLine(text);
    sw.Close();
   }

If you want the selected text instead, you can just use the SelectedItem:

using (StreamWriter sw = new StreamWriter(saveFile1.FileName, true))
      {
         sw.WriteLine(listBox1.SelectedItem);
         sw.Close();
      }


问:
what is the difference between ionic-native and @ionic-native/xxx in ionic 2
I am attempting to use Ionic Native functionality in my Ionic2 application. I am finding a significant amount of examples and installation instructions for ionic-native node module and also for @ionic-native/[package-name]. I am unclear as to which node-module to use. It appears as though ionic-native comes installed, but, all of the documentation at https://ionicframework.com/docs/native/ uses @ionic-native/[package-name]. What is the difference if any between these two packages? Which should be used in my ionic2 application?

Below is my current project info

答:
The difference is between
ionic-native v 2.x and ionic native v3.x

ionic-native v 2.x

If this is the version, all cordova wrappers will be available in the particular package and the plugins are used as global objects imported directly from ionic-native.

V2 readme.

ionic native v3.x

This is the current version (as of now 3.4.4).
You need to install npm install @ionic-native/core and then install the individual package.@ionic-native/[package-name]

For use you need to inject the plugin as a provider. Check answer here


问:
Splitting start and end date in python to separate years
I want to adapt the code here: Given a date range how can we break it up into N contiguous sub-intervals? to split a range of dates as follows:

Starting date is '2015-03-20' and end date is '2017-03-12'. I want to split it into 3 parts. One for each of the 3 years, so that I get a list like this:

```<code>[['2015-03-20', '2015-12-31'], ['2016-01-01', '2016-12-31'], ['2017-01-01', '2017-03-12']]
</code>```

Any pythonic way to do this?

答:
Modifying the original code that you linked:

```<code>from datetime import datetime, timedelta

def date_range(start, end, interval):
    start = datetime.strptime(start, "%Y%m%d")
    end = datetime.strptime(end, "%Y%m%d")
    diff = (end - start) / interval
    for i in range(interval):
        if i == 0:
            date_additive = 0
        else:
            date_additive = 1
        yield ["{0}-{1}-{2}".format(str(((start + diff * i) + timedelta(days=date_additive)).strftime("%Y").zfill(2)),
                                    str(((start + diff * i) + timedelta(days=date_additive)).strftime("%m").zfill(2)),
                                    str(((start + diff * i) + timedelta(days=date_additive)).strftime("%d").zfill(2))),
               "{0}-{1}-{2}".format(str((start + diff * (i + 1)).strftime("%Y").zfill(2)),
                                    str((start + diff * (i + 1)).strftime("%m").zfill(2)),
                                    str((start + diff * (i + 1)).strftime("%d").zfill(2)))]
</code>```

Input example:

```<code>def main():
    begin = "20150320"
    end = "20170312"
    interval = 3
    print(list(date_range(begin, end, interval)))

main()
</code>```

Results:

```<code>[['2015-03-20', '2015-11-16'], ['2015-11-17', '2016-07-14'], ['2016-07-15', '2017-03-12']]
</code>```

Body:
I want to adapt the code here: Given a date range how can we break it up into N contiguous sub-intervals? to split a range of dates as follows:

Starting date is '2015-03-20' and end date is '2017-03-12'. I want to split it into 3 parts. One for each of the 3 years, so that I get a list like this:

[['2015-03-20', '2015-12-31'], ['2016-01-01', '2016-12-31'], ['2017-01-01', '2017-03-12']]

Any pythonic way to do this?

Body:
Modifying the original code that you linked:

from datetime import datetime, timedelta

def date_range(start, end, interval):
    start = datetime.strptime(start, "%Y%m%d")
    end = datetime.strptime(end, "%Y%m%d")
    diff = (end - start) / interval
    for i in range(interval):
        if i == 0:
            date_additive = 0
        else:
            date_additive = 1
        yield ["{0}-{1}-{2}".format(str(((start + diff * i) + timedelta(days=date_additive)).strftime("%Y").zfill(2)),
                                    str(((start + diff * i) + timedelta(days=date_additive)).strftime("%m").zfill(2)),
                                    str(((start + diff * i) + timedelta(days=date_additive)).strftime("%d").zfill(2))),
               "{0}-{1}-{2}".format(str((start + diff * (i + 1)).strftime("%Y").zfill(2)),
                                    str((start + diff * (i + 1)).strftime("%m").zfill(2)),
                                    str((start + diff * (i + 1)).strftime("%d").zfill(2)))]

Input example:

def main():
    begin = "20150320"
    end = "20170312"
    interval = 3
    print(list(date_range(begin, end, interval)))

main()

Results:

[['2015-03-20', '2015-11-16'], ['2015-11-17', '2016-07-14'], ['2016-07-15', '2017-03-12']]


问:
what does "driver = new AndroidDriver(new URL("http://172.16.1.34:80"), capabilities); " mean in appium
I am new to appium and want to find out what certain line of basic code mean. can anyone tel me what the below code line indicate?
It will be nice if you mention what this url indicate: "http://172.16.1.34:80"
specially "80" and if it can be changed which other possible port number can be put.

driver = new AndroidDriver(new URL("http://172.16.1.34:80"), capabilities);

答:
The first parameter is </p>

```<code>remoteAddress - is the address of remotely/locally started Appium server
</code>```

<p>In "http://172.16.1.34:80" </p>

```<code>172.16.1.34 - IP of appium server
80 - Port on which appium is running
</code>```

Body:
The first parameter is

remoteAddress - is the address of remotely/locally started Appium server

In "http://172.16.1.34:80"

172.16.1.34 - IP of appium server
80 - Port on which appium is running


问:
Time starts reading in minus, while the end message still shows
My countdown timer I want to put on a site is having some issues. Countdown is normal, everything is fine, but at the end of the timer, instead of it to clear the timer and display the end message or a call back, it will rather display the end message by the side while time continues to read in the negative.

Can anyone show me what went wrong?

This is my code:

    // Set the date we're counting down to
    var countDownDate = new Date("March 31, 2017 09:35:00 PM").getTime();
    // Update the count down every 1 second

    var x = setInterval(function() {

        // Get todays date and time
        var now = new Date().getTime();

        // Find the distance between now an the count down date
        var distance = countDownDate - now;

        // Time calculations for days, hours, minutes and seconds
        var days = Math.floor(distance / (1000 * 60 * 60 * 24));
        var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
        var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
        var seconds = Math.floor((distance % (1000 * 60)) / 1000);

       // Output the result in an element with id="demo"

        document.getElementById("days").innerHTML = days;
        document.getElementById("hours").innerHTML = hours;
        document.getElementById("minutes").innerHTML = minutes;
        document.getElementById("seconds").innerHTML = seconds;

        // If the count down is over, write some text
     if (distance < 0) {
            clearInterval(x);
            document.getElementById("endmessage").innerHTML = "EXPIRED";

        }

    }, 1000);
    ```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
       background: #f6f6f6;
      }

      .countdownContainer{
       position: absolute;;
       top: 50%;
       left: 50%;
       transform : translateX(-50%) translateY(-50%);
       text-align: center;
       background: #ddd;
       border: 1px solid #999;
       padding: 10px;
       box-shadow: 0 0 5px 3px #ccc;
      }

      .info {
       font-size: 80px;
      }</code>```

<!DOCTYPE HTML>

        Countdown to April fool

        00
        00
        00
        00

        Days
        Hours
        Minutes
        Seconds

    ```

答:
Is it not already the 1st of april? It is counting down to a day already passed as in the 31 of march?

Also, you do not need PM, remove PM and just have 09 or 21 etc. Not AM/PM

```<code><script>

// Set the date we're counting down to
var countDownDate = new Date("April 1, 2017 09:35:00").getTime();
// Update the count down every 1 second

var x = setInterval(function() {

    // Get todays date and time
    var now = new Date().getTime();

    // Find the distance between now an the count down date
    var distance = countDownDate - now;

    // Time calculations for days, hours, minutes and seconds
    var days = Math.floor(distance / (1000 * 60 * 60 * 24));
    var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
    var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
    var seconds = Math.floor((distance % (1000 * 60)) / 1000);

   // Output the result in an element with id="demo"

    document.getElementById("days").innerHTML = days;
    document.getElementById("hours").innerHTML = hours;
    document.getElementById("minutes").innerHTML = minutes;
    document.getElementById("seconds").innerHTML = seconds;

    // If the count down is over, write some text
    if (distance < 0) {
        clearInterval(x);
        document.getElementById("endmessage").innerHTML = "EXPIRED";

    }

}, 1000);

</script>
</code>```

This counts down to 09:35, today.

Body:
My countdown timer I want to put on a site is having some issues. Countdown is normal, everything is fine, but at the end of the timer, instead of it to clear the timer and display the end message or a call back, it will rather display the end message by the side while time continues to read in the negative.

Can anyone show me what went wrong?

This is my code:

    // Set the date we're counting down to
    var countDownDate = new Date("March 31, 2017 09:35:00 PM").getTime();
    // Update the count down every 1 second

    var x = setInterval(function() {

        // Get todays date and time
        var now = new Date().getTime();

        // Find the distance between now an the count down date
        var distance = countDownDate - now;

        // Time calculations for days, hours, minutes and seconds
        var days = Math.floor(distance / (1000 * 60 * 60 * 24));
        var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
        var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
        var seconds = Math.floor((distance % (1000 * 60)) / 1000);

       // Output the result in an element with id="demo"

        document.getElementById("days").innerHTML = days;
        document.getElementById("hours").innerHTML = hours;
        document.getElementById("minutes").innerHTML = minutes;
        document.getElementById("seconds").innerHTML = seconds;

        // If the count down is over, write some text
     if (distance < 0) {
            clearInterval(x);
            document.getElementById("endmessage").innerHTML = "EXPIRED";

        }

    }, 1000);

body {
       background: #f6f6f6;
      }

      .countdownContainer{
       position: absolute;;
       top: 50%;
       left: 50%;
       transform : translateX(-50%) translateY(-50%);
       text-align: center;
       background: #ddd;
       border: 1px solid #999;
       padding: 10px;
       box-shadow: 0 0 5px 3px #ccc;
      }

      .info {
       font-size: 80px;
      }

<!DOCTYPE HTML>

        Countdown to April fool

        00
        00
        00
        00

        Days
        Hours
        Minutes
        Seconds

Body:
Is it not already the 1st of april? It is counting down to a day already passed as in the 31 of march?

Also, you do not need PM, remove PM and just have 09 or 21 etc. Not AM/PM

<script>

// Set the date we're counting down to
var countDownDate = new Date("April 1, 2017 09:35:00").getTime();
// Update the count down every 1 second

var x = setInterval(function() {

    // Get todays date and time
    var now = new Date().getTime();

    // Find the distance between now an the count down date
    var distance = countDownDate - now;

    // Time calculations for days, hours, minutes and seconds
    var days = Math.floor(distance / (1000 * 60 * 60 * 24));
    var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
    var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
    var seconds = Math.floor((distance % (1000 * 60)) / 1000);

   // Output the result in an element with id="demo"

    document.getElementById("days").innerHTML = days;
    document.getElementById("hours").innerHTML = hours;
    document.getElementById("minutes").innerHTML = minutes;
    document.getElementById("seconds").innerHTML = seconds;

    // If the count down is over, write some text
    if (distance < 0) {
        clearInterval(x);
        document.getElementById("endmessage").innerHTML = "EXPIRED";

    }

}, 1000);

</script>

This counts down to 09:35, today.


问:
Access Not Configured. Gmail API has not been used in project ********* before or it is disabled. (Python, Gmail API)
I am having this error
<"Access Not Configured. Gmail API has not been used in project ********* before or it is disabled. Enable it by visiting https://console.developers.google.com/apis/api/gmail/overview?project=********* then retry. If you enabled this API recently, wait a few minutes for the action to propagate to our systems and retry.">

I know Im having problem with the product ID. Couple of days ago my friend was running calendar API with my Pycharm and then he verified with his account with all the credentials. But I also created a new project>created new Credential. Downloaded the secret Json file and replaced with previous. I also checked the Json file, and the client ID was mine. But still Pycharm is still looking for that client ID which was my friends client ID. How do I resolve it?

I also tried opening new projects in Pycharm but still having same problem. I am new to python and Google APIs. If my question was too simple/obvious please pardon and help me out with the solutions.

The code I am using is given in this link, quickstart.py by Google developer page.

答: I finally solved the issue. I didn't enabled the gmail API from the console page. In the console page go to dashboard, next enable API and choose which API you want to enable. In my case it was Gmail.</p>


问:
Adding a preferences fragment in my xamarin/visualstudio project
Very new in android programming... I've created a simple priject just to learn.
Trying to add a preferences screen following this guide :
When I declare my Preferences class inside the namespace as follows:

```<code> public class MySettingsFragment extends PreferenceFragment
    {

        @Override
        public void OnCreate(Bundle savedInstanceState)
    {
        base.OnCreate(savedInstanceState);

        // Load the preferences from an XML resource
        AddPreferencesFromResource(Resource.Xml.preferences);
    }
</code>```

I get errors such as "extends" cannot be found and many other saying it is not the right context where to write it
what I am missing?

答:
It seems that you are mixing Java and C# syntax, in C# you use a colon instead of the word 'extends' to inherit a class, and the 'override' modifier is used instead of '@Override'

Your code would end up looking like this

```<code> public class MySettingsFragment : PreferenceFragment
 {

    public override void OnCreate(Bundle savedInstanceState)
    {
        base.OnCreate(savedInstanceState);

        // Load the preferences from an XML resource
        AddPreferencesFromResource(Resource.Xml.preferences);
    }
}
</code>```

Body:
Very new in android programming... I've created a simple priject just to learn.
Trying to add a preferences screen following this guide :
When I declare my Preferences class inside the namespace as follows:

 public class MySettingsFragment extends PreferenceFragment
    {

        @Override
        public void OnCreate(Bundle savedInstanceState)
    {
        base.OnCreate(savedInstanceState);

        // Load the preferences from an XML resource
        AddPreferencesFromResource(Resource.Xml.preferences);
    }

I get errors such as "extends" cannot be found and many other saying it is not the right context where to write it
what I am missing?

Body:
It seems that you are mixing Java and C# syntax, in C# you use a colon instead of the word 'extends' to inherit a class, and the 'override' modifier is used instead of '@Override'

Your code would end up looking like this

 public class MySettingsFragment : PreferenceFragment
 {

    public override void OnCreate(Bundle savedInstanceState)
    {
        base.OnCreate(savedInstanceState);

        // Load the preferences from an XML resource
        AddPreferencesFromResource(Resource.Xml.preferences);
    }
}


问:
Ionic 2 / Ionic 3 / Ionic 4 : (Lazy) Loading spinner for pictures
I'm using ion-img in my ionic2 application to load my pictures correctly. However, I wonder if there is a way to indicate to the user that the picture is actually loading.

Thank you for your help!

EDIT : Here is the answer if you absolutely need to use the ion-img tag. If not, you should use ionic-image-loader as AdminDev826 suggested.

I finally solved that problem with CSS! When an image is loading in ionic 2, the ion-img tag doesn't have any class. However, when the image is finally loaded, the ion-img tag get the class "img-loaded".

Here is my solution :

```<code>  <ion-img [src]="img.src"></ion-img>
  <ion-spinner></ion-spinner>
</code>```

And my CSS :

```<code>.img-loaded + ion-spinner {
  display:none;
}
</code>```

I hope it can help someone!

答:
If you want to use the img tag instead of ion-img here is the solution:

```<code>  <img src="{{image.src}}" (load)="loaded = true" [ngClass]="{'img-loaded':loaded}" [hidden]="!loaded" *ngIf="image_exists" />
  <ion-spinner [ngClass]="{'center':true}" *ngIf="!loaded"></ion-spinner>
</code>```

In your CSS file you should write the following:

```<code> .img-loaded + ion-spinner {
  display:none;
}
// .center in my case to make the spinner at the center
.center{
  margin-left: auto;
  margin-right: auto;
  display: block;
}
</code>```

loaded is a boolean variable with false default value you have to define in your component.

Body:
I'm using ion-img in my ionic2 application to load my pictures correctly. However, I wonder if there is a way to indicate to the user that the picture is actually loading.

Thank you for your help!

EDIT : Here is the answer if you absolutely need to use the ion-img tag. If not, you should use ionic-image-loader as AdminDev826 suggested.

I finally solved that problem with CSS! When an image is loading in ionic 2, the ion-img tag doesn't have any class. However, when the image is finally loaded, the ion-img tag get the class "img-loaded".

Here is my solution :

  <ion-img [src]="img.src"></ion-img>
  <ion-spinner></ion-spinner>

And my CSS :

.img-loaded + ion-spinner {
  display:none;
}

I hope it can help someone!

Body:
If you want to use the img tag instead of ion-img here is the solution:

  <img src="{{image.src}}" (load)="loaded = true" [ngClass]="{'img-loaded':loaded}" [hidden]="!loaded" *ngIf="image_exists" />
  <ion-spinner [ngClass]="{'center':true}" *ngIf="!loaded"></ion-spinner>

In your CSS file you should write the following:

 .img-loaded + ion-spinner {
  display:none;
}
// .center in my case to make the spinner at the center
.center{
  margin-left: auto;
  margin-right: auto;
  display: block;
}

loaded is a boolean variable with false default value you have to define in your component.


问:
Javascript dom manipulation by data object
I have HTML like this

```<code><div class="fruits">[ Banana Apple Orange Melon Papaya ][ Avocado Coconut Strawberry ]</div>
</code>```

I want to convert it become like this

```<code><div class="fruits">
<p id="pid_0" data-show="wid_0">
    <span id="wid_0" data-price="100" data-code="1">Banana</span>
    <span id="wid_1" data-price="200" data-code="2">Apple</span>
    <span id="wid_2" data-price="300" data-code="3">Orange</span>
    <span id="wid_3" data-price="400" data-code="4">Melon</span>
    <span id="wid_4" data-price="500" data-code="5">Papaya</span>
</p>
<p id="pid_5" data-show="wid_5">
    <span id="wid_5" data-price="600" data-code="6">Avocado</span>
    <span id="wid_6" data-price="700" data-code="7">Coconut</span>
    <span id="wid_7" data-price="800" data-code="8">Strawberry</span>
</p>
</code>```

This is how I got so far

```<code><script>
var price_arr = [100, 200, 300, 400, 500, 600, 700, 800];
var code_arr = [1, 2, 3, 4, 5, 6, 7, 8];

$(".fruits").each(function() {
    $(this).text($(this).text().replace(/\w+/g, "<span>$&</span>"));
    $(this).text($(this).text().replace(/\[/g, "<p> "));
    $(this).text($(this).text().replace(/\]/g, "</p>"));
});

var str = $(".fruits").text();
var words = str.split(" ");
var result = [];
var obj = {};

for (var i = 0; i < words.length - 1; i++) {
    // words
    words[i] += " ";

    var w = "wid_"+i;
    var p = "pid_"+i;

    var price = price_arr[i];
    var code = code_arr[i];
    var name = words[i] += " ";

    obj = {get_price:price, get_code:code, display:name};
    result.push(obj);
}
</script>
</code>```

I'm want to use data object(obj) and store it to each html attribute, but I'm getting stuck. Anyone please help me, I will be highly appreciate.

答:
Simply use with Array#map function append() function of jquery

first separate the html data in to two array

Then map with each array.

Finally map with each array with in arguments.

Then append with in a fruits

var price_arr = [100, 200, 300, 400, 500, 600, 700, 800];
var code_arr = [1, 2, 3, 4, 5, 6, 7, 8];

var a = $('.fruits').text().split('][')
$('.fruits').empty()
var k = 0;
var c = 0;
var result = []
var res = [];
a.map((a, b) => {
  $('.fruits').append('

')
  a.replace(/\]|\[/g, "").split(" ").map((a, b) => {
    if (a) {
      result[c] = {
        get_price: price_arr[c],
        get_code: code_arr[c],
        display: a,
      };
      $('#pid_' + k + '').append('' + a + '')
      c++;
    }
  })
  k = c
})
console.log(result);
console.log($('.fruits').html())```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div class="fruits">[ Banana Apple Orange Melon Papaya ][ Avocado Coconut Strawberry ]</div></code>```

Body:
I have HTML like this

[ Banana Apple Orange Melon Papaya ][ Avocado Coconut Strawberry ]

I want to convert it become like this

    Banana
    Apple
    Orange
    Melon
    Papaya

    Avocado
    Coconut
    Strawberry

This is how I got so far

I'm want to use data object(obj) and store it to each html attribute, but I'm getting stuck. Anyone please help me, I will be highly appreciate.

Body:
Simply use with Array#map function append() function of jquery

first separate the html data in to two array

Then map with each array.

Finally map with each array with in arguments.

Then append with in a fruits

var price_arr = [100, 200, 300, 400, 500, 600, 700, 800];
var code_arr = [1, 2, 3, 4, 5, 6, 7, 8];

var a = $('.fruits').text().split('][')
$('.fruits').empty()
var k = 0;
var c = 0;
var result = []
var res = [];
a.map((a, b) => {
  $('.fruits').append('<p id="pid_' + k + '" data-show="wid_' + k + '"></p>')
  a.replace(/\]|\[/g, "").split(" ").map((a, b) => {
    if (a) {
      result[c] = {
        get_price: price_arr[c],
        get_code: code_arr[c],
        display: a,
      };
      $('#pid_' + k + '').append('<span id="wid_' + c + '" data-price="' + price_arr[c] + '" data-code="' + code_arr[c] + '">' + a + '</span>')
      c++;
    }
  })
  k = c
})
console.log(result);
console.log($('.fruits').html())

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div class="fruits">[ Banana Apple Orange Melon Papaya ][ Avocado Coconut Strawberry ]</div>


问:
How to change the language of Google Speech API on Java?
I am using Google Speech API on Java.

I can find language configuration something like languagecode in Python version, but I can't find that in Java version.
I can find documents changing the language for Python, but I can't find for Java. And, I can't find something like languagecode or en_US in Java source.

How to change the language of Google Speech API on Java?

答:
It's a field of the RecognitionConfig object, so you should be able to set it here.

I don't have access to the Java code at the moment, but it's probably something like this:

```<code>RecognitionConfig config =
      RecognitionConfig.newBuilder()
          .setEncoding(AudioEncoding.LINEAR16)
          .setSampleRate(samplingRate)
          .setLanguageCode("en-US")
          .build();
</code>```

Of course, you can omit the encoding and sample rate if you're using the default values.

This field is part of the API so it may be defined in a protobuf file rather than in Java source files.

Body:
It's a field of the RecognitionConfig object, so you should be able to set it here.

I don't have access to the Java code at the moment, but it's probably something like this:

RecognitionConfig config =
      RecognitionConfig.newBuilder()
          .setEncoding(AudioEncoding.LINEAR16)
          .setSampleRate(samplingRate)
          .setLanguageCode("en-US")
          .build();

Of course, you can omit the encoding and sample rate if you're using the default values.

This field is part of the API so it may be defined in a protobuf file rather than in Java source files.


问:
How to create image or pdf from html having css filters?
I want to create an image or pdf from a html. The html consist of images with css filters like sepia, gray-scale etc. So it would be better if anyone have worked on that.

```<code><img class="dj_rot" src="/940/images/photos.png" style="filter: sepia(1);">
<img class="dj_rot" src="/940/images/photos.png" style="filter: grayscale(1);">
</code>```

Thanks
Deepak

答:
You might want to use pdf converting tools like html2pdf of mPDF for PHP.
I have used html2pdf successfully in the past, but I am pretty sure both of them have a good support for CSS.</p>

Body:
I want to create an image or pdf from a html. The html consist of images with css filters like sepia, gray-scale etc. So it would be better if anyone have worked on that.

Thanks
Deepak


问:
Wiki rendering in GWT
Client side rendering is useful when we want to use wiki like syntax. Unfortunately I have not found any library which gives wiki syntax rendering in GWT client side.

Does anyone knows such an API/library?

答:
Sounds like you want a Javascript wiki rendering API. There are a couple Mediawiki (Wikipedia syntax) ones listed at http://www.mediawiki.org/wiki/Alternative_parsers.

There are also some Java-based wiki markup parsers; you could simply parse the wiki markup on the server side. Here are some examples:

JWPL contains a Mediawiki markup parser.

MathEclipse Java Wikipedia API

Mylyn

java-wikipedia-parser

Googling might turn up parsers for other wiki syntaxes, though Mediawiki seems to be pretty well-known.

Title: Wiki rendering in GWT

LastEditorDisplayName: jamesh

OwnerDisplayName: Brian Clapper


问:
Including javascript files with templates
I am using AppEngine with the webapp framework (python). In my script I am generating javascript code dynamically with Django, for example:

python controller file

```<code>template_values = {
    'page': '1',
}

path = os.path.join(os.path.dirname(__file__), "../views/index.html")
self.response.out.write(template.render(path, template_values))
</code>```

index.html file

```<code><html>
<head>
...
<script>
{% if page %}
   alert("test");
{% endif %}
</script>
</head>
<body>

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

Now, instead of using inline

答:
You are either over-complicating a simple situation, or you haven't explained your problem clearly.

If you want to include an externally-located JavaScript file, you would use a
{% endif %}

...

```

<p>and <code>page</code> is not None, the template will render the following HTML to the browser:</p>

```

   <script type="text/javascript" src="/js/foo.js"></script>

...

```

and the browser will try to load the resource pointed to by the

Body:
I am using AppEngine with the webapp framework (python). In my script I am generating javascript code dynamically with Django, for example:

python controller file

template_values = {
    'page': '1',
}

path = os.path.join(os.path.dirname(__file__), "../views/index.html")
self.response.out.write(template.render(path, template_values))

index.html file

...

...

Now, instead of using inline

Body:
You are either over-complicating a simple situation, or you haven't explained your problem clearly.

If you want to include an externally-located JavaScript file, you would use a <script> tag, not <link>.

If you have template code like this:

<html>
<head>
{% if page %}
   <script type="text/javascript" src="/js/foo.js"></script>
{% endif %}
</head>
...
</html>

and page is not None, the template will render the following HTML to the browser:

<html>
<head>
   <script type="text/javascript" src="/js/foo.js"></script>
</head>
...
</html>

and the browser will try to load the resource pointed to by the <script> tag. The browser has no knowledge of how that tag got into the HTML that it loaded.


问:
XDebug configuration missing from php.ini in XAMPP
I've just installed the latest XAMPP for PHP 5.6 from the official website,  and I need to enable Xdebug, I find that the file php_xdebug.dll exists in the C:\xampp\php\ext , but there is no [XDebug] config at all in the php.ini and I have no idea how to make it work. It should be installed by default and pre-configured, we need just to uncomment the xdebug config in php.ini but it's not the case. I even tried to install it again using PECL commmand pecl install xdebug but I get the following error :

```<code>pecl install xdebug
downloading xdebug-2.5.0.tgz ...
Starting to download xdebug-2.5.0.tgz (267,640 bytes)
.........done: 267,640 bytes
ERROR: failed to mkdir C:\php\pear\docs\xdebug\contrib
</code>```

And in PHPStorm when I choose to add the interpreter by selecting the php.exe in the XAMPP directory, it says Debugger : Not installed too.

I re-installed XAMPP, but I still have the same problem.
Thanks in advance.

答:
For more details, you can find a tutorial that explains step by step procedure
php-debugging-with-xdebug-atom-and-xampp

As per this tutorial please follow these steps its works like a charm:

Steps to Install Xdebug:

Download xdebug-2.4.0.tgz

Unpack the downloaded file

```<code># navigate to the downloaded file
$ cd ~/Downloads

$ tar -xvzf xdebug-2.4.0.tgz
$ cd xdebug-2.4.0
</code>```

run phpize

```<code>$ phpize

# example output
Configuring for:
PHP Api Version:         20131106
Zend Module Api No:      20131226
Zend Extension Api No:   220131226

#Error possibilty
Cannot find autoconf. Please check your autoconf installation and the
$PHP_AUTOCONF environment variable. Then, rerun this script.

#In the above error case you need to install autoconf using below command(MAC) and rerun phpize
$ brew install autoconf
</code>```

The phpsize command is used to prepare the build environment for a
PHP extension.

Configure it by run:

```<code>$ ./configure
</code>```

run make

```<code>$ make
</code>```

A successful install will have created xdebug.so file.

Steps to Configure Xdebug:

A successful install will have created xdebug.so and put it into the PHP extensions directory.

You must copy this file to XAMPP php extension directory for that
run:-

```<code>$ sudo cp modules/xdebug.so /Applications/XAMPP/xamppfiles/lib/php/extensions/no-debug-non-zts-20160303
</code>```

Finally update /Applications/XAMPP/xamppfiles/etc/php.ini and add
the following lines to it

```<code>[Xdebug]
zend_extension = /Applications/XAMPP/xamppfiles/lib/php/extensions/no-debug-non-zts-20160303/xdebug.so
xdebug.remote_enable=1
xdebug.remote_connect_back=On
xdebug.remote_port="9000"
xdebug.profiler_enable=0
xdebug.remote_handler=dbgp
xdebug.remote_mode=req
xdebug.remote_autostart=true
</code>```

Restart Apache using XAMPP’s manager-osx

Congratz! You have completed!! To verify you successfully installed & configured XDebug, open the XAMPP phpinfo.php file in a web browser, for example, http://localhost/dashboard/phpinfo.php.

Search for XDebug section in PHPInfo details. If it exists, you successfully have done your installation
OR

In another browser window or tab, open https://xdebug.org/wizard.php and copy the phpinfo.php page content in the first window or tab and paste it into the textbox on the xdebug.org page. Then submit for analysis, it will give a summary of your installation status.

Body:
I've just installed the latest XAMPP for PHP 5.6 from the official website,  and I need to enable Xdebug, I find that the file php_xdebug.dll exists in the C:\xampp\php\ext , but there is no [XDebug] config at all in the php.ini and I have no idea how to make it work. It should be installed by default and pre-configured, we need just to uncomment the xdebug config in php.ini but it's not the case. I even tried to install it again using PECL commmand pecl install xdebug but I get the following error :

pecl install xdebug
downloading xdebug-2.5.0.tgz ...
Starting to download xdebug-2.5.0.tgz (267,640 bytes)
.........done: 267,640 bytes
ERROR: failed to mkdir C:\php\pear\docs\xdebug\contrib

And in PHPStorm when I choose to add the interpreter by selecting the php.exe in the XAMPP directory, it says Debugger : Not installed too.

I re-installed XAMPP, but I still have the same problem.
Thanks in advance.

Body:
For more details, you can find a tutorial that explains step by step procedure
php-debugging-with-xdebug-atom-and-xampp

As per this tutorial please follow these steps its works like a charm:

Steps to Install Xdebug:

Download xdebug-2.4.0.tgz

Unpack the downloaded file

# navigate to the downloaded file
$ cd ~/Downloads

$ tar -xvzf xdebug-2.4.0.tgz
$ cd xdebug-2.4.0

run phpize

$ phpize

# example output
Configuring for:
PHP Api Version:         20131106
Zend Module Api No:      20131226
Zend Extension Api No:   220131226

#Error possibilty
Cannot find autoconf. Please check your autoconf installation and the
$PHP_AUTOCONF environment variable. Then, rerun this script.

#In the above error case you need to install autoconf using below command(MAC) and rerun phpize
$ brew install autoconf

The phpsize command is used to prepare the build environment for a
PHP extension.

Configure it by run:

$ ./configure

run make

$ make

A successful install will have created xdebug.so file.

Steps to Configure Xdebug:

A successful install will have created xdebug.so and put it into the PHP extensions directory.

You must copy this file to XAMPP php extension directory for that
run:-

$ sudo cp modules/xdebug.so /Applications/XAMPP/xamppfiles/lib/php/extensions/no-debug-non-zts-20160303

Finally update /Applications/XAMPP/xamppfiles/etc/php.ini and add
the following lines to it

[Xdebug]
zend_extension = /Applications/XAMPP/xamppfiles/lib/php/extensions/no-debug-non-zts-20160303/xdebug.so
xdebug.remote_enable=1
xdebug.remote_connect_back=On
xdebug.remote_port="9000"
xdebug.profiler_enable=0
xdebug.remote_handler=dbgp
xdebug.remote_mode=req
xdebug.remote_autostart=true

Restart Apache using XAMPP’s manager-osx

Congratz! You have completed!! To verify you successfully installed & configured XDebug, open the XAMPP phpinfo.php file in a web browser, for example, http://localhost/dashboard/phpinfo.php.

Search for XDebug section in PHPInfo details. If it exists, you successfully have done your installation
OR

In another browser window or tab, open https://xdebug.org/wizard.php and copy the phpinfo.php page content in the first window or tab and paste it into the textbox on the xdebug.org page. Then submit for analysis, it will give a summary of your installation status.


问:
String index out of range: -1 within a crowded 'if' statement
I'm running a program that parses the text off of a website and then spell checks a string containing all of the text after it's been cleaned from HTML mark up.

Once the spell checker reaches the end of the string, it returns this this exception.
I saw similar questions which were resolved by setting the index greater than 0 in an "if" statement, but I've been struggling to fix this for some time now and would appreciate some help in figuring this out.

Exception thrown:

```<code>Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: -1
    at java.lang.String.substring(Unknown Source)
    at ParseCleanCheck.checkWord(ParseCleanCheck.java:173)
    at ParseCleanCheck.SpellChecker(ParseCleanCheck.java:101)
</code>```

Java line 173-175 is where the word is stripped of any punctuation marks:

```<code>if (length > 2 && word.substring(length - 2).equals(",\"") || word.substring(length - 2).equals(".\"")
                || word.substring(length - 2).equals("?\"") || word.substring(length - 2).equals("!\"")) {
            unpunctWord = word.substring(0, length - 2);
</code>```

Line 101 is documented below, I've added the relevant surrounding code that might be part of the exception being thrown

```<code>String user_text = "";
user_text = cleanString;
while (!user_text.equalsIgnoreCase("q")) {
                // check if necessary or if cleanString still works
                // PageScanner();
                user_text = cleanString;
                String[] words = user_text.split(" ");

                int error = 0;

                for (String word : words) {
                    suggestWord = true; // ~~~ Line 101 ~~~~
                    String outputWord = checkWord(word);

                    if (suggestWord) {
                        System.out.println("Suggestions for " + word + " are:  " + suggest.correct(outputWord) + "\n");
                        error++;
                    }
                }

                if (error == 0 & !user_text.equalsIgnoreCase("q")) {
                    System.out.println("No mistakes found");
                }
            }

        } catch (IOException e) {
            e.printStackTrace();
            System.exit(-1);
        }
</code>```

答:
Your problem is in if the condition you should change it, you only check if length > 2 for the first condition.

```<code>if (length > 2 && word.substring(length - 2).equals(",\"")
        || word.substring(length - 2).equals(".\"")
        || word.substring(length - 2).equals("?\"")
        || word.substring(length - 2).equals("!\"")) {
            unpunctWord = word.substring(0, length - 2);
</code>```

Change to:

```<code>if (length > 2
        && (word.substring(length - 2).equals(",\"")
        || word.substring(length - 2).equals(".\"")
        || word.substring(length - 2).equals("?\"")
        || word.substring(length - 2).equals("!\""))) {
        unpunctWord = word.substring(0, length - 2);
</code>```

Body:
I'm running a program that parses the text off of a website and then spell checks a string containing all of the text after it's been cleaned from HTML mark up.

Once the spell checker reaches the end of the string, it returns this this exception.
I saw similar questions which were resolved by setting the index greater than 0 in an "if" statement, but I've been struggling to fix this for some time now and would appreciate some help in figuring this out.

Exception thrown:

Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: -1
    at java.lang.String.substring(Unknown Source)
    at ParseCleanCheck.checkWord(ParseCleanCheck.java:173)
    at ParseCleanCheck.SpellChecker(ParseCleanCheck.java:101)

Java line 173-175 is where the word is stripped of any punctuation marks:

if (length > 2 && word.substring(length - 2).equals(",\"") || word.substring(length - 2).equals(".\"")
                || word.substring(length - 2).equals("?\"") || word.substring(length - 2).equals("!\"")) {
            unpunctWord = word.substring(0, length - 2);

Line 101 is documented below, I've added the relevant surrounding code that might be part of the exception being thrown

String user_text = "";
user_text = cleanString;
while (!user_text.equalsIgnoreCase("q")) {
                // check if necessary or if cleanString still works
                // PageScanner();
                user_text = cleanString;
                String[] words = user_text.split(" ");

                int error = 0;

                for (String word : words) {
                    suggestWord = true; // ~~~ Line 101 ~~~~
                    String outputWord = checkWord(word);

                    if (suggestWord) {
                        System.out.println("Suggestions for " + word + " are:  " + suggest.correct(outputWord) + "\n");
                        error++;
                    }
                }

                if (error == 0 & !user_text.equalsIgnoreCase("q")) {
                    System.out.println("No mistakes found");
                }
            }

        } catch (IOException e) {
            e.printStackTrace();
            System.exit(-1);
        }

Body:
Your problem is in if the condition you should change it, you only check if length > 2 for the first condition.

if (length > 2 && word.substring(length - 2).equals(",\"")
        || word.substring(length - 2).equals(".\"")
        || word.substring(length - 2).equals("?\"")
        || word.substring(length - 2).equals("!\"")) {
            unpunctWord = word.substring(0, length - 2);

Change to:

if (length > 2
        && (word.substring(length - 2).equals(",\"")
        || word.substring(length - 2).equals(".\"")
        || word.substring(length - 2).equals("?\"")
        || word.substring(length - 2).equals("!\""))) {
        unpunctWord = word.substring(0, length - 2);


问:
How to set id attribute to table?
I want to create a table with my id to my table with javascript, I am using setAttribute but it is not work, could you please help me?

```<code>var table = $('<table><thead><tr><th>Name</th><th>Age</th><th>Position</th><th>Note</th></tr></thead><tbody></tbody></table>').addClass('table table-bordered table-hover search-table table-striped');
table.setAttribute("id", "myid");
$('#content').html(table);
</code>```

答:
As table is a jQuery object, you need to use .attr(attributeName, value)

```<code>table.attr("id", "myid");
</code>```

Title: How to set id attribute to table?

Body:
I want to create a table with my id to my table with javascript, I am using setAttribute but it is not work, could you please help me?

var table = $('

Name	Age	Position	Note

').addClass('table table-bordered table-hover search-table table-striped');
table.setAttribute("id", "myid");
$('#content').html(table);

Body:
As table is a jQuery object, you need to use .attr(attributeName, value)

table.attr("id", "myid");


问:
Restart kivy-program respectively python with inotify
I fear that my question is a duplicate but I can't find the answer. Maybe you can help me?

I would like to restart my kivy-program if I save the kv or py file.

I tried with

```<code>inotifywait -mq -e close_write /home/name/kivy/ | while read FILE
do
  pkill python
  python /home/name/kivy/main.py
done
</code>```

If I change a file the first time, main.py starts, but if I change it again I need to close the program by hand before it restarts.

Instead of pkill python I also tried to use

```<code>kill $(ps aux | pgrep '[p]ython' | awk '{print $2}')
</code>```

but with the same result and the problem that the mintMenu.py is closing, too.

Should I use something totally different to inotify?

答:
I'm using entr to achieve the same thing. Once installed (e.g. via brew), just run the following command in your work directory /home/name/kivy/:

```<code>find . -name "*.py" -or -name "*.kv" | entr sh -c "pkill -f python main.py ; python main.py &"
</code>```

Body:
I fear that my question is a duplicate but I can't find the answer. Maybe you can help me?

I would like to restart my kivy-program if I save the kv or py file.

I tried with

inotifywait -mq -e close_write /home/name/kivy/ | while read FILE
do
  pkill python
  python /home/name/kivy/main.py
done

If I change a file the first time, main.py starts, but if I change it again I need to close the program by hand before it restarts.

Instead of pkill python I also tried to use

kill $(ps aux | pgrep '[p]ython' | awk '{print $2}')

but with the same result and the problem that the mintMenu.py is closing, too.

Should I use something totally different to inotify?

Body:
I'm using entr to achieve the same thing. Once installed (e.g. via brew), just run the following command in your work directory /home/name/kivy/:

find . -name "*.py" -or -name "*.kv" | entr sh -c "pkill -f python main.py ; python main.py &"