问:
Exclude/hide some columns while export datatable
I am using jquery datatable for displaying data in table, When I export tabel info to PDF,Excel or CSV I need to exclude or hide some columns.

$(document).ready(function() {
var oTable = $('#example').DataTable( {
        dom: 'Blfrtip',
        buttons: [
       {
           extend: 'pdf',
           footer: true
       },
       {
           extend: 'csv',
           footer: false
       },
       {
           extend: 'excel',
           footer: false
       }
    ]
    } );

} );```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link rel="stylesheet" href="https://cdn.datatables.net/buttons/1.1.0/css/buttons.dataTables.min.css" type="text/css"  />
<link rel="stylesheet" href="https://cdn.datatables.net/1.10.10/css/jquery.dataTables.min.css" type="text/css" />
<link rel="stylesheet" href="https://cdn.datatables.net/select/1.1.0/css/select.dataTables.min.css" type="text/css" />

<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script type="text/javascript" src="https://datatables.net/release-datatables/media/js/jquery.js"></script>
<script type="text/javascript" src="https://datatables.net/release-datatables/media/js/jquery.dataTables.js"></script>
<script type="text/javascript" scr="https://datatables.net/release-datatables/extensions/TableTools/js/dataTables.tableTools.js"></script>

<script src="https://cdn.datatables.net/buttons/1.1.0/js/dataTables.buttons.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jszip/2.5.0/jszip.min.js"></script>
<script src="https://cdn.rawgit.com/bpampuch/pdfmake/0.1.18/build/pdfmake.min.js"></script>
<script src="https://cdn.rawgit.com/bpampuch/pdfmake/0.1.18/build/vfs_fonts.js"></script>
<script src="https://cdn.datatables.net/buttons/1.1.0/js/buttons.html5.min.js"></script>

<script src="https://jquery-datatables-column-filter.googlecode.com/svn/trunk/media/js/jquery.dataTables.columnFilter.js" type="text/javascript"></script>

<table id="example" class="display" 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>

    </tbody>
</table></code>```

Can any one help me how do I exclude or hide some column like "AGE"...etc while exporting to PDF,Excel or CSV

答:
You can use following to export only visible column:</p>

```<code>exportOptions:{
       columns: ':visible'
 }
</code>```

Body:
I am using jquery datatable for displaying data in table, When I export tabel info to PDF,Excel or CSV I need to exclude or hide some columns.

$(document).ready(function() {
var oTable = $('#example').DataTable( {
        dom: 'Blfrtip',
        buttons: [
       {
           extend: 'pdf',
           footer: true
       },
       {
           extend: 'csv',
           footer: false
       },
       {
           extend: 'excel',
           footer: false
       }
    ]
    } );

} );

<link rel="stylesheet" href="https://cdn.datatables.net/buttons/1.1.0/css/buttons.dataTables.min.css" type="text/css"  />
<link rel="stylesheet" href="https://cdn.datatables.net/1.10.10/css/jquery.dataTables.min.css" type="text/css" />
<link rel="stylesheet" href="https://cdn.datatables.net/select/1.1.0/css/select.dataTables.min.css" type="text/css" />

            Name
            Position
            Office
            Age
            Start date
            Salary

            Name
            Position
            Office
            Age
            Start date
            Salary

            Tiger Nixon
            System Architect
            Edinburgh
            61
            2011/04/25
            $320,800

            Garrett Winters
            Accountant
            Tokyo
            63
            2011/07/25
            $170,750

            Ashton Cox
            Junior Technical Author
            San Francisco
            66
            2009/01/12
            $86,000

            Cedric Kelly
            Senior Javascript Developer
            Edinburgh
            22
            2012/03/29
            $433,060

            Airi Satou
            Accountant
            Tokyo
            33
            2008/11/28
            $162,700

            Brielle Williamson
            Integration Specialist
            New York
            61
            2012/12/02
            $372,000

            Herrod Chandler
            Sales Assistant
            San Francisco
            59
            2012/08/06
            $137,500

            Rhona Davidson
            Integration Specialist
            Tokyo
            55
            2010/10/14
            $327,900

            Colleen Hurst
            Javascript Developer
            San Francisco
            39
            2009/09/15
            $205,500

            Sonya Frost
            Software Engineer
            Edinburgh
            23
            2008/12/13
            $103,600

            Jena Gaines
            Office Manager
            London
            30
            2008/12/19
            $90,560

            Quinn Flynn
            Support Lead
            Edinburgh
            22
            2013/03/03
            $342,000

            Charde Marshall
            Regional Director
            San Francisco
            36
            2008/10/16
            $470,600

            Haley Kennedy
            Senior Marketing Designer
            London
            43
            2012/12/18
            $313,500

            Tatyana Fitzpatrick
            Regional Director
            London
            19
            2010/03/17
            $385,750

            Michael Silva
            Marketing Designer
            London
            66
            2012/11/27
            $198,500

            Paul Byrd
            Chief Financial Officer (CFO)
            New York
            64
            2010/06/09
            $725,000

            Gloria Little
            Systems Administrator
            New York
            59
            2009/04/10
            $237,500

            Bradley Greer
            Software Engineer
            London
            41
            2012/10/13
            $132,000

            Dai Rios
            Personnel Lead
            Edinburgh
            35
            2012/09/26
            $217,500

            Jenette Caldwell
            Development Lead
            New York
            30
            2011/09/03
            $345,000

            Yuri Berry
            Chief Marketing Officer (CMO)
            New York
            40
            2009/06/25
            $675,000

            Caesar Vance
            Pre-Sales Support
            New York
            21
            2011/12/12
            $106,450

            Doris Wilder
            Sales Assistant
            Sidney
            23
            2010/09/20
            $85,600

            Angelica Ramos
            Chief Executive Officer (CEO)
            London
            47
            2009/10/09
            $1,200,000

            Gavin Joyce
            Developer
            Edinburgh
            42
            2010/12/22
            $92,575

            Jennifer Chang
            Regional Director
            Singapore
            28
            2010/11/14
            $357,650

            Brenden Wagner
            Software Engineer
            San Francisco
            28
            2011/06/07
            $206,850

            Fiona Green
            Chief Operating Officer (COO)
            San Francisco
            48
            2010/03/11
            $850,000

            Shou Itou
            Regional Marketing
            Tokyo
            20
            2011/08/14
            $163,000

            Michelle House
            Integration Specialist
            Sidney
            37
            2011/06/02
            $95,400

            Suki Burks
            Developer
            London
            53
            2009/10/22
            $114,500

            Prescott Bartlett
            Technical Author
            London
            27
            2011/05/07
            $145,000

            Gavin Cortez
            Team Leader
            San Francisco
            22
            2008/10/26
            $235,500

            Martena Mccray
            Post-Sales support
            Edinburgh
            46
            2011/03/09
            $324,050

            Unity Butler
            Marketing Designer
            San Francisco
            47
            2009/12/09
            $85,675

            Howard Hatfield
            Office Manager
            San Francisco
            51
            2008/12/16
            $164,500

            Hope Fuentes
            Secretary
            San Francisco
            41
            2010/02/12
            $109,850

            Vivian Harrell
            Financial Controller
            San Francisco
            62
            2009/02/14
            $452,500

            Timothy Mooney
            Office Manager
            London
            37
            2008/12/11
            $136,200

            Jackson Bradshaw
            Director
            New York
            65
            2008/09/26
            $645,750

            Olivia Liang
            Support Engineer
            Singapore
            64
            2011/02/03
            $234,500

            Bruno Nash
            Software Engineer
            London
            38
            2011/05/03
            $163,500

            Sakura Yamamoto
            Support Engineer
            Tokyo
            37
            2009/08/19
            $139,575

Can any one help me how do I exclude or hide some column like "AGE"...etc while exporting to PDF,Excel or CSV

Body:
You can use following to export only visible column:

exportOptions:{
       columns: ':visible'
 }


来源: stackexchange

问:
Appcelerator / Titanium location of iOS simulator sqlite database
I'm posting this to assist users who will be encountering the same thing I did when trying to locate a sqlite database being used on the iOS simulator when using Appcelerator.

xCode Version: 8.3.x

Appcelerator Studio: 4.8.x / SDK: 6.x

Issue/Test Case: I need to test several iterations of loading data from the sqlite database to a remote mySQL server. I want to place an existing sqlite database file in the folder and have the simulator recognize this file so I can use it for testing/development.

Question: Where is the sqlite database stored on the iOS simulator, can I place an existing sqlite database in this folder and have my app recognize it?

Answer: Yes

Steps to achieve:
This is what I did to locate where the simulator/device is looking for

1. Find out where your application is located in the filesystem by adding this code in your index.js (or another file of your choosing).

Ti.API.info("app directory: " + Ti.Filesystem.applicationDataDirectory);

This will give you the long filesystem directory location:
/Users/[username]/Library/Developer/CoreSimulator/Devices/96662E38-C659-4568-B53F-C32DC6B2B73D/data/Containers/Data/Application/96662E38-C659-4568-B53F-C32AB6B2C03D /Documents/

2. This was almost the correct location but the sqlite database is actually stored in the following location:

/Users/[username]/Library/Developer/CoreSimulator/Devices/96662E38-C659-4568-B53F-C32DC6B2B73D/data/Containers/Data/Application/96662E38-C659-4568-B53F-C32AB6B2C03D /Library/Private Documents/[filename].sql

3. You can use this location to put an existing sqlite database file and execute sql statements against it.

4. I'm sure you could reference another directory in your app but I was looking for the default storage directory since my app uses this location.

Hope this helps someone, as I was looking for this specific functionality for testing/development.

Happy Coding!

答:
An easy way to get the database included is to simply add it to the resources folder, or a sub folder in the resources directory. Then you simply call the Ti.Database.install() method. This will copy the database into the simulator location you found. The upside with this method is that you don't have find the location for each iOS simulator (i.e. iPhone 5, 6, 6 plus, 7...).

