问:
Chart.js - How to show loading animation before plotting chart
I am using chart.js plugin to plot line chart.

I want to display loading before plotting chart.

I have tried following but nothing is happening.

Here it is showing jQuery error:

Uncaught ReferenceError: progress is not defined

But in my application it doesnt showing error.

How to show animation or loading before plotting graph?

I am using    semantic-ui as css framework.

new Chart(document.getElementById("line-chart"),{
  type: 'line',
  data:{
    labels: [1500, 1600, 1700, 1750, 1800, 1850, 1900, 1950, 1999, 2050],
    datasets: [{
        data: [86, 114, 106, 106, 107, 111, 133, 221, 783, 2478],
        label: "Africa",
        borderColor: "#3e95cd",
        fill: false
      },{
        data: [282, 350, 411, 502, 635, 809, 947, 1402, 3700, 5267],
        label: "Asia",
        borderColor: "#8e5ea2",
        fill: false
      },{
        data: [168, 170, 178, 190, 203, 276, 408, 547, 675, 734],
        label: "Europe",
        borderColor: "#3cba9f",
        fill: false
      },{
        data: [40, 20, 10, 16, 24, 38, 74, 167, 508, 784],
        label: "Latin America",
        borderColor: "#e8c3b9",
        fill: false
      },{
        data: [6, 3, 2, 2, 7, 26, 82, 172, 312, 433],
        label: "North America",
        borderColor: "#c45850",
        fill: false
      }
    ]
  },
  options:{
    title:{
      display: true,
      text: 'World population per region (in millions)'
    },
    animation:{
      onProgress: function (animation){
        progress.value = animation.animationObject.currentStep / animation.animationObject.numSteps;
      }
    }
  }
});```
<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>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.5.0/Chart.min.js"></script>

<canvas id="line-chart" ></canvas></code>```

答:
It seems like you are basing yourself on the code shown on the animations callbacks part of the chartjs documentation.

That code is only partial. The link on the page is broken, but here is the correct full code: progress-bar example

The function defined on the onProgress attribute is called every step of the chart animation, and thus used to fill the progress bar. The progress variable that is giving you the undefined error should be defined previously on your code. On the github link it's on line #26

Body:
I am using chart.js plugin to plot line chart.

I want to display loading before plotting chart.

I have tried following but nothing is happening.

Here it is showing jQuery error:

Uncaught ReferenceError: progress is not defined

But in my application it doesnt showing error.

How to show animation or loading before plotting graph?

I am using    semantic-ui as css framework.

new Chart(document.getElementById("line-chart"),{
  type: 'line',
  data:{
    labels: [1500, 1600, 1700, 1750, 1800, 1850, 1900, 1950, 1999, 2050],
    datasets: [{
        data: [86, 114, 106, 106, 107, 111, 133, 221, 783, 2478],
        label: "Africa",
        borderColor: "#3e95cd",
        fill: false
      },{
        data: [282, 350, 411, 502, 635, 809, 947, 1402, 3700, 5267],
        label: "Asia",
        borderColor: "#8e5ea2",
        fill: false
      },{
        data: [168, 170, 178, 190, 203, 276, 408, 547, 675, 734],
        label: "Europe",
        borderColor: "#3cba9f",
        fill: false
      },{
        data: [40, 20, 10, 16, 24, 38, 74, 167, 508, 784],
        label: "Latin America",
        borderColor: "#e8c3b9",
        fill: false
      },{
        data: [6, 3, 2, 2, 7, 26, 82, 172, 312, 433],
        label: "North America",
        borderColor: "#c45850",
        fill: false
      }
    ]
  },
  options:{
    title:{
      display: true,
      text: 'World population per region (in millions)'
    },
    animation:{
      onProgress: function (animation){
        progress.value = animation.animationObject.currentStep / animation.animationObject.numSteps;
      }
    }
  }
});

<canvas id="line-chart" ></canvas>


来源: stackexchange

问:
C# SqlDataReader reads only 1 row
I'm trying to read data from database to store in arrays, but SqlDataReader only reads 1 row which is either the last or the first depending if I use ORDER BY DESC or ASC which seems to bug me.

Code:

```<code>private void chkAdr()
{
    string connStr = "Data Source=MARINCHI\\SQLEXPRESS;Initial Catalog=login1;Integrated Security=True";

    SqlConnection conn = new SqlConnection(connStr);
    conn.Open();

    SqlCommand getAdr = new SqlCommand("SELECT adress, floor,city, state, country, zipcode FROM userAdress where userID = @userID", conn);

    SqlParameter parUserID = new SqlParameter("@userID", Login.id);
    getAdr.Parameters.Add(parUserID);

    getAdr.ExecuteNonQuery();

    SqlDataReader dr = getAdr.ExecuteReader();

    string[] adress = new string[100];
    string[] floor = new string[100];
    string[] city = new string[100];
    string[] state = new string[100];
    string[] country = new string[100];
    string[] zipcode = new string[100];

    while (dr.Read())
    {
        int count = dr.FieldCount;

        for (int i = 0; i < count; i++)
        {
            adress[i] = dr["adress"].ToString();
            floor[i] = dr["floor"].ToString();
            city[i] = dr["city"].ToString();
            state[i] = dr["state"].ToString();
            country[i] = dr["country"].ToString();
            zipcode[i] = dr["zipcode"].ToString();
        }

        // test to see, what values I get, no matter what adress[i] for I any number, always get the last data from my table in sql...
        textBox5.Text = adress[0];
        textBox6.Text = floor[0];
        textBox7.Text = city[0];
        textBox8.Text = state[1];
        textBox9.Text = country[1];
        textBox10.Text = zipcode[1];
    }

    dr.Close();
}
</code>```

I tried dr.HasRows but it didn't really work for me, and I searched on google and tried all combinations but nothing seems to work, I can't get it to work with reading from begging to last row..

This should be a component of my code to retrieve adress from database if a user added his address before, if it ends up true, its gonna be added to combobox as option "Saved address 1" and when u click on it, it should display it in textboxes. Same if there are 2 addresses, both should be added.

As I said my problem is I can't read all addresses the user has added as the SqlDataReader reads only either last row or first row only.. If anyone has a idea on how I can do this, please help! thanks!

答:
You looping is not correct, you should read like this:</p>

```<code>int i = 0;
while (dr.Read())
{
    adress[i] = dr["adress"].ToString();
    floor[i] = dr["floor"].ToString();
    city[i] = dr["city"].ToString();
    state[i] = dr["state"].ToString();
    country[i] = dr["country"].ToString();
    zipcode[i] = dr["zipcode"].ToString();
    i++;
}
</code>```

ContentLicense: CC BY-SA 3.0

Title: C# SqlDataReader reads only 1 row

Body:
I'm trying to read data from database to store in arrays, but SqlDataReader only reads 1 row which is either the last or the first depending if I use ORDER BY DESC or ASC which seems to bug me.

Code:

private void chkAdr()
{
    string connStr = "Data Source=MARINCHI\\SQLEXPRESS;Initial Catalog=login1;Integrated Security=True";

    SqlConnection conn = new SqlConnection(connStr);
    conn.Open();

    SqlCommand getAdr = new SqlCommand("SELECT adress, floor,city, state, country, zipcode FROM userAdress where userID = @userID", conn);

    SqlParameter parUserID = new SqlParameter("@userID", Login.id);
    getAdr.Parameters.Add(parUserID);

    getAdr.ExecuteNonQuery();

    SqlDataReader dr = getAdr.ExecuteReader();

    string[] adress = new string[100];
    string[] floor = new string[100];
    string[] city = new string[100];
    string[] state = new string[100];
    string[] country = new string[100];
    string[] zipcode = new string[100];

    while (dr.Read())
    {
        int count = dr.FieldCount;

        for (int i = 0; i < count; i++)
        {
            adress[i] = dr["adress"].ToString();
            floor[i] = dr["floor"].ToString();
            city[i] = dr["city"].ToString();
            state[i] = dr["state"].ToString();
            country[i] = dr["country"].ToString();
            zipcode[i] = dr["zipcode"].ToString();
        }

        // test to see, what values I get, no matter what adress[i] for I any number, always get the last data from my table in sql...
        textBox5.Text = adress[0];
        textBox6.Text = floor[0];
        textBox7.Text = city[0];
        textBox8.Text = state[1];
        textBox9.Text = country[1];
        textBox10.Text = zipcode[1];
    }

    dr.Close();
}

I tried dr.HasRows but it didn't really work for me, and I searched on google and tried all combinations but nothing seems to work, I can't get it to work with reading from begging to last row..

This should be a component of my code to retrieve adress from database if a user added his address before, if it ends up true, its gonna be added to combobox as option "Saved address 1" and when u click on it, it should display it in textboxes. Same if there are 2 addresses, both should be added.

As I said my problem is I can't read all addresses the user has added as the SqlDataReader reads only either last row or first row only.. If anyone has a idea on how I can do this, please help! thanks!

Body:
You looping is not correct, you should read like this:

int i = 0;
while (dr.Read())
{
    adress[i] = dr["adress"].ToString();
    floor[i] = dr["floor"].ToString();
    city[i] = dr["city"].ToString();
    state[i] = dr["state"].ToString();
    country[i] = dr["country"].ToString();
    zipcode[i] = dr["zipcode"].ToString();
    i++;
}


问:
Save to XML via PHP
Okay i could be doing this %100 wrong I'm having trouble With the PHP to XML I'm just trying to save the customer details.......(not trying to be secure yet just learning how to do it)

The Html is a simple form

for firstname, lastname, password, email, and optional phone number  (not needed at the moment)

The PHP code is initiated after the javascript calls it by the Javascript..

PHP

```<code><?php
            // header('Content-Type: text/xml');
                session_register('Customer');
                //session_start('customer');
            $doc = new DOMDocument();
            $doc->load('customer.xml');

            $firstname = $_GET["firstName"];
            $lastname = $_GET["lastName"];
            $email = $_GET["email"];
            $password = $_GET["password"];

            $MDA = $_SESSION["Customer"]; //assign the session varaible to MDA

            if (isset($firstname)) {
            $customerArray = array();
            $customerArray['firstname'] = $firstname;
            $customerArray['lastname'] = $lastname;
            $customerArray['email'] = $email;
            $customerArray['password'] = $password;
            $MDA[$firstname] = $customerArray;
            $_SESSION["Customer"] = $MDA;
                ECHO (toXml($MDA));
            }

            function toXml($MDA)
            {
                $doc = new DomDocument('1.0');
                $Customer = $doc->createElement('Customers');
                $Customer = $doc->appendChild($Customer);
                $root = $doc->appendChild($doc->createElement('Root'));

                foreach ($MDA as $a => $b)
                {
                    $nodeA = $doc->createElement('NodeA');
                    $root->appendChild($nodeA);
                    $nodeA->appendChild($attr1);
                    $attr1 = $doc->createAttribute('firstname');
                    $attr1->appendChild($doc->createTextNode($a['firstname']));

                $attr = $doc->createElement('firstname');
                $attr = $Customer->appendChild($person);

                $lastname = $doc->createElement('lastname');
                $lastname = $person->appendChild($lastname);
                $value = $doc->createTextNode($a);
                $value = $lastname->appendChild($value);

                $email = $doc->createElement('email');
                $email = $person->appendChild($email);
                $value2 = $doc->createTextNode($b['email']);
                $value2 = $email->appendChild($value2);

                $password = $doc->createElement('password');
                $password = $person->appendChild($password);
                $value3 = $doc->createTextNode($b['password']);
                $value3 = $password->appendChild($value3);
              }

                $doc->formatOutput = true;
                $strXml = $doc->saveXML();
                //$doc->save('customer.xml');
                return $strXml;
            }
        ?>
</code>```

