问:
How to compile an image file as icon into an EXE using GTK+ as GUI?
I know how to set up an image as the icon of a GtkWindow.

```<code>GtkWindow * window;
gtk_window_set_icon_from_file(window, "icon.png", NULL);
</code>```

and place icon.png together with the exe.

But what if I don't want to keep that image file in my folder? I want it somehow bundled inside the exe file.

I know this can be done with qrc in Qt. Can I do this in GTK+ too?

答:
Use GResource

An example .gresource.xml might look like:

```<code><?xml version="1.0" encoding="UTF-8"?>
<gresources>
    <gresource prefix="/com/example/myapp">
        <file>icon.png</file>
    </gresource>
</gresources>
</code>```

Then compile it to C:

```<code>glib-compile-resources.exe myapp.gresource.xml --generate-source --target=resources.c
</code>```

And include resources.c in you applications sources

Then to use the embedded file as the window icon:

```<code>gtk_window_set_icon_from_file (window, "resource:///com/example/myapp/icon.png", NULL);
</code>```

Also Consider setting the icon with gtk_window_set_default_icon_from_file to apply it to dialogs as well

Body:
I know how to set up an image as the icon of a GtkWindow.

GtkWindow * window;
gtk_window_set_icon_from_file(window, "icon.png", NULL);

and place icon.png together with the exe.

But what if I don't want to keep that image file in my folder? I want it somehow bundled inside the exe file.

I know this can be done with qrc in Qt. Can I do this in GTK+ too?

Body:
Use GResource

An example .gresource.xml might look like:

<?xml version="1.0" encoding="UTF-8"?>
<gresources>
    <gresource prefix="/com/example/myapp">
        <file>icon.png</file>
    </gresource>
</gresources>

Then compile it to C:

glib-compile-resources.exe myapp.gresource.xml --generate-source --target=resources.c

And include resources.c in you applications sources

Then to use the embedded file as the window icon:

gtk_window_set_icon_from_file (window, "resource:///com/example/myapp/icon.png", NULL);

Also Consider setting the icon with gtk_window_set_default_icon_from_file to apply it to dialogs as well


来源: stackexchange

问:
Get a .tmx file from its .json
I've been using Tiled to create .tmx maps for one of my projects, maps that I export to JSON before using with Phaser.js.

Problem is, a few months ago I mistakenly deleted the .tmx file for the game first map. It's still working fine but now I can't change anything on the first map layout with Tiled because I only have the JSON for it.

I've been looking for an answer with no success so far, but is there a way to convert a .json Tiled map exported from a .tmx file, back to its original format ?

答:
You should be able to simply open the JSON exported map in Tiled, and save it again as a TMX file. To be able to select the file, you may need to change the file type in the Open File dialog.

Btw, you should consider committing your project to a version control system (Git is a popular one), so that such mistakes will not generally lead to loss of data. You don't always get lucky.

ContentLicense: CC BY-SA 3.0

Title: Get a .tmx file from its .json


问:
two subscribe forms on same page with mailchimp
I want to have two mailchimp forms ( linked to the same mailchimp list ) within the same landingpage in a Shopify Store. *it is a long landing page so I want them to be able to subscribe two times along the way.

It seems the second form does not work and the only think it does is refreshing the page. I am pretty sure there is a conflict with their ID´s because the two forms have the same ID ( id="mailchimp" ) but I believe it is neccesary for them to work.

I may have a very easy-to-resolve question but i have been struggling with it for a while. It seems there is no documentation about it ( apart from inserting one of the forms within an iframe -> I am not confortable with this solution because I want to record with GTM ( GA ) customer succesuful submitions etc. ).

The code for the forms ( snippet that it is called two times within the page ):

```<code><!-- Newsletter Section -->
        <section id="services" class="small-section bg-gray-lighter">
            <div class="container relative">
                <form class="form align-center newsdown" id="mailchimp">
                    <div class="row">
                        <div class="col-md-8 col-md-offset-2">
                            <div class="mb-20">
                                <input placeholder="Introduce tu email" class="newsletter-field form-control input-md round mb-xs-10" type="email" pattern=".{5,100}" required/>

                                <button type="submit" class="btn btn-mod btn-border-c btn-medium btn-round mb-xs-10">
                                    Suscribe
                                </button>
                            </div>

                            <div id="subscribe-result"></div>

                        </div>
                    </div>
                </form>

            </div>
        </section>
        <!-- End Newsletter Section -->
</code>```

What can I do to have these two identical forms working on the same page? Have in mind I don't have access to the javascript ( because mailchimp has Shopify app that makes this connection ).

答:
As it appeared there were a conflict with two exact forms ( same javascript etc ) so I implemented the second form differently:</p>

```<code><!-- Newsletter Section -->
    <section id="services" class="small-section bg-gray-lighter">
        <div class="container relative">
             <form action="YOURACTION;id=YOURID" method="post" id="mc-embedded-subscribe-form" name="mc-embedded-subscribe-form" class="validate" target="_blank" novalidate>
                 <div class="row">
                     <div class="col-md-8 col-md-offset-2" style="text-align: center;">
                         <div class="newsletter-label font-alt">
                            ¿Te interesa? Recibe más noticias y tutoriales exclusivos
                            </div>
                            <div class="mb-20">
                                <input name="EMAIL" id="mce-EMAIL" placeholder="Introduce tu email" class="newsletter-field form-control input-md round mb-xs-10 required email" type="email" pattern=".{5,100}" required/>

                                <input type="submit" value="Subscribe" name="subscribe" id="mc-embedded-subscribe" class="button btn btn-mod btn-border-c btn-medium btn-round mb-xs-10">
                            </div>
                  <div id="mce-responses" class="clear">
                      <div class="response" id="mce-error-response" style="display:none"></div>
                      <div class="response" id="mce-success-response" style="display:none"></div>
                  </div>
                  <!-- real people should not fill this in and expect good things - do not remove this or risk form bot signups-->
                  <div style="position: absolute; left: -5000px;" aria-hidden="true"><input type="text" name="b_5307a1008b76c5446a7303622_18658ede2a" tabindex="-1" value=""></div>
                            <div class="form-tip">
                                <i class="fa fa-info-circle"></i> Pocos emails, pero de calidad. Nunca Spam. Te servirán.
                            </div>
                            <div id="subscribe-result"></div>
                        </div>
                    </div>
                </form>
            </div>
        </section>
        <!-- End Newsletter Section -->

<script type='text/javascript' src='//s3.amazonaws.com/downloads.mailchimp.com/js/mc-validate.js'></script><script type='text/javascript'>(function($) {window.fnames = new Array(); window.ftypes = new Array();fnames[0]='EMAIL';ftypes[0]='email';fnames[1]='FNAME';ftypes[1]='text';fnames[2]='LNAME';ftypes[2]='text';fnames[3]='MMERGE3';ftypes[3]='dropdown';fnames[4]='MMERGE4';ftypes[4]='phone';fnames[5]='MMERGE5';ftypes[5]='url';fnames[7]='MMERGE7';ftypes[7]='text';fnames[6]='MMERGE6';ftypes[6]='birthday';fnames[8]='MMERGE8';ftypes[8]='text';fnames[9]='MMERGE9';ftypes[9]='radio';}(jQuery));var $mcj = jQuery.noConflict(true);</script>
<!--End mc_embed_signup-->
</code>```

Body:
I want to have two mailchimp forms ( linked to the same mailchimp list ) within the same landingpage in a Shopify Store. *it is a long landing page so I want them to be able to subscribe two times along the way.

It seems the second form does not work and the only think it does is refreshing the page. I am pretty sure there is a conflict with their ID´s because the two forms have the same ID ( id="mailchimp" ) but I believe it is neccesary for them to work.

I may have a very easy-to-resolve question but i have been struggling with it for a while. It seems there is no documentation about it ( apart from inserting one of the forms within an iframe -> I am not confortable with this solution because I want to record with GTM ( GA ) customer succesuful submitions etc. ).

The code for the forms ( snippet that it is called two times within the page ):

                <form class="form align-center newsdown" id="mailchimp">

                                <input placeholder="Introduce tu email" class="newsletter-field form-control input-md round mb-xs-10" type="email" pattern=".{5,100}" required/>

                                <button type="submit" class="btn btn-mod btn-border-c btn-medium btn-round mb-xs-10">
                                    Suscribe
                                </button>

                </form>

What can I do to have these two identical forms working on the same page? Have in mind I don't have access to the javascript ( because mailchimp has Shopify app that makes this connection ).

Body:
As it appeared there were a conflict with two exact forms ( same javascript etc ) so I implemented the second form differently:

<!-- Newsletter Section -->
    <section id="services" class="small-section bg-gray-lighter">
        <div class="container relative">
             <form action="YOURACTION;id=YOURID" method="post" id="mc-embedded-subscribe-form" name="mc-embedded-subscribe-form" class="validate" target="_blank" novalidate>
                 <div class="row">
                     <div class="col-md-8 col-md-offset-2" style="text-align: center;">
                         <div class="newsletter-label font-alt">
                            ¿Te interesa? Recibe más noticias y tutoriales exclusivos
                            </div>
                            <div class="mb-20">
                                <input name="EMAIL" id="mce-EMAIL" placeholder="Introduce tu email" class="newsletter-field form-control input-md round mb-xs-10 required email" type="email" pattern=".{5,100}" required/>

                                <input type="submit" value="Subscribe" name="subscribe" id="mc-embedded-subscribe" class="button btn btn-mod btn-border-c btn-medium btn-round mb-xs-10">
                            </div>
                  <div id="mce-responses" class="clear">
                      <div class="response" id="mce-error-response" style="display:none"></div>
                      <div class="response" id="mce-success-response" style="display:none"></div>
                  </div>
                  <!-- real people should not fill this in and expect good things - do not remove this or risk form bot signups-->
                  <div style="position: absolute; left: -5000px;" aria-hidden="true"><input type="text" name="b_5307a1008b76c5446a7303622_18658ede2a" tabindex="-1" value=""></div>
                            <div class="form-tip">
                                <i class="fa fa-info-circle"></i> Pocos emails, pero de calidad. Nunca Spam. Te servirán.
                            </div>
                            <div id="subscribe-result"></div>
                        </div>
                    </div>
                </form>
            </div>
        </section>
        <!-- End Newsletter Section -->

<script type='text/javascript' src='//s3.amazonaws.com/downloads.mailchimp.com/js/mc-validate.js'></script><script type='text/javascript'>(function($) {window.fnames = new Array(); window.ftypes = new Array();fnames[0]='EMAIL';ftypes[0]='email';fnames[1]='FNAME';ftypes[1]='text';fnames[2]='LNAME';ftypes[2]='text';fnames[3]='MMERGE3';ftypes[3]='dropdown';fnames[4]='MMERGE4';ftypes[4]='phone';fnames[5]='MMERGE5';ftypes[5]='url';fnames[7]='MMERGE7';ftypes[7]='text';fnames[6]='MMERGE6';ftypes[6]='birthday';fnames[8]='MMERGE8';ftypes[8]='text';fnames[9]='MMERGE9';ftypes[9]='radio';}(jQuery));var $mcj = jQuery.noConflict(true);</script>
<!--End mc_embed_signup-->

ContentLicense: CC BY-SA 4.0


问:
How can I scrape all articles from a website (including possibly via an RSS reader)?
Please excuse my ignorance, I'm a regular computer user and have zero knowledge about programming. Anyway, my question is:

Is there a way to obtain (i.e. probably 'scrape' in programming lingo) all articles posted on a particular tech news website? I'd like the output (headline and article and possibly date and author) to ideally come up as plain text so that I can use it in a corpus tool called AntConc as part of my personal and not-for-profit research.

In fact, it would be super convenient if I could do it via my RSS feed reader (feedly or inoreader) for quite a few websites, but that's probably asking for too much, so 'one-by-one' scraping would be fine, too.

Would something like Portia do the trick? Please bear in mind that I know nothing about python, etc. and I need whatever method there is to be very, very simple and straightforward.

Thank you

答:
Yes it's very possible to load data like these from other websites provided they support the feature. In java/android we would just create a simple app that loads the data as Json and then parse it into views like listviews, imageviews etc using adapters,and maybe store in cache.

But here's a great and free course on Udemy you can quickly check it your dream solution

https://www.udemy.com/how-to-make-an-app-build-an-app-business-rss-feed-news-apps/

Or if you have up to $19 for a automatic, high quality RSS reader app without coding at all then you can check out
http://www.shoutem.com/app/rss-feed

Or less quality, simple but free
http://www.appsgeyser.com/create-rss-app/

But it's always best to find a little time and make the app or employ services of a developer


问:
How to refresh dataTable with setInterval?
I have project that need to refresh dataTable every 1 minute, I already code the php and the setInterval. The table shown nicely but the refresh with setInterval look doesn't work. I don't know whats the problem.

Here is my tableSpa.php:

```<code><?php
class x{
    function koneksi(){
        $serverName = "DESKTOP-49HH41E\SA";
        $conn = new PDO("sqlsrv:server=$serverName; Database=tebu", "sa", "sa12345");

        return $conn;
    }

    function get_hari(){
        date_default_timezone_set('Asia/Jakarta');
        return date("j F Y G:i:s");
    }

    function KueriSql(){
        $query = "SELECT     TOP (100) PERCENT a.KD_KT, a.DESA, a.NM_KUD, a.AFDL, a.kd_wil, a.kd_rayon, a.Rayon, a.KETUA,   ISNULL(MAX(b.libur), 0) AS Libur, ISNULL(MAX(b.aktif), 0) AS Aktif,
                          (SELECT     ISNULL(SUM(tambahan), 0) AS Tambahan
                            FROM          dbo.tblAlokasiSPTAA AS c
                            WHERE      (kd_kt = a.KD_KT) AND (tambahan <> 0) AND (tgl = '2017-05-28')) AS Tambahan, COUNT(d.spa) AS TotalCetak,
                          (SELECT     ISNULL(COUNT(spa), 0) AS Pemasukan
                            FROM          dbo.vSPATrimaGawang AS e
                            WHERE      (LEFT(Kdptn, 5) = a.KD_KT) AND (tglberlaku = '2017-05-28 23:59:59')) AS Pemasukan,
                          (SELECT     ISNULL(COUNT(spa), 0) AS SPTAMati
                            FROM          dbo.vSPTAMati AS f
                            WHERE      (LEFT(Kdptn, 5) = a.KD_KT) AND (tglberlaku = '2017-05-28 23:59:59')) AS SPTAMati
                        FROM         dbo.vM_KEL AS a LEFT OUTER JOIN
                                              dbo.TblJatahSPTA AS b ON a.KD_KT = b.kd_kt LEFT OUTER JOIN
                                              dbo.tblSPA AS d ON a.KD_KT = LEFT(d.Kdptn, 5) AND d.tglberlaku = '2017-05-28 23:59:59'
                    GROUP BY a.KD_KT, a.DESA, a.NM_KUD, a.AFDL, a.kd_wil, a.kd_rayon, a.Rayon, a.KETUA
                    ORDER BY a.KD_KT";

        $stmt = $this->koneksi()->prepare($query);
        $stmt->execute();

        $hasil = $stmt->fetchAll();
        return $hasil;
    }

    public $arr = array();
    public $arrX=0;

    function tampil_kueri(){

        foreach ($this->KueriSql() as $row) {

            $this->arr[$this->arrX][0] = $this->arrX;
            $this->arr[$this->arrX][1] = $row['KD_KT'];
            $this->arr[$this->arrX][2] = $row['KETUA'];
            $this->arr[$this->arrX][3] = $row['AFDL'];
            $this->arr[$this->arrX][4] = $row['Tambahan'];
            $this->arr[$this->arrX][5] = $row['TotalCetak'];
            $this->arr[$this->arrX][6] = $row['Pemasukan'];
            $this->arr[$this->arrX][7] = $row['SPTAMati'];

            $this->arrX++;
        }
    }

    function tampil_data(){
        for ($baris=0; $baris < $this->arrX; $baris++) {
                            echo "<tr>";

                        for ($kolom=0; $kolom < 8; $kolom++) {
                            echo "<td>".$this->arr[$baris][$kolom]."</td>";
                        }
                        echo "</tr>";
                    }
    }
}

$obj = new x();

if($obj->koneksi()){
    echo "Koneksi Datbase SQL SERVER Berhasil";
    $obj->tampil_kueri();

}

?>

<!DOCTYPE html>
<html>
<head>

<script type="text/javascript" src="assets/DataTables/media/js/jquery.js"></script>
    <script type="text/javascript" src="assets/DataTables/media/js/jquery.dataTables.js"></script>
    <link rel="stylesheet" type="text/css" href="assets/css/bootstrap.css">
    <link rel="stylesheet" type="text/css" href="assets/DataTables/media/css/jquery.dataTables.css">
    <link rel="stylesheet" type="text/css" href="assets/DataTables/media/css/dataTables.bootstrap.css">
</head>
<body>
    <center>

<h1>Tabel SPTA<br><?php echo $obj->get_hari();?></h1>
</center>
<br/>
<br/>
<div class="container-fluid">
    <div class="table-responsive">
    <table border = '0' class="table table-striped table-bordered data" id="tabelSpta">
        <thead>
            <tr>
                <th>No.</th>
                <th>Kode_KT</th>
                <th>Nama_KT</th>
                <th>Afdeling</th>
                <th>Tambahan</th>
                <th>Total Cetak</th>
                <th>Pemasukan</th>
                <th>SPTA Mati</th>

            </tr>
        </thead>
        <tbody>

            <?php echo $obj->tampil_data();         ?>

        </tbody>
    </table>
</div>
</div>
</body>
<script type="text/javascript">

$(document).ready(function(){
        var tabel = $('.data').DataTable();
    });

    setInterval(function () {
      tabel.ajax.reload();
  }, 60000);
</script>
</html>
</code>```