I do use your method when I need to query the database externally with SQLite manager or another such program.

You can read more here http://docs.appcelerator.com/platform/latest/#!/guide/Working_with_a_SQLite_Database

ContentLicense: CC BY-SA 3.0


问:
SQL 2005 - quick way to quickly duplicate a database + data
I have my development database, I want to spin off a duplicate for testing.  I want to do this often.

What's the fastest and easiest way to do this often?  I can get the job done by generating scripts w/ data included but I feel like there must be a better way.  Should I back up database 1 then screw around with it so I can restore it as a different name?

答: And you can also use the SQL Management Studio UI to create a file backup, and then restore it into a new database on the same or any other server. </p>

OwnerDisplayName: BPAndrew

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: Charles Bretana


问:
Integer vs char for DB record property
Say I have a table with real estate listings. Every listing can be either 'For sale' or 'For rent'. Therefore, I can map 'For sale' to 0, 'For rent' to 1 and store it as an INT in the database. However, it would be much more descriptive if I store it as 'sale' / 'rent' in a field of type CHAR. Or I can map 0 and 1 to two constants FOR_SALE and FOR_RENT in my program. Or use chars 'S' and 'R'. What are the best practices for storing such properties in a database with a condition that the total number of options for one such property is very small.</p>

答:
I'd just use a char(1) for such a simple thing; I'd also slap a CHECK constraint on it (if available) to give some measure of sanity checking. Adding an extra table for something with only two values is a bit pointless even if it is pendantically correct. Also, an S or R in the column will help you when you're debugging or mucking around in the database by hand, a 1 or 6 will be pretty much meaningless.

Of course, if you have values and can't come up with sensible mnemonic characters to represent them, then the "int and an FK" approach makes more sense.

You can change from char(1) to "int and an FK" quite easily if it ever becomes necessary.

Title: Integer vs char for DB record property


问:
Finding and grouping anagrams by Python
```<code>input: ['abc', 'cab', 'cafe', 'face', 'goo']
output: [['abc', 'cab'], ['cafe', 'face'], ['goo']]
</code>```

The problem is simple: it groups by anagrams. The order doesn't matter.