and not to sure if its needed but the javascript... it just checks the password atm

```<code>var xHRObject = false;
        if (window.XMLHttpRequest)
            xHRObject = new XMLHttpRequest();
        else if (window.ActiveXObject)
            xHRObject = new ActiveXObject("Microsoft.XMLHTTP");

        function test()
        {
            var firstname = document.getElementById("firstName").value;
            var lastname = document.getElementById("lastName").value;
            var email = document.getElementById("email").value;
            var password = document.getElementById("password").value;
            var password2 = document.getElementById("password2").value;
            var number = document.getElementById("pNumber").value;
            var type = "";
            var input = document.getElementsByTagName("input");
              xHRObject.open("GET", "testregristation.php?", true);
              xHRObject.onreadystatechange = function() {
                   if (xHRObject.readyState == 4 && xHRObject.status == 200)
                    if (password != password2) {
                    alert("Password is wrong");

                    }
                    else
                    {
                        alert("test " +firstname + " " +  lastname + " " + email + " : " + password);
                       document.getElementById('information').innerHTML = xHRObject.responseText;
              }
              xHRObject.send();
        };
        }
</code>```

答: Out of date Browser issue, This works fine in Firefox</p>

Title: Save to XML via PHP

Body:
Okay i could be doing this %100 wrong I'm having trouble With the PHP to XML I'm just trying to save the customer details.......(not trying to be secure yet just learning how to do it)

The Html is a simple form

for firstname, lastname, password, email, and optional phone number  (not needed at the moment)

The PHP code is initiated after the javascript calls it by the Javascript..

PHP

<?php
            // header('Content-Type: text/xml');
                session_register('Customer');
                //session_start('customer');
            $doc = new DOMDocument();
            $doc->load('customer.xml');

            $firstname = $_GET["firstName"];
            $lastname = $_GET["lastName"];
            $email = $_GET["email"];
            $password = $_GET["password"];

            $MDA = $_SESSION["Customer"]; //assign the session varaible to MDA

            if (isset($firstname)) {
            $customerArray = array();
            $customerArray['firstname'] = $firstname;
            $customerArray['lastname'] = $lastname;
            $customerArray['email'] = $email;
            $customerArray['password'] = $password;
            $MDA[$firstname] = $customerArray;
            $_SESSION["Customer"] = $MDA;
                ECHO (toXml($MDA));
            }

            function toXml($MDA)
            {
                $doc = new DomDocument('1.0');
                $Customer = $doc->createElement('Customers');
                $Customer = $doc->appendChild($Customer);
                $root = $doc->appendChild($doc->createElement('Root'));

                foreach ($MDA as $a => $b)
                {
                    $nodeA = $doc->createElement('NodeA');
                    $root->appendChild($nodeA);
                    $nodeA->appendChild($attr1);
                    $attr1 = $doc->createAttribute('firstname');
                    $attr1->appendChild($doc->createTextNode($a['firstname']));

                $attr = $doc->createElement('firstname');
                $attr = $Customer->appendChild($person);

                $lastname = $doc->createElement('lastname');
                $lastname = $person->appendChild($lastname);
                $value = $doc->createTextNode($a);
                $value = $lastname->appendChild($value);

                $email = $doc->createElement('email');
                $email = $person->appendChild($email);
                $value2 = $doc->createTextNode($b['email']);
                $value2 = $email->appendChild($value2);

                $password = $doc->createElement('password');
                $password = $person->appendChild($password);
                $value3 = $doc->createTextNode($b['password']);
                $value3 = $password->appendChild($value3);
              }

                $doc->formatOutput = true;
                $strXml = $doc->saveXML();
                //$doc->save('customer.xml');
                return $strXml;
            }
        ?>

and not to sure if its needed but the javascript... it just checks the password atm

var xHRObject = false;
        if (window.XMLHttpRequest)
            xHRObject = new XMLHttpRequest();
        else if (window.ActiveXObject)
            xHRObject = new ActiveXObject("Microsoft.XMLHTTP");

        function test()
        {
            var firstname = document.getElementById("firstName").value;
            var lastname = document.getElementById("lastName").value;
            var email = document.getElementById("email").value;
            var password = document.getElementById("password").value;
            var password2 = document.getElementById("password2").value;
            var number = document.getElementById("pNumber").value;
            var type = "";
            var input = document.getElementsByTagName("input");
              xHRObject.open("GET", "testregristation.php?", true);
              xHRObject.onreadystatechange = function() {
                   if (xHRObject.readyState == 4 && xHRObject.status == 200)
                    if (password != password2) {
                    alert("Password is wrong");

                    }
                    else
                    {
                        alert("test " +firstname + " " +  lastname + " " + email + " : " + password);
                       document.getElementById('information').innerHTML = xHRObject.responseText;
              }
              xHRObject.send();
        };
        }


Title: group data by months of 6 years

Body:
i have a csv file containing 6 years of data starting from 01/01/2006 to 01/01/2011 and i need to group data by each month of the 6 years.
here's an overview of my csv file :

 timestamp,heure,lat,lon,impact,type
 2006-01-01 00:00:00,13:58:43,33.837,-9.205,10.3,1
 2006-01-02 00:00:00,00:07:28,34.5293,-10.2384,17.7,1
 2007-02-01 00:00:00,23:01:03,35.0617,-1.435,-17.1,2
 2007-02-02 00:00:00,01:14:29,36.5685,0.9043,36.8,1
 2008-01-01 00:00:00,05:03:51,34.1919,-12.5061,-48.9,1
 2008-01-02 00:00:00,05:03:51,34.1919,-12.5061,-48.9,1
 ....
 2011-12-31 00:00:00,05:03:51,34.1919,-12.5061,-48.9,1

and here's the output desired :

 month 01   10 (counts of the columns)
 month 02   20
 .....
 month 12   30

any ideas ??

Body:
I mostly use resample to do this.

Here are my samples:

import numpy as np
import pandas as pd
index = pd.date_range('2017/1/1', '2017/10/1')
df = pd.DataFrame(np.ones((274, 1)), index)
df
          0
2017-01-01  1.0
2017-01-02  1.0
...         ...
2017-09-29  1.0
2017-09-30  1.0
2017-10-01  1.0

df.resample('M').count()  # use resample to agg data
2017-01-31  31
2017-02-28  28
2017-03-31  31
2017-04-30  30
2017-05-31  31
2017-06-30  30
2017-07-31  31
2017-08-31  31
2017-09-30  30
2017-10-31   1


问:
Listing elements without manually specifying them
I'm attempting to turn the old, "roll dice" program into something more different. I would like to add more numbers instead of 6, but typing all the numbers out seems painstaking. I'm sure you programmers have an easier way to do things like this.

Example:

```<code>hist = pygal.Bar()

    hist.title = "Results of rolling numbers 0-69 100 times."
    hist.x_labels = ['1', '2', '3']
    hist.x_title = "Numbers Rolled"
    hist.y_title = "Frequency of numbers rolled"
</code>```

On line 3, I want to be able to insert numbers 1-69, or even more if i wish to change it. How can I do this easily?

I thought the range() function would work, but it didn't, unless I'm doing something wrong. Thank you

答:
range() will work, but you have to convert each value to a string instead of an integer.

```<code>hist.x_labels = [ str(n) for n in range(69) ]
</code>```

Body:
I'm attempting to turn the old, "roll dice" program into something more different. I would like to add more numbers instead of 6, but typing all the numbers out seems painstaking. I'm sure you programmers have an easier way to do things like this.

Example:

hist = pygal.Bar()

    hist.title = "Results of rolling numbers 0-69 100 times."
    hist.x_labels = ['1', '2', '3']
    hist.x_title = "Numbers Rolled"
    hist.y_title = "Frequency of numbers rolled"

On line 3, I want to be able to insert numbers 1-69, or even more if i wish to change it. How can I do this easily?

I thought the range() function would work, but it didn't, unless I'm doing something wrong. Thank you

Body:
range() will work, but you have to convert each value to a string instead of an integer.

hist.x_labels = [ str(n) for n in range(69) ]


问:
Printing a warning message over multiple lines
I am trying to print a warning message that is a little long and includes 2 variable calls. Here's my code: </p>

```<code>warning( 'MATLAB:questionable_argument', ...
           'the arguments dt (%d) and h (%d) are sub-optimal. Consider increasing nt or decreasing nx.', ...
           dt, h )
</code>```

<p>Obviously, the line of text extends to the right when viewing the MATLAB code. How can I break it so it wraps nicely? I've tried multiple things but keep getting syntax errors. </p>

答:
As suggested in comments, just insert a \n where you want to break the line. You can also use a variable for the text, to make it easy to read also within the code:

```<code>txt = sprintf(['the arguments dt (%d) and h (%d) are sub-optimal.\n'...
    'Consider increasing nt or decreasing nx.'],dt,h);
warning( 'MATLAB:questionable_argument',txt)
</code>```

Body:
I am trying to print a warning message that is a little long and includes 2 variable calls. Here's my code:

warning( 'MATLAB:questionable_argument', ...
           'the arguments dt (%d) and h (%d) are sub-optimal. Consider increasing nt or decreasing nx.', ...
           dt, h )

Obviously, the line of text extends to the right when viewing the MATLAB code. How can I break it so it wraps nicely? I've tried multiple things but keep getting syntax errors.

Body:
As suggested in comments, just insert a \n where you want to break the line. You can also use a variable for the text, to make it easy to read also within the code:

txt = sprintf(['the arguments dt (%d) and h (%d) are sub-optimal.\n'...
    'Consider increasing nt or decreasing nx.'],dt,h);
warning( 'MATLAB:questionable_argument',txt)


问:
Javascript extract regular expression from string
I've tried a few ways of doing this and I can't figure out why my .match always returns null. Given the string below how can I extract the 04-Jun-2017 into it's own variable? </p>

```<code>var str = "I need the only the    date 04-Jun-2017\n"

str.replace(/\n/g,' ');
var date = str.match(/^[01][0-9]-(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)-\d{4}$/);
alert(date)
</code>```

答:
First of all, str.replace(/\n/g,' '); does not modify str var since strings are immutable. Then, you do not need the anchors ^ and $, as the date is inside the string, it is not equal to the string itself. Also, you need to match days from 1 to 31, but [01][0-9] only matches from 00 to 19.