答:
Use fnReloadAjax() instead of ajax.reload().
You need to add jquery plugin //cdn.datatables.net/plug-ins/1.10.15/api/fnReloadAjax.js after script jquery.dataTables.js into  tag.

Change

```<code>setInterval(function () {
      tabel.ajax.reload();
}, 60000);
</code>```

To

```<code>setInterval(function () {
      tabel.fnReloadAjax();
}, 60000);
</code>```

Body:
I have project that need to refresh dataTable every 1 minute, I already code the php and the setInterval. The table shown nicely but the refresh with setInterval look doesn't work. I don't know whats the problem.

Here is my tableSpa.php:

<?php
class x{
    function koneksi(){
        $serverName = "DESKTOP-49HH41E\SA";
        $conn = new PDO("sqlsrv:server=$serverName; Database=tebu", "sa", "sa12345");

        return $conn;
    }

    function get_hari(){
        date_default_timezone_set('Asia/Jakarta');
        return date("j F Y G:i:s");
    }

    function KueriSql(){
        $query = "SELECT     TOP (100) PERCENT a.KD_KT, a.DESA, a.NM_KUD, a.AFDL, a.kd_wil, a.kd_rayon, a.Rayon, a.KETUA,   ISNULL(MAX(b.libur), 0) AS Libur, ISNULL(MAX(b.aktif), 0) AS Aktif,
                          (SELECT     ISNULL(SUM(tambahan), 0) AS Tambahan
                            FROM          dbo.tblAlokasiSPTAA AS c
                            WHERE      (kd_kt = a.KD_KT) AND (tambahan <> 0) AND (tgl = '2017-05-28')) AS Tambahan, COUNT(d.spa) AS TotalCetak,
                          (SELECT     ISNULL(COUNT(spa), 0) AS Pemasukan
                            FROM          dbo.vSPATrimaGawang AS e
                            WHERE      (LEFT(Kdptn, 5) = a.KD_KT) AND (tglberlaku = '2017-05-28 23:59:59')) AS Pemasukan,
                          (SELECT     ISNULL(COUNT(spa), 0) AS SPTAMati
                            FROM          dbo.vSPTAMati AS f
                            WHERE      (LEFT(Kdptn, 5) = a.KD_KT) AND (tglberlaku = '2017-05-28 23:59:59')) AS SPTAMati
                        FROM         dbo.vM_KEL AS a LEFT OUTER JOIN
                                              dbo.TblJatahSPTA AS b ON a.KD_KT = b.kd_kt LEFT OUTER JOIN
                                              dbo.tblSPA AS d ON a.KD_KT = LEFT(d.Kdptn, 5) AND d.tglberlaku = '2017-05-28 23:59:59'
                    GROUP BY a.KD_KT, a.DESA, a.NM_KUD, a.AFDL, a.kd_wil, a.kd_rayon, a.Rayon, a.KETUA
                    ORDER BY a.KD_KT";

        $stmt = $this->koneksi()->prepare($query);
        $stmt->execute();

        $hasil = $stmt->fetchAll();
        return $hasil;
    }

    public $arr = array();
    public $arrX=0;

    function tampil_kueri(){

        foreach ($this->KueriSql() as $row) {

            $this->arr[$this->arrX][0] = $this->arrX;
            $this->arr[$this->arrX][1] = $row['KD_KT'];
            $this->arr[$this->arrX][2] = $row['KETUA'];
            $this->arr[$this->arrX][3] = $row['AFDL'];
            $this->arr[$this->arrX][4] = $row['Tambahan'];
            $this->arr[$this->arrX][5] = $row['TotalCetak'];
            $this->arr[$this->arrX][6] = $row['Pemasukan'];
            $this->arr[$this->arrX][7] = $row['SPTAMati'];

            $this->arrX++;
        }
    }

    function tampil_data(){
        for ($baris=0; $baris < $this->arrX; $baris++) {
                            echo "
";

                        for ($kolom=0; $kolom < 8; $kolom++) {
                            echo "".$this->arr[$baris][$kolom]."	";
                        }
                        echo "
";
                    }
    }
}

$obj = new x();

if($obj->koneksi()){
    echo "Koneksi Datbase SQL SERVER Berhasil";
    $obj->tampil_kueri();

}

?>

<!DOCTYPE html>

    <link rel="stylesheet" type="text/css" href="assets/css/bootstrap.css">
    <link rel="stylesheet" type="text/css" href="assets/DataTables/media/css/jquery.dataTables.css">
    <link rel="stylesheet" type="text/css" href="assets/DataTables/media/css/dataTables.bootstrap.css">

Tabel SPTA
<?php echo $obj->get_hari();?>

                No.
                Kode_KT
                Nama_KT
                Afdeling
                Tambahan
                Total Cetak
                Pemasukan
                SPTA Mati

            <?php echo $obj->tampil_data();         ?>

Body:
Use fnReloadAjax() instead of ajax.reload().
You need to add jquery plugin //cdn.datatables.net/plug-ins/1.10.15/api/fnReloadAjax.js after script jquery.dataTables.js into <head> tag.

Change

setInterval(function () {
      tabel.ajax.reload();
}, 60000);

To

setInterval(function () {
      tabel.fnReloadAjax();
}, 60000);


问:
if a number is divisible by all the entries of a list then
This came up while attempting Problem 5 of Project Euler, I'm sorry if this is vague or obvious I am new to programming.

Suppose I have a list of integers

v = range(1,n) = [1, ..., n]

What I want to do is this:

if m is divisible by all the entries of v then I want to set

m/v[i]  for i starting at 2 and iterating up

then I want to keep repeating this process until I eventually get something which is not divisible by all the entries of v.

Here is a specific example:

let v=[1,2,3,4] and m = 24

m is divisible by 1, 2, 3, and 4, so we divide m by 2 giving us

m=12 which is divisible by 1, 2, 3, and 4 , so we divide by 3

giving us m=4 which is not divisible by 1, 2, 3, and 4. So we stop here.

Is there a way to do this in python using a combination of loops?

答:
Try this out of size, have a feeling this is what you were asking for:

```<code>v = [1,2,3,4]
m = 24

cont = True
c = 1
d = m

while cont:
    d = d/c
    for i in v:
        if d % i != 0:
            cont = False
            result = d
            break
    c+=1

print (d)
</code>```

Got an output of 4.

Body:
Try this out of size, have a feeling this is what you were asking for:

v = [1,2,3,4]
m = 24

cont = True
c = 1
d = m

while cont:
    d = d/c
    for i in v:
        if d % i != 0:
            cont = False
            result = d
            break
    c+=1

print (d)

Got an output of 4.


问:
Iterate on a range of iterable
I have interface that returns a iterable object.
I need to iterate on the first 1000 items of it.
What is the best way to combine iterating using Iterator and stop after a certain count is reached.

Thanks

答:
What is your language?

C#:

```<code>using System.Linq;
//...
foreach (var item in iface.GetIterable().Take(1000))
{
    //...
}
</code>```

Python:

```<code>import itertools
#...
for item in itertools.islice(iface.get_iterable(), 1000):
    #...
</code>```

ContentLicense: CC BY-SA 2.5

Title: Iterate on a range of iterable

Body:
What is your language?

C#:

using System.Linq;
//...
foreach (var item in iface.GetIterable().Take(1000))
{
    //...
}

Python:

import itertools
#...
for item in itertools.islice(iface.get_iterable(), 1000):
    #...


问:
How to connect Node.js and PHP server using SocketIO
How to send data from node server to PHP server(Apache) using Socket.io

Server Side:

```<code>var socket = require( 'socket.io' );
var http = require( 'http' );

var io = require('socket.io').listen(8080);

io.sockets.on('connection', function (socket) {
  console.log('user connected!');
</code>```

Client Side (PHP SERVER, Javascript code):

```<code>var socket = io.connect( 'http://localhost:8080' );

$( "#messageForm" ).submit( function() {
    var nameVal = $( "#nameInput" ).val();
    var msg = $( "#messageInput" ).val();
    socket.emit( 'message', { name: nameVal, message: msg } );
    });

    return false;
});

socket.on( 'message', function( data ) {
    var actualContent = $( "#messages" ).html();
    var newMsgContent = '<li> <strong>' + data.name + '</strong> : ' + data.message + '</li>';
    var content = newMsgContent + actualContent;

    $( "#messages" ).html( content );
});

  socket.on('foo', function (data) {
    console.log('here we are in action event and data is: ' + data);
  });
});
</code>```

答: use localhost:8080 as url instead of 127.0.0.1:8080</p>

Body:
How to send data from node server to PHP server(Apache) using Socket.io