Of course, I can do this by C++ (that's my mother tongue). But, I'm wondering this can be done in a single line by Python. EDITED: If it's not possible, maybe 2 or 3 lines. I'm a newbie in Python.

To check whether two strings are anagram, I used sorting.

```<code>>>> input = ['abc', 'cab', 'cafe', 'face', 'goo']
>>> input2 = [''.join(sorted(x)) for x in input]
>>> input2
['abc', 'abc', 'acef', 'acef', 'goo']
</code>```

I think it may be doable by combining map or so. But, I need to use a dict as a hash table. I don't know yet whether this is doable in a single line. Any hints would be appreicated!

答:
Dave's answer is concise, however the sort which is required by groupby is a O(n log(n)) operation.
A faster solution is this:

```<code>from collections import defaultdict

def group_anagrams(strings):
    m = defaultdict(list)

    for s in strings:
        m[tuple(sorted(s))].append(s)

    return list(m.values())
</code>```

Title: Finding and grouping anagrams by Python

Body:
input: ['abc', 'cab', 'cafe', 'face', 'goo']
output: [['abc', 'cab'], ['cafe', 'face'], ['goo']]

The problem is simple: it groups by anagrams. The order doesn't matter.

Of course, I can do this by C++ (that's my mother tongue). But, I'm wondering this can be done in a single line by Python. EDITED: If it's not possible, maybe 2 or 3 lines. I'm a newbie in Python.

To check whether two strings are anagram, I used sorting.

>>> input = ['abc', 'cab', 'cafe', 'face', 'goo']
>>> input2 = [''.join(sorted(x)) for x in input]
>>> input2
['abc', 'abc', 'acef', 'acef', 'goo']

I think it may be doable by combining map or so. But, I need to use a dict as a hash table. I don't know yet whether this is doable in a single line. Any hints would be appreicated!

Body:
Dave's answer is concise, however the sort which is required by groupby is a O(n log(n)) operation.
A faster solution is this:

from collections import defaultdict

def group_anagrams(strings):
    m = defaultdict(list)

    for s in strings:
        m[tuple(sorted(s))].append(s)

    return list(m.values())


问:
PHP mail() function will not send to gmail but will send to my non-gmail account
For some reason the php mail() function is not working properly on a site I am building. I tried to troubleshoot the issue down to its simplest form, and came up with this file:

```<code><?php
mail('myEmail@gmail.com', 'the subject', 'the message', 'From: webmaster@example.com', '-fwebmaster@example.com');
?>
</code>```

when myEmail is a Gmail account, I never receive  the message. However when I use a non-gmail account, I do receive the message. I am at a loss and have tried everything to figure this out. I am starting to think it is an obscure host/server issue. You can see the server specs here: http://aopmfg.com/php.php

Any ideas?

EDIT - let me also add that this was all working fine a few weeks ago, the last time I tested it. No significant code changes since then at all.

EDIT 2 - After reading a similar post I tried adding From and Reply-To headers... still no luck. New code:

```<code><?
$headers = 'From: <some@email.com>' . "\r\n" .
'Reply-To: <some@email.com>';

mail('<myEmail@gmail.com>', 'the subject', 'the message', $headers,
'-fwebmaster@example.com');
?>
</code>```

答: I was having the same problem.  But when I checked my C:\xampp\mailoutput folder, the mail sent was received in this folder.  Now please check and do the needful.  It was sent in my testing local server.  If it is sent on the real server, that may be on your hosting server and you have to check through site hoster</p>

ContentLicense: CC BY-SA 4.0

Body:
For some reason the php mail() function is not working properly on a site I am building. I tried to troubleshoot the issue down to its simplest form, and came up with this file:

<?php
mail('myEmail@gmail.com', 'the subject', 'the message', 'From: webmaster@example.com', '-fwebmaster@example.com');
?>

when myEmail is a Gmail account, I never receive  the message. However when I use a non-gmail account, I do receive the message. I am at a loss and have tried everything to figure this out. I am starting to think it is an obscure host/server issue. You can see the server specs here: http://aopmfg.com/php.php

Any ideas?

EDIT - let me also add that this was all working fine a few weeks ago, the last time I tested it. No significant code changes since then at all.

EDIT 2 - After reading a similar post I tried adding From and Reply-To headers... still no luck. New code:

<?
$headers = 'From: <some@email.com>' . "\r\n" .
'Reply-To: <some@email.com>';

mail('<myEmail@gmail.com>', 'the subject', 'the message', $headers,
'-fwebmaster@example.com');
?>


问:
How do you remove a RigidArea from a JPanel
To add a RigidArea, say, to put space between components, you do:

```<code>panel.add(Box.createRigidArea(new Dimension(int, int))):
</code>```

In general, how would you remove that space from said panel?

答:
how would you remove that space from said panel?

The rigid area is a component just like a button or text field. So keep a reference to it:

```<code>Component emptySpace = Box.createRigidArea( ... );
panel.add( emptySpace );
</code>```

Then when you want to remove it you would use:

```<code>panel.remove( emptySpace );
panel.revalidate();
panel.repaint();
</code>```

Body:
To add a RigidArea, say, to put space between components, you do:

panel.add(Box.createRigidArea(new Dimension(int, int))):

In general, how would you remove that space from said panel?

Body:
how would you remove that space from said panel?

The rigid area is a component just like a button or text field. So keep a reference to it:

Component emptySpace = Box.createRigidArea( ... );
panel.add( emptySpace );

Then when you want to remove it you would use:

panel.remove( emptySpace );
panel.revalidate();
panel.repaint();


问:
C double pointers malloc
I am trying to understand pointers, and trying to define a structure as follows.

| header info (size_t) | pointer to cstring |

here is part of the code. I type defined string as char**.

```<code>string str_constructor(const char* const str)
{
    size_t* header = (size_t*)(malloc(sizeof(size_t) + sizeof(char**)));
    char** data = (char**)(header + 1); //data is now the address of the pointer to cstring
    *data = (char*)(malloc(strlen(str) + 1)); // plus one char for null character
    for (int i = 0; i != strlen(str); i++)
    {
        *data[i] = str[i]; // cstring deep copy
    }
    *header = strlen(str); // store length of string
    *data[*header] = '\0'; // append null character
    return data;
}
</code>```

The program crashed on 2nd iteration of the for-loop.

Basically I want to define a string, where *string would return the char*.

答:
This is a highly unorthodox way of creating a structure in memory, but if, as you say, you want to understand pointers, then who are we to tell you to do it differently?

The only real problem with the code you posted is that *data[i] = ... should be (*data)[i] = ....

That having been said, you might want to consider that your way of creating a structure in memory ignores the native alignment of the CPU, which means that you are bound to get sub-optimal performance.  Declaring a struct would have taken care of that.  On some architectures (not x86 luckily) your program may even crash if it attempts to make a non properly aligned memory access.

Title: C double pointers malloc

Body:
I am trying to understand pointers, and trying to define a structure as follows.

| header info (size_t) | pointer to cstring |

here is part of the code. I type defined string as char**.

string str_constructor(const char* const str)
{
    size_t* header = (size_t*)(malloc(sizeof(size_t) + sizeof(char**)));
    char** data = (char**)(header + 1); //data is now the address of the pointer to cstring
    *data = (char*)(malloc(strlen(str) + 1)); // plus one char for null character
    for (int i = 0; i != strlen(str); i++)
    {
        *data[i] = str[i]; // cstring deep copy
    }
    *header = strlen(str); // store length of string
    *data[*header] = '\0'; // append null character
    return data;
}

The program crashed on 2nd iteration of the for-loop.

Basically I want to define a string, where *string would return the char*.


问:
express.static only loading to index.html
I am trying to get the static files (images, js, css) which are all inside the public folder to be available to all my routes. I am able to ONLY load them to the index.html. The management.html files does not have access to the static files, I am getting 404 error on the Chrome console.

Folder Structure:

```<code>-app/
---index.html
---management.html
---public/
------css/
------js/
------img/
</code>```

server.js:

```<code>const express = require('express');
const path = require('path');

var app = express();

app.use(express.static(path.join(__dirname, 'public')));

app.get('/', function(req, res) {
    res.sendFile('index.html', {root: __dirname })
});

app.get('/management', function(req, res) {
    res.sendFile('management.html', {root: __dirname })
});

app.listen(3000);
</code>```

答:
Inside your HTML files you are probably referring to the relative paths of the static files. For example: . This link will be based on your current location.

When your current location is http://example.com/ (index.html), then it will refer to http://example.com/img/example.png, where the file is probably located.

But when your location is http://example.com/management (management.html), it refers to http://example.com/management/img/example.png, which will return a 404.

Using the absolute path of this file will solve this problem. You can do this by putting a / in front of the relative path: . Alternatively you could use a relative path in management.html like this: .

Body:
I am trying to get the static files (images, js, css) which are all inside the public folder to be available to all my routes. I am able to ONLY load them to the index.html. The management.html files does not have access to the static files, I am getting 404 error on the Chrome console.

Folder Structure:

-app/
---index.html
---management.html
---public/
------css/
------js/
------img/

server.js:

const express = require('express');
const path = require('path');

var app = express();

app.use(express.static(path.join(__dirname, 'public')));

app.get('/', function(req, res) {
    res.sendFile('index.html', {root: __dirname })
});

app.get('/management', function(req, res) {
    res.sendFile('management.html', {root: __dirname })
});

app.listen(3000);

Body:
Inside your HTML files you are probably referring to the relative paths of the static files. For example: <img src="img/example.png">. This link will be based on your current location.

When your current location is http://example.com/ (index.html), then it will refer to http://example.com/img/example.png, where the file is probably located.

But when your location is http://example.com/management (management.html), it refers to http://example.com/management/img/example.png, which will return a 404.

Using the absolute path of this file will solve this problem. You can do this by putting a / in front of the relative path: <img src="/img/example.png">. Alternatively you could use a relative path in management.html like this: <img src="../img/example.png">.


问:
How to redirect from index page to other page
How can I redirect by loading the page from localhost:xxxx/#/ to localhost:xxxx/#/month ?

I have such index.js code, that calling App class:

```<code>ReactDOM.render((
    <HashRouter>
        <Route path="/" component={App}>
        </Route>
    </HashRouter>
), document.getElementById('root'));
</code>```

App.js has static information and in component View will be dynamic information:

```<code>export default class App extends React.Component {
  render() {
    return (
      <div>
        Hello App)
        <View/>
      </div>
    );
  }
}
</code>```

View.js:

```<code>export default class View extends React.Component {
    render() {
        return(
                <div>
                    <p>this is View</p>
                    <ul>
                        <li><Link to="/month">Month</Link></li>
                        <li><Link to="/week">Week</Link></li>
                        <li><Link to="/day">Day</Link></li>
                        <li><Link to="/year">Year</Link></li>
                    </ul>
                    <Switch>
                        <Route exact path="/month" component={Month} />
                        <Route path="/week" component={Week} />
                        <Route path="/day" component={Day} />
                        <Route path="/year" component={Year} />
                    </Switch>
                </div>
        );
    }
}
</code>```

答:
You can use Redirect.</p>

```<code><Route exact path={your_root_path} render={() => <Redirect to={month_path} />} />
</code>```

Body:
How can I redirect by loading the page from localhost:xxxx/#/ to localhost:xxxx/#/month ?

I have such index.js code, that calling App class:

ReactDOM.render((
    <HashRouter>
        <Route path="/" component={App}>
        </Route>
    </HashRouter>
), document.getElementById('root'));

App.js has static information and in component View will be dynamic information:

export default class App extends React.Component {
  render() {
    return (

        Hello App)
        <View/>

    );
  }
}

View.js:

export default class View extends React.Component {
    render() {
        return(

this is View

<Link to="/month">Month</Link>

<Link to="/week">Week</Link>

<Link to="/day">Day</Link>

<Link to="/year">Year</Link>

                    <Switch>
                        <Route exact path="/month" component={Month} />
                        <Route path="/week" component={Week} />
                        <Route path="/day" component={Day} />
                        <Route path="/year" component={Year} />
                    </Switch>

        );
    }
}

Body:
You can use Redirect.

<Route exact path={your_root_path} render={() => <Redirect to={month_path} />} />


问:
How to forward existing domain name to AWS application?
I have deployed an application with Amazon's Elastic Beanstalk service, now it runs in http://sample-env-1.abcde.us-east-1.elasticbeanstalk.com/home, and now I want to point my domain name (registered with name.com) to this application. I created a hosted zone with Route 53, which gives me 4 namespaces, is it enough to add these records in my domain registrar's console?

I feel like I'm missing something since I didn't tell which application should this hosted zone be relevant to (since I can have multiple applications). How do I do that?

Thanks,

答:
Your way of doing it is right.

Type the domain name in Hosted Zone of Amazon Route 53 Management console.
And from your domain provider console point your domain to your Elastic Beanstalk environment namespace. Amazon will handle the rest, if the setup is done correctly.

As stated in the manual:

When an Amazon Route 53 DNS server receives a name request for your
  custom domain name, it resolves to the elasticbeanstalk.com subdomain,
  which resolves to the public DNS name of your Elastic Load Balancing
  load balancer, which relays requests to the instances in your
  environment.

Please refer to the Elastic Beanstalk manual for more information: http://docs.aws.amazon.com/elasticbeanstalk/latest/dg/customdomains.html


问:
Changing single item in foreach loop
I would like to generate a navigation menu using PHP and its foreach loop. So since the "Home" item is a bit different than the others, I would like to call him, and change its style in some certain condition. This code below works fine for all other menu items except the homepage, as it adds array to the
 tag for some reason. Can you please show the mistake I make here?

```<code><?php
  $menu = array("Home" => "http://mywebsite.com", "Projects" => "/projects/", "About" => "/about/", "Contact" => "/contact/");
  foreach ($menu as $opis => $link)
  {
    if (strtolower($opis) == $_GET['go'])
    {
      $style = "class=\"active\"";
    }
    else
    {
      if (!$_GET['go'] || $_GET['go'] == "home")
      {
        $style[0] = "class=\"active\"";
        echo $style[0] . " ";
      }
    }
    echo "<li ".$style."><a href=".$link.">".$opis."</a></li>";
  }
?>
</code>```

答:
This is because you've added a key to the variable $style when $GET['go'] is home -

```<code>$style[0] = "class=\"active\"";
</code>```

Change this to $style = "class=\"active\"";

Title: Changing single item in foreach loop

Body:
I would like to generate a navigation menu using PHP and its foreach loop. So since the "Home" item is a bit different than the others, I would like to call him, and change its style in some certain condition. This code below works fine for all other menu items except the homepage, as it adds array to the
 tag for some reason. Can you please show the mistake I make here?

<?php
  $menu = array("Home" => "http://mywebsite.com", "Projects" => "/projects/", "About" => "/about/", "Contact" => "/contact/");
  foreach ($menu as $opis => $link)
  {
    if (strtolower($opis) == $_GET['go'])
    {
      $style = "class=\"active\"";
    }
    else
    {
      if (!$_GET['go'] || $_GET['go'] == "home")
      {
        $style[0] = "class=\"active\"";
        echo $style[0] . " ";
      }
    }
    echo "
".$opis."
";
  }
?>

Body:
This is because you've added a key to the variable $style when $GET['go'] is home -

$style[0] = "class=\"active\"";

Change this to $style = "class=\"active\"";


问:
Number of tokens in compiler
I want to know number of tokens in the statement given below

```<code>a+++b---c
</code>```

Please tell me number of tokens
I told my viva teacher that there are 7 tokens but he said it is wrong.

答:
You are correct. There are seven tokens: (in C)</p>

```<code>a
++
+
b
--
-
c
</code>```

Title: Number of tokens in compiler

Body:
I want to know number of tokens in the statement given below

a+++b---c

Please tell me number of tokens
I told my viva teacher that there are 7 tokens but he said it is wrong.

Body:
You are correct. There are seven tokens: (in C)

a
++
+
b
--
-
c


问:
How to exclude text between two curly brackets with regex?
I am new to regular expressions, I have a text like this:

test{{this should not be selected and the curly brackets too}} but
  this one { or } should be selected.  So I want to exclude all text
  between an opening and closing curly brackets.

and I want this result

"test"

and

"but this one { or } should be selected.  So I want to exclude all text
  between an opening and closing curly brackets."

This is my expression I used:

```<code>$p = '/[a-zA-Z0-9#\' ]+(?![^{{]*}})/';
</code>```

But this excludes the single curly brackets.

I want to know how to include the single curly brackets with the text and exclude only text between two curly brackets

And please can you give me some good documentation about regex expression? I want to learn more about this.

答:
```<code>(?:^|(?:}}))(.+?)(?:$|{{)
</code>```

Try it: https://regex101.com/r/2Xy7gU/1/

What is happening here:

(?:^|(?:}})) - it starts with either beginning of string or }}

(.+?) - matches everything (ungreedy)

(?:$|{{) - match have to
end with either end of string or {{

What you want (without the brackets) is in first group.

Body:
I am new to regular expressions, I have a text like this:

test{{this should not be selected and the curly brackets too}} but
  this one { or } should be selected.  So I want to exclude all text
  between an opening and closing curly brackets.

and I want this result

"test"

and

"but this one { or } should be selected.  So I want to exclude all text
  between an opening and closing curly brackets."

This is my expression I used:

$p = '/[a-zA-Z0-9#\' ]+(?![^{{]*}})/';

But this excludes the single curly brackets.

I want to know how to include the single curly brackets with the text and exclude only text between two curly brackets

And please can you give me some good documentation about regex expression? I want to learn more about this.

Body:
(?:^|(?:}}))(.+?)(?:$|{{)

Try it: https://regex101.com/r/2Xy7gU/1/

What is happening here:

(?:^|(?:}})) - it starts with either beginning of string or }}

