问:
DataTables with Bootstrap's table-responsive always has small x-overflow
I am using DataTables and Bootstrap but always seeing a tiny bit of x-overflow on my tables, no matter how many or few columns I have. Screenshot:

My markup:

```<code><div class="table-responsive">
    <table class="table data-table">
        <thead>
            ...
        </thead>
        <tbody>
            ...
        </tbody>
    </table>
</div>
</code>```

I don't apply any styles to the data-table class and the table and table-responsive classes are both Bootstrap's.

My initialization code:

```<code>$('.data-table').DataTable();
</code>```

How can I eliminate this unnecessary x-scroll? I want it only to be used when the screen is much smaller and the columns obviously do not fit.

答:
I think Tasos K.'s answer pretty much sums it up. But there is actually an even better way to add the table-responsive div as a parent of the table. There is a dom setting that let's you define the order of DataTables components as well as additional HTML that should be inserted into the DataTables' markup.

The default value of the dom setting is lfrtip. This defines the order of the DataTables' components. Each letter represents a component (for example, the letter 't' represents the actual table). The letters are explained in the DataTables reference here: https://datatables.net/reference/option/dom#Options

You can also define additional HTML to insert into the DataTables' markup. DataTables has a special format to define how to add HTML. For instance, to wrap the table with a div with class table-responsive, you have to wrap the letter 't' with <'table-responsive' and >. The description of the markup format is explained here: https://datatables.net/reference/option/dom#Markup

When you use the Bootstrap integration, as is the case with the OP, the default value of dom is overwritten with a different value to make DataTables work with the Bootstrap layout. According to the online reference, the value of dom is changed to

```<code><'row'<'col-sm-6'l><'col-sm-6'f>><'row'<'col-sm-12'tr>><'row'<'col-sm-5'i><'col-sm-7'p>>
</code>```

In order to add a div with class table-responsive as a direct parent of the table, you will have to change this string to

```<code><'row'<'col-sm-6'l><'col-sm-6'f>><'row'<'col-sm-12'<'table-responsive't>r>><'row'<'col-sm-5'i><'col-sm-7'p>>
</code>```

Here is a snippet with my solution. I copied the code from Tasos K.'s answer.