Server Side:

var socket = require( 'socket.io' );
var http = require( 'http' );

var io = require('socket.io').listen(8080);

io.sockets.on('connection', function (socket) {
  console.log('user connected!');

Client Side (PHP SERVER, Javascript code):

var socket = io.connect( 'http://localhost:8080' );

$( "#messageForm" ).submit( function() {
    var nameVal = $( "#nameInput" ).val();
    var msg = $( "#messageInput" ).val();
    socket.emit( 'message', { name: nameVal, message: msg } );
    });

    return false;
});

socket.on( 'message', function( data ) {
    var actualContent = $( "#messages" ).html();
    var newMsgContent = '
 ' + data.name + ' : ' + data.message + '
';
    var content = newMsgContent + actualContent;

    $( "#messages" ).html( content );
});

  socket.on('foo', function (data) {
    console.log('here we are in action event and data is: ' + data);
  });
});


问:
Absolutely confused, how come this particular query is not working?
I do not understand because I can delete comments so far. However, when I attempt to update them, it does not update in the database. What is even more shocking to me is there are no error messages explaining why. Is there a particular reason for this?</p>

```<code><table class="table table-bordered table-hover">
                    <thead>
                        <tr>
                            <td>Id</td>
                            <td>Post Author</td>
                            <td>Author Email</td>
                            <td>Post Content</td>
                            <td>In Response To</td>
                            <td>Post Status</td>
                            <td>Date</td>
                            <td>Approve</td>
                            <td>Disapprove</td>
                        </tr>
                    </thead>
                    <tbody>
                        <?php

                        if(isset($_GET['delete'])) {

                            $comId = $_GET['delete'];

                            $deleteComment = $conn->prepare("
                            DELETE FROM comments
                            WHERE comment_id = ?
                            ");
                            $deleteComment->bind_param("i", $comId);
                            $deleteComment->execute();
                            $deleteComment->close();

                        }

                        if(isset($_GET['approve'])) {
                            $comIdApp = $_GET['approve'];
                            $approveStat = 'approved';

                            $approveComment = $conn->prepare("
                            UPDATE comments
                            SET comment_status = ?
                            WHERE comment_id = ?
                            ");
                            $approveComment->bind_param("si", $approveStat, $commIdApp);
                            $approveComment->execute();
                            $approveComment->close();

                        }

                        ?>
                        <?php
                        $post_output = $conn->query("SELECT * FROM comments");

                        while($row = $post_output->fetch_assoc()) {

                            $commentId = $row['comment_id'];
                            $postCommentId = $row['post_comment_id'];
                            $commentAuthor = $row['comment_author'];
                            $authorEmail = $row['author_email'];
                            $commentContent = $row['comment_content'];
                            $commentStatus = $row['comment_status'];
                            $commentDate = $row['comment_date'];

                        ?>
                            <tr>
                            <td><?php echo($commentId); ?></td>
                            <td><?php echo($commentAuthor); ?></td>
                            <td><?php echo($authorEmail); ?></td>
                            <td><?php echo($commentContent); ?></td>

                            <?php
                            $postCommentRelate = $conn->query("SELECT * FROM posts WHERE post_id = {$postCommentId}");

                            while($row = $postCommentRelate->fetch_assoc()) {
                                $postTitle = $row['post_title'];
                            ?>

                            <td><?php echo($postTitle); ?></td>

                            <?php } ?>

                            <td><?php echo($commentStatus); ?></td>
                            <td><?php echo($commentDate); ?></td>
                            <td><a href='admin_comments.php?approve=<?php echo($commentId); ?>'>Approve</a></td>
                            <td><a href='admin_comments.php?disapprove=<?php echo($commentId); ?>'>Disapprove</a></td>
                            <td><a href="admin_comments.php?delete=<?php echo($commentId); ?>">DELETE</a></td>
                            <td><a href=''>EDIT</a></td>
                            </tr>
                        <?php } ?>
                    </tbody>
                </table>
</code>```

答:
Your variables are spelled differently $comIdApp vs $commIdApp</p>

```<code>$comIdApp = $_GET['approve'];
$approveStat = 'approved';

$approveComment = $conn->prepare("UPDATE comments SET comment_status = ? WHERE comment_id = ?");
$approveComment->bind_param("si", $approveStat, $commIdApp);
</code>```