(.+?) - matches everything (ungreedy)

(?:$|{{) - match have to
end with either end of string or {{

What you want (without the brackets) is in first group.


问:
Problems returning false after using XMLHttpRequest
I have found this Related entry and a few others but I have not quite found my answer so I am posting new. I am trying to run a database query from JavaScript using what I understand of Ajax. I need to return false if the email is already in the database and return true if it does not, but I cannot seem to figure out what I am doing wrong. I have posted my first attempt before I started messing around and making it messy.

JavaScript: It seems to return true no matter what.

```<code>function emailvalid(){

var email = document.getElementById('email').value;
var confirmemail = document.getElementById('cemail').value;
if(email != '' && confirmemail != '')
{
    if(email == '')
    {
        document.getElementById('email').style.backgroundColor ='red';
        document.getElementById('tdemail').style.color = 'red';
        document.getElementById('tdemail').innerHTML = 'You must enter a valid email address.';
        document.getElementById('tdcemail').innerHTML = '';
        document.getElementById('cemail').value = '';
        return false;
    }

xmlhttp = new XMLHttpRequest();
var url="phpfiles/checkemail.php";
url = url+"?email="+email+"&cemail="+confirmemail;
xmlhttp.onreadystatechange = function()
{
    if (xmlhttp.readyState==4)
    {
        var answer = xmlhttp.responseText;
        if(answer == 'r0')
        {

        document.getElementById('email').style.backgroundColor ='green';
        document.getElementById('tdemail').style.color = 'red';
        document.getElementById('tdemail').innerHTML = 'This email address is already associated with an exiting account. Please login or use a different email address.';
        document.getElementById('tdcemail').innerHTML = '';
        document.getElementById('cemail').value = '';
        return false;
        }
        else if(answer == 'r1')
        {

        document.getElementById('tdemail').style.color = 'green';
        document.getElementById('email').style.backgroundColor ='green';
        document.getElementById('tdemail').innerHTML = "Emails match and are valid";
        document.getElementById('tdcemail').style.color = 'green';
        document.getElementById('tdcemail').innerHTML = "Emails match and are valid";
        document.getElementById('cemail').style.backgroundColor ='green';
        return true;
        }
        else if(answer == 'r2')
        {

        document.getElementById('tdemail').style.color = 'red';
        document.getElementById('email').style.backgroundColor ='red';
        document.getElementById('tdemail').innerHTML = "Email is not valid";
        document.getElementById('tdcemail').style.color = 'red';
        document.getElementById('tdcemail').innerHTML = "Email is not valid.";
        document.getElementById('cemail').style.backgroundColor ='red';
        return false;
        }
        else if(answer == 'r3')
        {

        document.getElementById('tdemail').style.color = 'green';
        document.getElementById('email').style.backgroundColor ='green';
        document.getElementById('tdemail').innerHTML = "Email is valid";
        document.getElementById('tdcemail').style.color = 'red';
        document.getElementById('tdcemail').innerHTML = "Emails do not match";
        document.getElementById('cemail').style.backgroundColor ='red';
        return false;
        }
        else if(answer == 'r4')
        {

        document.getElementById('tdemail').style.color = 'red';
        document.getElementById('email').style.backgroundColor ='red';
        document.getElementById('tdemail').innerHTML = 'Please enter a valid email address.';
        document.getElementById('tdcemail').style.color = 'red';
        document.getElementById('tdcemail').innerHTML = 'Please enter a valid email address.';
        document.getElementById('cemail').style.backgroundColor ='red';
        return false;
        }
    }
}
    xmlhttp.open("GET",url,true);
    xmlhttp.send(null);

}
else
{
    document.getElementById('tdemail').style.color = 'red';
    document.getElementById('email').style.backgroundColor ='red';
    document.getElementById('tdemail').innerHTML = "Email is not valid";
    document.getElementById('tdcemail').style.color = 'red';
    document.getElementById('tdcemail').innerHTML = "Email is not valid.";
    document.getElementById('cemail').style.backgroundColor ='red';
    return false;
}
}
</code>```

The innerHTML stuff works just fine which is also why I am confused.

PHP: works fine as far as I can tell.

```<code><?php
$email = $_GET['email'];
$cemail = $_GET['cemail'];
$emailvalidstring = "/^[a-z0-9]+([_\\.-][a-z0-9]+)*@([a-z0-9]+([\.-][a-z0-9]+)*)+\\.[a-z]{2,}$/i";
include('connection.php');

$checkemailquery = "SELECT email FROM users WHERE email='".$email."'";
$checkemailresult = mysql_query($checkemailquery);

// if query failed.
if(!$checkemailresult)
{
    $error = mysql_error();
    print $error;
    exit;
}
//if the query did run, the email exists. Print error and exit.
if(mysql_affected_rows() != 0)
{
    echo "r0";
    return false;
}
else{
    if(preg_match($emailvalidstring, $email) && $email == $cemail)
    {
        echo "r1";
        return true;
    }
    else if(!preg_match($emailvalidstring, $email) && $email == $cemail)
    {
            echo "r2";
            return false;
    }
    else if(preg_match($emailvalidstring, $email) && $email != $cemail)
    {
        echo "r3";
        return false;
    }
    else if(!preg_match($emailvalidstring, $email) && $email != $cemail)
    {
        echo "r4";
        return false;
    }
}
?>
</code>```

html: I have it do a double check, once to alert the user if it is already taken, and then a second check on the server to make sure it is still true. cemail is the confirmation email.

```<code><form  id="newaccount" name="newaccount" method="post" action="phpfiles/accountcode.php" onSubmit="return emailvalid()" >
<input type="text" id="email" onBlur="emailvalid()"/>
<input type="text" id="cemail" onBlur="emailvalid()" />
<input type="submit" value="New"/>
</form>
</code>```

I hope I have laid it out well enough. I am open to ANY ideas as I am rather new at this.

答: You're returning false in the anonymous callback function not in the emailValid function. Just declare a global boolean variable and alter it accordingly in the anonymous callback function.

Body:
I have found this Related entry and a few others but I have not quite found my answer so I am posting new. I am trying to run a database query from JavaScript using what I understand of Ajax. I need to return false if the email is already in the database and return true if it does not, but I cannot seem to figure out what I am doing wrong. I have posted my first attempt before I started messing around and making it messy.

JavaScript: It seems to return true no matter what.

function emailvalid(){

var email = document.getElementById('email').value;
var confirmemail = document.getElementById('cemail').value;
if(email != '' && confirmemail != '')
{
    if(email == '')
    {
        document.getElementById('email').style.backgroundColor ='red';
        document.getElementById('tdemail').style.color = 'red';
        document.getElementById('tdemail').innerHTML = 'You must enter a valid email address.';
        document.getElementById('tdcemail').innerHTML = '';
        document.getElementById('cemail').value = '';
        return false;
    }

xmlhttp = new XMLHttpRequest();
var url="phpfiles/checkemail.php";
url = url+"?email="+email+"&cemail="+confirmemail;
xmlhttp.onreadystatechange = function()
{
    if (xmlhttp.readyState==4)
    {
        var answer = xmlhttp.responseText;
        if(answer == 'r0')
        {

        document.getElementById('email').style.backgroundColor ='green';
        document.getElementById('tdemail').style.color = 'red';
        document.getElementById('tdemail').innerHTML = 'This email address is already associated with an exiting account. Please login or use a different email address.';
        document.getElementById('tdcemail').innerHTML = '';
        document.getElementById('cemail').value = '';
        return false;
        }
        else if(answer == 'r1')
        {

        document.getElementById('tdemail').style.color = 'green';
        document.getElementById('email').style.backgroundColor ='green';
        document.getElementById('tdemail').innerHTML = "Emails match and are valid";
        document.getElementById('tdcemail').style.color = 'green';
        document.getElementById('tdcemail').innerHTML = "Emails match and are valid";
        document.getElementById('cemail').style.backgroundColor ='green';
        return true;
        }
        else if(answer == 'r2')
        {

        document.getElementById('tdemail').style.color = 'red';
        document.getElementById('email').style.backgroundColor ='red';
        document.getElementById('tdemail').innerHTML = "Email is not valid";
        document.getElementById('tdcemail').style.color = 'red';
        document.getElementById('tdcemail').innerHTML = "Email is not valid.";
        document.getElementById('cemail').style.backgroundColor ='red';
        return false;
        }
        else if(answer == 'r3')
        {

        document.getElementById('tdemail').style.color = 'green';
        document.getElementById('email').style.backgroundColor ='green';
        document.getElementById('tdemail').innerHTML = "Email is valid";
        document.getElementById('tdcemail').style.color = 'red';
        document.getElementById('tdcemail').innerHTML = "Emails do not match";
        document.getElementById('cemail').style.backgroundColor ='red';
        return false;
        }
        else if(answer == 'r4')
        {

        document.getElementById('tdemail').style.color = 'red';
        document.getElementById('email').style.backgroundColor ='red';
        document.getElementById('tdemail').innerHTML = 'Please enter a valid email address.';
        document.getElementById('tdcemail').style.color = 'red';
        document.getElementById('tdcemail').innerHTML = 'Please enter a valid email address.';
        document.getElementById('cemail').style.backgroundColor ='red';
        return false;
        }
    }
}
    xmlhttp.open("GET",url,true);
    xmlhttp.send(null);

}
else
{
    document.getElementById('tdemail').style.color = 'red';
    document.getElementById('email').style.backgroundColor ='red';
    document.getElementById('tdemail').innerHTML = "Email is not valid";
    document.getElementById('tdcemail').style.color = 'red';
    document.getElementById('tdcemail').innerHTML = "Email is not valid.";
    document.getElementById('cemail').style.backgroundColor ='red';
    return false;
}
}

The innerHTML stuff works just fine which is also why I am confused.

PHP: works fine as far as I can tell.

<?php
$email = $_GET['email'];
$cemail = $_GET['cemail'];
$emailvalidstring = "/^[a-z0-9]+([_\\.-][a-z0-9]+)*@([a-z0-9]+([\.-][a-z0-9]+)*)+\\.[a-z]{2,}$/i";
include('connection.php');

$checkemailquery = "SELECT email FROM users WHERE email='".$email."'";
$checkemailresult = mysql_query($checkemailquery);

// if query failed.
if(!$checkemailresult)
{
    $error = mysql_error();
    print $error;
    exit;
}
//if the query did run, the email exists. Print error and exit.
if(mysql_affected_rows() != 0)
{
    echo "r0";
    return false;
}
else{
    if(preg_match($emailvalidstring, $email) && $email == $cemail)
    {
        echo "r1";
        return true;
    }
    else if(!preg_match($emailvalidstring, $email) && $email == $cemail)
    {
            echo "r2";
            return false;
    }
    else if(preg_match($emailvalidstring, $email) && $email != $cemail)
    {
        echo "r3";
        return false;
    }
    else if(!preg_match($emailvalidstring, $email) && $email != $cemail)
    {
        echo "r4";
        return false;
    }
}
?>

html: I have it do a double check, once to alert the user if it is already taken, and then a second check on the server to make sure it is still true. cemail is the confirmation email.

<form  id="newaccount" name="newaccount" method="post" action="phpfiles/accountcode.php" onSubmit="return emailvalid()" >
<input type="text" id="email" onBlur="emailvalid()"/>
<input type="text" id="cemail" onBlur="emailvalid()" />
<input type="submit" value="New"/>
</form>

I hope I have laid it out well enough. I am open to ANY ideas as I am rather new at this.


问:
How to create a GMSPlace
I'm using the Google Maps iOS SDK and would like to store recent places (GMSPlace objects) that users search for. I'm running into a problem retrieving those places, as it doesn't seem like GMSPlaces can be instantiated directly.

Is it possible to instantiate a GMSPlace object?

Thanks!

答: No, you can't instantiate a GMSPlace object.

Title: How to create a GMSPlace


问:
Getting Max date from the given two dates in mysql
I have a table with below structure and data.

```<code>id ean           Control_date qty
1  4046228081410 26.05.2017   568
2  4046228081410 05.06.2017   900
</code>```

My expected result would be like below

```<code>2  4046228081410 05.06.2017   1468
</code>```

To acheive this i am using the below query

```<code> SELECT EAN,Control_date,SUM(Qty) AS Qty FROM mytable WHERE
(STR_TO_DATE(`Control_date`,'%d.%m.%Y') <= STR_TO_DATE('03.06.2017','%d.%m.%Y')
OR
STR_TO_DATE(`Control_date`, '%d.%m.%Y') <= DATE_ADD(STR_TO_DATE('03.06.2017', '%d.%m.%Y'), INTERVAL 7 DAY))
AND ean = 4046228081410
</code>```

Here i need to sum up the qty where control date< today date and control date > today date and should be less than todaydate + 7 days . Here 2nd control date is 05.06.2017 and greater than today date and less than (03.05.2017 +7 days)
But always i am getting where contorl date is less than today date.

```<code>1  4046228081410 26.05.2017   1468
</code>```

But i need data with control date 05.06.2017.
Any help would be greatly appreciated.

答:
You should really fix your date formats.  If you stored the value as a date, the query would simply be:

```<code>SELECT EAN, MAX(Control_date), SUM(Qty) AS Qty
FROM mytable
WHERE Control_date < CURDATE() + INTERVAL 7 DAYS AND
      Control_date >= CURDATE() AND
      ean = 4046228081410
GROUP BY ean;
</code>```

Note:  You can use a constant such as '2017-06-03' if you want a constant date.  However, your question specifically says the current date.

Just because you have bogus date formats stored in your data doesn't mean you have to use the same format in queries.  The expression '2017-06-03' (or DATE('2017-06-03')) is simpler than the more complex STR_TO_DATE() expression.

In your case, bite the bullet and output the date in a correct format, so you can do:

```<code>SELECT EAN, MAX(STR_TO_DATE(`Control_date`, '%d.%m.%Y')), SUM(Qty) AS Qty
FROM mytable
WHERE STR_TO_DATE(`Control_date`, '%d.%m.%Y') < CURDATE() + INTERVAL 7 DAYS AND
      STR_TO_DATE(`Control_date`, '%d.%m.%Y') >= CURDATE() AND
      ean = 4046228081410
GROUP BY ean;
</code>```

Body:
I have a table with below structure and data.

id ean           Control_date qty
1  4046228081410 26.05.2017   568
2  4046228081410 05.06.2017   900

My expected result would be like below

2  4046228081410 05.06.2017   1468

To acheive this i am using the below query

 SELECT EAN,Control_date,SUM(Qty) AS Qty FROM mytable WHERE
(STR_TO_DATE(`Control_date`,'%d.%m.%Y') <= STR_TO_DATE('03.06.2017','%d.%m.%Y')
OR
STR_TO_DATE(`Control_date`, '%d.%m.%Y') <= DATE_ADD(STR_TO_DATE('03.06.2017', '%d.%m.%Y'), INTERVAL 7 DAY))
AND ean = 4046228081410

Here i need to sum up the qty where control date< today date and control date > today date and should be less than todaydate + 7 days . Here 2nd control date is 05.06.2017 and greater than today date and less than (03.05.2017 +7 days)
But always i am getting where contorl date is less than today date.

1  4046228081410 26.05.2017   1468

But i need data with control date 05.06.2017.
Any help would be greatly appreciated.

Body:
You should really fix your date formats.  If you stored the value as a date, the query would simply be:

SELECT EAN, MAX(Control_date), SUM(Qty) AS Qty
FROM mytable
WHERE Control_date < CURDATE() + INTERVAL 7 DAYS AND
      Control_date >= CURDATE() AND
      ean = 4046228081410
GROUP BY ean;

Note:  You can use a constant such as '2017-06-03' if you want a constant date.  However, your question specifically says the current date.

Just because you have bogus date formats stored in your data doesn't mean you have to use the same format in queries.  The expression '2017-06-03' (or DATE('2017-06-03')) is simpler than the more complex STR_TO_DATE() expression.

In your case, bite the bullet and output the date in a correct format, so you can do:

SELECT EAN, MAX(STR_TO_DATE(`Control_date`, '%d.%m.%Y')), SUM(Qty) AS Qty
FROM mytable
WHERE STR_TO_DATE(`Control_date`, '%d.%m.%Y') < CURDATE() + INTERVAL 7 DAYS AND
      STR_TO_DATE(`Control_date`, '%d.%m.%Y') >= CURDATE() AND
      ean = 4046228081410
GROUP BY ean;


问:
Check whether Laravel Controller Action is defined
I have an application where I will be storing links in the database allowing the user to assign actions to the link. I want to avoid the situation where the action does not exist and I get this error;

Action App\Http\Controllers\PermissionController@index2 not defined.

So I would like to check whether an action exists and has route. If possible in blade but anywhere else is fine.

答:
There isn't any built in way to do this. But we have a action helper method which generates route url based on the controller action. We can make use of this and create a simple helper function to achieve the same result. The method also checks if the given controller method is linked to a route, so it does exactly what you need.

```<code>function action_exists($action) {
    try {
        action($action);
    } catch (\Exception $e) {
        return false;
    }

    return true;
}

// Sample route
Route::get('index', 'TestController@index');

$result = action_exists('TestController@index');
// $result is true

$result = action_exists('TestController@index1');
// $result is false
</code>```

You could also verify the existence of the action method using the class directly, but this would return true if the method exists but isn't linked to a route.

Body:
There isn't any built in way to do this. But we have a action helper method which generates route url based on the controller action. We can make use of this and create a simple helper function to achieve the same result. The method also checks if the given controller method is linked to a route, so it does exactly what you need.

function action_exists($action) {
    try {
        action($action);
    } catch (\Exception $e) {
        return false;
    }

    return true;
}

// Sample route
Route::get('index', 'TestController@index');

$result = action_exists('TestController@index');
// $result is true

$result = action_exists('TestController@index1');
// $result is false

You could also verify the existence of the action method using the class directly, but this would return true if the method exists but isn't linked to a route.


问:
array of pointers and pointer to an array in c++
i have a class in which it's protected section i need to declare an array with unknown size (the size is given to the constructor as a parameter), so i looked around and found out that the best possible solution is to declare an array of pointers, each element points to an integer:

```<code>int* some_array_;
</code>```

and simply in the constructor i'll use the "new" operator:

```<code>some_array_ = new int[size];
</code>```

and it worked, my question is: can i declare an array in a class without defining the size? and if yes how do i do it, if not then why does it work for pointers and not for a normal array?

EDIT: i know vecotrs will solve the problem but i can't use them on my HW

答:
You could always use a vector. To do this, add this line of code: #include <vector> at the top of your code, and then define the vector as follows:

vector<int> vectorName;

Keep in mind that vectors are not arrays and should not be treated as such. For example, in a loop, you would want to retrieve an element of a vector like this: vectorName.at(index) and not like this: vectorName[index]

Body:
i have a class in which it's protected section i need to declare an array with unknown size (the size is given to the constructor as a parameter), so i looked around and found out that the best possible solution is to declare an array of pointers, each element points to an integer:

int* some_array_;

and simply in the constructor i'll use the "new" operator:

some_array_ = new int[size];

and it worked, my question is: can i declare an array in a class without defining the size? and if yes how do i do it, if not then why does it work for pointers and not for a normal array?

EDIT: i know vecotrs will solve the problem but i can't use them on my HW


问:
Complexity Computation
i have to analyse this code's complexity but i'm very comfused with the condition of IF.

```<code>sum=0;
for(i=1;i<n;i++){
  for(j=1;j<i*i; j++){
      if(j%i==0){
         for(k=0;k<j;k++){
          sum++;
         }
      }
   }
}
</code>```

If the "(j%i==0)" if-condition was not there i would be able to compute the complexity but i cant understand it. I need some explanation about how we can compute how many times this condition will be true.

Thank you.

答:
The complexity of the algorithm would be O(n^3), because of the 3 for statements.

You can have a look at if statement - how does IF affect complexity

where there is a nice link on more information.

Title: Complexity Computation

Body:
i have to analyse this code's complexity but i'm very comfused with the condition of IF.

sum=0;
for(i=1;i<n;i++){
  for(j=1;j<i*i; j++){
      if(j%i==0){
         for(k=0;k<j;k++){
          sum++;
         }
      }
   }
}

If the "(j%i==0)" if-condition was not there i would be able to compute the complexity but i cant understand it. I need some explanation about how we can compute how many times this condition will be true.

Thank you.


答:
A couple of issues in your statement.

Date conditions are redundant

Need a MAX function on Control_date

Need group by n EAN

SELECT
    EAN,
    max(Control_date) AS control_date,
    SUM(Qty) AS Qty
FROM mytable
WHERE
    STR_TO_DATE(Control_date, '%d.%m.%Y') <= DATE_ADD(STR_TO_DATE('03.06.2017', '%d.%m.%Y'), INTERVAL 7 DAY)
    AND
    ean = 4046228081410
GROUP BY EAN

Title: Getting Max date from the given two dates in mysql


答:
According to the C standard (pre-C11 draft): http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1548.pdf

6.4 Lexical elements

3 A token is the minimal lexical element of the language in translation phases 7 and 8. The categories of tokens are: keywords, identifiers, constants, string literals, and punctuators. ...

4 If the input stream has been parsed into preprocessing tokens up to a given character, the next preprocessing token is the longest sequence of characters that could constitute a preprocessing token.
... 6 EXAMPLE 2 The program fragment x+++++y is parsed as x ++ ++ + y, which violates a constraint on increment operators, even though the parse x ++ + ++ y might yield a correct expression

6.4.6 Punctuators .. punctuator: one of ++ -- ... + -

So, https://en.wikipedia.org/wiki/Maximal_munch rule is used as was noted in https://stackoverflow.com/a/7485174 and comment about a+++b fragment: What does the operation c=a+++b mean?  Shahbaz Sep 20 2011: "the lexer of C and C++, try to match the biggest string they can when they see something. ... Therefore, when the lexer sees the first plus, it tries the next character, it sees that it can match both characters as a ++, then continues on to see the next +. Hence, the parser sees a ++ + b"

While gcc and clang have complex code and may mix different translation phases of standard in the single code samples (so they are not best guides to the language, as rici said), we may check parsing implementation for ++ and --. When it sees char + it may generate different tokens based on what is the next char, if is + too, emit plusplus token, otherwise emit plus token:

http://code.metager.de/source/xref/llvm/clang/lib/Lex/Lexer.cpp#3264

```<code>3264  case '+':
3265    Char = getCharAndSize(CurPtr, SizeTmp);
3266    if (Char == '+') {
3267      CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3268      Kind = tok::plusplus;
3269    } else if (Char == '=') {
3270      CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3271      Kind = tok::plusequal;
3272    } else {
3273      Kind = tok::plus;
3274    }
3275    break;
</code>```

http://code.metager.de/source/xref/gnu/gcc/libcpp/lex.c#2633

```<code>2633    case '+':
2634      result->type = CPP_PLUS;
2635      if (*buffer->cur == '+')
2636        buffer->cur++, result->type = CPP_PLUS_PLUS;
2637      else if (*buffer->cur == '=')
2638        buffer->cur++, result->type = CPP_PLUS_EQ;
2639      break;
</code>```

So, tokens of a+++b---c expression are a ++ + b -- - c. Advisor may say you are wrong, but only wanting you to explain why you think you counted 7. And if the question is the same task as given and it is parsed according to C standard (or C++ which is same lexing for this example), you can explain your answer and show him relevant parts of language standards.

Title: Number of tokens in compiler

Body:
According to the C standard (pre-C11 draft): http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1548.pdf

6.4 Lexical elements

3 A token is the minimal lexical element of the language in translation phases 7 and 8. The categories of tokens are: keywords, identifiers, constants, string literals, and punctuators. ...

4 If the input stream has been parsed into preprocessing tokens up to a given character, the next preprocessing token is the longest sequence of characters that could constitute a preprocessing token.
... 6 EXAMPLE 2 The program fragment x+++++y is parsed as x ++ ++ + y, which violates a constraint on increment operators, even though the parse x ++ + ++ y might yield a correct expression

6.4.6 Punctuators .. punctuator: one of ++ -- ... + -

So, https://en.wikipedia.org/wiki/Maximal_munch rule is used as was noted in https://stackoverflow.com/a/7485174 and comment about a+++b fragment: What does the operation c=a+++b mean?  Shahbaz Sep 20 2011: "the lexer of C and C++, try to match the biggest string they can when they see something. ... Therefore, when the lexer sees the first plus, it tries the next character, it sees that it can match both characters as a ++, then continues on to see the next +. Hence, the parser sees a ++ + b"

While gcc and clang have complex code and may mix different translation phases of standard in the single code samples (so they are not best guides to the language, as rici said), we may check parsing implementation for ++ and --. When it sees char + it may generate different tokens based on what is the next char, if is + too, emit plusplus token, otherwise emit plus token:

http://code.metager.de/source/xref/llvm/clang/lib/Lex/Lexer.cpp#3264

3264  case '+':
3265    Char = getCharAndSize(CurPtr, SizeTmp);
3266    if (Char == '+') {
3267      CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3268      Kind = tok::plusplus;
3269    } else if (Char == '=') {
3270      CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3271      Kind = tok::plusequal;
3272    } else {
3273      Kind = tok::plus;
3274    }
3275    break;

http://code.metager.de/source/xref/gnu/gcc/libcpp/lex.c#2633

2633    case '+':
2634      result->type = CPP_PLUS;
2635      if (*buffer->cur == '+')
2636        buffer->cur++, result->type = CPP_PLUS_PLUS;
2637      else if (*buffer->cur == '=')
2638        buffer->cur++, result->type = CPP_PLUS_EQ;
2639      break;

So, tokens of a+++b---c expression are a ++ + b -- - c. Advisor may say you are wrong, but only wanting you to explain why you think you counted 7. And if the question is the same task as given and it is parsed according to C standard (or C++ which is same lexing for this example), you can explain your answer and show him relevant parts of language standards.


问:
Availability using Access Database
I am attempting to make a hotel booking system. However the availability has got me a bit confused. I have about 15 buttons which I am able to save the number to the database but when the form loads/ date changed. I need the button to stay red and be unclickable. For example if I had a room 11 booked from 3/06/17 to 5/06/17 then I'd need the button to remain red from the 3/06/17 to 4/06/17 since the room is able to still be booked on the 5/06/17 after cleaning. I hope this makes sense. Below is the code I am using to try to do this. The code does run however the button does not turn red.

I was thinking does my SQL statement need to be changed but I'm not too sure. I'm pretty new to coding so an explanation would be helpful. Thanks.

```<code>Private Sub ReadRecords()
            Dim btn As Button = Nothing
            Dim BookingFound As Boolean = False
            Using MyConn As New OleDbConnection
                MyConn.ConnectionString = connString
                MyConn.Open()
                Dim check As String = "SELECT COUNT(*) FROM [BookingInformation] WHERE [Date In] = '" & dtpDateIn.Value.Date & "' AND [Date Out] = '" & dtpDateOut.Value.Date & "'"
                Dim BookingExists As Boolean = False
                Dim command As OleDbCommand = New OleDbCommand(check, MyConn)
                Using reader As OleDbDataReader = command.ExecuteReader()
                    While reader.Read()
                        If reader(0) = 0 Then
                            BookingExists = False
                        Else
                            BookingExists = True
                        End If
                    End While
                End Using
                If BookingExists = True Then
                    Dim getData As String = "SELECT * FROM [BookingInformation] WHERE [Date Out] = '" & dtpDateOut.Text & "'"
                    Dim command2 As OleDbCommand = New OleDbCommand(getData, MyConn)
                    Using reader As OleDbDataReader = command2.ExecuteReader()
                        While reader.Read()
                            BookingFound = True
                            strDateIn = reader("Date In").ToString()
                            strDateOut = reader("DateOut").ToString
                            strRoomNumber = reader("Room Number").ToString
                        End While
                        If BookingFound = True Then
                            btn.BackColor = Color.Red
                        End If
                    End Using
                End If
                MyConn.Close()
            End Using
        End Sub

         Private Sub Room_Booking_Load(sender As Object, e As EventArgs) Handles MyBase.Load
            ReadRecords()
        End Sub
</code>```

答:
You should make your access database understand your input as date, access database is very sensitive to datatypes, for example if you write

```<code> "SELECT * FROM [user_tb] WHERE user_id=1"
</code>```

Your code will work fine if your user_id data type is autonumber.
so try

```<code> Dim getData As String = "SELECT * FROM [BookingInformation] WHERE [Date Out] = #" & dtpDateOut.Text & "#"
</code>```

Instead of

```<code> Dim getData As String = "SELECT * FROM [BookingInformation] WHERE [Date Out] = '" & dtpDateOut.Text & "'"
</code>```

That is replace ' with #

Title: Availability using Access Database

Body:
I am attempting to make a hotel booking system. However the availability has got me a bit confused. I have about 15 buttons which I am able to save the number to the database but when the form loads/ date changed. I need the button to stay red and be unclickable. For example if I had a room 11 booked from 3/06/17 to 5/06/17 then I'd need the button to remain red from the 3/06/17 to 4/06/17 since the room is able to still be booked on the 5/06/17 after cleaning. I hope this makes sense. Below is the code I am using to try to do this. The code does run however the button does not turn red.

I was thinking does my SQL statement need to be changed but I'm not too sure. I'm pretty new to coding so an explanation would be helpful. Thanks.

Private Sub ReadRecords()
            Dim btn As Button = Nothing
            Dim BookingFound As Boolean = False
            Using MyConn As New OleDbConnection
                MyConn.ConnectionString = connString
                MyConn.Open()
                Dim check As String = "SELECT COUNT(*) FROM [BookingInformation] WHERE [Date In] = '" & dtpDateIn.Value.Date & "' AND [Date Out] = '" & dtpDateOut.Value.Date & "'"
                Dim BookingExists As Boolean = False
                Dim command As OleDbCommand = New OleDbCommand(check, MyConn)
                Using reader As OleDbDataReader = command.ExecuteReader()
                    While reader.Read()
                        If reader(0) = 0 Then
                            BookingExists = False
                        Else
                            BookingExists = True
                        End If
                    End While
                End Using
                If BookingExists = True Then
                    Dim getData As String = "SELECT * FROM [BookingInformation] WHERE [Date Out] = '" & dtpDateOut.Text & "'"
                    Dim command2 As OleDbCommand = New OleDbCommand(getData, MyConn)
                    Using reader As OleDbDataReader = command2.ExecuteReader()
                        While reader.Read()
                            BookingFound = True
                            strDateIn = reader("Date In").ToString()
                            strDateOut = reader("DateOut").ToString
                            strRoomNumber = reader("Room Number").ToString
                        End While
                        If BookingFound = True Then
                            btn.BackColor = Color.Red
                        End If
                    End Using
                End If
                MyConn.Close()
            End Using
        End Sub

         Private Sub Room_Booking_Load(sender As Object, e As EventArgs) Handles MyBase.Load
            ReadRecords()
        End Sub

Body:
You should make your access database understand your input as date, access database is very sensitive to datatypes, for example if you write

 "SELECT * FROM [user_tb] WHERE user_id=1"

Your code will work fine if your user_id data type is autonumber.
so try

 Dim getData As String = "SELECT * FROM [BookingInformation] WHERE [Date Out] = #" & dtpDateOut.Text & "#"

Instead of

 Dim getData As String = "SELECT * FROM [BookingInformation] WHERE [Date Out] = '" & dtpDateOut.Text & "'"

That is replace ' with #


问:
Review a pull request locally before merging?
How do I review a bitbucket pull request through command line in my local machine before merging ?</p>

答:
The merge itself takes place in Bitbucket, remotely, so the Bitbucket UI is the ideal place to be reviewing the pull request.  That being said, if you want to do some reviewing locally, the best thing might be for you to pull the branch in question.  After pulling, you can build and even test the feature branch.  In addition, with the branch on your local machine, you can also view a diff of every file which was changed.  An IDE with a Git plugin would be a good choice to view the diffs of files.

To pull the branch locally using the bash just use git fetch origin followed by git checkout branch_to_review.


问:
How do I split a string into a list of characters?
How do I split a string into a list of characters? str.split does not work.

```<code>"foobar"    →    ['f', 'o', 'o', 'b', 'a', 'r']
</code>```

答:
If you want to process your String one character at a time. you have various options.

```<code>uhello = u'Hello\u0020World'
</code>```

Using List comprehension:

```<code>print([x for x in uhello])
</code>```

Output:

```<code>['H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd']
</code>```

Using map:

```<code>print(list(map(lambda c2: c2, uhello)))
</code>```

Output:

```<code>['H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd']
</code>```

Calling Built in list function:

```<code>print(list(uhello))
</code>```

Output:

```<code>['H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd']
</code>```

Using for loop:

```<code>for c in uhello:
    print(c)
</code>```

Output:

```<code>H
e
l
l
o

W
o
r
l
d
</code>```

Body:
How do I split a string into a list of characters? str.split does not work.

"foobar"    →    ['f', 'o', 'o', 'b', 'a', 'r']

Body:
If you want to process your String one character at a time. you have various options.

uhello = u'Hello\u0020World'

Using List comprehension:

print([x for x in uhello])

Output:

['H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd']

Using map:

print(list(map(lambda c2: c2, uhello)))

Output:

['H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd']

Calling Built in list function:

print(list(uhello))

Output:

['H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd']

Using for loop:

for c in uhello:
    print(c)

Output:

H
e
l
l
o

W
o
r
l
d


问:
Data storage suggestions
My very first post on this forum but I have a problem with choosing how to store the data that my website will generate.

Its a project I'm working on for my boss and its a Time/Project management tool written in ASP.NET

The system is supposed to track the amount of work hours each person spends on a project and store this data for a minimum of 3 years, Now I was thinking of going with SQL but I'm having doubts when it comes to fetching older data further ahead and with queries taking too long.

About 2500 entries per month with starting and ending time, the id of the person and an id for the project they have been working on.

What would be the best solution here?

Right now it's supposed to be for the company only but might go public further ahead and in that case would the same solution still hold?

Using Azure for hosting.

Thank you

答:
A SQL database can handle millions of entries without a problem, don't worry about that. If performance issues should occur you could take a look at sql index, a way to improve lookup speed for a certain column, e.g. matching a name like in a nvarchar (..) column.

Any other storage solution is probably a lot slower and less maintainable in the future, especially since you need to store your data up to three years

Edit 1:

Also, like mentioned in the comments;

NoSQL database like Azure Table Storage / CosmosDB can perform very
  well as well

That said, any database like approach will probably work.

Title: Data storage suggestions


问:
Get IndexPath of CollectionViewCell outside of Cell
First of all I am a newbie in swift, so be gentle. I have a problem fetching the indexPath of the cell outside of the cell. I want to get that index path to a function and use it to send the content to another view. The image was created programatically in the cell, it has a tap gesture recogniser sending to this function (where "myIndex" is defined as an Int : var myIndex = 0):

```<code>// tap image to go at the indexpath of the user
func imageTapped(tapGestureRecognizer: UITapGestureRecognizer) {
   print("image tapped")

    let storyboard = UIStoryboard(name: "Main", bundle: nil)
    let secondViewController = storyboard.instantiateViewController(withIdentifier: "patientProfile") as! PatientProfileVC
    secondViewController.userID = posts[myIndex].userID
    secondViewController.patientName = posts[myIndex].author

    print("Passed data to the other view")

    self.show(secondViewController, sender: self)

}
</code>```

I know that I could use didSelectItem at IndexPath where I also have the declaration of the myIndex but I have something that will be triggered from a segue there:

```<code>//standard functon for item selected
override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {

    //get the index of the cell
    myIndex = indexPath.row

    print("Cell is selected")

    //perform the segue
    self.performSegue(withIdentifier: "CommentsVC", sender: self)
    print(myIndex)

}
</code>```

and my perform for segue looks like this:` override

func prepare(for segue: UIStoryboardSegue, sender: Any?) {

```<code>    print("Segue Initiated")
    feed.navigationItem.title = nil

    //if segue.destination is CommentsFullVC{
        print("Comments segue initiated")
        let secondViewController = segue.destination as! CommentsFullVC
        secondViewController.questionData = posts[myIndex].postContent
        secondViewController.authorName = posts[myIndex].author
        secondViewController.date = posts[myIndex].normalDate
        secondViewController.profileImagePath = posts[myIndex].pathToImage
        secondViewController.typeOfClinic = posts[myIndex].clinic
        secondViewController.postID = posts[myIndex].postID
        secondViewController.followersForPost = posts[myIndex].followers

}
</code>```

So my question is, how do I pass those 2 fields to the other view without using prepareForSegue? I am struggling with this for 20 hours now and still can not figure it out.

```<code>secondViewController.userID = posts[myIndex].userID
secondViewController.patientName = posts[myIndex].author
</code>```

UPDATE: Got it to work thanks to Jose answer, now it looks like this... in case anybody has the same problem as I had.

```<code> // tap image to go at the indexpath of the user
func imageTapped(tapGestureRecognizer: UITapGestureRecognizer) {
   print("image tapped")

    let pointInCollectionView = tapGestureRecognizer.location(in: collectionView)
    let indexPath = collectionView?.indexPathForItem(at: pointInCollectionView)
    print(indexPath!)

    // this one works - show segue
    let storyboard = UIStoryboard(name: "Main", bundle: nil)
    let secondViewController = storyboard.instantiateViewController(withIdentifier: "patientProfile") as! PatientProfileVC
    secondViewController.userID = posts[(indexPath?.row)!].userID
    secondViewController.patientName = posts[(indexPath?.row)!].author

    print("Passed data to the other view")

    self.show(secondViewController, sender: self)

}
</code>```

答:
If your code write like below like then try this

collection view cell for row Method

```<code>cell.image = indexPath.row
let tap = UITapGestureRecognizer.init(target: self, action: #selector(imageTapped(_:)))
tap.accessibilityElements = [indexPath]
cell.image.addGestureRecognizer(tap)
</code>```

Your function out side of collection view

```<code>func imageTapped (_ sender:UITapGestureRecognizer) {
     let index = sender.accessibilityElements?.first as! IndexPath
     print(index.row)
     myIndex = index.row
}
</code>```

Body:
First of all I am a newbie in swift, so be gentle. I have a problem fetching the indexPath of the cell outside of the cell. I want to get that index path to a function and use it to send the content to another view. The image was created programatically in the cell, it has a tap gesture recogniser sending to this function (where "myIndex" is defined as an Int : var myIndex = 0):

// tap image to go at the indexpath of the user
func imageTapped(tapGestureRecognizer: UITapGestureRecognizer) {
   print("image tapped")

    let storyboard = UIStoryboard(name: "Main", bundle: nil)
    let secondViewController = storyboard.instantiateViewController(withIdentifier: "patientProfile") as! PatientProfileVC
    secondViewController.userID = posts[myIndex].userID
    secondViewController.patientName = posts[myIndex].author

    print("Passed data to the other view")

    self.show(secondViewController, sender: self)

}

I know that I could use didSelectItem at IndexPath where I also have the declaration of the myIndex but I have something that will be triggered from a segue there:

//standard functon for item selected
override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {

    //get the index of the cell
    myIndex = indexPath.row

    print("Cell is selected")

    //perform the segue
    self.performSegue(withIdentifier: "CommentsVC", sender: self)
    print(myIndex)

}

and my perform for segue looks like this:` override

func prepare(for segue: UIStoryboardSegue, sender: Any?) {

    print("Segue Initiated")
    feed.navigationItem.title = nil

    //if segue.destination is CommentsFullVC{
        print("Comments segue initiated")
        let secondViewController = segue.destination as! CommentsFullVC
        secondViewController.questionData = posts[myIndex].postContent
        secondViewController.authorName = posts[myIndex].author
        secondViewController.date = posts[myIndex].normalDate
        secondViewController.profileImagePath = posts[myIndex].pathToImage
        secondViewController.typeOfClinic = posts[myIndex].clinic
        secondViewController.postID = posts[myIndex].postID
        secondViewController.followersForPost = posts[myIndex].followers

}

So my question is, how do I pass those 2 fields to the other view without using prepareForSegue? I am struggling with this for 20 hours now and still can not figure it out.

secondViewController.userID = posts[myIndex].userID
secondViewController.patientName = posts[myIndex].author

UPDATE: Got it to work thanks to Jose answer, now it looks like this... in case anybody has the same problem as I had.

 // tap image to go at the indexpath of the user
func imageTapped(tapGestureRecognizer: UITapGestureRecognizer) {
   print("image tapped")

    let pointInCollectionView = tapGestureRecognizer.location(in: collectionView)
    let indexPath = collectionView?.indexPathForItem(at: pointInCollectionView)
    print(indexPath!)

    // this one works - show segue
    let storyboard = UIStoryboard(name: "Main", bundle: nil)
    let secondViewController = storyboard.instantiateViewController(withIdentifier: "patientProfile") as! PatientProfileVC
    secondViewController.userID = posts[(indexPath?.row)!].userID
    secondViewController.patientName = posts[(indexPath?.row)!].author

    print("Passed data to the other view")

    self.show(secondViewController, sender: self)

}

Body:
If your code write like below like then try this

collection view cell for row Method

cell.image = indexPath.row
let tap = UITapGestureRecognizer.init(target: self, action: #selector(imageTapped(_:)))
tap.accessibilityElements = [indexPath]
cell.image.addGestureRecognizer(tap)

Your function out side of collection view

func imageTapped (_ sender:UITapGestureRecognizer) {
     let index = sender.accessibilityElements?.first as! IndexPath
     print(index.row)
     myIndex = index.row
}


问:
Do wordpress website with other host shows ads?
I am using Godaddy hosting and uses wordpress application to build my website. I want to apply for Google Adsense and want to monetize my site. Will ads appear on my website?</p>

答: Yes, ads can be added on your site. You can either insert your ads code directly on your page content or simply get a plugin that can help you integrate ads on your site.</p>


问:
Change HTML Content using jQuery 3, then change it back
Basically, what I want to do:
When you press the button #change, the content in the div #board has to change to nothing but:

```<code><h2>Hi!</h2>
<button type="button" onclick="ChangeAgain();">
</code>```

Then when you click that button, it has to change back to what it used to be, that is:

```<code><h2>Welcome to this page.</h2>
<p>It's quite boring in here. Why don't you click the button?</p>
<button onClick="Change();">Button for you to Click</button>
</code>```

Here's my JavaScript (jQuery 3.2.1), which is not working.

```<code>$(function () {
  var inThere = "";
  function Change() {
    inThere += $("#board").html();
    $("#board").html("<h2>Hi!</h2> \n
    <button type=\"button\" onclick=\"ChangeAgain();\">")
  }
  function ChangeAgain () {
    $("#board").html(inThere);
  }
})
</code>```

答:
Don't define the function in the document ready handler scope. You must be getting error like

"Uncaught ReferenceError: Change is not defined",

var inThere = "";

function Change() {
  inThere += $("#board").html();
  $("#board").html("
Hi!
 \n <button type = \"button\" onclick=\"ChangeAgain();\">Button for you to Click</button>")
}

function ChangeAgain() {
  $("#board").html(inThere);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="board">
  <h2>Welcome to this page.</h2>
  <p>It's quite boring in here. Why don't you click the button?</p>
  <button onClick="Change();">Button for you to Click</button>
</div></code>```

Body:
Basically, what I want to do:
When you press the button #change, the content in the div #board has to change to nothing but:

Hi!

<button type="button" onclick="ChangeAgain();">

Then when you click that button, it has to change back to what it used to be, that is:

Welcome to this page.

It's quite boring in here. Why don't you click the button?

<button onClick="Change();">Button for you to Click</button>

Here's my JavaScript (jQuery 3.2.1), which is not working.

$(function () {
  var inThere = "";
  function Change() {
    inThere += $("#board").html();
    $("#board").html("
Hi!
 \n
    <button type=\"button\" onclick=\"ChangeAgain();\">")
  }
  function ChangeAgain () {
    $("#board").html(inThere);
  }
})

Body:
Don't define the function in the document ready handler scope. You must be getting error like

"Uncaught ReferenceError: Change is not defined",

var inThere = "";

function Change() {
  inThere += $("#board").html();
  $("#board").html("<h2>Hi!</h2> \n <button type = \"button\" onclick=\"ChangeAgain();\">Button for you to Click</button>")
}

function ChangeAgain() {
  $("#board").html(inThere);
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="board">
  <h2>Welcome to this page.</h2>
  <p>It's quite boring in here. Why don't you click the button?</p>
  <button onClick="Change();">Button for you to Click</button>
</div>


问:
Weblogic 10.3.6 Domain Wizard Could not create the JVM
I try to run WLS Domain Wizard to create a new domain for WebLogic installed in virtual environment Citrix 12.3.400.3. It requires to run /Middleware/wlserver_10.3/common/bin/config.exe
But as I do that the error arises immediately:

```<code>Error: Could not create the Java Virtual Machine
Error: A fatal exception has occurred. Program will exit.
</code>```

I have installed there:

```<code>Java SE Development Kit 8 Update 51 (64-bit) - C:\Program Files\Java\jdk1.8.0_51
Java(TM) 6 Update 27 (64-bit) - C:\Program Files\Java\jre6
Java(TM) 7 Update 3 (64-bit) - C:\Program Files\Java\jre7
Java(TM) SE Development Kit 7 Update 3 (64-bit) - C:\Program Files\Java\jdk1.7.0_3
</code>```

Env var:
JAVA_HOME=C:\Program Files\Java\jre1.8.0_51

```<code>►java -version

java version "1.6.0_45"
Java(TM) SE Runtime Environment (build 1.6.0_45-b06)
Oracle JRockit(R) (build R28.2.7-7-155314-1.6.0_45-20130329-0646-windows-x86_64, compiled mode)
</code>```

So, is there any hope to resolve this problem?

答:
Open %HOME%\oracle_common\common\bin\commEnv.cmd

Set USER_MEM_ARGS environment variable after ":continue" tag

You can do this using below  (or with higer values):

SET USER_MEM_ARGS=-Xms32m -Xmx1024m -XX:MaxPermSize=512m -XX:MaxHeapSize=512m

Try to re-create default domain again

Body:
I try to run WLS Domain Wizard to create a new domain for WebLogic installed in virtual environment Citrix 12.3.400.3. It requires to run /Middleware/wlserver_10.3/common/bin/config.exe
But as I do that the error arises immediately:

Error: Could not create the Java Virtual Machine
Error: A fatal exception has occurred. Program will exit.

I have installed there:

Java SE Development Kit 8 Update 51 (64-bit) - C:\Program Files\Java\jdk1.8.0_51
Java(TM) 6 Update 27 (64-bit) - C:\Program Files\Java\jre6
Java(TM) 7 Update 3 (64-bit) - C:\Program Files\Java\jre7
Java(TM) SE Development Kit 7 Update 3 (64-bit) - C:\Program Files\Java\jdk1.7.0_3

Env var:
JAVA_HOME=C:\Program Files\Java\jre1.8.0_51

►java -version

java version "1.6.0_45"
Java(TM) SE Runtime Environment (build 1.6.0_45-b06)
Oracle JRockit(R) (build R28.2.7-7-155314-1.6.0_45-20130329-0646-windows-x86_64, compiled mode)

So, is there any hope to resolve this problem?


问:
Compile Failing for iOS 4 with Sqlite
I wrote an iPhone app against SDK 2.2, I have updated my XCode and SDK so now I only have SDK 4.2 and I want to update my app to run with that.

The problem is I can't even get it to compile!

I get the following error:

/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator4.2.sdk/usr/include/sqlite3.h:5772: error: expected '=', ',', ';', 'asm' or 'attribute' before 'int'

The line in question is:

SQLITE_API int sqlite3_rtree_geometry_callback(
  sqlite3 *db,
  const char *zGeom,
  int (*xGeom)(sqlite3_rtree_geometry *, int nCoord, double *aCoord, int *pRes),
  void *pContext
);

I have tried relinking the newer sqlite frameworks, both libsqlite3.dylib and libsqlite3.dylib, but both still cause this error.

If I comment out my import statement (#import "sqlite3.h"), it compiles just fine.  (Although it crashes when I run it, obviously.)

答:
I've used the same way Sqlite.h use to import this library:

```<code>   #import <sqlite3.h>
</code>```

and it solved the issue.

Title: Compile Failing for iOS 4 with Sqlite

Body:
I've used the same way Sqlite.h use to import this library:

   #import <sqlite3.h>

and it solved the issue.