$(document).ready(function () {
    var table = $('#example').DataTable({
        "dom": "<'row'<'col-sm-6'l><'col-sm-6'f>><'row'<'col-sm-12'<'table-responsive't>r>><'row'<'col-sm-5'i><'col-sm-7'p>>"
    });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://cdn.datatables.net/r/bs-3.3.5/dt-1.10.9/datatables.min.js"></script>
<link href="https://cdn.datatables.net/r/bs-3.3.5/dt-1.10.9/datatables.min.css" rel="stylesheet"/>
<div class="container-fluid">
    <table id="example" class="table" cellspacing="0" width="100%">
        <thead>
            <tr>
                <th>Name</th>
                <th>Position</th>
                <th>Office</th>
                <th>Age</th>
                <th>Start date</th>
                <th>Salary</th>
            </tr>
        </thead>
        <tfoot>
            <tr>
                <th>Name</th>
                <th>Position</th>
                <th>Office</th>
                <th>Age</th>
                <th>Start date</th>
                <th>Salary</th>
            </tr>
        </tfoot>
        <tbody>
            <tr>
                <td>Tiger Nixon</td>
                <td>System Architect</td>
                <td>Edinburgh</td>
                <td>61</td>
                <td>2011/04/25</td>
                <td>$320,800</td>
            </tr>
            <tr>
                <td>Garrett Winters</td>
                <td>Accountant</td>
                <td>Tokyo</td>
                <td>63</td>
                <td>2011/07/25</td>
                <td>$170,750</td>
            </tr>
            <tr>
                <td>Ashton Cox</td>
                <td>Junior Technical Author</td>
                <td>San Francisco</td>
                <td>66</td>
                <td>2009/01/12</td>
                <td>$86,000</td>
            </tr>
            <tr>
                <td>Cedric Kelly</td>
                <td>Senior Javascript Developer</td>
                <td>Edinburgh</td>
                <td>22</td>
                <td>2012/03/29</td>
                <td>$433,060</td>
            </tr>
            <tr>
                <td>Airi Satou</td>
                <td>Accountant</td>
                <td>Tokyo</td>
                <td>33</td>
                <td>2008/11/28</td>
                <td>$162,700</td>
            </tr>
            <tr>
                <td>Brielle Williamson</td>
                <td>Integration Specialist</td>
                <td>New York</td>
                <td>61</td>
                <td>2012/12/02</td>
                <td>$372,000</td>
            </tr>
            <tr>
                <td>Herrod Chandler</td>
                <td>Sales Assistant</td>
                <td>San Francisco</td>
                <td>59</td>
                <td>2012/08/06</td>
                <td>$137,500</td>
            </tr>
            <tr>
                <td>Rhona Davidson</td>
                <td>Integration Specialist</td>
                <td>Tokyo</td>
                <td>55</td>
                <td>2010/10/14</td>
                <td>$327,900</td>
            </tr>
            <tr>
                <td>Colleen Hurst</td>
                <td>Javascript Developer</td>
                <td>San Francisco</td>
                <td>39</td>
                <td>2009/09/15</td>
                <td>$205,500</td>
            </tr>
            <tr>
                <td>Sonya Frost</td>
                <td>Software Engineer</td>
                <td>Edinburgh</td>
                <td>23</td>
                <td>2008/12/13</td>
                <td>$103,600</td>
            </tr>
            <tr>
                <td>Jena Gaines</td>
                <td>Office Manager</td>
                <td>London</td>
                <td>30</td>
                <td>2008/12/19</td>
                <td>$90,560</td>
            </tr>
            <tr>
                <td>Quinn Flynn</td>
                <td>Support Lead</td>
                <td>Edinburgh</td>
                <td>22</td>
                <td>2013/03/03</td>
                <td>$342,000</td>
            </tr>
            <tr>
                <td>Charde Marshall</td>
                <td>Regional Director</td>
                <td>San Francisco</td>
                <td>36</td>
                <td>2008/10/16</td>
                <td>$470,600</td>
            </tr>
            <tr>
                <td>Haley Kennedy</td>
                <td>Senior Marketing Designer</td>
                <td>London</td>
                <td>43</td>
                <td>2012/12/18</td>
                <td>$313,500</td>
            </tr>
            <tr>
                <td>Tatyana Fitzpatrick</td>
                <td>Regional Director</td>
                <td>London</td>
                <td>19</td>
                <td>2010/03/17</td>
                <td>$385,750</td>
            </tr>
            <tr>
                <td>Michael Silva</td>
                <td>Marketing Designer</td>
                <td>London</td>
                <td>66</td>
                <td>2012/11/27</td>
                <td>$198,500</td>
            </tr>
            <tr>
                <td>Paul Byrd</td>
                <td>Chief Financial Officer (CFO)</td>
                <td>New York</td>
                <td>64</td>
                <td>2010/06/09</td>
                <td>$725,000</td>
            </tr>
            <tr>
                <td>Gloria Little</td>
                <td>Systems Administrator</td>
                <td>New York</td>
                <td>59</td>
                <td>2009/04/10</td>
                <td>$237,500</td>
            </tr>
            <tr>
                <td>Bradley Greer</td>
                <td>Software Engineer</td>
                <td>London</td>
                <td>41</td>
                <td>2012/10/13</td>
                <td>$132,000</td>
            </tr>
            <tr>
                <td>Dai Rios</td>
                <td>Personnel Lead</td>
                <td>Edinburgh</td>
                <td>35</td>
                <td>2012/09/26</td>
                <td>$217,500</td>
            </tr>
            <tr>
                <td>Jenette Caldwell</td>
                <td>Development Lead</td>
                <td>New York</td>
                <td>30</td>
                <td>2011/09/03</td>
                <td>$345,000</td>
            </tr>
            <tr>
                <td>Yuri Berry</td>
                <td>Chief Marketing Officer (CMO)</td>
                <td>New York</td>
                <td>40</td>
                <td>2009/06/25</td>
                <td>$675,000</td>
            </tr>
            <tr>
                <td>Caesar Vance</td>
                <td>Pre-Sales Support</td>
                <td>New York</td>
                <td>21</td>
                <td>2011/12/12</td>
                <td>$106,450</td>
            </tr>
            <tr>
                <td>Doris Wilder</td>
                <td>Sales Assistant</td>
                <td>Sidney</td>
                <td>23</td>
                <td>2010/09/20</td>
                <td>$85,600</td>
            </tr>
            <tr>
                <td>Angelica Ramos</td>
                <td>Chief Executive Officer (CEO)</td>
                <td>London</td>
                <td>47</td>
                <td>2009/10/09</td>
                <td>$1,200,000</td>
            </tr>
            <tr>
                <td>Gavin Joyce</td>
                <td>Developer</td>
                <td>Edinburgh</td>
                <td>42</td>
                <td>2010/12/22</td>
                <td>$92,575</td>
            </tr>
            <tr>
                <td>Jennifer Chang</td>
                <td>Regional Director</td>
                <td>Singapore</td>
                <td>28</td>
                <td>2010/11/14</td>
                <td>$357,650</td>
            </tr>
            <tr>
                <td>Brenden Wagner</td>
                <td>Software Engineer</td>
                <td>San Francisco</td>
                <td>28</td>
                <td>2011/06/07</td>
                <td>$206,850</td>
            </tr>
            <tr>
                <td>Fiona Green</td>
                <td>Chief Operating Officer (COO)</td>
                <td>San Francisco</td>
                <td>48</td>
                <td>2010/03/11</td>
                <td>$850,000</td>
            </tr>
            <tr>
                <td>Shou Itou</td>
                <td>Regional Marketing</td>
                <td>Tokyo</td>
                <td>20</td>
                <td>2011/08/14</td>
                <td>$163,000</td>
            </tr>
            <tr>
                <td>Michelle House</td>
                <td>Integration Specialist</td>
                <td>Sidney</td>
                <td>37</td>
                <td>2011/06/02</td>
                <td>$95,400</td>
            </tr>
            <tr>
                <td>Suki Burks</td>
                <td>Developer</td>
                <td>London</td>
                <td>53</td>
                <td>2009/10/22</td>
                <td>$114,500</td>
            </tr>
            <tr>
                <td>Prescott Bartlett</td>
                <td>Technical Author</td>
                <td>London</td>
                <td>27</td>
                <td>2011/05/07</td>
                <td>$145,000</td>
            </tr>
            <tr>
                <td>Gavin Cortez</td>
                <td>Team Leader</td>
                <td>San Francisco</td>
                <td>22</td>
                <td>2008/10/26</td>
                <td>$235,500</td>
            </tr>
            <tr>
                <td>Martena Mccray</td>
                <td>Post-Sales support</td>
                <td>Edinburgh</td>
                <td>46</td>
                <td>2011/03/09</td>
                <td>$324,050</td>
            </tr>
            <tr>
                <td>Unity Butler</td>
                <td>Marketing Designer</td>
                <td>San Francisco</td>
                <td>47</td>
                <td>2009/12/09</td>
                <td>$85,675</td>
            </tr>
            <tr>
                <td>Howard Hatfield</td>
                <td>Office Manager</td>
                <td>San Francisco</td>
                <td>51</td>
                <td>2008/12/16</td>
                <td>$164,500</td>
            </tr>
            <tr>
                <td>Hope Fuentes</td>
                <td>Secretary</td>
                <td>San Francisco</td>
                <td>41</td>
                <td>2010/02/12</td>
                <td>$109,850</td>
            </tr>
            <tr>
                <td>Vivian Harrell</td>
                <td>Financial Controller</td>
                <td>San Francisco</td>
                <td>62</td>
                <td>2009/02/14</td>
                <td>$452,500</td>
            </tr>
            <tr>
                <td>Timothy Mooney</td>
                <td>Office Manager</td>
                <td>London</td>
                <td>37</td>
                <td>2008/12/11</td>
                <td>$136,200</td>
            </tr>
            <tr>
                <td>Jackson Bradshaw</td>
                <td>Director</td>
                <td>New York</td>
                <td>65</td>
                <td>2008/09/26</td>
                <td>$645,750</td>
            </tr>
            <tr>
                <td>Olivia Liang</td>
                <td>Support Engineer</td>
                <td>Singapore</td>
                <td>64</td>
                <td>2011/02/03</td>
                <td>$234,500</td>
            </tr>
            <tr>
                <td>Bruno Nash</td>
                <td>Software Engineer</td>
                <td>London</td>
                <td>38</td>
                <td>2011/05/03</td>
                <td>$163,500</td>
            </tr>
            <tr>
                <td>Sakura Yamamoto</td>
                <td>Support Engineer</td>
                <td>Tokyo</td>
                <td>37</td>
                <td>2009/08/19</td>
                <td>$139,575</td>
            </tr>
            <tr>
                <td>Thor Walton</td>
                <td>Developer</td>
                <td>New York</td>
                <td>61</td>
                <td>2013/08/11</td>
                <td>$98,540</td>
            </tr>
            <tr>
                <td>Finn Camacho</td>
                <td>Support Engineer</td>
                <td>San Francisco</td>
                <td>47</td>
                <td>2009/07/07</td>
                <td>$87,500</td>
            </tr>
            <tr>
                <td>Serge Baldwin</td>
                <td>Data Coordinator</td>
                <td>Singapore</td>
                <td>64</td>
                <td>2012/04/09</td>
                <td>$138,575</td>
            </tr>
            <tr>
                <td>Zenaida Frank</td>
                <td>Software Engineer</td>
                <td>New York</td>
                <td>63</td>
                <td>2010/01/04</td>
                <td>$125,250</td>
            </tr>
            <tr>
                <td>Zorita Serrano</td>
                <td>Software Engineer</td>
                <td>San Francisco</td>
                <td>56</td>
                <td>2012/06/01</td>
                <td>$115,000</td>
            </tr>
            <tr>
                <td>Jennifer Acosta</td>
                <td>Junior Javascript Developer</td>
                <td>Edinburgh</td>
                <td>43</td>
                <td>2013/02/01</td>
                <td>$75,650</td>
            </tr>
            <tr>
                <td>Cara Stevens</td>
                <td>Sales Assistant</td>
                <td>New York</td>
                <td>46</td>
                <td>2011/12/06</td>
                <td>$145,600</td>
            </tr>
            <tr>
                <td>Hermione Butler</td>
                <td>Regional Director</td>
                <td>London</td>
                <td>47</td>
                <td>2011/03/21</td>
                <td>$356,250</td>
            </tr>
            <tr>
                <td>Lael Greer</td>
                <td>Systems Administrator</td>
                <td>London</td>
                <td>21</td>
                <td>2009/02/27</td>
                <td>$103,500</td>
            </tr>
            <tr>
                <td>Jonas Alexander</td>
                <td>Developer</td>
                <td>San Francisco</td>
                <td>30</td>
                <td>2010/07/14</td>
                <td>$86,500</td>
            </tr>
            <tr>
                <td>Shad Decker</td>
                <td>Regional Director</td>
                <td>Edinburgh</td>
                <td>51</td>
                <td>2008/11/13</td>
                <td>$183,000</td>
            </tr>
            <tr>
                <td>Michael Bruce</td>
                <td>Javascript Developer</td>
                <td>Singapore</td>
                <td>29</td>
                <td>2011/06/27</td>
                <td>$183,000</td>
            </tr>
            <tr>
                <td>Donna Snider</td>
                <td>Customer Support</td>
                <td>New York</td>
                <td>27</td>
                <td>2011/01/25</td>
                <td>$112,000</td>
            </tr>
        </tbody>
    </table>
</div></code>```

Body:
I am using DataTables and Bootstrap but always seeing a tiny bit of x-overflow on my tables, no matter how many or few columns I have. Screenshot:

My markup:

            ...

            ...

I don't apply any styles to the data-table class and the table and table-responsive classes are both Bootstrap's.

My initialization code:

$('.data-table').DataTable();

How can I eliminate this unnecessary x-scroll? I want it only to be used when the screen is much smaller and the columns obviously do not fit.

Body:
I think Tasos K.'s answer pretty much sums it up. But there is actually an even better way to add the table-responsive div as a parent of the table. There is a dom setting that let's you define the order of DataTables components as well as additional HTML that should be inserted into the DataTables' markup.

The default value of the dom setting is lfrtip. This defines the order of the DataTables' components. Each letter represents a component (for example, the letter 't' represents the actual table). The letters are explained in the DataTables reference here: https://datatables.net/reference/option/dom#Options

You can also define additional HTML to insert into the DataTables' markup. DataTables has a special format to define how to add HTML. For instance, to wrap the table with a div with class table-responsive, you have to wrap the letter 't' with <'table-responsive' and >. The description of the markup format is explained here: https://datatables.net/reference/option/dom#Markup

When you use the Bootstrap integration, as is the case with the OP, the default value of dom is overwritten with a different value to make DataTables work with the Bootstrap layout. According to the online reference, the value of dom is changed to

<'row'<'col-sm-6'l><'col-sm-6'f>><'row'<'col-sm-12'tr>><'row'<'col-sm-5'i><'col-sm-7'p>>

In order to add a div with class table-responsive as a direct parent of the table, you will have to change this string to

<'row'<'col-sm-6'l><'col-sm-6'f>><'row'<'col-sm-12'<'table-responsive't>r>><'row'<'col-sm-5'i><'col-sm-7'p>>

Here is a snippet with my solution. I copied the code from Tasos K.'s answer.

$(document).ready(function () {
    var table = $('#example').DataTable({
        "dom": "<'row'<'col-sm-6'l><'col-sm-6'f>><'row'<'col-sm-12'<'table-responsive't>r>><'row'<'col-sm-5'i><'col-sm-7'p>>"
    });
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://cdn.datatables.net/r/bs-3.3.5/dt-1.10.9/datatables.min.js"></script>
<link href="https://cdn.datatables.net/r/bs-3.3.5/dt-1.10.9/datatables.min.css" rel="stylesheet"/>
<div class="container-fluid">
    <table id="example" class="table" cellspacing="0" width="100%">
        <thead>
            <tr>
                <th>Name</th>
                <th>Position</th>
                <th>Office</th>
                <th>Age</th>
                <th>Start date</th>
                <th>Salary</th>
            </tr>
        </thead>
        <tfoot>
            <tr>
                <th>Name</th>
                <th>Position</th>
                <th>Office</th>
                <th>Age</th>
                <th>Start date</th>
                <th>Salary</th>
            </tr>
        </tfoot>
        <tbody>
            <tr>
                <td>Tiger Nixon</td>
                <td>System Architect</td>
                <td>Edinburgh</td>
                <td>61</td>
                <td>2011/04/25</td>
                <td>$320,800</td>
            </tr>
            <tr>
                <td>Garrett Winters</td>
                <td>Accountant</td>
                <td>Tokyo</td>
                <td>63</td>
                <td>2011/07/25</td>
                <td>$170,750</td>
            </tr>
            <tr>
                <td>Ashton Cox</td>
                <td>Junior Technical Author</td>
                <td>San Francisco</td>
                <td>66</td>
                <td>2009/01/12</td>
                <td>$86,000</td>
            </tr>
            <tr>
                <td>Cedric Kelly</td>
                <td>Senior Javascript Developer</td>
                <td>Edinburgh</td>
                <td>22</td>
                <td>2012/03/29</td>
                <td>$433,060</td>
            </tr>
            <tr>
                <td>Airi Satou</td>
                <td>Accountant</td>
                <td>Tokyo</td>
                <td>33</td>
                <td>2008/11/28</td>
                <td>$162,700</td>
            </tr>
            <tr>
                <td>Brielle Williamson</td>
                <td>Integration Specialist</td>
                <td>New York</td>
                <td>61</td>
                <td>2012/12/02</td>
                <td>$372,000</td>
            </tr>
            <tr>
                <td>Herrod Chandler</td>
                <td>Sales Assistant</td>
                <td>San Francisco</td>
                <td>59</td>
                <td>2012/08/06</td>
                <td>$137,500</td>
            </tr>
            <tr>
                <td>Rhona Davidson</td>
                <td>Integration Specialist</td>
                <td>Tokyo</td>
                <td>55</td>
                <td>2010/10/14</td>
                <td>$327,900</td>
            </tr>
            <tr>
                <td>Colleen Hurst</td>
                <td>Javascript Developer</td>
                <td>San Francisco</td>
                <td>39</td>
                <td>2009/09/15</td>
                <td>$205,500</td>
            </tr>
            <tr>
                <td>Sonya Frost</td>
                <td>Software Engineer</td>
                <td>Edinburgh</td>
                <td>23</td>
                <td>2008/12/13</td>
                <td>$103,600</td>
            </tr>
            <tr>
                <td>Jena Gaines</td>
                <td>Office Manager</td>
                <td>London</td>
                <td>30</td>
                <td>2008/12/19</td>
                <td>$90,560</td>
            </tr>
            <tr>
                <td>Quinn Flynn</td>
                <td>Support Lead</td>
                <td>Edinburgh</td>
                <td>22</td>
                <td>2013/03/03</td>
                <td>$342,000</td>
            </tr>
            <tr>
                <td>Charde Marshall</td>
                <td>Regional Director</td>
                <td>San Francisco</td>
                <td>36</td>
                <td>2008/10/16</td>
                <td>$470,600</td>
            </tr>
            <tr>
                <td>Haley Kennedy</td>
                <td>Senior Marketing Designer</td>
                <td>London</td>
                <td>43</td>
                <td>2012/12/18</td>
                <td>$313,500</td>
            </tr>
            <tr>
                <td>Tatyana Fitzpatrick</td>
                <td>Regional Director</td>
                <td>London</td>
                <td>19</td>
                <td>2010/03/17</td>
                <td>$385,750</td>
            </tr>
            <tr>
                <td>Michael Silva</td>
                <td>Marketing Designer</td>
                <td>London</td>
                <td>66</td>
                <td>2012/11/27</td>
                <td>$198,500</td>
            </tr>
            <tr>
                <td>Paul Byrd</td>
                <td>Chief Financial Officer (CFO)</td>
                <td>New York</td>
                <td>64</td>
                <td>2010/06/09</td>
                <td>$725,000</td>
            </tr>
            <tr>
                <td>Gloria Little</td>
                <td>Systems Administrator</td>
                <td>New York</td>
                <td>59</td>
                <td>2009/04/10</td>
                <td>$237,500</td>
            </tr>
            <tr>
                <td>Bradley Greer</td>
                <td>Software Engineer</td>
                <td>London</td>
                <td>41</td>
                <td>2012/10/13</td>
                <td>$132,000</td>
            </tr>
            <tr>
                <td>Dai Rios</td>
                <td>Personnel Lead</td>
                <td>Edinburgh</td>
                <td>35</td>
                <td>2012/09/26</td>
                <td>$217,500</td>
            </tr>
            <tr>
                <td>Jenette Caldwell</td>
                <td>Development Lead</td>
                <td>New York</td>
                <td>30</td>
                <td>2011/09/03</td>
                <td>$345,000</td>
            </tr>
            <tr>
                <td>Yuri Berry</td>
                <td>Chief Marketing Officer (CMO)</td>
                <td>New York</td>
                <td>40</td>
                <td>2009/06/25</td>
                <td>$675,000</td>
            </tr>
            <tr>
                <td>Caesar Vance</td>
                <td>Pre-Sales Support</td>
                <td>New York</td>
                <td>21</td>
                <td>2011/12/12</td>
                <td>$106,450</td>
            </tr>
            <tr>
                <td>Doris Wilder</td>
                <td>Sales Assistant</td>
                <td>Sidney</td>
                <td>23</td>
                <td>2010/09/20</td>
                <td>$85,600</td>
            </tr>
            <tr>
                <td>Angelica Ramos</td>
                <td>Chief Executive Officer (CEO)</td>
                <td>London</td>
                <td>47</td>
                <td>2009/10/09</td>
                <td>$1,200,000</td>
            </tr>
            <tr>
                <td>Gavin Joyce</td>
                <td>Developer</td>
                <td>Edinburgh</td>
                <td>42</td>
                <td>2010/12/22</td>
                <td>$92,575</td>
            </tr>
            <tr>
                <td>Jennifer Chang</td>
                <td>Regional Director</td>
                <td>Singapore</td>
                <td>28</td>
                <td>2010/11/14</td>
                <td>$357,650</td>
            </tr>
            <tr>
                <td>Brenden Wagner</td>
                <td>Software Engineer</td>
                <td>San Francisco</td>
                <td>28</td>
                <td>2011/06/07</td>
                <td>$206,850</td>
            </tr>
            <tr>
                <td>Fiona Green</td>
                <td>Chief Operating Officer (COO)</td>
                <td>San Francisco</td>
                <td>48</td>
                <td>2010/03/11</td>
                <td>$850,000</td>
            </tr>
            <tr>
                <td>Shou Itou</td>
                <td>Regional Marketing</td>
                <td>Tokyo</td>
                <td>20</td>
                <td>2011/08/14</td>
                <td>$163,000</td>
            </tr>
            <tr>
                <td>Michelle House</td>
                <td>Integration Specialist</td>
                <td>Sidney</td>
                <td>37</td>
                <td>2011/06/02</td>
                <td>$95,400</td>
            </tr>
            <tr>
                <td>Suki Burks</td>
                <td>Developer</td>
                <td>London</td>
                <td>53</td>
                <td>2009/10/22</td>
                <td>$114,500</td>
            </tr>
            <tr>
                <td>Prescott Bartlett</td>
                <td>Technical Author</td>
                <td>London</td>
                <td>27</td>
                <td>2011/05/07</td>
                <td>$145,000</td>
            </tr>
            <tr>
                <td>Gavin Cortez</td>
                <td>Team Leader</td>
                <td>San Francisco</td>
                <td>22</td>
                <td>2008/10/26</td>
                <td>$235,500</td>
            </tr>
            <tr>
                <td>Martena Mccray</td>
                <td>Post-Sales support</td>
                <td>Edinburgh</td>
                <td>46</td>
                <td>2011/03/09</td>
                <td>$324,050</td>
            </tr>
            <tr>
                <td>Unity Butler</td>
                <td>Marketing Designer</td>
                <td>San Francisco</td>
                <td>47</td>
                <td>2009/12/09</td>
                <td>$85,675</td>
            </tr>
            <tr>
                <td>Howard Hatfield</td>
                <td>Office Manager</td>
                <td>San Francisco</td>
                <td>51</td>
                <td>2008/12/16</td>
                <td>$164,500</td>
            </tr>
            <tr>
                <td>Hope Fuentes</td>
                <td>Secretary</td>
                <td>San Francisco</td>
                <td>41</td>
                <td>2010/02/12</td>
                <td>$109,850</td>
            </tr>
            <tr>
                <td>Vivian Harrell</td>
                <td>Financial Controller</td>
                <td>San Francisco</td>
                <td>62</td>
                <td>2009/02/14</td>
                <td>$452,500</td>
            </tr>
            <tr>
                <td>Timothy Mooney</td>
                <td>Office Manager</td>
                <td>London</td>
                <td>37</td>
                <td>2008/12/11</td>
                <td>$136,200</td>
            </tr>
            <tr>
                <td>Jackson Bradshaw</td>
                <td>Director</td>
                <td>New York</td>
                <td>65</td>
                <td>2008/09/26</td>
                <td>$645,750</td>
            </tr>
            <tr>
                <td>Olivia Liang</td>
                <td>Support Engineer</td>
                <td>Singapore</td>
                <td>64</td>
                <td>2011/02/03</td>
                <td>$234,500</td>
            </tr>
            <tr>
                <td>Bruno Nash</td>
                <td>Software Engineer</td>
                <td>London</td>
                <td>38</td>
                <td>2011/05/03</td>
                <td>$163,500</td>
            </tr>
            <tr>
                <td>Sakura Yamamoto</td>
                <td>Support Engineer</td>
                <td>Tokyo</td>
                <td>37</td>
                <td>2009/08/19</td>
                <td>$139,575</td>
            </tr>
            <tr>
                <td>Thor Walton</td>
                <td>Developer</td>
                <td>New York</td>
                <td>61</td>
                <td>2013/08/11</td>
                <td>$98,540</td>
            </tr>
            <tr>
                <td>Finn Camacho</td>
                <td>Support Engineer</td>
                <td>San Francisco</td>
                <td>47</td>
                <td>2009/07/07</td>
                <td>$87,500</td>
            </tr>
            <tr>
                <td>Serge Baldwin</td>
                <td>Data Coordinator</td>
                <td>Singapore</td>
                <td>64</td>
                <td>2012/04/09</td>
                <td>$138,575</td>
            </tr>
            <tr>
                <td>Zenaida Frank</td>
                <td>Software Engineer</td>
                <td>New York</td>
                <td>63</td>
                <td>2010/01/04</td>
                <td>$125,250</td>
            </tr>
            <tr>
                <td>Zorita Serrano</td>
                <td>Software Engineer</td>
                <td>San Francisco</td>
                <td>56</td>
                <td>2012/06/01</td>
                <td>$115,000</td>
            </tr>
            <tr>
                <td>Jennifer Acosta</td>
                <td>Junior Javascript Developer</td>
                <td>Edinburgh</td>
                <td>43</td>
                <td>2013/02/01</td>
                <td>$75,650</td>
            </tr>
            <tr>
                <td>Cara Stevens</td>
                <td>Sales Assistant</td>
                <td>New York</td>
                <td>46</td>
                <td>2011/12/06</td>
                <td>$145,600</td>
            </tr>
            <tr>
                <td>Hermione Butler</td>
                <td>Regional Director</td>
                <td>London</td>
                <td>47</td>
                <td>2011/03/21</td>
                <td>$356,250</td>
            </tr>
            <tr>
                <td>Lael Greer</td>
                <td>Systems Administrator</td>
                <td>London</td>
                <td>21</td>
                <td>2009/02/27</td>
                <td>$103,500</td>
            </tr>
            <tr>
                <td>Jonas Alexander</td>
                <td>Developer</td>
                <td>San Francisco</td>
                <td>30</td>
                <td>2010/07/14</td>
                <td>$86,500</td>
            </tr>
            <tr>
                <td>Shad Decker</td>
                <td>Regional Director</td>
                <td>Edinburgh</td>
                <td>51</td>
                <td>2008/11/13</td>
                <td>$183,000</td>
            </tr>
            <tr>
                <td>Michael Bruce</td>
                <td>Javascript Developer</td>
                <td>Singapore</td>
                <td>29</td>
                <td>2011/06/27</td>
                <td>$183,000</td>
            </tr>
            <tr>
                <td>Donna Snider</td>
                <td>Customer Support</td>
                <td>New York</td>
                <td>27</td>
                <td>2011/01/25</td>
                <td>$112,000</td>
            </tr>
        </tbody>
    </table>
</div>


来源: stackexchange

问:
Is it possible to abort a map function on a Swift collection?
We have a case where we're being handed an object of type Array<Any> which we need to convert to an Array<Codable>. If any of the items in the original array don't adhere to Codable, then we want the entire thing to abort and return nil.

Or current approach is to manually loop over everything, testing along the way, like so...

```<code>func makeCodable(sourceArray:Array<Any>) -> Array<Codable>?{

    var codableArray = Array<Codable>()

    for item in sourceArray{

        guard let codableItem = item as? Codable else {
            return nil
        }

        codableArray.append(codableItem)
    }

    return codableArray
}
</code>```

However, I'm wondering if there's an easier way to do this with the map command, but it would require it to short-circuit if any of the elements can't be mapped.  That's what I'm not sure or not is possible.

For instance, this pseudo-code...

```<code>func makeCodable(sourceArray:Array<Any>) -> Array<Codable>?{

    return sourceArray.map({ $0 as? Codable});
}
</code>```

Is this possible, or is our original way the correct/only way?

答:
Here's one solution using map and throws.

```<code>func makeCodable(sourceArray: [Any]) -> [Codable]? {
    enum CodableError: Error {
        case notCodable
    }

    let res: [Codable]? = try? sourceArray.map {
        guard let codable = $0 as? Codable else {
            throw CodableError.notCodable
        }

        return codable
    }

    return res
}

let res = makeCodable2(sourceArray: [5, 6.5, "Hi", UIView()])
print(res) // nil
</code>```

Here's a variation that makes makeCodable throw and return a non-optional array:

```<code>enum CodableError: Error {
    case notCodable
}

func makeCodable(sourceArray: [Any]) throws -> [Codable] {
    let res: [Codable] = try sourceArray.map {
        guard let cod = $0 as? Codable else {
            throw CodableError.notCodable
        }

        return cod
    }

    return res
}

do {
    let res = try makeCodable(sourceArray: [5, 6.5, "Hi"])
    print(res) // prints array
    let bad = try makeCodable(sourceArray: [5, 6.5, "Hi", UIView()])
    print(bad)
} catch {
    print(error) // goes here on 2nd call
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
We have a case where we're being handed an object of type Array<Any> which we need to convert to an Array<Codable>. If any of the items in the original array don't adhere to Codable, then we want the entire thing to abort and return nil.

Or current approach is to manually loop over everything, testing along the way, like so...

func makeCodable(sourceArray:Array<Any>) -> Array<Codable>?{

    var codableArray = Array<Codable>()

    for item in sourceArray{

        guard let codableItem = item as? Codable else {
            return nil
        }

        codableArray.append(codableItem)
    }

    return codableArray
}

However, I'm wondering if there's an easier way to do this with the map command, but it would require it to short-circuit if any of the elements can't be mapped.  That's what I'm not sure or not is possible.

For instance, this pseudo-code...

func makeCodable(sourceArray:Array<Any>) -> Array<Codable>?{

    return sourceArray.map({ $0 as? Codable});
}

Is this possible, or is our original way the correct/only way?

Body:
Here's one solution using map and throws.

func makeCodable(sourceArray: [Any]) -> [Codable]? {
    enum CodableError: Error {
        case notCodable
    }

    let res: [Codable]? = try? sourceArray.map {
        guard let codable = $0 as? Codable else {
            throw CodableError.notCodable
        }

        return codable
    }

    return res
}

let res = makeCodable2(sourceArray: [5, 6.5, "Hi", UIView()])
print(res) // nil

Here's a variation that makes makeCodable throw and return a non-optional array:

enum CodableError: Error {
    case notCodable
}

func makeCodable(sourceArray: [Any]) throws -> [Codable] {
    let res: [Codable] = try sourceArray.map {
        guard let cod = $0 as? Codable else {
            throw CodableError.notCodable
        }

        return cod
    }

    return res
}

do {
    let res = try makeCodable(sourceArray: [5, 6.5, "Hi"])
    print(res) // prints array
    let bad = try makeCodable(sourceArray: [5, 6.5, "Hi", UIView()])
    print(bad)
} catch {
    print(error) // goes here on 2nd call
}


答:
Whenever you get a blob of JSON data that you can't immediately understand, first try to run it through a beautifier (aka formatter) to see the structure.

I uploaded your JSON into this only JSON formatter:

https://jsonformatter.curiousconcept.com

and below is the result. Now you can start making sense of it.

It looks like the outline block below represents one day. Write your code accordingly to parse it.

Title: How to parse OpenWeatherMap 16-day json?

Body:
Hi I'm trying to create an android application that will display the weather from opneweathermap. So far I have the application displaying today's weather, but I'm not able to parse 16-day JSON. I am trying to get the min and max temp of each of the days. Any help will be appreciated.

{"cod":"200","message":0.4667,"cnt":7,"list":[{"dt":1512777600,"main":{"temp":0.71,"temp_min":0.71,"temp_max":5.21,"pressure":1030.25,"sea_level":1035.12,"grnd_level":1030.25,"humidity":100,"temp_kf":-4.5},"weather":[{"id":800,"main":"Clear","description":"clear sky","icon":"01n"}],"clouds":{"all":0},"wind":{"speed":8.86,"deg":304.5},"rain":{},"sys":{"pod":"n"},"dt_txt":"2017-12-09 00:00:00"},{"dt":1512788400,"main":{"temp":1.35,"temp_min":1.35,"temp_max":4.72,"pressure":1029.09,"sea_level":1034,"grnd_level":1029.09,"humidity":100,"temp_kf":-3.38},"weather":[{"id":800,"main":"Clear","description":"clear sky","icon":"01n"}],"clouds":{"all":0},"wind":{"speed":8.07,"deg":292},"rain":{},"sys":{"pod":"n"},"dt_txt":"2017-12-09 03:00:00"},{"dt":1512799200,"main":{"temp":2.21,"temp_min":2.21,"temp_max":4.46,"pressure":1027.47,"sea_level":1032.37,"grnd_level":1027.47,"humidity":100,"temp_kf":-2.25},"weather":[{"id":801,"main":"Clouds","description":"few clouds","icon":"02n"}],"clouds":{"all":24},"wind":{"speed":7.66,"deg":280.001},"rain":{},"sys":{"pod":"n"},"dt_txt":"2017-12-09 06:00:00"},{"dt":1512810000,"main":{"temp":3.35,"temp_min":3.35,"temp_max":4.47,"pressure":1025.64,"sea_level":1030.48,"grnd_level":1025.64,"humidity":100,"temp_kf":-1.13},"weather":[{"id":802,"main":"Clouds","description":"scattered clouds","icon":"03d"}],"clouds":{"all":48},"wind":{"speed":6.69,"deg":275.001},"rain":{},"sys":{"pod":"d"},"dt_txt":"2017-12-09 09:00:00"},{"dt":1512820800,"main":{"temp":5.02,"temp_min":5.02,"temp_max":5.02,"pressure":1023.2,"sea_level":1028.06,"grnd_level":1023.2,"humidity":100,"temp_kf":0},"weather":[{"id":803,"main":"Clouds","description":"broken clouds","icon":"04d"}],"clouds":{"all":68},"wind":{"speed":6.12,"deg":266},"rain":{},"sys":{"pod":"d"},"dt_txt":"2017-12-09 12:00:00"},{"dt":1512831600,"main":{"temp":5.29,"temp_min":5.29,"temp_max":5.29,"pressure":1019.44,"sea_level":1024.28,"grnd_level":1019.44,"humidity":100,"temp_kf":0},"weather":[{"id":802,"main":"Clouds","description":"scattered clouds","icon":"03d"}],"clouds":{"all":44},"wind":{"speed":4.76,"deg":266.002},"rain":{},"sys":{"pod":"d"},"dt_txt":"2017-12-09 15:00:00"},{"dt":1512842400,"main":{"temp":4.54,"temp_min":4.54,"temp_max":4.54,"pressure":1016.14,"sea_level":1021.07,"grnd_level":1016.14,"humidity":100,"temp_kf":0},"weather":[{"id":800,"main":"Clear","description":"clear sky","icon":"01n"}],"clouds":{"all":0},"wind":{"speed":3.37,"deg":254.504},"rain":{},"sys":{"pod":"n"},"dt_txt":"2017-12-09 18:00:00"}],"city":{"id":2964574,"name":"Dublin","coord":{"lat":53.344,"lon":-6.2672},"country":"IE"}}

private void renderWeather(JSONObject json)
{
    /*
    //minField.setText(json.toString());

    try
    {
        JSONArray resultArray = json.getJSONArray("list");
        for(int i = 0; i < resultArray.length(); i++)
        {
            JSONObject obj = resultArray.getJSONObject(i);
            //store your variable
            String tempMin = obj.getString("temp_min");
            Log.i("TAG","Temp Min " + i + ": "+ tempMin);
        }
    }
    catch (JSONException e) {
        e.printStackTrace();
    }
    */

    String yourJsonString = json.toString();

    JSONArray jsonArray = null;
    try
    {
        jsonArray = new JSONArray(yourJsonString);

        for (int i = 0; i < jsonArray.length(); i++)
        {
            JSONObject obj1 = jsonArray.getJSONObject(i);
            JSONArray results = obj1.getJSONArray("list");
            String tempMin =  results.getJSONObject(0).getString("temp_min");
            Log.i("TAG","Temp Min " + i + ": "+ tempMin);
        }
    }

    catch (JSONException e)
    {
        e.printStackTrace();
    }
}

I've tried the two ways shown in the code and neither work. The first way gets a JSONException: No value for temp_min error. The second way gets a JSONException: Value error.


问:
react-native-config unable to use env variables in build.gradle
I have react-native-config set up and use it in javascript no problem but am unable to use it like this in build.gradle.

```<code>release {
     if (project.hasProperty('MYAPP_RELEASE_STORE_FILE')) {
         storeFile file(project.env.get("MYAPP_RELEASE_STORE_FILE"))
         storePassword project.env.get("MYAPP_RELEASE_STORE_PASSWORD")
         keyAlias project.env.get("MYAPP_RELEASE_KEY_ALIAS")
         keyPassword project.env.get("MYAPP_RELEASE_KEY_PASSWORD")
     }
}
</code>```

versions

```<code>react-native-cli: 2.0.1
react-native: 0.49.5
react: 16.0.0
react-native-config: 0.11.1
</code>```

Output

```<code>$ ./gradlew assembleRelease`
... shortened output
FAILURE: Build failed with an exception.
* What went wrong:
Execution failed for task ':app:validateSigningRelease'.
> Keystore file not set for signing config release
</code>```

答:
It seems like the file in MYAPP_RELEASE_STORE_FILE doesn't exist. What value do you have in there? Does the file exist in the same folder?

But also notice you shouldn't store signing secrets in .env; From the react-native-config readme:

Keep in mind this module doesn't obfuscate or encrypt secrets for packaging, so do not store sensitive keys in .env. It's basically impossible to prevent users from reverse engineering mobile app secrets, so design your app (and APIs) with that in mind.

What you can do instead is use a Gradle property file to keep your secrets. For instance, in ~/.gradle/gradle.properties:

```<code>MYAPP_RELEASE_KEY_ALIAS=myapp
MYAPP_RELEASE_STORE_PASSWORD=abc
MYAPP_RELEASE_KEY_PASSWORD=def
</code>```

These are then just available in build.gradle:

```<code>signingConfigs {
    release {
        storeFile "myapp.keystore"
        keyAlias MYAPP_RELEASE_KEY_ALIAS
        storePassword MYAPP_RELEASE_STORE_PASSWORD
        keyPassword MYAPP_RELEASE_KEY_PASSWORD
    }
}
</code>```

Body:
I have react-native-config set up and use it in javascript no problem but am unable to use it like this in build.gradle.

release {
     if (project.hasProperty('MYAPP_RELEASE_STORE_FILE')) {
         storeFile file(project.env.get("MYAPP_RELEASE_STORE_FILE"))
         storePassword project.env.get("MYAPP_RELEASE_STORE_PASSWORD")
         keyAlias project.env.get("MYAPP_RELEASE_KEY_ALIAS")
         keyPassword project.env.get("MYAPP_RELEASE_KEY_PASSWORD")
     }
}

versions

react-native-cli: 2.0.1
react-native: 0.49.5
react: 16.0.0
react-native-config: 0.11.1

Output

$ ./gradlew assembleRelease`
... shortened output
FAILURE: Build failed with an exception.
* What went wrong:
Execution failed for task ':app:validateSigningRelease'.
> Keystore file not set for signing config release

Body:
It seems like the file in MYAPP_RELEASE_STORE_FILE doesn't exist. What value do you have in there? Does the file exist in the same folder?

But also notice you shouldn't store signing secrets in .env; From the react-native-config readme:

Keep in mind this module doesn't obfuscate or encrypt secrets for packaging, so do not store sensitive keys in .env. It's basically impossible to prevent users from reverse engineering mobile app secrets, so design your app (and APIs) with that in mind.

What you can do instead is use a Gradle property file to keep your secrets. For instance, in ~/.gradle/gradle.properties:

MYAPP_RELEASE_KEY_ALIAS=myapp
MYAPP_RELEASE_STORE_PASSWORD=abc
MYAPP_RELEASE_KEY_PASSWORD=def

These are then just available in build.gradle:

signingConfigs {
    release {
        storeFile "myapp.keystore"
        keyAlias MYAPP_RELEASE_KEY_ALIAS
        storePassword MYAPP_RELEASE_STORE_PASSWORD
        keyPassword MYAPP_RELEASE_KEY_PASSWORD
    }
}


问:
FCM notification on-click always open in new tab (web-app Polymer)
I'm trying to implement Firebase Cloud Messaging in a web-app (with Polymer and a service-worker and using the custom-sw of the SDK).

It is working great (on both desktop and android) but when the user click on the notification it is always opening the click_action in a new tab even if a tab of the same origin is opened (but not focused).

click_action = "https://example.firebaseapp.com/demo/command"

Url of inactive tab = "https://example.firebaseapp.com/demo"

It seems that the getWindowClient_ method of the FCM SDK is not parsing correctly the URL of active clients and so can't call focus() on the inactive tab.

Any idea how to resolve this ?

答:
That is how it is designed. It caught me off guard at first, but after I thought about it, the new tab/window made sense.

1) the service worker is a separate process from the browser.
2) when a notification displays it is not associated with a browser tab/window.
3) changing the url in an existing window would most likely confuse/irritate the user.