You may consider using

var str = "I need the only the    date 04-Jun-2017\n"
var date = str.match(/\b\d{1,2}-(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)-\d{4}\b/i);
if (date) {
  console.log(date[0]);
}```

The anchors are replaced with word boundaries \b and the day part is changed into \d{1,2} matching any 1 or 2 digits. The i modifier will make the pattern case insensitive.

Body:
I've tried a few ways of doing this and I can't figure out why my .match always returns null. Given the string below how can I extract the 04-Jun-2017 into it's own variable?

var str = "I need the only the    date 04-Jun-2017\n"

str.replace(/\n/g,' ');
var date = str.match(/^[01][0-9]-(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)-\d{4}$/);
alert(date)

Body:
First of all, str.replace(/\n/g,' '); does not modify str var since strings are immutable. Then, you do not need the anchors ^ and $, as the date is inside the string, it is not equal to the string itself. Also, you need to match days from 1 to 31, but [01][0-9] only matches from 00 to 19.

You may consider using

var str = "I need the only the    date 04-Jun-2017\n"
var date = str.match(/\b\d{1,2}-(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)-\d{4}\b/i);
if (date) {
  console.log(date[0]);
}

The anchors are replaced with word boundaries \b and the day part is changed into \d{1,2} matching any 1 or 2 digits. The i modifier will make the pattern case insensitive.


问:
How do I get the row data from a Prepared statement and then use it with AJAX() function
With Mysqli my code is working fine, but when I try to use a prepared statement, for more security, I can't get the values back to my AJAX() function.

this is my js code

```<code>function validateCoSigner(){
var contractNo = $('#cosigner_reference_number').val();
var firstName = $('#cosigner_firstname').val();
var lastName = $('#cosigner_lastname').val();
$.ajax({
    type: 'POST',
    url: 'php/retrieve-applicant1-details.php',
    // dataType: 'json',
    data: {
        'contractNo': contractNo,
        'firstName' : firstName,
        'lastName'  : lastName
    },
    success: function(json) {
        showCoSigner();
        console.log(json);
        $('#contractID').val(json.contractID);
        $('#loanpurpose').val(json.loanpurpose);
        $('#applicant1_firstname').val(json.applicant1_firstname);
        $('#applicant1_middlename').val(json.applicant1_middlename);
        $('#applicant1_surname').val(json.applicant1_surname);
        $('#applicant1_dateofbirth').val(json.applicant1_dateofbirth);
    },
    error: function() {
        alert ('error2');

    }
});
</code>```

}

This is the retrieve-applicant1-details.php file with the mysqli functions that works:

```<code><?php
header('Content-Type: application/json');
$conn = mysqli_connect("localhost", "root","","xxx");

$contractno = $_POST['contractNo'];
$firstname = $_POST['firstName'];
$lastname = $_POST['lastName'];

$sql = "SELECT * FROM contract WHERE contractID='$contractno' AND applicant1_firstname='$firstname' AND applicant1_surname='$lastname'";
$query = mysqli_query($conn,$sql);
$num_row = mysqli_num_rows($query);
$row=mysqli_fetch_assoc($query);
if( $num_row == 1 ) {
    $obj = [
        'contractID'                =>($row['contractID']),
        'loanpurpose'               =>($row['loanpurpose']),
        'applicant1_firstname'      =>($row['applicant1_firstname']),
        'applicant1_middlename'     =>($row['applicant1_middlename']),
        'applicant1_surname'        =>($row['applicant1_surname']),
        'applicant1_dateofbirth'    =>($row['applicant1_dateofbirth']),
    ];
    }
else {
    echo 'The reference number, firstname and lastname does not match';
    exit;
}

echo json_encode($obj);
?>
</code>```

If I use prepared statement as below, I can't figure out how to properly fetch the data so that I can get the values back to my Ajax function so that it can be displayed in my form.

```<code><?php
header('Content-Type: application/json');
$conn = mysqli_connect("localhost", "root","","xxx");

$contractno = $_POST['contractNo'];  //not sure if I still need to use mysqli_real_escape_string here.
$firstname = $_POST['firstName'];
$lastname = $_POST['lastName'];

// prepare statement
$stmt = $conn->prepare("SELECT * FROM contract WHERE contractID=? AND applicant1_firstname=? AND applicant1_surname=?");
// bind
$stmt->bind_param("iss", $contractno, $firstname, $lastname);
// execute
$stmt->execute();
if ($stmt->errno) {
    echo "FAILURE!!! " . $stmt->error;
}
else echo "Updated {$stmt->affected_rows} rows";

$row = $stmt->fetchObject();
$obj = (
    'contractID'                =>($row['contractID']),
    'loanpurpose'               =>($row['loanpurpose']),
    'applicant1_firstname'      =>($row['applicant1_firstname']),
    'applicant1_middlename'     =>($row['applicant1_middlename']),
    'applicant1_surname'        =>($row['applicant1_surname']),
    'applicant1_dateofbirth'    =>($row['applicant1_dateofbirth']),
);

echo json_encode($obj);
?>
</code>```

I'm a Newbie. Any recommendations would be much appreciated.

答:
When preparing a statement in MySQLi, you need to use bind_result() to bind the resulting columns into variables, which you'll use instead of the $row array you'd use if you weren't preparing the statement (like you'd use mysqli_fetch_*() functions).

Its important that the number of variables you bind match the number of selected columns. This is why I have modified your query, to match that.

Then you need to fetch() the results. With those changes implemented, your query should look something like this

```<code>$stmt = $conn->prepare("SELECT contractID,
                               loanpurpose,
                               applicant1_firstname,
                               applicant1_middlename,
                               applicant1_surname,
                               applicant1_dateofbirth
                        FROM contract
                        WHERE contractID=?
                          AND applicant1_firstname=?
                          AND applicant1_surname=?");
$stmt->bind_param("iss", $contractno, $firstname, $lastname);
$stmt->execute();
$stmt->bind_result($contractID, $loanpurpose, $applicant1_firstname, $applicant1_middlename, $applicant1_surname, $applicant1_dateofbirth);
if ($stmt->errno) {
    die("Query failed to execute: " . $stmt->error);
}
if ($stmt->fetch()) {
    echo json_encode(array("contractID" => $contractID,
                           "loanpurpose" => $loanpurpose,
                           "applicant1_firstname" => $applicant1_firstname,
                           "applicant1_middlename" => $applicant1_middlename,
                           "applicant1_surname" => $applicant1_surname,
                           "applicant1_dateofbirth" => $applicant1_dateofbirth));
} else {
    echo "No matching rows returned.";
}
$stmt->close();
</code>```

And no, you should not use mysqli_real_escape_string() when using a prepared statement - that'd ruin the data, by escaping quotes which does not need to be escaped (IF I use mysqli prepared statements do i need to escape).

Instead of using $stmt->num_rows == 1, you can check if $stmt->fetch() returned true - because you only expect one row, you don't need to check the amount - just that something was fetched. As per the manual, $stmt->fetch() returns true for successful queries, null if no rows was returned.

The reason why this approach might be better, is because you avoid having to call $stmt->store_result(); before you can use $stmt->num_rows;. This is more efficient in terms of resources, but also saves you some typing ;-)

Also note that echo "Updated {$stmt->affected_rows} rows"; wouldn't make sense to use here, as you're running a SELECT query, not an UPDATE one. If you want to see the number of rows returned, you can use $stmt->num_rows; instead.

http://php.net/mysqli-stmt.bind-result

http://php.net/mysqli-stmt.fetch

http://php.net/mysqli-stmt.num-rows

Body:
With Mysqli my code is working fine, but when I try to use a prepared statement, for more security, I can't get the values back to my AJAX() function.

this is my js code

function validateCoSigner(){
var contractNo = $('#cosigner_reference_number').val();
var firstName = $('#cosigner_firstname').val();
var lastName = $('#cosigner_lastname').val();
$.ajax({
    type: 'POST',
    url: 'php/retrieve-applicant1-details.php',
    // dataType: 'json',
    data: {
        'contractNo': contractNo,
        'firstName' : firstName,
        'lastName'  : lastName
    },
    success: function(json) {
        showCoSigner();
        console.log(json);
        $('#contractID').val(json.contractID);
        $('#loanpurpose').val(json.loanpurpose);
        $('#applicant1_firstname').val(json.applicant1_firstname);
        $('#applicant1_middlename').val(json.applicant1_middlename);
        $('#applicant1_surname').val(json.applicant1_surname);
        $('#applicant1_dateofbirth').val(json.applicant1_dateofbirth);
    },
    error: function() {
        alert ('error2');

    }
});

}

This is the retrieve-applicant1-details.php file with the mysqli functions that works:

<?php
header('Content-Type: application/json');
$conn = mysqli_connect("localhost", "root","","xxx");

$contractno = $_POST['contractNo'];
$firstname = $_POST['firstName'];
$lastname = $_POST['lastName'];

$sql = "SELECT * FROM contract WHERE contractID='$contractno' AND applicant1_firstname='$firstname' AND applicant1_surname='$lastname'";
$query = mysqli_query($conn,$sql);
$num_row = mysqli_num_rows($query);
$row=mysqli_fetch_assoc($query);
if( $num_row == 1 ) {
    $obj = [
        'contractID'                =>($row['contractID']),
        'loanpurpose'               =>($row['loanpurpose']),
        'applicant1_firstname'      =>($row['applicant1_firstname']),
        'applicant1_middlename'     =>($row['applicant1_middlename']),
        'applicant1_surname'        =>($row['applicant1_surname']),
        'applicant1_dateofbirth'    =>($row['applicant1_dateofbirth']),
    ];
    }
else {
    echo 'The reference number, firstname and lastname does not match';
    exit;
}

echo json_encode($obj);
?>

If I use prepared statement as below, I can't figure out how to properly fetch the data so that I can get the values back to my Ajax function so that it can be displayed in my form.

<?php
header('Content-Type: application/json');
$conn = mysqli_connect("localhost", "root","","xxx");

$contractno = $_POST['contractNo'];  //not sure if I still need to use mysqli_real_escape_string here.
$firstname = $_POST['firstName'];
$lastname = $_POST['lastName'];

// prepare statement
$stmt = $conn->prepare("SELECT * FROM contract WHERE contractID=? AND applicant1_firstname=? AND applicant1_surname=?");
// bind
$stmt->bind_param("iss", $contractno, $firstname, $lastname);
// execute
$stmt->execute();
if ($stmt->errno) {
    echo "FAILURE!!! " . $stmt->error;
}
else echo "Updated {$stmt->affected_rows} rows";

$row = $stmt->fetchObject();
$obj = (
    'contractID'                =>($row['contractID']),
    'loanpurpose'               =>($row['loanpurpose']),
    'applicant1_firstname'      =>($row['applicant1_firstname']),
    'applicant1_middlename'     =>($row['applicant1_middlename']),
    'applicant1_surname'        =>($row['applicant1_surname']),
    'applicant1_dateofbirth'    =>($row['applicant1_dateofbirth']),
);

echo json_encode($obj);
?>

I'm a Newbie. Any recommendations would be much appreciated.

Body:
When preparing a statement in MySQLi, you need to use bind_result() to bind the resulting columns into variables, which you'll use instead of the $row array you'd use if you weren't preparing the statement (like you'd use mysqli_fetch_*() functions).

Its important that the number of variables you bind match the number of selected columns. This is why I have modified your query, to match that.

Then you need to fetch() the results. With those changes implemented, your query should look something like this

$stmt = $conn->prepare("SELECT contractID,
                               loanpurpose,
                               applicant1_firstname,
                               applicant1_middlename,
                               applicant1_surname,
                               applicant1_dateofbirth
                        FROM contract
                        WHERE contractID=?
                          AND applicant1_firstname=?
                          AND applicant1_surname=?");
$stmt->bind_param("iss", $contractno, $firstname, $lastname);
$stmt->execute();
$stmt->bind_result($contractID, $loanpurpose, $applicant1_firstname, $applicant1_middlename, $applicant1_surname, $applicant1_dateofbirth);
if ($stmt->errno) {
    die("Query failed to execute: " . $stmt->error);
}
if ($stmt->fetch()) {
    echo json_encode(array("contractID" => $contractID,
                           "loanpurpose" => $loanpurpose,
                           "applicant1_firstname" => $applicant1_firstname,
                           "applicant1_middlename" => $applicant1_middlename,
                           "applicant1_surname" => $applicant1_surname,
                           "applicant1_dateofbirth" => $applicant1_dateofbirth));
} else {
    echo "No matching rows returned.";
}
$stmt->close();

And no, you should not use mysqli_real_escape_string() when using a prepared statement - that'd ruin the data, by escaping quotes which does not need to be escaped (IF I use mysqli prepared statements do i need to escape).

Instead of using $stmt->num_rows == 1, you can check if $stmt->fetch() returned true - because you only expect one row, you don't need to check the amount - just that something was fetched. As per the manual, $stmt->fetch() returns true for successful queries, null if no rows was returned.

The reason why this approach might be better, is because you avoid having to call $stmt->store_result(); before you can use $stmt->num_rows;. This is more efficient in terms of resources, but also saves you some typing ;-)

Also note that echo "Updated {$stmt->affected_rows} rows"; wouldn't make sense to use here, as you're running a SELECT query, not an UPDATE one. If you want to see the number of rows returned, you can use $stmt->num_rows; instead.

http://php.net/mysqli-stmt.bind-result

http://php.net/mysqli-stmt.fetch

http://php.net/mysqli-stmt.num-rows


问:
Sharing photo on FB's latest apk
I am trying to share a photo on Facebook.

I have login working, and the share dialog will pop up with sharelinkcontent but not with photo.

It will not pop up at all, but it is running and hitting this code.

Here is my code:

```<code>if (ShareDialog.canShow(SharePhotoContent.class)) {
//            ShareLinkContent linkContent = new ShareLinkContent.Builder()
//                    .build();
//            shareDialog.show(linkContent);

        Bitmap icon = BitmapFactory.decodeResource(this.getResources(),
                R.drawable.common_plus_signin_btn_text_light);

        SharePhoto photo = new SharePhoto.Builder()
                .setBitmap(icon)
                .build();

        SharePhotoContent photoContent = new SharePhotoContent.Builder()
                .addPhoto(photo)
                .build();

        shareDialog.show(photoContent);

    }
</code>```

答:
Facebook SDK's versions 4.0+ have changed the way you can share content on facebook.
For photos, you need to use PhotoShareContent.

For links, the ShareLinkContent.

A requirement of the SharePhotoContent is that you must have installed the native faceboook app in order to share photos.

From Facebook Doc

Photos

People can share photos from your app to Facebook with the Share
  Dialog or with a custom interface.

The photos must be less than 12MB in size

People need the native Facebook for Android app installed, version 7.0 or higher

On the other hand, to share a link is not necessary the facebook app, that's why your code works when you use ShareLinkContent

Title: Sharing photo on FB's latest apk

Body:
I am trying to share a photo on Facebook.

I have login working, and the share dialog will pop up with sharelinkcontent but not with photo.

It will not pop up at all, but it is running and hitting this code.

Here is my code:

if (ShareDialog.canShow(SharePhotoContent.class)) {
//            ShareLinkContent linkContent = new ShareLinkContent.Builder()
//                    .build();
//            shareDialog.show(linkContent);

        Bitmap icon = BitmapFactory.decodeResource(this.getResources(),
                R.drawable.common_plus_signin_btn_text_light);

        SharePhoto photo = new SharePhoto.Builder()
                .setBitmap(icon)
                .build();

        SharePhotoContent photoContent = new SharePhotoContent.Builder()
                .addPhoto(photo)
                .build();

        shareDialog.show(photoContent);

    }


问:
Run bash script from Windows PowerShell
In cygwin, I could just do ./script.sh args, but this opens the script file in notepad in PowerShell.

What do I need to do have it execute?

答:
There is now a "native" solution on Windows 10, after enabling Bash on Windows, you can enter Bash shell by typing bash:

You can run Bash script like bash ./script.sh, but keep in mind that C drive is located at /mnt/c, and external hard drives are not mountable. So you might need to change your script a bit so it is compatible to Windows.

Also, even as root, you can still get permission denied when moving files around in /mnt, but you have your full root power in the / file system.

Also make sure your shell script is formatted with Unix style, or there can be errors.

ContentLicense: CC BY-SA 2.5

Title: Run bash script from Windows PowerShell


问:
The constructor Random() is not visible
I am creating a gwt application.I get the error "The constructor Random() is not visible" in the method below.I have tried putting it in the main onModuleLoad() as well.

```<code>public void jump(){
 Random generator = new Random();
}
</code>```

I have imported random via the following

```<code>import com.google.gwt.user.client.Random;
</code>```

No matter where I put this I still keep getting that error.

Thanks

答:
The com.google.gwt.user.client.Random class has no public constructor, and all of its methods are static.  The javadoc says:

This class can be used as a substitute for java.util.Random. The semantics differ in that the underlying browser's implementation is used. The random generator cannot be seeded or otherwise used to reproduce a particular sequence of results.

I suspect that the reason for this design (i.e. static methods and no public constructor) is that the GWT Random class is really just a skin for the ECMAScript function Math.random(),  which is a static function and which cannot be seeded.

I guess using java.util.Random is an alternative, but I would not trust it to be able to seed itself from a browser-side source of entropy.

Title: The constructor Random() is not visible

Body:
I am creating a gwt application.I get the error "The constructor Random() is not visible" in the method below.I have tried putting it in the main onModuleLoad() as well.

public void jump(){
 Random generator = new Random();
}

I have imported random via the following

import com.google.gwt.user.client.Random;

No matter where I put this I still keep getting that error.

Thanks


答:
At first you should be more clear about your question.
Second here's what may be the answer

```<code>var str = "I need the only the    date 04-Jun-2017\n"
var result  = str.replace('I need the only the    ','');
alert(result);
</code>```

See how the .replace(valueToSearch,valueToReplace) function needs two parameters, first is the text to replace, so what ever you put inside it will search for inside the string, the second parameter is the value that it will replace it with, so in case you want to get rid of it just place an empty string.

Title: Javascript extract regular expression from string

Body:
At first you should be more clear about your question.
Second here's what may be the answer

var str = "I need the only the    date 04-Jun-2017\n"
var result  = str.replace('I need the only the    ','');
alert(result);

See how the .replace(valueToSearch,valueToReplace) function needs two parameters, first is the text to replace, so what ever you put inside it will search for inside the string, the second parameter is the value that it will replace it with, so in case you want to get rid of it just place an empty string.


问:
SQL Unique Key iff not Deleted
I have table as below:

```<code>+----------+---------+
| ParentId | ChildId |
+----------+---------+
</code>```

It is a one-to-many relationship (one parent, multiple children) at the moment the primary key is the child id because a child can only map to one parent (all pretty straight forward so far).

My question comes in now tho I want to add a secondary column as below:

```<code>+----------+---------+---------+
| ParentId | ChildId | Deleted |
+----------+---------+---------+
</code>```

So the situation is I need to keep track, for audit reasons, mappings of deleted parents, my thought was to make Child Id unique iff  Deleted is well false. Question is how do I achieve this? Is it possible or should a create a secondary table that I used to archive the deleted entries, any other suggest how I can either achieve this or another approach I can take?

答:
I think this is your question:

my thought was to make Child Id unique iff Deleted is well false.
  Question is how do I achieve this?

If so, you can use a filtered unique index:

```<code>create unique index unq_t_parent_child on t(parent, child)
    where isdeleted = 0;
</code>```

Title: SQL Unique Key iff not Deleted

Body:
I have table as below:

+----------+---------+
| ParentId | ChildId |
+----------+---------+

It is a one-to-many relationship (one parent, multiple children) at the moment the primary key is the child id because a child can only map to one parent (all pretty straight forward so far).

My question comes in now tho I want to add a secondary column as below:

+----------+---------+---------+
| ParentId | ChildId | Deleted |
+----------+---------+---------+

So the situation is I need to keep track, for audit reasons, mappings of deleted parents, my thought was to make Child Id unique iff  Deleted is well false. Question is how do I achieve this? Is it possible or should a create a secondary table that I used to archive the deleted entries, any other suggest how I can either achieve this or another approach I can take?

Body:
I think this is your question:

my thought was to make Child Id unique iff Deleted is well false.
  Question is how do I achieve this?

If so, you can use a filtered unique index:

create unique index unq_t_parent_child on t(parent, child)
    where isdeleted = 0;


问:
How to replace all \ char into ' in javascript
if, a = "Bob\'s house"

how would you replace the backslash with another '?
I want a to equal "Bob''s house"

I would assume that I can do a.replace("\", "'") but this doesn't work

答:
It does not work because \' is treated as a single character. In Javascript \ is used to initiate an escape character, which means "literally the character after \".

In order to show \ you therefore need to write \\. And if you want to change escaped ' into '' what you need to do is simply a.replace("\'", "\'\'");


答:
basically a = "Bob\'s house" is interpreted as "Bob's house", youre just escaping the '. there is no backslash in the string.

to have your wanted result ("Bob''s house"), simply do the following:

```<code>a.replace("\'", "\'\'")
</code>```

Title: How to replace all \ char into ' in javascript

Body:
if, a = "Bob\'s house"

how would you replace the backslash with another '?
I want a to equal "Bob''s house"

I would assume that I can do a.replace("\", "'") but this doesn't work

Body:
basically a = "Bob\'s house" is interpreted as "Bob's house", youre just escaping the '. there is no backslash in the string.

to have your wanted result ("Bob''s house"), simply do the following:

a.replace("\'", "\'\'")


问:
Create a new file in any desktop using an excel file with a command button to execute that task
I have an excel file, BookDatabase.xls, which holds a database of books and has a command button that backup some contents of a worksheet to a new excel file.

My problem is BookDatabase.xls will be used in a laptop and a desktop, how can I make this button to work in both devices.

Below is my portion of my code for the creation of the file and I'm expecting that this will not work in the other device because the path is only for the desktop.

```<code>ActiveWorkbook.SaveAs Filename:="C:\Users\Karen\Documents\BookDatabase.xls"
</code>```

I'm not very good with VBA and would like to learn more. I hope you can also place a comment in the code so the I could better understand the function of the code lines.

答:
If the problem is only that the User Name is not the same on the laptop, the following should work:</p>

```<code>ActiveWorkbook.SaveAs Filename:=Environ("USERPROFILE") & "\Documents\BookDatabase.xls"
</code>```

Body:
I have an excel file, BookDatabase.xls, which holds a database of books and has a command button that backup some contents of a worksheet to a new excel file.

My problem is BookDatabase.xls will be used in a laptop and a desktop, how can I make this button to work in both devices.

Below is my portion of my code for the creation of the file and I'm expecting that this will not work in the other device because the path is only for the desktop.

ActiveWorkbook.SaveAs Filename:="C:\Users\Karen\Documents\BookDatabase.xls"

I'm not very good with VBA and would like to learn more. I hope you can also place a comment in the code so the I could better understand the function of the code lines.

Body:
If the problem is only that the User Name is not the same on the laptop, the following should work:

ActiveWorkbook.SaveAs Filename:=Environ("USERPROFILE") & "\Documents\BookDatabase.xls"


问:
Making text appear over time with javascript
I am trying to create a simple web page when I ran into a problem that I might need everyone to help me solve. Say I was writing some text in font, and I want
text to appear right under it under 10 seconds. Is this possible? I've tried Google already. It's results weren't so decent.</p>

答:
As your question was not very clear, I guess this might (or might not) be what you are looking for:

setTimeout(function() {
    document.getElementById('element').innerHTML += '
More text';
}, 10000);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="element">Some text</div></code>```

Body:
As your question was not very clear, I guess this might (or might not) be what you are looking for:

setTimeout(function() {
    document.getElementById('element').innerHTML += '<br>More text';
}, 10000);

<div id="element">Some text</div>


问:
Is there a Wikipedia API?
On my Wikipedia user page, I run a Wikipedia script that displays my statistics (number of pages edited, number of new pages, monthly activity, etc.).

I'd like to put this information on my blog.

Is there an API that would allow me to do something like this?

答:
If you want to extract structured data from Wikipedia, you may consider using DbPedia http://dbpedia.org/

It provides means to query data using given criteria using SPARQL and returns data from parsed Wikipedia infobox templates

Here is a quick example how it could be done in .NET http://www.kozlenko.info/blog/2010/07/20/executing-sparql-query-on-wikipedia-in-net/

There are some SPARQL libraries available for multiple platforms to make queries easier

OwnerDisplayName: nzpcmad

Title: Is there a Wikipedia API?


问:
Array number that are multiples of 3
I need to get all number that multiples of 3.
Can someone help me to write it?  Here is what I have so far:</p>

```<code>int[] myList = { 1, 2, 3, 4, 5, 6, 7, 8, 9, };

public class Main {
public static void main(String[] args) {
    int[] myList = { 1, 2, 3, 4, 5, 6, 7, 8, 9, };
    int share = myList[0];
    for (int i / 3; i / myList.length;) {

        }
    }
    System.out.println(i / 3 );

}

}
</code>```

答:
You should read java Tutorials and Documentation before trying to write your own program code.

Your code is full of syntax errors and logic mistakes.

I don't advice you to begin programming java before understanding core programming concepts:

Declaring variables , if else conditions, loops (while, for), reading inputs, printing outputs, logical operators (&& , ||, !), arithmetic operators(+, -, *, /, %), relational operators(==, !=, >, <) , operators precedence ....

These concepts are basics in almost every programming language

Programming is a logic thinking not just typing

Check these references to learn java:

Oracle Documentation

Tutorialspoint

In order to get numbers that multiples of 3 in the array list

you can use % mod operator to check if a number is divisible by 3:

```<code> int[] myList = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
for(int i = 0; i < myList.length; i++){
     if( myList[i] % 3 == 0){
       System.out.println(myList[i]);
     }
}
</code>```

Output:

```<code>3
6
9
BUILD SUCCESSFUL (total time: 0 seconds)
</code>```

Title: Array number that are multiples of 3

Body:
I need to get all number that multiples of 3.
Can someone help me to write it?  Here is what I have so far:

int[] myList = { 1, 2, 3, 4, 5, 6, 7, 8, 9, };

public class Main {
public static void main(String[] args) {
    int[] myList = { 1, 2, 3, 4, 5, 6, 7, 8, 9, };
    int share = myList[0];
    for (int i / 3; i / myList.length;) {

        }
    }
    System.out.println(i / 3 );

}

}

Body:
You should read java Tutorials and Documentation before trying to write your own program code.

Your code is full of syntax errors and logic mistakes.

I don't advice you to begin programming java before understanding core programming concepts:

Declaring variables , if else conditions, loops (while, for), reading inputs, printing outputs, logical operators (&& , ||, !), arithmetic operators(+, -, *, /, %), relational operators(==, !=, >, <) , operators precedence ....

These concepts are basics in almost every programming language

Programming is a logic thinking not just typing

Check these references to learn java:

Oracle Documentation

Tutorialspoint

In order to get numbers that multiples of 3 in the array list

you can use % mod operator to check if a number is divisible by 3:

 int[] myList = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
for(int i = 0; i < myList.length; i++){
     if( myList[i] % 3 == 0){
       System.out.println(myList[i]);
     }
}

Output:

3
6
9
BUILD SUCCESSFUL (total time: 0 seconds)


问:
 works but not .gifv
Any idea why this won't load?

```<code><img src="http://i.imgur.com/tgmCpsv.gifv"> <!-- won't load -->
</code>```

Codepen

But it works if you change gifv to gif.

http://i.imgur.com/tgmCpsv.gifv = src

http://i.imgur.com/tgmCpsv.gif = gif src

答:
That is because the .gifv is not an actual image. It is a url that is handled by imgur.com and shows the image in an html page (hence the download button and imgur link)

The .gif on the other hand, is a direct link to the image.

Title: <img src="my_image.GIF"> works but not .gifv

Body:
Any idea why this won't load?

Codepen

But it works if you change gifv to gif.

http://i.imgur.com/tgmCpsv.gifv = src

http://i.imgur.com/tgmCpsv.gif = gif src


问:
If a certain value is in a certain range, print what ever the value is in java
I am not exactly sure how this is called and how it should be done, but I am learning Java and my assignment is to create a data class that will be able to add days to certain date and subtract and show the difference and so on.
My current issue is that I want to implement a rule for every month of the year, I am sure this can be done differently, but I want to try and do this.

Let us say we are given the date in format Year, month, day. 2017.09.31
I want to check before it is printed if month 09 is allowed to have 31 days.
So I wanted to go and write this:

```<code>if (MM==1 || MM==01);
</code>```

where MM is month, to say that the value of day for MM can be in a range from 1-30, if the number D is in that range print the number D.
Is there any function in Java that lets u use range in this manner?

答:
java.time

Perhaps not appropriate for your homework, but Java does offer the java.time classes for such work. Specifically, the YearMonth class.

```<code>YearMonth.of(
    LocalDate.parse(
        "2017.09.31".replace( "." , "-" )
    )
).lengthOfMonth() == 31
</code>```

If that day-of-month component might be invalid, then extract the year and month parts to construct a YearMonth object.

```<code>YearMonth.parse(
    "2017.09.31".substring( 0, 6 ).replace( "." , "-" )
).lengthOfMonth()
</code>```

To manage your rules, your number of days to add per month, you can use an EnumMap with the Month enum found in java.time.

```<code>Map< Month , Integer > rules = new EnumMap<>() ;

rules.put( Month.JANUARY , 3 ) ;
rules.put( Month.FEBRUARY , 7 ) ;
…
</code>```

Body:
I am not exactly sure how this is called and how it should be done, but I am learning Java and my assignment is to create a data class that will be able to add days to certain date and subtract and show the difference and so on.
My current issue is that I want to implement a rule for every month of the year, I am sure this can be done differently, but I want to try and do this.

Let us say we are given the date in format Year, month, day. 2017.09.31
I want to check before it is printed if month 09 is allowed to have 31 days.
So I wanted to go and write this:

if (MM==1 || MM==01);

where MM is month, to say that the value of day for MM can be in a range from 1-30, if the number D is in that range print the number D.
Is there any function in Java that lets u use range in this manner?

Body:
java.time

Perhaps not appropriate for your homework, but Java does offer the java.time classes for such work. Specifically, the YearMonth class.

YearMonth.of(
    LocalDate.parse(
        "2017.09.31".replace( "." , "-" )
    )
).lengthOfMonth() == 31

If that day-of-month component might be invalid, then extract the year and month parts to construct a YearMonth object.

YearMonth.parse(
    "2017.09.31".substring( 0, 6 ).replace( "." , "-" )
).lengthOfMonth()

To manage your rules, your number of days to add per month, you can use an EnumMap with the Month enum found in java.time.

Map< Month , Integer > rules = new EnumMap<>() ;

rules.put( Month.JANUARY , 3 ) ;
rules.put( Month.FEBRUARY , 7 ) ;
…


问:
How does the client verify servers certificate in SSL?
I read a lot about this topic and all "detailed" explanations seem to miss a step:

For the client to verify the server, it does the following (according to my understanding):

It obtains the certificate from the server. The certificate will contain public key and digital signature.

2?) Client verifies using the public key that the signature is OK.