Body:
I do not understand because I can delete comments so far. However, when I attempt to update them, it does not update in the database. What is even more shocking to me is there are no error messages explaining why. Is there a particular reason for this?

                            Id
                            Post Author
                            Author Email
                            Post Content
                            In Response To
                            Post Status
                            Date
                            Approve
                            Disapprove

                        <?php

                        if(isset($_GET['delete'])) {

                            $comId = $_GET['delete'];

                            $deleteComment = $conn->prepare("
                            DELETE FROM comments
                            WHERE comment_id = ?
                            ");
                            $deleteComment->bind_param("i", $comId);
                            $deleteComment->execute();
                            $deleteComment->close();

                        }

                        if(isset($_GET['approve'])) {
                            $comIdApp = $_GET['approve'];
                            $approveStat = 'approved';

                            $approveComment = $conn->prepare("
                            UPDATE comments
                            SET comment_status = ?
                            WHERE comment_id = ?
                            ");
                            $approveComment->bind_param("si", $approveStat, $commIdApp);
                            $approveComment->execute();
                            $approveComment->close();

                        }

                        ?>
                        <?php
                        $post_output = $conn->query("SELECT * FROM comments");

                        while($row = $post_output->fetch_assoc()) {

                            $commentId = $row['comment_id'];
                            $postCommentId = $row['post_comment_id'];
                            $commentAuthor = $row['comment_author'];
                            $authorEmail = $row['author_email'];
                            $commentContent = $row['comment_content'];
                            $commentStatus = $row['comment_status'];
                            $commentDate = $row['comment_date'];

                        ?>

                            <?php echo($commentId); ?>
                            <?php echo($commentAuthor); ?>
                            <?php echo($authorEmail); ?>
                            <?php echo($commentContent); ?>

                            <?php
                            $postCommentRelate = $conn->query("SELECT * FROM posts WHERE post_id = {$postCommentId}");

                            while($row = $postCommentRelate->fetch_assoc()) {
                                $postTitle = $row['post_title'];
                            ?>

                            <?php echo($postTitle); ?>

                            <?php } ?>

                            <?php echo($commentStatus); ?>
                            <?php echo($commentDate); ?>
                            <a href='admin_comments.php?approve=<?php echo($commentId); ?>'>Approve
                            <a href='admin_comments.php?disapprove=<?php echo($commentId); ?>'>Disapprove
                            <a href="admin_comments.php?delete=<?php echo($commentId); ?>">DELETE
                            EDIT

                        <?php } ?>

Body:
Your variables are spelled differently $comIdApp vs $commIdApp

$comIdApp = $_GET['approve'];
$approveStat = 'approved';

$approveComment = $conn->prepare("UPDATE comments SET comment_status = ? WHERE comment_id = ?");
$approveComment->bind_param("si", $approveStat, $commIdApp);


问:
Perl, how to read argv as hash?
So, I've read some guides about how to use Getopt::Long and similar libs to work with argv options, and still has no clue how to use it properly because of totally unclear (as for me) documentation and guides.

I have a script. It has next arguments:
-qp,
-pr,
-rp,
-vr, and most of them are for filenames.

Currently I have this use of Getopt::Long, which I find unsuitable because I need to check what is after option every time:

```<code>for(my $i = 0; $i < @ARGV; $i+=2){
    if ($ARGV[$i] eq "-qp"){
        unless ($ARGV[$i+1] eq "-vr" or $ARGV[$i+1] eq "-pr" or $ARGV[$i+1] eq "-rp"){
            $query_params = $ARGV[$i+1];
        }
    }
    elsif ($ARGV[$i] eq "-pr"){
        unless ($ARGV[$i+1] eq "-qp" or $ARGV[$i+1] eq "-pr" or $ARGV[$i+1] eq "-rp"){
            $params = $ARGV[$i+1];
        }
    }
    elsif ($ARGV[$i] eq "-vr"){
        unless ($ARGV[$i+1] eq "-vr" or $ARGV[$i+1] eq "-qp" or $ARGV[$i+1] eq "-rp"){
            $variables = $ARGV[$i+1];
        }
    }
    elsif ($ARGV[$i] eq "-rp"){
        unless ($ARGV[$i+1] eq "-qp" or $ARGV[$i+1] eq "-pr" or $ARGV[$i+1] eq "-vr"){
            $replace = $ARGV[$i+1];
        }
    }
}
</code>```

Maybe I don't need to use exact Getopt libs for Unix, I need just to pass some args to script. Is there any way to make it more simple and correct?

答:
A quick example from the docs of Getopt::Long.

You could now call this script with script --qp=file1 --pr=file2 --rp=file2

What Getopt:Long does for you is sort out the values given on command line to where you tell it to put them, as well as some basic validation (the =s here means you're expecting a string).

If you want to check, for example, that the given files exist, you need to do that by hand.

```<code>use strict;
use warnings;

use Getopt::Long;

my ($qp,$pr,$rp);
my $verbose;

GetOptions (
    "qp=s" => \$qp,
    "pr=s" => \$pr,
    "rp=s" => \$rp,
    "verbose" => \$verbose,
) or die "Error in command line arguments";

print "Being verbose.\n" if $verbose;

# Quick check all are there if they're all required (?)
die "qp,pr and rp are required!" if grep{ !$_ }($qp,$pr,$rp);

for my $fn ( $qp,$pr,$rp ){
    die "Cannot find file '$fn'" unless -f $fn;
}

print "you've given: qp $qp, pr $pr, rp $rp.\n";
</code>```

Title: Perl, how to read argv as hash?

Body:
So, I've read some guides about how to use Getopt::Long and similar libs to work with argv options, and still has no clue how to use it properly because of totally unclear (as for me) documentation and guides.

I have a script. It has next arguments:
-qp,
-pr,
-rp,
-vr, and most of them are for filenames.

Currently I have this use of Getopt::Long, which I find unsuitable because I need to check what is after option every time:

for(my $i = 0; $i < @ARGV; $i+=2){
    if ($ARGV[$i] eq "-qp"){
        unless ($ARGV[$i+1] eq "-vr" or $ARGV[$i+1] eq "-pr" or $ARGV[$i+1] eq "-rp"){
            $query_params = $ARGV[$i+1];
        }
    }
    elsif ($ARGV[$i] eq "-pr"){
        unless ($ARGV[$i+1] eq "-qp" or $ARGV[$i+1] eq "-pr" or $ARGV[$i+1] eq "-rp"){
            $params = $ARGV[$i+1];
        }
    }
    elsif ($ARGV[$i] eq "-vr"){
        unless ($ARGV[$i+1] eq "-vr" or $ARGV[$i+1] eq "-qp" or $ARGV[$i+1] eq "-rp"){
            $variables = $ARGV[$i+1];
        }
    }
    elsif ($ARGV[$i] eq "-rp"){
        unless ($ARGV[$i+1] eq "-qp" or $ARGV[$i+1] eq "-pr" or $ARGV[$i+1] eq "-vr"){
            $replace = $ARGV[$i+1];
        }
    }
}

Maybe I don't need to use exact Getopt libs for Unix, I need just to pass some args to script. Is there any way to make it more simple and correct?

Body:
A quick example from the docs of Getopt::Long.

You could now call this script with script --qp=file1 --pr=file2 --rp=file2

What Getopt:Long does for you is sort out the values given on command line to where you tell it to put them, as well as some basic validation (the =s here means you're expecting a string).

If you want to check, for example, that the given files exist, you need to do that by hand.

use strict;
use warnings;

use Getopt::Long;

my ($qp,$pr,$rp);
my $verbose;

GetOptions (
    "qp=s" => \$qp,
    "pr=s" => \$pr,
    "rp=s" => \$rp,
    "verbose" => \$verbose,
) or die "Error in command line arguments";

print "Being verbose.\n" if $verbose;

# Quick check all are there if they're all required (?)
die "qp,pr and rp are required!" if grep{ !$_ }($qp,$pr,$rp);

for my $fn ( $qp,$pr,$rp ){
    die "Cannot find file '$fn'" unless -f $fn;
}

print "you've given: qp $qp, pr $pr, rp $rp.\n";


问:
How can I select the first specific inner element?
Here is my HTML?

```<code><ul>
    <li>
        <a href="./link1">
            <div>something</div>
            <span><a href="./link2">link</a></span>
        </a>
    </li>
</ul>
</code>```

And this is my jQuery code:

```<code>$('li').on('click', function(){
    var link = $(this).find('a').attr('href');
})
</code>```

As you see, there is two  tags. And .find() refersh to both of them. While I just want to select the  which is right inside (one level) in the
 tag. So expected result is ./link.

What alternative should I use instead of .find() ?

答:
Don't do so. How is the browser meant to know which link to follow? It'd be invalid HTML

I suggest you using this instead:

```<code><a href="page1">start</a><a href="page2">middle</a><a href="page1">end</a>
</code>```

As you can see start and end are linked to page1 but the middle points to page2.

Body:
Here is my HTML?

something

            link

And this is my jQuery code:

$('li').on('click', function(){
    var link = $(this).find('a').attr('href');
})

As you see, there is two  tags. And .find() refersh to both of them. While I just want to select the  which is right inside (one level) in the
 tag. So expected result is ./link.

What alternative should I use instead of .find() ?

Body:
Don't do so. How is the browser meant to know which link to follow? It'd be invalid HTML

I suggest you using this instead:

<a href="page1">start</a><a href="page2">middle</a><a href="page1">end</a>

As you can see start and end are linked to page1 but the middle points to page2.


问:
Is it possible to deploy just one function in an Azure function app when there are multiple functions?
I'm setting up a deployment pipeline for a new Azure function that I'm creating. As we already use TeamCity and Octopus deploy at work for deployments, I'm thinking of using the KUDU REST API to deploy the Azure function as detailed here where the Powershell commands are run from Octopus deploy.

As Azure functions reside in an Azure function app and an app can have multiple functions, is it possible to just deploy one function within the app at a time?

答:
I think @Mikhail's answer is more about "is it possible to have a function app with only one function?", while the question is probably more "is it possible to individually deploy a function even if there are already others?".

And the answer is that it is possible if you use the Kudu zip controller, since you can aim it at any folder you want. So if you deploy to /api/zip/site/wwwroot/MyFunc1/, you only affect that one function.

One thing to be aware of: the zip controller does not propagate deletions. So if you publish a file with a function, and later publish a new zip without it for that same function, the file will remain. msdeploy can be used instead as it supports this.


问:
Unable to move and animate an ImageView along a path in Android using ObjectAnimator
I'm trying to move an ImageView along a path using ObjectAnimator. I'm facing an NPE. Here's the code I'm trying.

```<code>path = new Path();
path.moveTo((float)(maxX/2)+(maxX/4),maxY/4);
path.quadTo((float)(maxX/2)+(maxX/4),maxY/4, (float)(maxX/2)+(maxX/4)+30,maxY/2);

ObjectAnimator animator = new ObjectAnimator();
        animator.ofFloat(img,View.X,View.Y,path);
        animator.setDuration(1000);
        animator.setStartDelay(600);
        animator.start();
</code>```

The exception is :

```<code>Caused by: java.lang.NullPointerException: Attempt to get length of null array
at android.animation.ValueAnimator.initAnimation(ValueAnimator.java:534)
at android.animation.ObjectAnimator.initAnimation(ObjectAnimator.java:880)
at android.animation.ValueAnimator.setCurrentFraction(ValueAnimator.java:610)
at android.animation.ValueAnimator.setCurrentPlayTime(ValueAnimator.java:589)
at android.animation.ValueAnimator.start(ValueAnimator.java:1106)
at android.animation.ValueAnimator.start(ValueAnimator.java:1117)
at android.animation.ObjectAnimator.start(ObjectAnimator.java:852)
at com.example.user.curveanimation.MainActivity.onCreate(MainActivity.java:48)
at android.app.Activity.performCreate(Activity.java:6251)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1108)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2403)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2510)
at android.app.ActivityThread.-wrap11(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1363)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5461)
at java.lang.reflect.Method.invoke(Native Method)
</code>```

If there's anything I'm doing wrong, Can somebody please help me animate via a path. SOmebody, Please help! Thanks.

答:
I have animated ImageButton1     </p>

```<code>TranslateAnimation a = new TranslateAnimation(0, amountToMove, 0, 0);
                            a.setDuration(1000);

                            // Finalize movement when animation ends
                            a.setAnimationListener(new Animation.AnimationListener() {
                                @Override
                                public void onAnimationEnd(Animation animation) {
                                    RelativeLayout.LayoutParams rp = (RelativeLayout.LayoutParams) imageButton1.getLayoutParams();
                                    // Restore measured width and change left margin
                                    //rp.width = mButtonWidth;
                                   try {
                                       rp.leftMargin = rp.leftMargin + amountToMove;
                                       imageButton1.setLayoutParams(rp);
                                       // amountToMove = -amountToMove;
                                   }  finally{
                                       Context context = getApplicationContext();

                                   }

                                }

                                @Override
                                public void onAnimationStart(Animation animation) { /* Do nothing */
                                RelativeLayout.LayoutParams rp=(RelativeLayout.LayoutParams)imageButton1.getLayoutParams();
                                imageButton1.setLayoutParams(rp);
                                }

                                @Override
                                public void onAnimationRepeat(Animation animation) { /* Do nothing */ }
                            });
                            imageButton1.startAnimation(a);
</code>```

Body:
I'm trying to move an ImageView along a path using ObjectAnimator. I'm facing an NPE. Here's the code I'm trying.

path = new Path();
path.moveTo((float)(maxX/2)+(maxX/4),maxY/4);
path.quadTo((float)(maxX/2)+(maxX/4),maxY/4, (float)(maxX/2)+(maxX/4)+30,maxY/2);

ObjectAnimator animator = new ObjectAnimator();
        animator.ofFloat(img,View.X,View.Y,path);
        animator.setDuration(1000);
        animator.setStartDelay(600);
        animator.start();

The exception is :

Caused by: java.lang.NullPointerException: Attempt to get length of null array
at android.animation.ValueAnimator.initAnimation(ValueAnimator.java:534)
at android.animation.ObjectAnimator.initAnimation(ObjectAnimator.java:880)
at android.animation.ValueAnimator.setCurrentFraction(ValueAnimator.java:610)
at android.animation.ValueAnimator.setCurrentPlayTime(ValueAnimator.java:589)
at android.animation.ValueAnimator.start(ValueAnimator.java:1106)
at android.animation.ValueAnimator.start(ValueAnimator.java:1117)
at android.animation.ObjectAnimator.start(ObjectAnimator.java:852)
at com.example.user.curveanimation.MainActivity.onCreate(MainActivity.java:48)
at android.app.Activity.performCreate(Activity.java:6251)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1108)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2403)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2510)
at android.app.ActivityThread.-wrap11(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1363)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5461)
at java.lang.reflect.Method.invoke(Native Method)