When the user clicks your button the notification assumes no active tab on the origin. So it opens a new window.


问:
Getting Keras trained model predictions in c#
As title states I'm trying to use my Keras (tf backend) pretrained model for predicitions in c#. What's the best approach?

I've tried IronPython but it gave me errors, after search I found it isn't supported. Simply calling python script won't work since target Windows devices won't have python interpreters installed.

答:
This question is somewhat vague, but I'll try to answer it the best I can:

Tensorflow core is written in c++ and exposes an interface, which can be consumed by a client written in whichever language (although yes, the Python one is the most developed so far).

What could you do:

You could use a python script to train the keras model and save its computation graph in a file. Then use TensorFlowSharp --- which is the project that contracts with the tensorflow API using c# -- to reload the computation graph and generate predictions with the trained network.

If your devices are phones, tablets and such, Tensorflow for mobile could help you too. It would work similarly to the option above. I'm not sure if they offer support to windows phones, though.

You mentioned:

[...] devices won't have python interpreters installed.

Well, okay. You could, however, define an boot process that would cascade the installation of the necessary dependencies (cpython included). Some applications do that to set databases, for example. In this case, you could create a microservice that boots tensorflow and answers to prediction requests through a file, pipe or socket. Your c# application would then connect to your microservice and request predictions.