Here is why I am confused. Say I am the man in the middle. I can connect to the server and obtain any information the server provides me, and then forward it to the client. How can the client tell who actually presented the certificate?

Here is what I also know in general:

Client knows public key. It encrypts a message with it and sends it to server.

Server knows private key, decrypts the message, and sends it back.

Now client can share symmetric key with server.

A man in the middle can be present, but it doesn't matter because data cannot be decrypted without private key.

So how does that relate to the (static?) digital signature in the certificate?

Please help me understand that specific step (verifying signature).

答:
I think I can answer this question for you in regards to the process.

the clients sends a TLS request with information regarding what it can support.

The server receives it and say I can support that and provides public key and server certificate signed by Verisign or Go Daddy, etc.

The client receives it, verifies the validity based info in its local trust store, creates a secret key wrapped in the server public key back to the server, and then they form a secure encrypted channel.
In order for some to MITM, they would need to have CA root signed cert with the exact CN, Location, City, and site name, etc. which should be impossible as CA's don't assigned twin certificates.

ContentLicense: CC BY-SA 4.0


问:
If all my sql server database access is done thru stored procedures
If all my sql server database access is done thru stored procedures, and I plan on continuing that practice, is using linq2sql and/or the entity framework for future projects an unnecessary layer of complexity that doesn't add much value?