If there's anything I'm doing wrong, Can somebody please help me animate via a path. SOmebody, Please help! Thanks.

Body:
I have animated ImageButton1

TranslateAnimation a = new TranslateAnimation(0, amountToMove, 0, 0);
                            a.setDuration(1000);

                            // Finalize movement when animation ends
                            a.setAnimationListener(new Animation.AnimationListener() {
                                @Override
                                public void onAnimationEnd(Animation animation) {
                                    RelativeLayout.LayoutParams rp = (RelativeLayout.LayoutParams) imageButton1.getLayoutParams();
                                    // Restore measured width and change left margin
                                    //rp.width = mButtonWidth;
                                   try {
                                       rp.leftMargin = rp.leftMargin + amountToMove;
                                       imageButton1.setLayoutParams(rp);
                                       // amountToMove = -amountToMove;
                                   }  finally{
                                       Context context = getApplicationContext();

                                   }

                                }

                                @Override
                                public void onAnimationStart(Animation animation) { /* Do nothing */
                                RelativeLayout.LayoutParams rp=(RelativeLayout.LayoutParams)imageButton1.getLayoutParams();
                                imageButton1.setLayoutParams(rp);
                                }

                                @Override
                                public void onAnimationRepeat(Animation animation) { /* Do nothing */ }
                            });
                            imageButton1.startAnimation(a);


问:
Java file get content to first empty line
I need to split the first section of a file in Java, before the first empty line and the second section, after this line. How can I do this? Currently, I read the files with this code:

```<code>try {
        Scanner scanner = new Scanner(file);
        return scanner.useDelimiter("\\Z").next();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (Exception e) {
        return "500 - Server Error";
    }
</code>```

Any suggestions ?

答:
Here is my approach: read the whole file, then split by "\n\n" into two parts:

```<code>import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

public class SplitFileByBlankLine {
    public static void main(String[] args) throws IOException {
        final String blankLine = System.getProperty("line.separator") + "{2}";

        // Read the whole contents, assuming small to moderate size
        String contents = new String(Files.readAllBytes(Paths.get("data.txt")));

        // Split the contents by blank line into two parts
        String[] partition = contents.split(blankLine, 2);

        // Print out for visual verification
        System.out.println(partition[0]); // Text before the blank line
        System.out.println("-----");
        System.out.println(partition[1]); // Text after
    }
}
</code>```

It seems you are trying to parse the http response. I am new to Java, but I think there must be a library somewhere to do the task.

Body:
I need to split the first section of a file in Java, before the first empty line and the second section, after this line. How can I do this? Currently, I read the files with this code:

try {
        Scanner scanner = new Scanner(file);
        return scanner.useDelimiter("\\Z").next();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (Exception e) {
        return "500 - Server Error";
    }

Any suggestions ?

Body:
Here is my approach: read the whole file, then split by "\n\n" into two parts:

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

public class SplitFileByBlankLine {
    public static void main(String[] args) throws IOException {
        final String blankLine = System.getProperty("line.separator") + "{2}";

        // Read the whole contents, assuming small to moderate size
        String contents = new String(Files.readAllBytes(Paths.get("data.txt")));

        // Split the contents by blank line into two parts
        String[] partition = contents.split(blankLine, 2);

        // Print out for visual verification
        System.out.println(partition[0]); // Text before the blank line
        System.out.println("-----");
        System.out.println(partition[1]); // Text after
    }
}

It seems you are trying to parse the http response. I am new to Java, but I think there must be a library somewhere to do the task.


问:
Need only 2 digits after decimal point
I want my function to return value with only 2 decimal places. I have tried following code :

```<code>private static double CalculateSlabTax(int nSlabStartTaxable,
                                       int nSlabEndTaxable,
                                       float fSlabRate)
{
    double dblSlabResult = 0;
    try
    {
        dblSlabResult = (nSlabStartTaxable - nSlabEndTaxable) * fSlabRate;
        dblSlabResult = Math.Round(dblSlabResult , 2);
        return dblSlabResult;
    }
    catch (Exception)
    {
        return -1;
    }
}
</code>```

Expected output is : dblSlabResult = ####.## - two digits (eg. 1002.05)

Getting output as : eg. dblSlabResult = 1002.1

答:
Very simple. Try this</p>

```<code>public double UptoTwoDecimalPoints(double num)
{
    var totalCost = Convert.ToDouble(String.Format("{0:0.00}", num));
    return totalCost;
}
</code>```

Title: Need only 2 digits after decimal point

Body:
I want my function to return value with only 2 decimal places. I have tried following code :

private static double CalculateSlabTax(int nSlabStartTaxable,
                                       int nSlabEndTaxable,
                                       float fSlabRate)
{
    double dblSlabResult = 0;
    try
    {
        dblSlabResult = (nSlabStartTaxable - nSlabEndTaxable) * fSlabRate;
        dblSlabResult = Math.Round(dblSlabResult , 2);
        return dblSlabResult;
    }
    catch (Exception)
    {
        return -1;
    }
}

Expected output is : dblSlabResult = ####.## - two digits (eg. 1002.05)

Getting output as : eg. dblSlabResult = 1002.1

Body:
Very simple. Try this

public double UptoTwoDecimalPoints(double num)
{
    var totalCost = Convert.ToDouble(String.Format("{0:0.00}", num));
    return totalCost;
}


问:
How to unbind event only from one item in a list
I have a list with 3 input elements. Every element have name attribute with the same value "shipping_method" and have different id values.

```<code><ul>
<li>
<input type="radio" name="shipping_method" id="shipping_method_1"  class="shipping_method" checked="checked">
<label for="shipping_method_1">Method 1</label>
</li>
<li>
<input type="radio" name="shipping_method" id="shipping_method_2"  class="shipping_method">
<label for="shipping_method_1">Method 2</label>
</li>
<li>
<input type="radio" name="shipping_method" id="shipping_method_3"  class="shipping_method">
<label for="shipping_method_1">Method 3</label>
</li>
</ul>
</code>```

To each element using jquery .on() event bound

```<code>$(document).on("change", "input[name^=shipping_method]", shipping_method_selected)
</code>```

I can't change the code which binds the event! I have to decouple event from the second input element. I have tried to use jquery .off(), but in this case, it unbinds the events of the three elements. What are the options of unbinding events in such situations?

答:
You can do this: Exclude second input from event binding by using :not and the id of the second input.

$(document).on("change", "input[name^=shipping_method]:not(#shipping_method_2)", shipping_method_selected);

function shipping_method_selected() {
  console.log('selected');
}```
<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>
<ul>
  <li>
    <input type="radio" name="shipping_method" id="shipping_method_1" class="shipping_method" checked="checked">
    <label for="shipping_method_1">Method 1</label>
  </li>
  <li>
    <input type="radio" name="shipping_method" id="shipping_method_2" class="shipping_method">
    <label for="shipping_method_1">Method 2</label>
  </li>
  <li>
    <input type="radio" name="shipping_method" id="shipping_method_3" class="shipping_method">
    <label for="shipping_method_1">Method 3</label>
  </li>
</ul></code>```

Body:
I have a list with 3 input elements. Every element have name attribute with the same value "shipping_method" and have different id values.

<input type="radio" name="shipping_method" id="shipping_method_1"  class="shipping_method" checked="checked">
Method 1

<input type="radio" name="shipping_method" id="shipping_method_2"  class="shipping_method">
Method 2

<input type="radio" name="shipping_method" id="shipping_method_3"  class="shipping_method">
Method 3

To each element using jquery .on() event bound

$(document).on("change", "input[name^=shipping_method]", shipping_method_selected)

I can't change the code which binds the event! I have to decouple event from the second input element. I have tried to use jquery .off(), but in this case, it unbinds the events of the three elements. What are the options of unbinding events in such situations?

Body:
You can do this: Exclude second input from event binding by using :not and the id of the second input.

$(document).on("change", "input[name^=shipping_method]:not(#shipping_method_2)", shipping_method_selected);

function shipping_method_selected() {
  console.log('selected');
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
  <li>
    <input type="radio" name="shipping_method" id="shipping_method_1" class="shipping_method" checked="checked">
    <label for="shipping_method_1">Method 1</label>
  </li>
  <li>
    <input type="radio" name="shipping_method" id="shipping_method_2" class="shipping_method">
    <label for="shipping_method_1">Method 2</label>
  </li>
  <li>
    <input type="radio" name="shipping_method" id="shipping_method_3" class="shipping_method">
    <label for="shipping_method_1">Method 3</label>
  </li>
</ul>


问:
Powershell: How to output List content as table?
I have an arraylist of objects, but I want to output them to the console in a tabular format like Get-Process does for processes.

How can I output a List as a Table?

Format-Table just throws an error

```<code>$bulidsList | Format-Table -Auto -InputObject $bulidsList
</code>```

"The input object cannot be bound to any parameters for the command either because the command does not take pipeline input or the input and its properties do not match any of the parameters that take pipeline input"

答:
Why do you use both pipe and -InputObject? (and at least one has a typo I guess)</p>

```<code>$bulidList | Format-Table
</code>```

Body:
I have an arraylist of objects, but I want to output them to the console in a tabular format like Get-Process does for processes.

How can I output a List as a Table?

Format-Table just throws an error

$bulidsList | Format-Table -Auto -InputObject $bulidsList

"The input object cannot be bound to any parameters for the command either because the command does not take pipeline input or the input and its properties do not match any of the parameters that take pipeline input"

Body:
Why do you use both pipe and -InputObject? (and at least one has a typo I guess)

$bulidList | Format-Table


问:
Mootools form submit & content change
I'd like to replace my_div's content after user clicks the submit button with the output that comes from my.php. I want to achieve this using mootools javascript library. How can I do this?

```<code>
<div id="my_div">
<form name="myform" action="http://www.domain.com/my.php" method="POST">
<br><br>
<input type="text" size="25" value="Enter your name here!">
<br><input type="submit" value="Send me your name!">
</div>
</code>```

Thanks for reading.

答:
You should give the submit button an id, I chose 'fsubmit' in this example. And 'f' is the id of the form.

```<code>$('fsubmit').addEvent('click', function(e) {
    e = new Event(e).stop();

    var url = $('f').get('action');

    var request = new Request({
        url: url,
        method: 'get',
        onComplete: function(response) {
            $('my_div').set('html', response);
        }
    });

    request.send();
});
</code>```

Or you could use a shortcut:
http://mootools.net/docs/core/Request/Request.HTML

Title: Mootools form submit & content change

Body:
I'd like to replace my_div's content after user clicks the submit button with the output that comes from my.php. I want to achieve this using mootools javascript library. How can I do this?

<form name="myform" action="http://www.domain.com/my.php" method="POST">

<input type="text" size="25" value="Enter your name here!">

<input type="submit" value="Send me your name!">

Thanks for reading.

Body:
You should give the submit button an id, I chose 'fsubmit' in this example. And 'f' is the id of the form.

$('fsubmit').addEvent('click', function(e) {
    e = new Event(e).stop();

    var url = $('f').get('action');

    var request = new Request({
        url: url,
        method: 'get',
        onComplete: function(response) {
            $('my_div').set('html', response);
        }
    });

    request.send();
});

Or you could use a shortcut:
http://mootools.net/docs/core/Request/Request.HTML


问:
How to global a js var in a function?
It is possible to global a variable inside a function, if not, how can I access a var in function b from function a.</p>

```<code>var money;
var moneyInput = document.getElementById('input');

function check(){
if (moneyInput.value == "") {
    money = 100;
}

function hit() {
    document.write(money) // will this money var be 100 or undefined?
}
</code>```

答:
/* 1 */

```<code>var a = 'sample text';

function one() {
  a = 'modified text';
}

function two() {
  console.log(a);
}

one();
two();
</code>```

/* 2 */

```<code>function one(callback) {
  var a = 'sample text callback';
  callback(a);
}

function two() {
  one(function(a) {
    console.log(a);
  });
}

two();
</code>```

/* 3 */

```<code>var one = new Promise(function(resolve, reject) {
  var a = 'sample text promise';
  resolve(a);
});

function two() {
  one.then(function(a) {
    console.log(a);
  });
}

two();
</code>```

/* 4 */

```<code>var myGlobals = {};

function one() {
  myGlobals.a = 'sample text';
}

function two() {
  console.log(myGlobals.a);
}

one();
two();
</code>```

Title: How to global a js var in a function?

Body:
It is possible to global a variable inside a function, if not, how can I access a var in function b from function a.

var money;
var moneyInput = document.getElementById('input');

function check(){
if (moneyInput.value == "") {
    money = 100;
}

function hit() {
    document.write(money) // will this money var be 100 or undefined?
}

Body:
/* 1 */

var a = 'sample text';

function one() {
  a = 'modified text';
}

function two() {
  console.log(a);
}

one();
two();

/* 2 */

function one(callback) {
  var a = 'sample text callback';
  callback(a);
}

function two() {
  one(function(a) {
    console.log(a);
  });
}

two();

/* 3 */

var one = new Promise(function(resolve, reject) {
  var a = 'sample text promise';
  resolve(a);
});

function two() {
  one.then(function(a) {
    console.log(a);
  });
}

two();

/* 4 */

var myGlobals = {};

function one() {
  myGlobals.a = 'sample text';
}

function two() {
  console.log(myGlobals.a);
}

one();
two();


问:
Improve switch statement in PHP or suggest an alternative workaround
I am trying to improve the below switch statement. What's happening here is that the code is called multiple times based on an x amount of tokens found, so the below code runs once per token.

If the $post->ID is not found then a notification is sent to that token and the id gets added in the database.

This works however at some point it's stopping after around 40% of tokens checked presumably because the ID is found? Since I am on wordpress, I used the update_option to store the id in a table but perhaps an alternative approach can be used?

```<code>$os = $this->os;
switch ($os) {

    case "iOS":
        $iOS_pastPushSavedID = get_option( 'iOS_pastPushSavedID',  $default = false);
        if($post->ID != $iOS_pastPushSavedID) {
            update_option( 'iOS_pastPushSavedID', $post->ID, no);
            $sendPush = true;
            //$title = ($os . '_New Push = ' . ' storedID: ' . $iOS_pastPushSavedID . ' / postID: ' . $post->ID);
        } else {
            //$title = ($os . '_Duplicate Push = ' . ' storedID: ' . $iOS_pastPushSavedID . ' / postID: ' . $post->ID);
            $sendPush = false;
        }
    break;

    case "Android":
        $android_pastPushSavedID = get_option( 'android_pastPushSavedID',  $default = false);
        if($post->ID != $android_pastPushSavedID) {
            //$title = ($os . '_New Push = ' . ' storedID: ' . $android_pastPushSavedID . ' / postID: ' . $post->ID);
            update_option( 'android_pastPushSavedID', $post->ID, no);
            $sendPush = true;
        } else {
            //$title = ($os . '_Duplicate Push = ' . ' storedID: ' . $android_pastPushSavedID . ' / postID: ' . $post->ID);
            $sendPush = false;
        }
    break;

    case "Fire OS":
        $fireos_pastPushSavedID = get_option( 'fireos_pastPushSavedID',  $default = false);
        if($post->ID != $fireos_pastPushSavedID) {
            //$title = ($os . '_New Push = ' . ' storedID: ' . $fireos_pastPushSavedID . ' / postID: ' . $post->ID);
            update_option( 'fireos_pastPushSavedID', $post->ID, no);
            $sendPush = true;
        } else {
            //$title = ($os . '_Duplicate Push = ' . ' storedID: ' . $fireos_pastPushSavedID . ' / postID: ' . $post->ID);
            $sendPush = false;
        }
    break;

    case "Safari":
        $safari_pastPushSavedID = get_option( 'safari_pastPushSavedID',  $default = false);
        if($post->ID != $safari_pastPushSavedID) {
            //$title = ($os . '_New Push = ' . ' storedID: ' . $safari_pastPushSavedID . ' / postID: ' . $post->ID);
            update_option( 'safari_pastPushSavedID', $post->ID, no);
            $sendPush = true;

        } else {
            //$title = ($os . '_Duplicate Push = ' . ' storedID: ' . $safari_pastPushSavedID . ' / postID: ' . $post->ID);
            $sendPush = false;
        }
    break;

    case "Chrome":
        $chrome_pastPushSavedID = get_option( 'chrome_pastPushSavedID',  $default = false);
        if($post->ID != $chrome_pastPushSavedID) {
            //$title = ($os . '_New Push = ' . ' storedID: ' . $chrome_pastPushSavedID . ' / postID: ' . $post->ID);
            update_option( 'chrome_pastPushSavedID', $post->ID, no);
            $sendPush = true;
        } else {
            //$title = ($os . '_Duplicate Push = ' . ' storedID: ' . $chrome_pastPushSavedID . ' / postID: ' . $post->ID);
            $sendPush = false;
        }
    break;

    case "Firefox":
        $firefox_pastPushSavedID = get_option( 'firefox_pastPushSavedID',  $default = false);
        if($post->ID != $firefox_pastPushSavedID) {
            //$title = ($os . '_New Push = ' . ' storedID: ' . $firefox_pastPushSavedID . ' / postID: ' . $post->ID);
            update_option( 'firefox_pastPushSavedID', $post->ID, no);
            $sendPush = true;

        } else {
        //$title = ($os . '_Duplicate Push = ' . ' storedID: ' . $firefox_pastPushSavedID . ' / postID: ' . $post->ID);
            $sendPush = false;
        }
    break;

    default:
        $sendPush = false;
}
</code>```

答:
Id write it more like this

```<code>function getOptionSpecifier() {

    switch ($this->os) {
        case "iOS":
            return 'iOS_pastPushSavedID';
        case "Android":
            return 'android_pastPushSavedID';
        case "Android":
            return 'android_pastPushSavedID';
        case "Fire OS":
            return 'fireos_pastPushSavedID';
        case "Safari":
            return 'safari_pastPushSavedID';
        case "Chrome":
            return 'chrome_pastPushSavedID';
        case "Firefox":
            return 'firefox_pastPushSavedID';
        default:
            return '';

    }
}

function send_notification($id) {
    $optionSpecifier = getOptionSpecifier();

    if ($optionSpecifier === NULL) {
        return false;
    }

    $pastPushSavedID = get_option( $optionSpecifier,  $default = false);

    if($id != $pastPushSavedID) {
        update_option( $optionSpecifier, $id, no);
        return true;
        //$title = ($os . '_New Push = ' . ' storedID: ' . $iOS_pastPushSavedID . ' / postID: ' . $post->ID);
    } else {
        //$title = ($os . '_Duplicate Push = ' . ' storedID: ' . $iOS_pastPushSavedID . ' / postID: ' . $post->ID);
        return false;
    }
}

$sendPush  = send_notification($post->ID);
</code>```

Multiple functions ala "separation of concerns" and so ...

Body:
I am trying to improve the below switch statement. What's happening here is that the code is called multiple times based on an x amount of tokens found, so the below code runs once per token.

If the $post->ID is not found then a notification is sent to that token and the id gets added in the database.

This works however at some point it's stopping after around 40% of tokens checked presumably because the ID is found? Since I am on wordpress, I used the update_option to store the id in a table but perhaps an alternative approach can be used?

$os = $this->os;
switch ($os) {

    case "iOS":
        $iOS_pastPushSavedID = get_option( 'iOS_pastPushSavedID',  $default = false);
        if($post->ID != $iOS_pastPushSavedID) {
            update_option( 'iOS_pastPushSavedID', $post->ID, no);
            $sendPush = true;
            //$title = ($os . '_New Push = ' . ' storedID: ' . $iOS_pastPushSavedID . ' / postID: ' . $post->ID);
        } else {
            //$title = ($os . '_Duplicate Push = ' . ' storedID: ' . $iOS_pastPushSavedID . ' / postID: ' . $post->ID);
            $sendPush = false;
        }
    break;

    case "Android":
        $android_pastPushSavedID = get_option( 'android_pastPushSavedID',  $default = false);
        if($post->ID != $android_pastPushSavedID) {
            //$title = ($os . '_New Push = ' . ' storedID: ' . $android_pastPushSavedID . ' / postID: ' . $post->ID);
            update_option( 'android_pastPushSavedID', $post->ID, no);
            $sendPush = true;
        } else {
            //$title = ($os . '_Duplicate Push = ' . ' storedID: ' . $android_pastPushSavedID . ' / postID: ' . $post->ID);
            $sendPush = false;
        }
    break;

    case "Fire OS":
        $fireos_pastPushSavedID = get_option( 'fireos_pastPushSavedID',  $default = false);
        if($post->ID != $fireos_pastPushSavedID) {
            //$title = ($os . '_New Push = ' . ' storedID: ' . $fireos_pastPushSavedID . ' / postID: ' . $post->ID);
            update_option( 'fireos_pastPushSavedID', $post->ID, no);
            $sendPush = true;
        } else {
            //$title = ($os . '_Duplicate Push = ' . ' storedID: ' . $fireos_pastPushSavedID . ' / postID: ' . $post->ID);
            $sendPush = false;
        }
    break;

    case "Safari":
        $safari_pastPushSavedID = get_option( 'safari_pastPushSavedID',  $default = false);
        if($post->ID != $safari_pastPushSavedID) {
            //$title = ($os . '_New Push = ' . ' storedID: ' . $safari_pastPushSavedID . ' / postID: ' . $post->ID);
            update_option( 'safari_pastPushSavedID', $post->ID, no);
            $sendPush = true;

        } else {
            //$title = ($os . '_Duplicate Push = ' . ' storedID: ' . $safari_pastPushSavedID . ' / postID: ' . $post->ID);
            $sendPush = false;
        }
    break;

    case "Chrome":
        $chrome_pastPushSavedID = get_option( 'chrome_pastPushSavedID',  $default = false);
        if($post->ID != $chrome_pastPushSavedID) {
            //$title = ($os . '_New Push = ' . ' storedID: ' . $chrome_pastPushSavedID . ' / postID: ' . $post->ID);
            update_option( 'chrome_pastPushSavedID', $post->ID, no);
            $sendPush = true;
        } else {
            //$title = ($os . '_Duplicate Push = ' . ' storedID: ' . $chrome_pastPushSavedID . ' / postID: ' . $post->ID);
            $sendPush = false;
        }
    break;

    case "Firefox":
        $firefox_pastPushSavedID = get_option( 'firefox_pastPushSavedID',  $default = false);
        if($post->ID != $firefox_pastPushSavedID) {
            //$title = ($os . '_New Push = ' . ' storedID: ' . $firefox_pastPushSavedID . ' / postID: ' . $post->ID);
            update_option( 'firefox_pastPushSavedID', $post->ID, no);
            $sendPush = true;

        } else {
        //$title = ($os . '_Duplicate Push = ' . ' storedID: ' . $firefox_pastPushSavedID . ' / postID: ' . $post->ID);
            $sendPush = false;
        }
    break;

    default:
        $sendPush = false;
}

Body:
Id write it more like this

function getOptionSpecifier() {

    switch ($this->os) {
        case "iOS":
            return 'iOS_pastPushSavedID';
        case "Android":
            return 'android_pastPushSavedID';
        case "Android":
            return 'android_pastPushSavedID';
        case "Fire OS":
            return 'fireos_pastPushSavedID';
        case "Safari":
            return 'safari_pastPushSavedID';
        case "Chrome":
            return 'chrome_pastPushSavedID';
        case "Firefox":
            return 'firefox_pastPushSavedID';
        default:
            return '';

    }
}

function send_notification($id) {
    $optionSpecifier = getOptionSpecifier();

    if ($optionSpecifier === NULL) {
        return false;
    }

    $pastPushSavedID = get_option( $optionSpecifier,  $default = false);

    if($id != $pastPushSavedID) {
        update_option( $optionSpecifier, $id, no);
        return true;
        //$title = ($os . '_New Push = ' . ' storedID: ' . $iOS_pastPushSavedID . ' / postID: ' . $post->ID);
    } else {
        //$title = ($os . '_Duplicate Push = ' . ' storedID: ' . $iOS_pastPushSavedID . ' / postID: ' . $post->ID);
        return false;
    }
}

$sendPush  = send_notification($post->ID);

Multiple functions ala "separation of concerns" and so ...


问:
Error `window not defined` in Node.js
I know window doesn't exist in Node.js, but I'm using React and the same code on both client and server. Any method I use to check if window exists nets me:

Uncaught ReferenceError: window is not defined

How do I get around the fact that I can't do window && window.scroll(0, 0)?

答:
```<code><Router onUpdate={() => window.scrollTo(0, 0)} history= {browserHistory}>
</code>```

if you need to open new page on top in React JS app, use this code in router.js

Title: Error `window not defined` in Node.js

Body:
<Router onUpdate={() => window.scrollTo(0, 0)} history= {browserHistory}>

if you need to open new page on top in React JS app, use this code in router.js