ContentLicense: CC BY-SA 4.0


问:
Use sed or awk to remove lines not adjacent to pattern in bash

I need to delete any line that is not surrounding a ">" symbol.

Here is some sample data:

```<code>sample1.fasta
>R00003
ATCATACTACTACG
sample2.fasta
sample3.fasta
sample4.fasta
>R00003
ATACTACGTA
sample7.fasta
>R00003
ATGCATCAT
sample8.fasta
>R00003
AATCATCGACCT
sample9.fasta
sample10.fasta
>R00003
AGCATCTCAGTC
</code>```

I tried using awk to help reveal the issue:

```<code>awk '{/fasta/?f++:f=0} f==2' R3.fasta
</code>```

This returns:

```<code>sample3.fasta
sample10.fasta
</code>```

This is diagnostic in that it shows where duplicates are present. However, I want to remove the lines that are not flanking the ">" symbol on either side. This does not remove them and only displays the second.

The result I expect is:

```<code>sample1.fasta
>R00003
ATCATACTACTACG
sample4.fasta
>R00003
ATACTACGTA
sample7.fasta
>R00003
ATGCATCAT
sample8.fasta
>R00003
AATCATCGACCT
sample10.fasta
>R0003
AGCATCTCAGTC
</code>```

Where the lines not flaking the ">" symbol have been removed