Related question: is Microsoft trying to steer developers away from relying on stored procs for data access?

答: I use Linq2sql for calling my stored procedures as well just because its so fast to generate .net code I can call from my app, its just drag and drop, basically done in seconds. Still I think you need to ask yourself how much time you spend maintaing those stored procedures. If you do you would save a lot of time using linq2sql doing your crud calls. I use sprocs only when doing multiple step operations on the database.</p>

OwnerDisplayName: E.J. Brennan

OwnerDisplayName: TT


问:
Multiline regular expression in Autoit3
I am trying to match multi-line HTML source code with a regular expression (using AutoIt). HTML source code to match:

```<code><li class="mission">
    <div>
        <div class="missionTitle">
            <h3>Eat a quarter-pounder with cheese</h3>
            <div class="missionProgress">
                <span>100%</span>
                <div class="missionProgressBar" style="width: 100%;"></div>
            </div>
        </div>
        <div class="missionDetails">
            <ul class="missionRewards">
                <li class="rewardCash">5,000–8,000</li>
                <li class="rewardXP">XP +5</li>
                                </ul>
                            <div class="fightItems clearfix">
                <h5><span>Prerequisites:</span></h5>
                                    <div class="fightItemsWrap">
                                            <div class="fightItem tooltip" title="Sunglasses" data-attack="Attack: 2" data-defence="Defence: 2">
                        <img src="/img/enhancement/3.jpg" alt="">
                        <span>× 1</span>
                    </div>
                                            <div class="fightItem tooltip" title="Broad Shoulders" data-attack="Attack: 0" data-defence="Defence: 3">
                        <img src="/img/enhancement/1003.jpg" alt="">
                        <span>× 1</span>
                    </div>
                                            <div class="fightItem tooltip" title="Irish Fond Anglia" data-attack="Attack: 4" data-defence="Defence: 8">
                        <img src="/img/enhancement/2004.jpg" alt="">
                        <span>× 1</span>
                    </div>
                                        </div>
            </div>
                            <form action="/quest/index/i/kdKJBrgjdGWKqtfDrHEkRM2duXVn1ntH/h/c0b2d58642cd862bfad47abf7110042e/t/1336917311" method="post">
                <input type="hidden" id="id" name="id" value="17"/>
                <button class="button buttonIcon btnEnergy"><em>5</em></button>
            </form>
        </div>
    </div>
</li>
</code>```