答:
another awk

```<code>$ awk '{if (/fasta/) f=$0;
        else {if(f) print f; f=""; print}}' file
</code>```

doesn't depend on number of lines in between.

Body:
I need to delete any line that is not surrounding a ">" symbol.

Here is some sample data:

sample1.fasta
>R00003
ATCATACTACTACG
sample2.fasta
sample3.fasta
sample4.fasta
>R00003
ATACTACGTA
sample7.fasta
>R00003
ATGCATCAT
sample8.fasta
>R00003
AATCATCGACCT
sample9.fasta
sample10.fasta
>R00003
AGCATCTCAGTC

I tried using awk to help reveal the issue:

awk '{/fasta/?f++:f=0} f==2' R3.fasta

This returns:

sample3.fasta
sample10.fasta

This is diagnostic in that it shows where duplicates are present. However, I want to remove the lines that are not flanking the ">" symbol on either side. This does not remove them and only displays the second.

The result I expect is:

sample1.fasta
>R00003
ATCATACTACTACG
sample4.fasta
>R00003
ATACTACGTA
sample7.fasta
>R00003
ATGCATCAT
sample8.fasta
>R00003
AATCATCGACCT
sample10.fasta
>R0003
AGCATCTCAGTC

Where the lines not flaking the ">" symbol have been removed

Body:
another awk

$ awk '{if (/fasta/) f=$0;
        else {if(f) print f; f=""; print}}' file

doesn't depend on number of lines in between.


问:
Background Image Wont Show
I'm trying to get this style to work for the body of the HTML page, it works when the style is applied within the  tags but not when used with an external style sheet.

CSS Doesn't work with this code.

```<code>body {
    background-image:url(img/geometric.jpg);
}
</code>```

HTML Works here.

```<code><body style="background-image:url('img/geometric.jpg');">
</body>
</code>```

I want to use external styling for the whole page. I'm curious on how to fix this odd issue.

答: The path to the image must be relative to the CSS file that references it, not the HTML file that it will appear in.</p>

Title: Background Image Wont Show

Body:
I'm trying to get this style to work for the body of the HTML page, it works when the style is applied within the  tags but not when used with an external style sheet.

CSS Doesn't work with this code.

body {
    background-image:url(img/geometric.jpg);
}

HTML Works here.

I want to use external styling for the whole page. I'm curious on how to fix this odd issue.


问:
Batch looping an if statement on the same line
I want to loop the if exist line once so that the line will run continuously until a unused sequential number is found (it has to loop on the same line so it becomes part of the if statement). Is there a better way to achieve this ?

```<code>if exist "*%num%*" (set /a num+=jump)
</code>```

update

```<code>@echo off
set /p usrname=enter folder name
set /a num=100
set /a jump=10

if exist "*%num%*" (set /a num+=jump)

MD %num%_%usrname%
</code>```

答:
Personally, I'd use</p>

```<code>@echo off
set /p usrname=enter folder name
set /a num=100
set /a jump=10

for /L %%a in (%num%,%jump%,2000000000) do if not exist "*%%a*" set /a num=%%a & MD %%a_%usrname%&goto done
:done
</code>```

Body:
I want to loop the if exist line once so that the line will run continuously until a unused sequential number is found (it has to loop on the same line so it becomes part of the if statement). Is there a better way to achieve this ?

if exist "*%num%*" (set /a num+=jump)

update

@echo off
set /p usrname=enter folder name
set /a num=100
set /a jump=10

if exist "*%num%*" (set /a num+=jump)

MD %num%_%usrname%

Body:
Personally, I'd use

@echo off
set /p usrname=enter folder name
set /a num=100
set /a jump=10

for /L %%a in (%num%,%jump%,2000000000) do if not exist "*%%a*" set /a num=%%a & MD %%a_%usrname%&goto done
:done


问:
Codeigniter - in view while foreach-ing get row count from another table by id
I have Categories Controller - index

```<code>public function index()
    {

        $query = $this->db->query("SELECT * FROM categories ORDER BY priority");
        $this->_viewdata['categories'] = $query->result();
        //-- I will use model for mysql queries!

        $this->load->view('admin/categories', $this->_viewdata);
    }
</code>```

In view Im printing results using foreach:

```<code><?php
    foreach ($categories as $category) {
?>
       Name: <?=$category->name;?> // and etc...
       Subcategories: // <- I want to get subcats count for every category by its id (where catid='$category->id') like this
    <?php
    }
    ?>
</code>```

I have another table called "subcategories" and I have "catid" column inside it. And I want to get every Subcategories count by Category and display it inside view. How can I do this?

答:
Like I said in the comments what I would do is Join the tables like:

```<code>SELECT * FROM categories c JOIN subcategories s ON s.catid = c.id ORDER BY c.priority
</code>```

Or since you are using Codeigniter you could even use:

```<code>$this->db->join('subcategories', 'subcategories.catid = categories.id');
</code>```

Then I would save the subcats to a different array and iterate through those.

```<code><?php
    $newCategories;
    foreach ($categories as $category) {
      if($category->name != $cat){
       //New category
       $cat = $category->name;
       $newCategories[$cat][] = $category;
      }
      else{
       $newCategories[$cat][] = $category;
      }
    }
    foreach($newCategories as $name => $cat){
?>
       Name: <?php echo $name ?>.
       Subcategories: <?php
                       foreach($cat as $sub){
                        echo $sub->..; //Fill in your template
                       }
                      ?>
</code>```

I'm sure it can be done better though.

Body:
I have Categories Controller - index

public function index()
    {

        $query = $this->db->query("SELECT * FROM categories ORDER BY priority");
        $this->_viewdata['categories'] = $query->result();
        //-- I will use model for mysql queries!

        $this->load->view('admin/categories', $this->_viewdata);
    }

In view Im printing results using foreach:

<?php
    foreach ($categories as $category) {
?>
       Name: <?=$category->name;?> // and etc...
       Subcategories: // <- I want to get subcats count for every category by its id (where catid='$category->id') like this
    <?php
    }
    ?>

I have another table called "subcategories" and I have "catid" column inside it. And I want to get every Subcategories count by Category and display it inside view. How can I do this?

Body:
Like I said in the comments what I would do is Join the tables like:

SELECT * FROM categories c JOIN subcategories s ON s.catid = c.id ORDER BY c.priority

Or since you are using Codeigniter you could even use:

$this->db->join('subcategories', 'subcategories.catid = categories.id');

Then I would save the subcats to a different array and iterate through those.