It is present multiple times on a single page (but items within
...
 vary).

I need to match

Eat a quarter-pounder with cheese
,

the first span 100% and

<input type="hidden" id="id" name="id" value="17"/>.

Expected result (for every occurrence on a page):

```<code>$a[0] = "Eat a quarter-pounder with cheese"
$a[1] = "100%"
$a[2] = "17"
</code>```

What I came up with:

```<code>(?U)(?:<div class="missionTitle">\s+<h3>(.*)</h3>\s+<div class="missionProgress">\s+<span>(.*)</span>)|(?:<form .*\s+.*<input\stype="hidden"\sid="id"\sname="id"\svalue="(\d+)"/>\s+.*\s+</form>)
</code>```

But that leaves some array-items empty. I also tried the (?s) flag, but then it only captures first occurrence (and stops matching after).

答:
Regular expression to match multi-line HTML source code:

As per documentation;

\R matches newline characters (?>\r\n|\n|\r),

dot . does not (unless (?s) is set).

\s matches white space characters.

Generally some combination is required (like \R\s*?).

Non-capturing groups are redundant (match without capturing instead).

If uniquely enclosed, single characters may be excluded instead (like attribute="([^"]*?)" for text between double-quotes).

Example (contains double-quotes; treat as per Documentation - FAQ - double quotes):

```<code>(?s)<div class="missionTitle">.*?<h3>(.*?)</h3>.*?<div class="missionProgress">.*?<span>([^<]*?)</span>.*?<input type="hidden" id="id" name="id" value="([^"]*?)"/>
</code>```

Visual explanation:

If regular expressions should be used on HTML (beyond simple listings like this) is a different question (been, done, T-shirt).

Title: Multiline regular expression in Autoit3

Body:
I am trying to match multi-line HTML source code with a regular expression (using AutoIt). HTML source code to match:

Eat a quarter-pounder with cheese

                100%

5,000–8,000

XP +5

Prerequisites:

                        × 1

                        × 1

                        × 1

                            <form action="/quest/index/i/kdKJBrgjdGWKqtfDrHEkRM2duXVn1ntH/h/c0b2d58642cd862bfad47abf7110042e/t/1336917311" method="post">
                <input type="hidden" id="id" name="id" value="17"/>
                <button class="button buttonIcon btnEnergy">5</button>
            </form>

It is present multiple times on a single page (but items within
...
 vary).

I need to match

Eat a quarter-pounder with cheese
,

the first span 100% and

<input type="hidden" id="id" name="id" value="17"/>.

Expected result (for every occurrence on a page):

$a[0] = "Eat a quarter-pounder with cheese"
$a[1] = "100%"
$a[2] = "17"

What I came up with:

(?U)(?:
\s+
(.*)
\s+
\s+(.*))|(?:<form .*\s+.*<input\stype="hidden"\sid="id"\sname="id"\svalue="(\d+)"/>\s+.*\s+</form>)

But that leaves some array-items empty. I also tried the (?s) flag, but then it only captures first occurrence (and stops matching after).

Body:
Regular expression to match multi-line HTML source code:

As per documentation;

\R matches newline characters (?>\r\n|\n|\r),

dot . does not (unless (?s) is set).

\s matches white space characters.

Generally some combination is required (like \R\s*?).

Non-capturing groups are redundant (match without capturing instead).

If uniquely enclosed, single characters may be excluded instead (like attribute="([^"]*?)" for text between double-quotes).

Example (contains double-quotes; treat as per Documentation - FAQ - double quotes):

(?s)<div class="missionTitle">.*?<h3>(.*?)</h3>.*?<div class="missionProgress">.*?<span>([^<]*?)</span>.*?<input type="hidden" id="id" name="id" value="([^"]*?)"/>

Visual explanation:

If regular expressions should be used on HTML (beyond simple listings like this) is a different question (been, done, T-shirt).


问:
String Equal to String Control Flow
When using = for the TDEE Calculation control flow comparison operators, the flow stops at if (activityLevel = 'sedentary'). When I use == it works as expected. I've been stuck on this for 2 hours and I've read about 3 documentations but I cant figure it out.

I know == is used for same value and meaning and === is used for same value and type, however I don't think that has anything to do with it. For a moment I thought maybe = is used for type, in this case if activityLevel equals a string, but I'm pretty sure thats not it either as I didn't come across that in documentations for =.

Note: The commented figures in the TDEE control flow are what the results should be, not what they are.

```<code>// REE Calculation
// Males - 10 x weight (kg) + 6.25 x height (cm) – 5 x age (y) + 5 = REE
// Females - 10 x weight (kg) + 6.25 x height (cm) – 5 x age (y) – 161 = REE

const gender = 'male'; // prompt('Are you male or female?');
const weight = 100; // prompt('How much do you weigh in KG?');
const height = 185; // prompt('What is your height in cm?');
const age = 23; // prompt('What is your age');

if (sex = 'male') {
    stepOne = 10 * weight;
    stepTwo = 6.25 * height;
    stepThree = 5 * age + 5;
    var ree = stepOne + stepTwo - stepThree;
}

if (sex = 'f') {
    stepOne = 10 * weight;
    stepTwo = 6.25 * height;
    stepThree = 5 * age - 161;
    var ree = stepOne + stepTwo - stepThree;
}

console.log(ree.toFixed(0)) // Answer is correct - 2171

// TDEE Calculation

var activityLevel = 'moderate activity' // prompt('What is your activity level?\nsedentary/light activity/moderate activity/very active');

if (activityLevel = 'sedentary') {
    var tdee = ree * 1.2; // 2642.40
} else if (activityLevel = 'light activity') {
        var tdee = ree * 1.375; // 3027.75
    } else if (activityLevel = 'moderate activity') {
            var tdee = ree * 1.55; // 3413.10
        } else { // 3798.45
                var tdee = ree * 1.725;
            }

console.log(tdee.toFixed(0))
</code>```

答:
If you want to get the type of something you can use the typeof operator. When you use the assignment operator (=) in your if-statement, it will always* pass the condition. If you want to check equality you should use the == or === operators.

for example, if you want to check the activity level you can do so by:

```<code>var activityLevel = 'moderate activity';
if (activityLevel === 'moderate activity'){
    console.log("Moderate Activity");
}
</code>```

This is a good document about the different operator in JS.

Update: Also just noticed that the variable sex is not defined. You defined gender at the beginning, but you are checking against the variable sex.

Title: String Equal to String Control Flow

Body:
When using = for the TDEE Calculation control flow comparison operators, the flow stops at if (activityLevel = 'sedentary'). When I use == it works as expected. I've been stuck on this for 2 hours and I've read about 3 documentations but I cant figure it out.

I know == is used for same value and meaning and === is used for same value and type, however I don't think that has anything to do with it. For a moment I thought maybe = is used for type, in this case if activityLevel equals a string, but I'm pretty sure thats not it either as I didn't come across that in documentations for =.

Note: The commented figures in the TDEE control flow are what the results should be, not what they are.

// REE Calculation
// Males - 10 x weight (kg) + 6.25 x height (cm) – 5 x age (y) + 5 = REE
// Females - 10 x weight (kg) + 6.25 x height (cm) – 5 x age (y) – 161 = REE

const gender = 'male'; // prompt('Are you male or female?');
const weight = 100; // prompt('How much do you weigh in KG?');
const height = 185; // prompt('What is your height in cm?');
const age = 23; // prompt('What is your age');

if (sex = 'male') {
    stepOne = 10 * weight;
    stepTwo = 6.25 * height;
    stepThree = 5 * age + 5;
    var ree = stepOne + stepTwo - stepThree;
}

if (sex = 'f') {
    stepOne = 10 * weight;
    stepTwo = 6.25 * height;
    stepThree = 5 * age - 161;
    var ree = stepOne + stepTwo - stepThree;
}

console.log(ree.toFixed(0)) // Answer is correct - 2171

// TDEE Calculation

var activityLevel = 'moderate activity' // prompt('What is your activity level?\nsedentary/light activity/moderate activity/very active');

if (activityLevel = 'sedentary') {
    var tdee = ree * 1.2; // 2642.40
} else if (activityLevel = 'light activity') {
        var tdee = ree * 1.375; // 3027.75
    } else if (activityLevel = 'moderate activity') {
            var tdee = ree * 1.55; // 3413.10
        } else { // 3798.45
                var tdee = ree * 1.725;
            }

console.log(tdee.toFixed(0))

Body:
If you want to get the type of something you can use the typeof operator. When you use the assignment operator (=) in your if-statement, it will always* pass the condition. If you want to check equality you should use the == or === operators.

for example, if you want to check the activity level you can do so by:

var activityLevel = 'moderate activity';
if (activityLevel === 'moderate activity'){
    console.log("Moderate Activity");
}

This is a good document about the different operator in JS.

Update: Also just noticed that the variable sex is not defined. You defined gender at the beginning, but you are checking against the variable sex.


问:
Can't resize image using CSS
I've tried every answer I could find on all the sites I could find, but still haven't been able to properly resize an image using CSS. I've got it inside a div, and tried resizing either one and resizing both. I'm trying to fit the image (underneath my navigation bar) to the page (meaning: as wide as the page, and relative height).

```<code><div id="banner"><img src="resources/img/banner.png" class="myImage"></div>
</code>```

First attempt:

```<code>.myImage{
    max-width: 100%;
    height: auto;
    left: 0px;
    right: 0px;
}
</code>```

Second attempt:

```<code>#banner{
    max-width: 100%;
    height: auto;
    left: 0px;
    right: 0px;
}
</code>```

Third attempt:

```<code><div id="banner"><img src="resources/img/banner.png" id="myImage"></div>

#banner{
    max-width: 100%;
    height: auto;
    left: 0px;
    right: 0px;
}

#myImage{
    max-width: 100%;
    height: auto;
    left: 0px;
    right: 0px;
}
</code>```

答:
You have to give the id banner a specific width that is less than 100%. You don't need a height, it already is automatic. You have to target the image inside the banner and not the class added to the image. So it should look like this:</p>

```<code><div id="banner"><img src="resources/img/banner.png" class="myImage"></div>

#banner{
    width: 60%;
    left: 0px;
    right: 0px;
}

#banner img{
    width: 100%;
    left: 0px;
    right: 0px;
}
</code>```

Title: Can't resize image using CSS

Body:
I've tried every answer I could find on all the sites I could find, but still haven't been able to properly resize an image using CSS. I've got it inside a div, and tried resizing either one and resizing both. I'm trying to fit the image (underneath my navigation bar) to the page (meaning: as wide as the page, and relative height).

First attempt:

.myImage{
    max-width: 100%;
    height: auto;
    left: 0px;
    right: 0px;
}

Second attempt:

#banner{
    max-width: 100%;
    height: auto;
    left: 0px;
    right: 0px;
}

Third attempt:

#banner{
    max-width: 100%;
    height: auto;
    left: 0px;
    right: 0px;
}

#myImage{
    max-width: 100%;
    height: auto;
    left: 0px;
    right: 0px;
}

Body:
You have to give the id banner a specific width that is less than 100%. You don't need a height, it already is automatic. You have to target the image inside the banner and not the class added to the image. So it should look like this:

<div id="banner"><img src="resources/img/banner.png" class="myImage"></div>

#banner{
    width: 60%;
    left: 0px;
    right: 0px;
}

#banner img{
    width: 100%;
    left: 0px;
    right: 0px;
}


问:
Delphi Application internationalization and localization
I had read documentation about localizing Embarcadero DocWiki.

But I do not know how to:

change language in Run-Time - for example I would to click in application menu change language to English or Polish

Show translated text in dialogs, e.g: ShowMessage('Zmieniłeś język');

答:
1.
There was sample project (shipped with Delphi) called RichEdit which had run-time change of language. To achieve that, Reinit unit was used (you can take it from here) which actually reloads all the resources.

It's working normally on simple programs like that, but may be real pain to implement in something more complex, as all the controls on form are reverted to initial state in which they have been at start-up, so it's your responsibility to keep your data consistent.

Though in proper implementation where all the application logic is separated from GUI (so there are no vars on TForm, no storing user data in edit boxes etc), it should work normally.

See RichEdit sample's source code to understand how to use Reinit.pas

2.
 The classical approach is to use ResourceString. In interface section of your unit or better in separate unit, write:

```<code>ResourceString
  ChangeLanguageStr = 'Zmieniłeś język';
  //another strings here
</code>```

and for showing message:

```<code>ShowMessage(ChangeLanguageStr);
</code>```

These strings will be shown in translation manager.

Body:
1.
There was sample project (shipped with Delphi) called RichEdit which had run-time change of language. To achieve that, Reinit unit was used (you can take it from here) which actually reloads all the resources.

It's working normally on simple programs like that, but may be real pain to implement in something more complex, as all the controls on form are reverted to initial state in which they have been at start-up, so it's your responsibility to keep your data consistent.

Though in proper implementation where all the application logic is separated from GUI (so there are no vars on TForm, no storing user data in edit boxes etc), it should work normally.

See RichEdit sample's source code to understand how to use Reinit.pas

2.
 The classical approach is to use ResourceString. In interface section of your unit or better in separate unit, write:

ResourceString
  ChangeLanguageStr = 'Zmieniłeś język';
  //another strings here

and for showing message:

ShowMessage(ChangeLanguageStr);

These strings will be shown in translation manager.


问:
Concatenating triple quoted strings in python
What is the best way to concatenate two triple quoted strings in python?

Example:

```<code>varA= """INSERT ....... """
VarB= """SELECT.......""""
</code>```

Desired Final Query =

```<code>  """INSERT........
     SELECT........"""
</code>```

When I do :

```<code>varC=varA+varB
</code>```

I get something like :

```<code>      """INSERT........

SELECT........"""
</code>```

That is, I don't get the style I desire. How can I achieve this? Thanks in advance :)

答:
Are you using print() to show varC?
Try this,</p>

```<code>varA = """INSERT ....... """

varB = """SELECT......."""

varC = varA + '\n' + varB

print(varC)
</code>```

Body:
What is the best way to concatenate two triple quoted strings in python?

Example:

varA= """INSERT ....... """
VarB= """SELECT.......""""

Desired Final Query =

  """INSERT........
     SELECT........"""

When I do :

varC=varA+varB

I get something like :

      """INSERT........

SELECT........"""

That is, I don't get the style I desire. How can I achieve this? Thanks in advance :)

Body:
Are you using print() to show varC?
Try this,

varA = """INSERT ....... """

varB = """SELECT......."""

varC = varA + '\n' + varB

print(varC)


问:
Does Angular CLI use SystemJS?
I typed dir /s/b systemjs.config.js into the Windows command line from the root directory of a new Angular app that was installed by Angular CLI, but the Windows command line responded by saying File Not Found.

Is SystemJS installed by default by Angular CLI?  If yes, how do I find its config file?  If not, what is used instead?

答: Angular CLI does not use SystemJS anymore. They have moved over to Webpack, so there will not be a systemjs.config.js file in your project.

Title: Does Angular CLI use SystemJS?


答:
Kinda rough, but gets the point across if what you want is text to display directly under some other text. (However, looks like you simply wanted a paragraph line break using
.)

setTimeout(function(){
    var _text = document.getElementById('text-over'),
        under = document.createElement('span');

    under.className = 'text-under';
    under.textContent = 'Under';

    _text.append(under);

    console.log(_text, under);
}, 10000);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#text-over {
  position: relative;
  display: inline-block;
}
.text-under {
  position: absolute;
  bottom: -20px;
  left: 0;
}</code>```

  Text will go under there.

```

Title: Making text appear over time with javascript

Body:
I am trying to create a simple web page when I ran into a problem that I might need everyone to help me solve. Say I was writing some text in font, and I want
text to appear right under it under 10 seconds. Is this possible? I've tried Google already. It's results weren't so decent.

Body:
Kinda rough, but gets the point across if what you want is text to display directly under some other text. (However, looks like you simply wanted a paragraph line break using <br>.)

setTimeout(function(){
    var _text = document.getElementById('text-over'),
        under = document.createElement('span');

    under.className = 'text-under';
    under.textContent = 'Under';

    _text.append(under);

    console.log(_text, under);
}, 10000);

#text-over {
  position: relative;
  display: inline-block;
}
.text-under {
  position: absolute;
  bottom: -20px;
  left: 0;
}

<p>
  <span id='text-over'>Text</span> will go under there.
</p>


问:
Parsing Strange JSON Data in PHP
My example json data is below, I have tried to parse it however, I couldn't get the data with $response[0] or $response[1] etc... How can I parse it?

Thanks!

```<code>[
  {
    "Tags": [
      "diyarbakır",
      "bağlar",
      "patlama"
    ]
  },
  {
    "Tags": [
      "gazetehaberleri",
      "galatasaray lisesi",
      "kadri gürsel"
    ]
  }
]
</code>```

UPDATE

```<code>$response = json_decode($response);

foreach($response as $key => $value){
   echo $value;
}
</code>```

Warning: Invalid argument supplied for foreach()

答:
As hinted upon by Varuog, the reason you cannot access the elements properly is because you seem to be confusing the result of json_decode(). By default, it converts the JSON objects into PHP objects.

You should still be able to get the data using $response[0] and $response[1], however the way you access the data from there is different.

For your current implementation, to access the "Tags" element, you must do:

```<code>$response = json_decode($response);

foreach($response as $key => $value){
   print_r($value->{'Tags'});
}
</code>```

Which gives the output:

```<code>Array
(
    [0] => diyarbakır
    [1] => bağlar
    [2] => patlama
)
</code>```

If you set the second argument of json_decode() to true, it will convert the objects to arrays and you can access it via $value['Tags']:

```<code>$response = json_decode($response, true);

foreach($response as $key => $value){
   print_r($value['Tags']);
}
</code>```

Title: Parsing Strange JSON Data in PHP

Body:
My example json data is below, I have tried to parse it however, I couldn't get the data with $response[0] or $response[1] etc... How can I parse it?

Thanks!

[
  {
    "Tags": [
      "diyarbakır",
      "bağlar",
      "patlama"
    ]
  },
  {
    "Tags": [
      "gazetehaberleri",
      "galatasaray lisesi",
      "kadri gürsel"
    ]
  }
]

UPDATE

$response = json_decode($response);

foreach($response as $key => $value){
   echo $value;
}

Warning: Invalid argument supplied for foreach()

Body:
As hinted upon by Varuog, the reason you cannot access the elements properly is because you seem to be confusing the result of json_decode(). By default, it converts the JSON objects into PHP objects.

You should still be able to get the data using $response[0] and $response[1], however the way you access the data from there is different.

For your current implementation, to access the "Tags" element, you must do:

$response = json_decode($response);

foreach($response as $key => $value){
   print_r($value->{'Tags'});
}

Which gives the output:

Array
(
    [0] => diyarbakır
    [1] => bağlar
    [2] => patlama
)

If you set the second argument of json_decode() to true, it will convert the objects to arrays and you can access it via $value['Tags']:

$response = json_decode($response, true);

foreach($response as $key => $value){
   print_r($value['Tags']);
}


答:
In python the main use of triple quotes strings are for multiline strings. Thus str1="bees" is equivalent to str1="""bees""", but

```<code>str1="""
   bees"""
</code>```

is not equivalent to

```<code>str1="
   bees"
</code>```

Anyway, using your two strings, if you just want to have str2 under str1, you can:

```<code>str1 = """INSERT......."""
str2 = """SELECT......."""

str3 = str1 + "\n" + str2

# >>> str1 = """INSERT......."""
# >>> str2 = """SELECT......."""
# >>> print str1 + "\n" + str2
# INSERT.......
# SELECT.......
</code>```

or

```<code>print "{0}\n{1}".format(str1, str2)
</code>```