<?php
    $newCategories;
    foreach ($categories as $category) {
      if($category->name != $cat){
       //New category
       $cat = $category->name;
       $newCategories[$cat][] = $category;
      }
      else{
       $newCategories[$cat][] = $category;
      }
    }
    foreach($newCategories as $name => $cat){
?>
       Name: <?php echo $name ?>.
       Subcategories: <?php
                       foreach($cat as $sub){
                        echo $sub->..; //Fill in your template
                       }
                      ?>

I'm sure it can be done better though.


问:
Running Wordpress on rails subdirectory using nginx
I have new wordpress website and existing rails app on two different servers.
I wanted my wordpress website to be https://example.com/blog

My current nginx config for mydomain.com is

```<code>location /blog {
proxy_pass http://<ip-address of wp server>;
proxy_http_version                  1.1;
proxy_set_header  Connection        "";
proxy_set_header  Host              $host;
proxy_set_header  X-Forwarded-For   $proxy_add_x_forwarded_for;
proxy_set_header  X-Real-IP         $remote_addr;
}
</code>```

My wordpress config is

```<code>$_SERVER['HTTPS'] = 'on';
define('WP_HOME', "https://example.com/blog");
define('WP_SITEURL', "https://example.com/blog");
</code>```

Everything is working fine(admin and home page)
But when i click on post-page on hover its showing right url
which is https://example.com/blog/post but its redirecting to
https://example.com/post

答:
I managed to solve this by changing my nginx config</p>

```<code>    location /blog {
  proxy_set_header  X-Real-IP  $remote_addr;
  proxy_set_header  X-Forwarded-For $proxy_add_x_forwarded_for;
  proxy_redirect false;

  if (!-f $request_filename) {
    rewrite ^/blog$     /;
    rewrite ^/blog/(.*)$ /$1;
    proxy_pass http://blog.domain.com;
    break;
  }
}
</code>```

Body:
I have new wordpress website and existing rails app on two different servers.
I wanted my wordpress website to be https://example.com/blog

My current nginx config for mydomain.com is

location /blog {
proxy_pass http://<ip-address of wp server>;
proxy_http_version                  1.1;
proxy_set_header  Connection        "";
proxy_set_header  Host              $host;
proxy_set_header  X-Forwarded-For   $proxy_add_x_forwarded_for;
proxy_set_header  X-Real-IP         $remote_addr;
}

My wordpress config is

$_SERVER['HTTPS'] = 'on';
define('WP_HOME', "https://example.com/blog");
define('WP_SITEURL', "https://example.com/blog");

Everything is working fine(admin and home page)
But when i click on post-page on hover its showing right url
which is https://example.com/blog/post but its redirecting to
https://example.com/post

Body:
I managed to solve this by changing my nginx config

    location /blog {
  proxy_set_header  X-Real-IP  $remote_addr;
  proxy_set_header  X-Forwarded-For $proxy_add_x_forwarded_for;
  proxy_redirect false;

  if (!-f $request_filename) {
    rewrite ^/blog$     /;
    rewrite ^/blog/(.*)$ /$1;
    proxy_pass http://blog.domain.com;
    break;
  }
}


问:
logging configuration in wildfly10
Hi I have to create two log files for EJB application deployed in wildfly 10 server,first one is default one server.log along with that i want create one more log file lets say server_short.log, in this file i don't want full stack trace of exception messages, but the problem is happening that exception is writing by the internal interceptor and other jvm configuration files to the log file , so is there any to disable jvm stack trace for second log file? or any other way to accomplish this

```<code><subsystem xmlns="urn:jboss:domain:logging:3.0">
            <console-handler name="CONSOLE">
                <level name="INFO"/>
                <formatter>
                    <named-formatter name="COLOR-PATTERN"/>
                </formatter>
            </console-handler>

            <periodic-rotating-file-handler name="FILE" autoflush="true">
                <level name="INFO"/>
                <formatter>
                    <named-formatter name="PATTERN"/>
                </formatter>
                <file relative-to="jboss.server.log.dir" path="server.log"/>
                <suffix value=".yyyy-MM-dd"/>
                <append value="true"/>
            </periodic-rotating-file-handler>

            <periodic-rotating-file-handler name="SHORTFILE" autoflush="true">
                <level name="INFO"/>
                <formatter>
                    <named-formatter name="PATTERN"/>
                </formatter>
                <file relative-to="jboss.server.log.dir" path="server_short.log"/>
                <suffix value=".yyyy-MM-dd"/>
                <append value="true"/>
                <error-manager>
                 <only-once/>
                </error-manager
            </periodic-rotating-file-handler>

            <logger category="com.arjuna">
                <level name="WARN"/>
            </logger>
            <logger category="org.jboss.as.config">
                <level name="DEBUG"/>
            </logger>
            <logger category="sun.rmi">
                <level name="WARN"/>
            </logger>

            <root-logger>
                <level name="INFO"/>
                <handlers>
                    <handler name="CONSOLE"/>
                    <handler name="FILE"/>
                    <handler name="SHORTFILE"/>
                </handlers>
            </root-logger>
            </formatter>
        </subsystem>
</code>```

should generate simple exception message without full stacktrace both log file is identical

答:
If you don't want exceptions to be logged in the SHORTFILE you need to use a different format pattern.

As an example here are two CLI commands to create a new pattern and add the file handler.

```<code>/subsystem=logging/pattern-formatter=SHORT_PATTERN:add(pattern="%d{yyyy-MM-dd HH:mm:ss,SSS} %-5p [%c] (%t) %s%n")
/subsystem=logging/periodic-rotating-file-handler=SHORTFILE:add(level=INFO, named-formatter=SHORT_PATTERN, suffix=".yyyy-MM-dd", append=true, file={relative-to=jboss.server.log.dir, path="server_short.log"})
</code>```

One thing I did notice is the XML you've got does not look correct either.

Title: logging configuration in wildfly10

Body:
Hi I have to create two log files for EJB application deployed in wildfly 10 server,first one is default one server.log along with that i want create one more log file lets say server_short.log, in this file i don't want full stack trace of exception messages, but the problem is happening that exception is writing by the internal interceptor and other jvm configuration files to the log file , so is there any to disable jvm stack trace for second log file? or any other way to accomplish this

<subsystem xmlns="urn:jboss:domain:logging:3.0">
            <console-handler name="CONSOLE">
                <level name="INFO"/>
                <formatter>
                    <named-formatter name="COLOR-PATTERN"/>
                </formatter>
            </console-handler>

            <periodic-rotating-file-handler name="FILE" autoflush="true">
                <level name="INFO"/>
                <formatter>
                    <named-formatter name="PATTERN"/>
                </formatter>
                <file relative-to="jboss.server.log.dir" path="server.log"/>
                <suffix value=".yyyy-MM-dd"/>
                <append value="true"/>
            </periodic-rotating-file-handler>

            <periodic-rotating-file-handler name="SHORTFILE" autoflush="true">
                <level name="INFO"/>
                <formatter>
                    <named-formatter name="PATTERN"/>
                </formatter>
                <file relative-to="jboss.server.log.dir" path="server_short.log"/>
                <suffix value=".yyyy-MM-dd"/>
                <append value="true"/>
                <error-manager>
                 <only-once/>
                </error-manager
            </periodic-rotating-file-handler>

            <logger category="com.arjuna">
                <level name="WARN"/>
            </logger>
            <logger category="org.jboss.as.config">
                <level name="DEBUG"/>
            </logger>
            <logger category="sun.rmi">
                <level name="WARN"/>
            </logger>

            <root-logger>
                <level name="INFO"/>
                <handlers>
                    <handler name="CONSOLE"/>
                    <handler name="FILE"/>
                    <handler name="SHORTFILE"/>
                </handlers>
            </root-logger>
            </formatter>
        </subsystem>

should generate simple exception message without full stacktrace both log file is identical

Body:
If you don't want exceptions to be logged in the SHORTFILE you need to use a different format pattern.

As an example here are two CLI commands to create a new pattern and add the file handler.

/subsystem=logging/pattern-formatter=SHORT_PATTERN:add(pattern="%d{yyyy-MM-dd HH:mm:ss,SSS} %-5p [%c] (%t) %s%n")
/subsystem=logging/periodic-rotating-file-handler=SHORTFILE:add(level=INFO, named-formatter=SHORT_PATTERN, suffix=".yyyy-MM-dd", append=true, file={relative-to=jboss.server.log.dir, path="server_short.log"})

One thing I did notice is the XML you've got does not look correct either.


问:
Sorting a JSON object in Android studios (java)
I've been searching for a while on how to sort a JSON object like this.  It has a lot of attributes but I'm just trying to sort the objects into alphabetical order by "name":

I'm really new to java so you have any information to get started that'll be great!

//update:

So I figured out how to extract the attributes of each restaurant and now I'm trying to implement a comparator to sort the json objects but I'm confused on how to call the comparator and what arg to input

This is the comparator I'm using (got it from the internet)

```<code>public class AlphabeticalComparator  implements Comparator<String> {
        public int compare(String obj1, String obj2) {
            if (obj1 == null) {
                return -1;
            }
            if (obj2 == null) {
                return 1;
            }
            if (obj1.equals( obj2 )) {
                return 0;
            }
            return obj1.compareTo(obj2);
        }
    }
</code>```

I'm also a little confused on how this sorts the objects since it will only return an integer.  The json object im trying to sort is below

This is the JSON Object I get in response when I connect to the zomato API

``

```<code>{
  "results_found": 10573,
  "results_start": 0,
  "results_shown": 20,
  "restaurants": [
    {
      "restaurant": {
        "R": {
          "res_id": 16795271
        },
        "apikey": "fa221c30c201daf8380ac435cedfebe9",
        "id": "16795271",
        "name": "Craigie On Main", //This is what I want to sort it by
        "url": "https://www.zomato.com/boston/craigie-on-main-cambridge?utm_source=api_basic_user&utm_medium=api&utm_campaign=v2.1",
        "location": {
          "address": "853 Main St, Cambridge 02139",
          "locality": "Central Square",
          "city": "Boston",
          "city_id": 289,
          "latitude": "42.3634820000",
          "longitude": "-71.0985660000",
          "zipcode": "02139",
          "country_id": 216,
          "locality_verbose": "Central Square, Boston"
        },
        "switch_to_order_menu": 0,
        "cuisines": "European, French",
        "average_cost_for_two": 275,
        "price_range": 4,
        "currency": "$",
        "offers": [],
        "thumb": "https://b.zmtcdn.com/data/res_imagery/16795271_CHAIN_bd36a0893cde3f70ab4a67f1e086d5f5.jpg?fit=around%7C200%3A200&crop=200%3A200%3B%2A%2C%2A",
        "user_rating": {
          "aggregate_rating": "4.2",
          "rating_text": "Very Good",
          "rating_color": "5BA829",
          "votes": "342"
        },
        "photos_url": "https://www.zomato.com/boston/craigie-on-main-cambridge/photos?utm_source=api_basic_user&utm_medium=api&utm_campaign=v2.1#tabtop",
        "menu_url": "https://www.zomato.com/boston/craigie-on-main-cambridge/menu?utm_source=api_basic_user&utm_medium=api&utm_campaign=v2.1&openSwipeBox=menu&showMinimal=1#tabtop",
        "featured_image": "https://b.zmtcdn.com/data/res_imagery/16795271_CHAIN_bd36a0893cde3f70ab4a67f1e086d5f5.jpg",
        "has_online_delivery": 0,
        "is_delivering_now": 0,
        "deeplink": "zomato://restaurant/16795271",
        "has_table_booking": 0,
        "events_url": "https://www.zomato.com/boston/craigie-on-main-cambridge/events#tabtop?utm_source=api_basic_user&utm_medium=api&utm_campaign=v2.1",
        "establishment_types": []
      }
    },
    {
      "restaurant": {
        "R": {
          "res_id": 16798941
        },
        "apikey": "fa221c30c201daf8380ac435cedfebe9",
        "id": "16798941",
        "name": "O Ya",
        "url": "https://www.zomato.com/boston/o-ya-boston?utm_source=api_basic_user&utm_medium=api&utm_campaign=v2.1",
        "location": {
          "address": "9 East St, Boston 02111",
          "locality": "Leather District",
          "city": "Boston",
          "city_id": 289,
          "latitude": "42.3513170000",
          "longitude": "-71.0570370000",
          "zipcode": "02111",
          "country_id": 216,
          "locality_verbose": "Leather District, Boston"
        },
        "switch_to_order_menu": 0,
        "cuisines": "Japanese, Sushi",
        "average_cost_for_two": 275,
        "price_range": 4,
        "currency": "$",
        "offers": [],
        "thumb": "https://b.zmtcdn.com/data/res_imagery/16798941_CHAIN_d58be7a0f56ad4fbad498ba65b746a67.jpg?fit=around%7C200%3A200&crop=200%3A200%3B%2A%2C%2A",
        "user_rating": {
          "aggregate_rating": "4.3",
          "rating_text": "Very Good",
          "rating_color": "5BA829",
          "votes": "192"
        },
        "photos_url": "https://www.zomato.com/boston/o-ya-boston/photos?utm_source=api_basic_user&utm_medium=api&utm_campaign=v2.1#tabtop",
        "menu_url": "https://www.zomato.com/boston/o-ya-boston/menu?utm_source=api_basic_user&utm_medium=api&utm_campaign=v2.1&openSwipeBox=menu&showMinimal=1#tabtop",
        "featured_image": "https://b.zmtcdn.com/data/res_imagery/16798941_CHAIN_d58be7a0f56ad4fbad498ba65b746a67.jpg?output-format=webp",
        "has_online_delivery": 0,
        "is_delivering_now": 0,
        "deeplink": "zomato://restaurant/16798941",
        "has_table_booking": 0,
        "events_url": "https://www.zomato.com/boston/o-ya-boston/events#tabtop?utm_source=api_basic_user&utm_medium=api&utm_campaign=v2.1",
        "establishment_types": []
      }
    },
    {
      "restaurant": {
        "R": {
          "res_id": 16798079
        },
        "apikey": "fa221c30c201daf8380ac435cedfebe9",
        "id": "16798079",
        "name": "Solea Restaurant and Tapas Bar",
        "url": "https://www.zomato.com/boston/solea-restaurant-and-tapas-bar-waltham?utm_source=api_basic_user&utm_medium=api&utm_campaign=v2.1",
        "location": {
          "address": "388 Moody St, Waltham 02453",
          "locality": "Waltham",
          "city": "Boston",
          "city_id": 289,
          "latitude": "42.3695490000",
          "longitude": "-71.2370130000",
          "zipcode": "02453",
          "country_id": 216,
          "locality_verbose": "Waltham, Boston"
        },
        "switch_to_order_menu": 0,
        "cuisines": "Spanish, Tapas",
        "average_cost_for_two": 275,
        "price_range": 4,
        "currency": "$",
        "offers": [],
        "thumb": "",
        "user_rating": {
          "aggregate_rating": "4.2",
          "rating_text": "Very Good",
          "rating_color": "5BA829",
          "votes": "303"
        },
        "photos_url": "https://www.zomato.com/boston/solea-restaurant-and-tapas-bar-waltham/photos?utm_source=api_basic_user&utm_medium=api&utm_campaign=v2.1#tabtop",
        "menu_url": "https://www.zomato.com/boston/solea-restaurant-and-tapas-bar-waltham/menu?utm_source=api_basic_user&utm_medium=api&utm_campaign=v2.1&openSwipeBox=menu&showMinimal=1#tabtop",
        "featured_image": "",
        "has_online_delivery": 0,
        "is_delivering_now": 0,
        "deeplink": "zomato://restaurant/16798079",
        "has_table_booking": 0,
        "events_url": "https://www.zomato.com/boston/solea-restaurant-and-tapas-bar-waltham/events#tabtop?utm_source=api_basic_user&utm_medium=api&utm_campaign=v2.1",
        "establishment_types": []
      }
    },
"restaurant": {
        "R": {
          "res_id": 16796139
        },
        "apikey": "fa221c30c201daf8380ac435cedfebe9",
        "id": "16796139",
        "name": "Harvest",
        "url": "https://www.zomato.com/boston/harvest-cambridge?utm_source=api_basic_user&utm_medium=api&utm_campaign=v2.1",
        "location": {
          "address": "44 Brattle St, Cambridge 02138",
          "locality": "Harvard Square",
          "city": "Boston",
          "city_id": 289,
          "latitude": "42.3742680000",
          "longitude": "-71.1219960000",
          "zipcode": "02138",
          "country_id": 216,
          "locality_verbose": "Harvard Square, Boston"
        },
        "switch_to_order_menu": 0,
        "cuisines": "American, Breakfast",
        "average_cost_for_two": 275,
        "price_range": 4,
        "currency": "$",
        "offers": [],
        "thumb": "https://b.zmtcdn.com/data/res_imagery/16796139_RESTAURANT_4f9960714d6bd153a4571dd062c4ff45.jpg?fit=around%7C200%3A200&crop=200%3A200%3B%2A%2C%2A",
        "user_rating": {
          "aggregate_rating": "3.9",
          "rating_text": "Good",
          "rating_color": "9ACD32",
          "votes": "190"
        },
        "photos_url": "https://www.zomato.com/boston/harvest-cambridge/photos?utm_source=api_basic_user&utm_medium=api&utm_campaign=v2.1#tabtop",
        "menu_url": "https://www.zomato.com/boston/harvest-cambridge/menu?utm_source=api_basic_user&utm_medium=api&utm_campaign=v2.1&openSwipeBox=menu&showMinimal=1#tabtop",
        "featured_image": "https://b.zmtcdn.com/data/res_imagery/16796139_RESTAURANT_4f9960714d6bd153a4571dd062c4ff45.jpg",
        "has_online_delivery": 0,
        "is_delivering_now": 0,
        "deeplink": "zomato://restaurant/16796139",
        "has_table_booking": 0,
        "events_url": "https://www.zomato.com/boston/harvest-cambridge/events#tabtop?utm_source=api_basic_user&utm_medium=api&utm_campaign=v2.1",
        "establishment_types": []
      }
    },
</code>```

答:
Write a Comparator that orders a pair of JSON objects based on their respective name attributes.  Then use that to sort your array of JSON objects; e.g. using Arrays.sort(objects, comparator).

Here is a (more general) example:

https://stackoverflow.com/a/45555429/139985

You can modify that code to replace the OffersOrder class with your JSON object type (or a custom class) and then implement the comparator to compare objects and return the appropriate value.

Body:
I've been searching for a while on how to sort a JSON object like this.  It has a lot of attributes but I'm just trying to sort the objects into alphabetical order by "name":

I'm really new to java so you have any information to get started that'll be great!

//update:

So I figured out how to extract the attributes of each restaurant and now I'm trying to implement a comparator to sort the json objects but I'm confused on how to call the comparator and what arg to input

This is the comparator I'm using (got it from the internet)

public class AlphabeticalComparator  implements Comparator<String> {
        public int compare(String obj1, String obj2) {
            if (obj1 == null) {
                return -1;
            }
            if (obj2 == null) {
                return 1;
            }
            if (obj1.equals( obj2 )) {
                return 0;
            }
            return obj1.compareTo(obj2);
        }
    }

I'm also a little confused on how this sorts the objects since it will only return an integer.  The json object im trying to sort is below

This is the JSON Object I get in response when I connect to the zomato API

``

{
  "results_found": 10573,
  "results_start": 0,
  "results_shown": 20,
  "restaurants": [
    {
      "restaurant": {
        "R": {
          "res_id": 16795271
        },
        "apikey": "fa221c30c201daf8380ac435cedfebe9",
        "id": "16795271",
        "name": "Craigie On Main", //This is what I want to sort it by
        "url": "https://www.zomato.com/boston/craigie-on-main-cambridge?utm_source=api_basic_user&utm_medium=api&utm_campaign=v2.1",
        "location": {
          "address": "853 Main St, Cambridge 02139",
          "locality": "Central Square",
          "city": "Boston",
          "city_id": 289,
          "latitude": "42.3634820000",
          "longitude": "-71.0985660000",
          "zipcode": "02139",
          "country_id": 216,
          "locality_verbose": "Central Square, Boston"
        },
        "switch_to_order_menu": 0,
        "cuisines": "European, French",
        "average_cost_for_two": 275,
        "price_range": 4,
        "currency": "$",
        "offers": [],
        "thumb": "https://b.zmtcdn.com/data/res_imagery/16795271_CHAIN_bd36a0893cde3f70ab4a67f1e086d5f5.jpg?fit=around%7C200%3A200&crop=200%3A200%3B%2A%2C%2A",
        "user_rating": {
          "aggregate_rating": "4.2",
          "rating_text": "Very Good",
          "rating_color": "5BA829",
          "votes": "342"
        },
        "photos_url": "https://www.zomato.com/boston/craigie-on-main-cambridge/photos?utm_source=api_basic_user&utm_medium=api&utm_campaign=v2.1#tabtop",
        "menu_url": "https://www.zomato.com/boston/craigie-on-main-cambridge/menu?utm_source=api_basic_user&utm_medium=api&utm_campaign=v2.1&openSwipeBox=menu&showMinimal=1#tabtop",
        "featured_image": "https://b.zmtcdn.com/data/res_imagery/16795271_CHAIN_bd36a0893cde3f70ab4a67f1e086d5f5.jpg",
        "has_online_delivery": 0,
        "is_delivering_now": 0,
        "deeplink": "zomato://restaurant/16795271",
        "has_table_booking": 0,
        "events_url": "https://www.zomato.com/boston/craigie-on-main-cambridge/events#tabtop?utm_source=api_basic_user&utm_medium=api&utm_campaign=v2.1",
        "establishment_types": []
      }
    },
    {
      "restaurant": {
        "R": {
          "res_id": 16798941
        },
        "apikey": "fa221c30c201daf8380ac435cedfebe9",
        "id": "16798941",
        "name": "O Ya",
        "url": "https://www.zomato.com/boston/o-ya-boston?utm_source=api_basic_user&utm_medium=api&utm_campaign=v2.1",
        "location": {
          "address": "9 East St, Boston 02111",
          "locality": "Leather District",
          "city": "Boston",
          "city_id": 289,
          "latitude": "42.3513170000",
          "longitude": "-71.0570370000",
          "zipcode": "02111",
          "country_id": 216,
          "locality_verbose": "Leather District, Boston"
        },
        "switch_to_order_menu": 0,
        "cuisines": "Japanese, Sushi",
        "average_cost_for_two": 275,
        "price_range": 4,
        "currency": "$",
        "offers": [],
        "thumb": "https://b.zmtcdn.com/data/res_imagery/16798941_CHAIN_d58be7a0f56ad4fbad498ba65b746a67.jpg?fit=around%7C200%3A200&crop=200%3A200%3B%2A%2C%2A",
        "user_rating": {
          "aggregate_rating": "4.3",
          "rating_text": "Very Good",
          "rating_color": "5BA829",
          "votes": "192"
        },
        "photos_url": "https://www.zomato.com/boston/o-ya-boston/photos?utm_source=api_basic_user&utm_medium=api&utm_campaign=v2.1#tabtop",
        "menu_url": "https://www.zomato.com/boston/o-ya-boston/menu?utm_source=api_basic_user&utm_medium=api&utm_campaign=v2.1&openSwipeBox=menu&showMinimal=1#tabtop",
        "featured_image": "https://b.zmtcdn.com/data/res_imagery/16798941_CHAIN_d58be7a0f56ad4fbad498ba65b746a67.jpg?output-format=webp",
        "has_online_delivery": 0,
        "is_delivering_now": 0,
        "deeplink": "zomato://restaurant/16798941",
        "has_table_booking": 0,
        "events_url": "https://www.zomato.com/boston/o-ya-boston/events#tabtop?utm_source=api_basic_user&utm_medium=api&utm_campaign=v2.1",
        "establishment_types": []
      }
    },
    {
      "restaurant": {
        "R": {
          "res_id": 16798079
        },
        "apikey": "fa221c30c201daf8380ac435cedfebe9",
        "id": "16798079",
        "name": "Solea Restaurant and Tapas Bar",
        "url": "https://www.zomato.com/boston/solea-restaurant-and-tapas-bar-waltham?utm_source=api_basic_user&utm_medium=api&utm_campaign=v2.1",
        "location": {
          "address": "388 Moody St, Waltham 02453",
          "locality": "Waltham",
          "city": "Boston",
          "city_id": 289,
          "latitude": "42.3695490000",
          "longitude": "-71.2370130000",
          "zipcode": "02453",
          "country_id": 216,
          "locality_verbose": "Waltham, Boston"
        },
        "switch_to_order_menu": 0,
        "cuisines": "Spanish, Tapas",
        "average_cost_for_two": 275,
        "price_range": 4,
        "currency": "$",
        "offers": [],
        "thumb": "",
        "user_rating": {
          "aggregate_rating": "4.2",
          "rating_text": "Very Good",
          "rating_color": "5BA829",
          "votes": "303"
        },
        "photos_url": "https://www.zomato.com/boston/solea-restaurant-and-tapas-bar-waltham/photos?utm_source=api_basic_user&utm_medium=api&utm_campaign=v2.1#tabtop",
        "menu_url": "https://www.zomato.com/boston/solea-restaurant-and-tapas-bar-waltham/menu?utm_source=api_basic_user&utm_medium=api&utm_campaign=v2.1&openSwipeBox=menu&showMinimal=1#tabtop",
        "featured_image": "",
        "has_online_delivery": 0,
        "is_delivering_now": 0,
        "deeplink": "zomato://restaurant/16798079",
        "has_table_booking": 0,
        "events_url": "https://www.zomato.com/boston/solea-restaurant-and-tapas-bar-waltham/events#tabtop?utm_source=api_basic_user&utm_medium=api&utm_campaign=v2.1",
        "establishment_types": []
      }
    },
"restaurant": {
        "R": {
          "res_id": 16796139
        },
        "apikey": "fa221c30c201daf8380ac435cedfebe9",
        "id": "16796139",
        "name": "Harvest",
        "url": "https://www.zomato.com/boston/harvest-cambridge?utm_source=api_basic_user&utm_medium=api&utm_campaign=v2.1",
        "location": {
          "address": "44 Brattle St, Cambridge 02138",
          "locality": "Harvard Square",
          "city": "Boston",
          "city_id": 289,
          "latitude": "42.3742680000",
          "longitude": "-71.1219960000",
          "zipcode": "02138",
          "country_id": 216,
          "locality_verbose": "Harvard Square, Boston"
        },
        "switch_to_order_menu": 0,
        "cuisines": "American, Breakfast",
        "average_cost_for_two": 275,
        "price_range": 4,
        "currency": "$",
        "offers": [],
        "thumb": "https://b.zmtcdn.com/data/res_imagery/16796139_RESTAURANT_4f9960714d6bd153a4571dd062c4ff45.jpg?fit=around%7C200%3A200&crop=200%3A200%3B%2A%2C%2A",
        "user_rating": {
          "aggregate_rating": "3.9",
          "rating_text": "Good",
          "rating_color": "9ACD32",
          "votes": "190"
        },
        "photos_url": "https://www.zomato.com/boston/harvest-cambridge/photos?utm_source=api_basic_user&utm_medium=api&utm_campaign=v2.1#tabtop",
        "menu_url": "https://www.zomato.com/boston/harvest-cambridge/menu?utm_source=api_basic_user&utm_medium=api&utm_campaign=v2.1&openSwipeBox=menu&showMinimal=1#tabtop",
        "featured_image": "https://b.zmtcdn.com/data/res_imagery/16796139_RESTAURANT_4f9960714d6bd153a4571dd062c4ff45.jpg",
        "has_online_delivery": 0,
        "is_delivering_now": 0,
        "deeplink": "zomato://restaurant/16796139",
        "has_table_booking": 0,
        "events_url": "https://www.zomato.com/boston/harvest-cambridge/events#tabtop?utm_source=api_basic_user&utm_medium=api&utm_campaign=v2.1",
        "establishment_types": []
      }
    },


问:
Anybody know a valid mechanism to detect the degree of similarity between two strings
I need to know how far the two strings are similar in terms of some measuring index</p>

答:
Lucky for you, Python comes with the difflib module :)

Check out get_close_matches function

ContentLicense: CC BY-SA 2.5


问:
Change binary search tree to balance
I have just learnt how to create a binary search data structure, which is going to be used to store thousands of words from a dictionary. The problem that I am getting is that it is taking a long time to count add and remove data. Usually 199263ms or 200 seconds for 100000 words to count. I was told that having a tree that can self balance will improve the efficiency and make the operations faster.

My question is how can I make my tree auto balance so to make it efficient. I have made slight improvements by eliminating duplicate words to make the height of the tree to be shorter.

If someone can give me advice on how i can make the tree efficient and how I can implement balancing tree in java will be helpful.

答:
You should look into red/black trees, which are self balancing. The nodes store a color in addition to an element, and every time the tree is modified, you rebalance the tree so that it meets the properties of a red/black tree:

(From Wikipedia:)

Each node is either red or black.

The root is black.

All leaves (NIL) are black.

If a node is red, then both its children are black.

Every path from a given node to any of its descendant NIL nodes
contains the same number of black nodes.

To get started implementing a red black tree, I recommend looking at this example implementation on github, and reading this explanation of red black trees.

Title: Change binary search tree to balance


问:
js or-equal operator equivalent as in ruby
In Ruby, I can do the following:

```<code>very_long_dictionary_name = {}
very_long_key_name = "a"

# this code usually will run inside a function invoked twice,
# first with parameter "b" and after with parameter "c", so
# I don't know if very_long_dictionary_name[very_long_key_name]
# was initialized, inside the function
(very_long_dictionary_name[very_long_key_name] ||= []).push("b")
(very_long_dictionary_name[very_long_key_name] ||= []).push("c")

very_long_dictionary_name    #=> {"a" => ["b", "c"]}
</code>```

I tried it in Javascript and I got syntax error at ||=. Is there a way to set the very_long_dictionary_name[very_long_key_name] as an empty array in javascript only if it is undefined, without repeating that long name?

答:
I can do the job if I add a helper method to my very_long_dictionary_name object, what needs to be made only once.

```<code>var very_long_dictionary_name = {}
var very_long_key_name = "a"

very_long_dictionary_name.push = function(key, value) {
  if (!this.hasOwnProperty(key)) this[key] = []
  this[key].push(value)
}

very_long_dictionary_name.push(very_long_key_name, "b")
very_long_dictionary_name.push(very_long_key_name, "c")

return JSON.stringify(very_long_dictionary_name)
// {"a":["b","c"]}
</code>```

No repetition of very_long_dictionary_name nor very_long_key_name in the same instruction.

Furthermore, I must be sure that the helper method name won't conflict with some possible future key.

Body:
In Ruby, I can do the following:

very_long_dictionary_name = {}
very_long_key_name = "a"

# this code usually will run inside a function invoked twice,
# first with parameter "b" and after with parameter "c", so
# I don't know if very_long_dictionary_name[very_long_key_name]
# was initialized, inside the function
(very_long_dictionary_name[very_long_key_name] ||= []).push("b")
(very_long_dictionary_name[very_long_key_name] ||= []).push("c")

very_long_dictionary_name    #=> {"a" => ["b", "c"]}

I tried it in Javascript and I got syntax error at ||=. Is there a way to set the very_long_dictionary_name[very_long_key_name] as an empty array in javascript only if it is undefined, without repeating that long name?

Body:
I can do the job if I add a helper method to my very_long_dictionary_name object, what needs to be made only once.

var very_long_dictionary_name = {}
var very_long_key_name = "a"

very_long_dictionary_name.push = function(key, value) {
  if (!this.hasOwnProperty(key)) this[key] = []
  this[key].push(value)
}

very_long_dictionary_name.push(very_long_key_name, "b")
very_long_dictionary_name.push(very_long_key_name, "c")

return JSON.stringify(very_long_dictionary_name)
// {"a":["b","c"]}

No repetition of very_long_dictionary_name nor very_long_key_name in the same instruction.

Furthermore, I must be sure that the helper method name won't conflict with some possible future key.


问:
How to configure static and media files with django and nginx?
I have next settings.py on my local server.

```<code>STATICFILES_DIRS = (
    os.path.join(BASE_DIR, "static"),
)
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(os.path.dirname(BASE_DIR), "static_root")
MEDIA_URL = '/media/'
MEDIA_ROOT= os.path.join(os.path.dirname(BASE_DIR), "media_root")
</code>```

I know that in production Nginx should handle static and media. Okay.
I use gunicorn and supervisor on my prod server.
My nginx config:

```<code>server {
    listen 8000;
    server_name 194.87.95.46;
    access_log  /var/log/nginx/example.log;

    location /static {
        alias /home/split/static_root/;
    }

     location /media {
        alias /home/split/media_root/;
    }

    location / {
        proxy_pass http://127.0.0.1:8003;
        proxy_set_header Host $server_name;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    }
  }
</code>```

But nginx doesnt handle static and media, what's the problem?

答:
I think your issue is caused by trailing slashes - you haven't provided a trailing slash in the location definition, but you have in the alias. Try this instead:

```<code>location /static/ {
    alias /home/split/static_root/;
}

location /media/ {
    alias /home/split/media_root/;
}
</code>```

Body:
I have next settings.py on my local server.

STATICFILES_DIRS = (
    os.path.join(BASE_DIR, "static"),
)
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(os.path.dirname(BASE_DIR), "static_root")
MEDIA_URL = '/media/'
MEDIA_ROOT= os.path.join(os.path.dirname(BASE_DIR), "media_root")

I know that in production Nginx should handle static and media. Okay.
I use gunicorn and supervisor on my prod server.
My nginx config:

server {
    listen 8000;
    server_name 194.87.95.46;
    access_log  /var/log/nginx/example.log;

    location /static {
        alias /home/split/static_root/;
    }

     location /media {
        alias /home/split/media_root/;
    }

    location / {
        proxy_pass http://127.0.0.1:8003;
        proxy_set_header Host $server_name;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    }
  }

But nginx doesnt handle static and media, what's the problem?

Body:
I think your issue is caused by trailing slashes - you haven't provided a trailing slash in the location definition, but you have in the alias. Try this instead:

location /static/ {
    alias /home/split/static_root/;
}

location /media/ {
    alias /home/split/media_root/;
}