Title: Concatenating triple quoted strings in python

Body:
In python the main use of triple quotes strings are for multiline strings. Thus str1="bees" is equivalent to str1="""bees""", but

str1="""
   bees"""

is not equivalent to

str1="
   bees"

Anyway, using your two strings, if you just want to have str2 under str1, you can:

str1 = """INSERT......."""
str2 = """SELECT......."""

str3 = str1 + "\n" + str2

# >>> str1 = """INSERT......."""
# >>> str2 = """SELECT......."""
# >>> print str1 + "\n" + str2
# INSERT.......
# SELECT.......

or

print "{0}\n{1}".format(str1, str2)


问:
What is the 'realtime' process priority setting for
From what I've read in the past, you're encouraged not to change the priority of your windows applications programmatically, and if you do, you should never change them to 'realtime'.

What does the 'realtime' process priority setting do, compared to 'High', and 'Above Normal'?

My Processor is an i7 4710 HQ 2.50GHz.

答:
This is explained in Scheduling Priorities on MSDN (emphasis mine):

You should almost never use REALTIME_PRIORITY_CLASS, because this interrupts system threads that manage mouse input, keyboard input, and background disk flushing. This class can be appropriate for applications that "talk" directly to hardware or that perform brief tasks that should have limited interruptions.

So that's the theory.  In practice, if you need to do this, you're probably doing something wrong.


问:
Python: parse JSON in loop
I have a function that pick-ups Country,City,Latitude,Longitude from a database and search on Yelp API for particular business.

And everything works fine:

```<code>def get_movietheaters_for(country, city, latitude, longitude):
    connection2 = pyodbc.connect('DRIVER={SQL Server};'
                                 'SERVER=ASPIRES3;'
                                 'DATABASE=worldcitiespop;'
                                 'UID=sqlninja;'
                                 'PWD=sqlninja')
    cursor2 = connection2.cursor()
    # Call Yelp API to pull business data
    # (Yelp v3 API: https://nz.yelp.com/developers/documentation/v3)
    url = 'https://api.yelp.com/v3/businesses/search'
    params = {'cc': country,
              'location': city,
              'cll': "%s,%s" % (latitude, longitude),
              'categories': args.category,
              'limit': args.limit}
    response = requests.get(url = url, headers = headers, params=params)
    # if response.status_code == 200:
    response_data = response.json()

    sqlStatement = "INSERT INTO VistaYelp (ID, Name, City, Zip_code, Country, State, Address1, Address2, Address3, Latitude, Longitude, Phone, Yelp_URL, Review_Count, Rating) values (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)" # Query
    # Here we go to store JSON elements for SQL

    for SQL_element in response_data['businesses']:
        SQL_ID = SQL_element['id']
        SQL_Name = SQL_element['name']
        SQL_City = SQL_element['location']['city']
        SQL_Zip_code = SQL_element['location']['zip_code']
        SQL_Country = SQL_element['location']['country']
        SQL_State = SQL_element['location']['state']
        SQL_Address1 = SQL_element['location']['address1']
        SQL_Address2 = SQL_element['location']['address2']
        SQL_Address3 = SQL_element['location']['address3']
        SQL_Latitude = SQL_element['coordinates']['latitude']
        SQL_Longitude = SQL_element['coordinates']['longitude']
        SQL_Phone = SQL_element['phone']
        SQL_YelpURL = SQL_element['url']
        SQL_Review = SQL_element['review_count']
        SQL_Rating = SQL_element['rating']

        if args.do == 'show':
            print (SQL_ID,SQL_Name,SQL_City,SQL_Zip_code,SQL_Country,SQL_State,
                SQL_Address1,SQL_Address2,SQL_Address3,SQL_Latitude,SQL_Longitude,SQL_Phone)
        elif args.do == 'save':
            cursor2.execute(sqlStatement, SQL_ID,SQL_Name,SQL_City,SQL_Zip_code,SQL_Country,SQL_State,SQL_Address1,SQL_Address2,SQL_Address3,SQL_Latitude,SQL_Longitude,SQL_Phone,SQL_YelpURL,SQL_Review,SQL_Rating)
            connection2.commit()

    if args.do == 'show':
        print ('\nTotal Cinemas found: ' , len(response_data['businesses']),' for Latitude and Longitude ', latitude, longitude)
    elif args.do == 'save':
        print ('\nTotal Cinemas found and saved in database: ' , len(response_data['businesses']),' for', latitude, longitude)
</code>```

Problem start when the script search for a town that doesn't exists or is not in the Yelp database, so JSON call returns me:

```<code>{
  "error": {
    "code": "LOCATION_NOT_FOUND",
    "description": "Could not execute search, try specifying a more exact location."
  }
}
</code>```

and the script dies in terrible pain (my pain actually):

And it make sense to me, Python is saying:

```<code>    for SQL_element in response_data['businesses']:
KeyError: 'businesses'
</code>```

Which translated means:"Hey dude, you know 'businesses' JSON element, there is no such element in the response, so I don't know what to do, so I stop here."

How can I structure something like: keep doing your job and if response_data['error']['code'] == 'LOCATION_NOT_FOUND': do nothing?

答:
```<code>response_data = response.json()

if response_data['error']['code'] == 'LOCATION_NOT_FOUND':
    # if nothing found, print a message and terminate the function
    print('No cinemas found.')
    return

# otherwise keep on going
sqlStatement = "INSERT INTO ..."
</code>```

Title: Python: parse JSON in loop

Body:
I have a function that pick-ups Country,City,Latitude,Longitude from a database and search on Yelp API for particular business.

And everything works fine:

def get_movietheaters_for(country, city, latitude, longitude):
    connection2 = pyodbc.connect('DRIVER={SQL Server};'
                                 'SERVER=ASPIRES3;'
                                 'DATABASE=worldcitiespop;'
                                 'UID=sqlninja;'
                                 'PWD=sqlninja')
    cursor2 = connection2.cursor()
    # Call Yelp API to pull business data
    # (Yelp v3 API: https://nz.yelp.com/developers/documentation/v3)
    url = 'https://api.yelp.com/v3/businesses/search'
    params = {'cc': country,
              'location': city,
              'cll': "%s,%s" % (latitude, longitude),
              'categories': args.category,
              'limit': args.limit}
    response = requests.get(url = url, headers = headers, params=params)
    # if response.status_code == 200:
    response_data = response.json()

    sqlStatement = "INSERT INTO VistaYelp (ID, Name, City, Zip_code, Country, State, Address1, Address2, Address3, Latitude, Longitude, Phone, Yelp_URL, Review_Count, Rating) values (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)" # Query
    # Here we go to store JSON elements for SQL

    for SQL_element in response_data['businesses']:
        SQL_ID = SQL_element['id']
        SQL_Name = SQL_element['name']
        SQL_City = SQL_element['location']['city']
        SQL_Zip_code = SQL_element['location']['zip_code']
        SQL_Country = SQL_element['location']['country']
        SQL_State = SQL_element['location']['state']
        SQL_Address1 = SQL_element['location']['address1']
        SQL_Address2 = SQL_element['location']['address2']
        SQL_Address3 = SQL_element['location']['address3']
        SQL_Latitude = SQL_element['coordinates']['latitude']
        SQL_Longitude = SQL_element['coordinates']['longitude']
        SQL_Phone = SQL_element['phone']
        SQL_YelpURL = SQL_element['url']
        SQL_Review = SQL_element['review_count']
        SQL_Rating = SQL_element['rating']

        if args.do == 'show':
            print (SQL_ID,SQL_Name,SQL_City,SQL_Zip_code,SQL_Country,SQL_State,
                SQL_Address1,SQL_Address2,SQL_Address3,SQL_Latitude,SQL_Longitude,SQL_Phone)
        elif args.do == 'save':
            cursor2.execute(sqlStatement, SQL_ID,SQL_Name,SQL_City,SQL_Zip_code,SQL_Country,SQL_State,SQL_Address1,SQL_Address2,SQL_Address3,SQL_Latitude,SQL_Longitude,SQL_Phone,SQL_YelpURL,SQL_Review,SQL_Rating)
            connection2.commit()

    if args.do == 'show':
        print ('\nTotal Cinemas found: ' , len(response_data['businesses']),' for Latitude and Longitude ', latitude, longitude)
    elif args.do == 'save':
        print ('\nTotal Cinemas found and saved in database: ' , len(response_data['businesses']),' for', latitude, longitude)

Problem start when the script search for a town that doesn't exists or is not in the Yelp database, so JSON call returns me:

{
  "error": {
    "code": "LOCATION_NOT_FOUND",
    "description": "Could not execute search, try specifying a more exact location."
  }
}

and the script dies in terrible pain (my pain actually):

And it make sense to me, Python is saying:

    for SQL_element in response_data['businesses']:
KeyError: 'businesses'

Which translated means:"Hey dude, you know 'businesses' JSON element, there is no such element in the response, so I don't know what to do, so I stop here."

How can I structure something like: keep doing your job and if response_data['error']['code'] == 'LOCATION_NOT_FOUND': do nothing?


问:
How to add a UIButton to Swift Playground?
So I opened up playground, I just want to add a simple UIButton (or a simple UIView) for testing purposes. I can't get it to display though. This is what I have so far:

```<code>import UIKit

var uiButton    = UIButton.buttonWithType(UIButtonType.System) as UIButton
uiButton.frame  = CGRectMake(0, 0, 100, 100)
uiButton.setTitle("Test", forState: UIControlState.Normal);
//self.view.addSubview(uiButton) <-- doesn't work
</code>```

Do you guys know what I'm doing wrong? Thanks

答:
import XCPlayground has been deprecated and is now import PlaygroundSupport.
You need to create your view first and give it a size.

let view = UIView(frame: CGRect(x: 0, y: 0, width: 300, height: 300))
view.backgroundColor = UIColor.black

then add PlaygroundPage.current.liveView = view to be able to see the view in the assistant editor.

now that you have created your view, and you can see the live preview of it.  You can now add other views to it.  In my playground I added several views so I created simple function with a default width and height.

func addSquareView(x: Int, y: Int, width: Int = 100, height: Int = 100, color: UIColor) {
    let newView = UIView(frame: CGRect(x: x, y: y, width: width, height: height))
    newView.backgroundColor = color
    view.addSubview(newView)
}

addSquareView(x: 100, y: 100, color: .blue)

Now there is a blue square in the center of my view.

Body:
So I opened up playground, I just want to add a simple UIButton (or a simple UIView) for testing purposes. I can't get it to display though. This is what I have so far:

import UIKit

var uiButton    = UIButton.buttonWithType(UIButtonType.System) as UIButton
uiButton.frame  = CGRectMake(0, 0, 100, 100)
uiButton.setTitle("Test", forState: UIControlState.Normal);
//self.view.addSubview(uiButton) <-- doesn't work

Do you guys know what I'm doing wrong? Thanks


答:
```<code>response_data = response.json()
if response_data.get('error'):
  return  # Do nothing and return
</code>```

Title: Python: parse JSON in loop