问:
Error: INSERT INTO / VALUES ('Array'); Column count doesn't match value count at row 1
I spent all Sunday trying to figure this out but, I am not sure how to word it right. It checks every hour via Cron job for new sales. Then takes the product number and receipt number. It uses the product number to check an information database and gather all that info from each row for the newly sold products. Then for each sold product, I need to add the receipt number on the end of the array and insert all that information into a 3rd database that saves all the sales.

My main problem is I merge them and it won't insert into the database. I had it working the first time but only grabbed the first row.

```<code><?php
//find out current time and 1 hour ago
$current_time = strtotime("now");
$tenmin_ago = strtotime('-10 min');
$hour_ago = strtotime('-1 hour');

//////////////////////////////////////////////////////////////////
/////////////////// Connect to Sales Database  ///////////////////
//////////////////////////////////////////////////////////////////

// connect to EMAP sales MySQL server
$server='localhost';
$user='user';
$password='pass';
$database='sales_data';

$con = mysqli_connect($server,$user,$password,$database);

// Check connection
if (mysqli_connect_errno())
  {
  echo "Failed to connect to MySQL: SALES " . mysqli_connect_error();
  }

//////////////////////////////////////////////////////////////////
///////////////////// Connect to EM Database  ////////////////////
//////////////////////////////////////////////////////////////////

//EM connect to DLGuard-EM MySQL server
$em_server='localhost';
$em_user='user';
$em_password='pass';
$em_database='databaseEM';

$em_con = mysqli_connect($em_server,$em_user,$em_password,$em_database);

//EM Check connection
if (mysqli_connect_errno())
  {
  echo "Failed to connect to MySQL: EM " . mysqli_connect_error();
  }

//EM grab store name
$em_dlg_store = "EM";

$em_rows = array();
$em_request = "SELECT * FROM customers WHERE date BETWEEN $hour_ago AND {$current_time}";
$em_result = mysqli_query($em_con, $em_request) or die("ERROR NO SALES EM");
 while ($em_row = mysqli_fetch_array($em_result)) {
    $em_prod_num = $em_row["prod_num"];
    $em_rows[] = $em_row["receipt"];
    }

//////////////////////////////////////////////////////////////////
///////////////////// Grab info for EM Sales  ////////////////////
//////////////////////////////////////////////////////////////////

$emap_rows = array();
$emap_request = "SELECT * FROM all_products WHERE dlgprod_num='{$em_prod_num}' AND dlg_store='{$em_dlg_store}'";
$emap_result = mysqli_query($con, $emap_request) or die("ERROR dlg prod num EM");
 while ($emap_row = mysqli_fetch_array($emap_result)) $emap_rows[] = $emap_row;

$em_emap_rows = array_merge($em_rows, $emap_rows);
 /*VALUES ('$emap_sku', '$emap_dlgprod_num', '$emap_book_title', '$emap_dlgprod_price', '$emap_author_name', '$emap_author_email', '$emap_publisher', '$emap_dlg_store', '$em_receipt');";*/
// 1
$em_add_sql  = "INSERT INTO all_author_sales (sku, dlgprod_num, dlgprod_nam, dlgprod_price, author_name, author_email, publisher, dlg_store, dlgcustomer_receipt)
VALUES ('$em_emap_rows');";
if ($con->multi_query($em_add_sql) === TRUE) {
} else {
    echo "Error: " . $em_add_sql . "<br>" . $con->error;
}

?>
</code>```

xxxxxxxxxxxxxxxxxxxxxxxxx Update 2/27/17 xxxxxxxxxxxxxxxxxxxxxx

Here is an updated version and it grabs the information but it loses the array for receipt somewhere in the merge or string section. Also, it puts the order wrong. instead of UPC, product number, title, price, etc. then start the next line for the second sale it mixes them together like upc, UPC, product number, product number, title, title, price, price when there are two sales.
 Here is the new error. I am so close to figuring this out thank you. I am going to make 4 scripts and have them alternating checking all 4 stores for sales every hour.

```<code>Warning: array_map(): Argument #2 should be an array in  /home1/lotscav1/public_html/Sales/scripts/sales-notif.php on line 53
Warning: implode(): Invalid arguments passed in  /home1/lotscav1/public_html/Sales/scripts/sales-notif.php on line 53
Error: INSERT INTO all_author_sales (sku, dlgprod_num, dlgprod_nam,  dlgprod_price, author_name, author_email, publisher, dlg_store,  dlgcustomer_receipt) VALUES ('('EM2200002','EM2200002','1','1','Island  Girl','Island Girl','4.95','4.95','Marshall Gibson','Marshall  Gibson','jasminerice1993@gmail.com','jasminerice1993@gmail.com','Dan  Cuneo','Dan Cuneo','EM','EM'),(),');
You have an error in your SQL syntax; check the manual that    corresponds to your MySQL server version for the right syntax to use near   'EM2200002','EM2200002','1','1','Island Girl','Island   Girl','4.95','4.95','Marsha' at line 2
Array
</code>```

Here is the updated code

```<code>    <?php
//find out current time and 1 hour ago
$current_time = strtotime("now");
$hour_ago = strtotime('-24 hour');

//////////////////////////////////////////////////////////////////
/////////////////// Connect to Sales Database  ///////////////////
//////////////////////////////////////////////////////////////////

// connect to EMAP sales MySQL server
$mysqli = new mysqli("localhost", "username", "password",     "database");
if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") "  . $mysqli->connect_error;
}

//////////////////////////////////////////////////////////////////
///////////////////// Connect to EM Database  ////////////////////
//////////////////////////////////////////////////////////////////
$mysqli_em = new mysqli("localhost", "username", "password",    "database");
if ($mysqli_em->connect_errno) {
echo "Failed to connect to MySQL_EM: (" . $mysqli_em->connect_errno .     ") " . $mysqli_em->connect_error;
}

//EM grab store name
$em_dlg_store = "EM";

$em_rows = array();
$em_request = "SELECT * FROM customers WHERE date BETWEEN '$hour_ago'    AND '$current_time'";
$em_result = mysqli_query($mysqli_em, $em_request) or die("Error No      Sales EM");
while ($em_row = mysqli_fetch_array($em_result)) {
$em_prod_num = $em_row["prod_num"];
$em_rows[] = $em_row["receipt"];
}
//////////////////////////////////////////////////////////////////
///////////////////// Grab info for EM Sales  ////////////////////
//////////////////////////////////////////////////////////////////
$emap_rows = array();
$emap_request = "SELECT * FROM all_products WHERE       dlgprod_num='$em_prod_num' AND dlg_store='$em_dlg_store'";
$emap_result = mysqli_query($mysqli, $emap_request) or die("Error dlg  prod num EM");
while ($emap_row = mysqli_fetch_array($emap_result)) $emap_rows[] =     $emap_row;

$em_emap_rows = array_merge($emap_rows, $em_rows);
/*VALUES ('$emap_sku', '$emap_dlgprod_num', '$emap_book_title',    '$emap_dlgprod_price', '$emap_author_name', '$emap_author_email',     '$emap_publisher', '$emap_dlg_store', '$em_receipt');";*/
// 1
$string = "";
foreach ($em_emap_rows as $key => $innerArr) {
$result = implode( array_map('quoteItems', $innerArr), ",");
$string .= "(" . $result . ")";

if( $key != count($array) - 1 ){
    $string .= ",";
}
}
function quoteItems($item){
return "'" . $item . "'";
}
//$em_rowss = implode(",", $em_rows); this turns the receipt array     into a string
$em_add_sql  = "INSERT INTO all_author_sales (sku, dlgprod_num,      dlgprod_nam, dlgprod_price, author_name, author_email, publisher,       dlg_store, dlgcustomer_receipt)
VALUES ('$string');";
if ($mysqli->multi_query($em_add_sql) === TRUE) {
} else {
echo "Error: " . $em_add_sql . "<br>" . $mysqli->error . "<br>" .           $em_rows;
}

?>
</code>```

答:
Thank you for all the help. I couldn't make work what you gave me for my unique situation. However, it inspired me towards my working solution along with a little help from an old friend. Here is the code that now works.</p>

```<code>    <?php
//find out current time and 1 hour ago
date_default_timezone_set('America/New_York');
$current_time = strtotime("now");
$hour_ago = strtotime('-1 hour');

//////////////////////////////////////////////////////////////////
/////////////////// Connect to Sales Database  ///////////////////
//////////////////////////////////////////////////////////////////

$mysqli_s = new mysqli("localhost", "user", "password",
"server_sales_data");
if ($mysqli_s->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli_s->connect_errno . ")
" . $mysqli_s->connect_error;
}

//////////////////////////////////////////////////////////////////
///////////////////// Connect to EM Database  ////////////////////
//////////////////////////////////////////////////////////////////

$mysqli_em = new mysqli("localhost", "user", "password",
"server_dlgEM");
if ($mysqli_em->connect_errno) {
echo "Failed to connect to MySQL_EM: (" . $mysqli_em->connect_errno .
") " . $mysqli_em->connect_error;
}

//Grab store name
$dlg_store = "EM";

$em_request = "SELECT * FROM customers WHERE date BETWEEN '$hour_ago'
AND '$current_time'";
$em_result = mysqli_query($mysqli_em, $em_request) or die("Error No
Sales EM");
while ($em_row = mysqli_fetch_array($em_result)) {
$em_prod_num = $em_row["prod_num"];
$em_receipt = $em_row["receipt"];

//////////////////////////////////////////////////////////////////
///////////////////// Grab info for EM Sales  ////////////////////
//////////////////////////////////////////////////////////////////

$request_s = "SELECT * FROM all_products WHERE
dlgprod_num='$em_prod_num' AND dlg_store='$dlg_store'";
$result_s = mysqli_query($mysqli_s, $request_s) or die("Error dlg
prod num EM");
while ($row_s = mysqli_fetch_array($result_s)) {
        $sku_s = $row_s["sku"];
        $dlgprod_num_s = $row_s["dlgprod_num"];
        $book_title_s = addslashes($row_s["book_title"]);
        $dlgprod_price_s = $row_s["dlgprod_price"];
        $author_name_s = addslashes($row_s["author_name"]);
        $author_email_s = $row_s["author_email"];
        $publisher_s = $row_s["publisher"];
        $dlg_store_s = $row_s["dlg_store"];

            $add_sql_s  = "INSERT INTO all_author_sales SET
            `sku`='$sku_s',
            `dlgprod_num`='$dlgprod_num_s',
            `dlgprod_nam`='$book_title_s',
            `dlgprod_price`='$dlgprod_price_s',
            `author_name`='$author_name_s',
            `author_email`='$author_email_s',
            `publisher`='$publisher_s',
            `dlg_store`='$dlg_store_s',
            `dlgcustomer_receipt`='$em_receipt' ";

//create signature
$sig = "The Admin Team at www.website.com";
//to
$admin_email = "admin@website.com";
$to = array($author_email_s, $admin_email);

//setup email headers
$headers='From: ' . $admin_email . "\r\n" .
'Reply-To: ' . $admin_email . "\r\n" .
'X-Mailer: PHP/' . phpversion();
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
$headers .= $emailbody."\n\n";

//email subject and body
$subject = "Your book stats";
$message = "
Hi $author_name_s,<br />
I just wanted to send you a message and let you know that the book or
books below have just been purchased.<br /><br />

Store: $dlg_store_s<br />
Receipt: $em_receipt<br />
Sku Number: $sku_s<br /><br />

Book Title: $book_title_s<br />
Publisher: $publisher_s<br />
Product Number: $dlgprod_num_s<br />
Price: $dlgprod_price_s<br /><br />

Sincerely,<br />
$sig<br /><br />

To remove yourself from this notification, please send an email to
$admin_email with Unsubscribe in the subject line.
";

            if ($mysqli_s->multi_query($add_sql_s) === TRUE) {
            mail (implode(',', $to), $subject, $message, $headers);
            } else {
                echo "Error: " . $add_sql_s . "<br>" . $mysqli_s-
>error . "<br>" . $string;
            }

    }

}

?>
</code>```

Body:
I spent all Sunday trying to figure this out but, I am not sure how to word it right. It checks every hour via Cron job for new sales. Then takes the product number and receipt number. It uses the product number to check an information database and gather all that info from each row for the newly sold products. Then for each sold product, I need to add the receipt number on the end of the array and insert all that information into a 3rd database that saves all the sales.

My main problem is I merge them and it won't insert into the database. I had it working the first time but only grabbed the first row.

<?php
//find out current time and 1 hour ago
$current_time = strtotime("now");
$tenmin_ago = strtotime('-10 min');
$hour_ago = strtotime('-1 hour');

//////////////////////////////////////////////////////////////////
/////////////////// Connect to Sales Database  ///////////////////
//////////////////////////////////////////////////////////////////

// connect to EMAP sales MySQL server
$server='localhost';
$user='user';
$password='pass';
$database='sales_data';

$con = mysqli_connect($server,$user,$password,$database);

// Check connection
if (mysqli_connect_errno())
  {
  echo "Failed to connect to MySQL: SALES " . mysqli_connect_error();
  }

//////////////////////////////////////////////////////////////////
///////////////////// Connect to EM Database  ////////////////////
//////////////////////////////////////////////////////////////////

//EM connect to DLGuard-EM MySQL server
$em_server='localhost';
$em_user='user';
$em_password='pass';
$em_database='databaseEM';

$em_con = mysqli_connect($em_server,$em_user,$em_password,$em_database);

//EM Check connection
if (mysqli_connect_errno())
  {
  echo "Failed to connect to MySQL: EM " . mysqli_connect_error();
  }

//EM grab store name
$em_dlg_store = "EM";

$em_rows = array();
$em_request = "SELECT * FROM customers WHERE date BETWEEN $hour_ago AND {$current_time}";
$em_result = mysqli_query($em_con, $em_request) or die("ERROR NO SALES EM");
 while ($em_row = mysqli_fetch_array($em_result)) {
    $em_prod_num = $em_row["prod_num"];
    $em_rows[] = $em_row["receipt"];
    }

//////////////////////////////////////////////////////////////////
///////////////////// Grab info for EM Sales  ////////////////////
//////////////////////////////////////////////////////////////////

$emap_rows = array();
$emap_request = "SELECT * FROM all_products WHERE dlgprod_num='{$em_prod_num}' AND dlg_store='{$em_dlg_store}'";
$emap_result = mysqli_query($con, $emap_request) or die("ERROR dlg prod num EM");
 while ($emap_row = mysqli_fetch_array($emap_result)) $emap_rows[] = $emap_row;

$em_emap_rows = array_merge($em_rows, $emap_rows);
 /*VALUES ('$emap_sku', '$emap_dlgprod_num', '$emap_book_title', '$emap_dlgprod_price', '$emap_author_name', '$emap_author_email', '$emap_publisher', '$emap_dlg_store', '$em_receipt');";*/
// 1
$em_add_sql  = "INSERT INTO all_author_sales (sku, dlgprod_num, dlgprod_nam, dlgprod_price, author_name, author_email, publisher, dlg_store, dlgcustomer_receipt)
VALUES ('$em_emap_rows');";
if ($con->multi_query($em_add_sql) === TRUE) {
} else {
    echo "Error: " . $em_add_sql . "
" . $con->error;
}

?>

xxxxxxxxxxxxxxxxxxxxxxxxx Update 2/27/17 xxxxxxxxxxxxxxxxxxxxxx

Here is an updated version and it grabs the information but it loses the array for receipt somewhere in the merge or string section. Also, it puts the order wrong. instead of UPC, product number, title, price, etc. then start the next line for the second sale it mixes them together like upc, UPC, product number, product number, title, title, price, price when there are two sales.
 Here is the new error. I am so close to figuring this out thank you. I am going to make 4 scripts and have them alternating checking all 4 stores for sales every hour.

Warning: array_map(): Argument #2 should be an array in  /home1/lotscav1/public_html/Sales/scripts/sales-notif.php on line 53
Warning: implode(): Invalid arguments passed in  /home1/lotscav1/public_html/Sales/scripts/sales-notif.php on line 53
Error: INSERT INTO all_author_sales (sku, dlgprod_num, dlgprod_nam,  dlgprod_price, author_name, author_email, publisher, dlg_store,  dlgcustomer_receipt) VALUES ('('EM2200002','EM2200002','1','1','Island  Girl','Island Girl','4.95','4.95','Marshall Gibson','Marshall  Gibson','jasminerice1993@gmail.com','jasminerice1993@gmail.com','Dan  Cuneo','Dan Cuneo','EM','EM'),(),');
You have an error in your SQL syntax; check the manual that    corresponds to your MySQL server version for the right syntax to use near   'EM2200002','EM2200002','1','1','Island Girl','Island   Girl','4.95','4.95','Marsha' at line 2
Array

Here is the updated code

    <?php
//find out current time and 1 hour ago
$current_time = strtotime("now");
$hour_ago = strtotime('-24 hour');

//////////////////////////////////////////////////////////////////
/////////////////// Connect to Sales Database  ///////////////////
//////////////////////////////////////////////////////////////////

// connect to EMAP sales MySQL server
$mysqli = new mysqli("localhost", "username", "password",     "database");
if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") "  . $mysqli->connect_error;
}

//////////////////////////////////////////////////////////////////
///////////////////// Connect to EM Database  ////////////////////
//////////////////////////////////////////////////////////////////
$mysqli_em = new mysqli("localhost", "username", "password",    "database");
if ($mysqli_em->connect_errno) {
echo "Failed to connect to MySQL_EM: (" . $mysqli_em->connect_errno .     ") " . $mysqli_em->connect_error;
}

//EM grab store name
$em_dlg_store = "EM";

$em_rows = array();
$em_request = "SELECT * FROM customers WHERE date BETWEEN '$hour_ago'    AND '$current_time'";
$em_result = mysqli_query($mysqli_em, $em_request) or die("Error No      Sales EM");
while ($em_row = mysqli_fetch_array($em_result)) {
$em_prod_num = $em_row["prod_num"];
$em_rows[] = $em_row["receipt"];
}
//////////////////////////////////////////////////////////////////
///////////////////// Grab info for EM Sales  ////////////////////
//////////////////////////////////////////////////////////////////
$emap_rows = array();
$emap_request = "SELECT * FROM all_products WHERE       dlgprod_num='$em_prod_num' AND dlg_store='$em_dlg_store'";
$emap_result = mysqli_query($mysqli, $emap_request) or die("Error dlg  prod num EM");
while ($emap_row = mysqli_fetch_array($emap_result)) $emap_rows[] =     $emap_row;

$em_emap_rows = array_merge($emap_rows, $em_rows);
/*VALUES ('$emap_sku', '$emap_dlgprod_num', '$emap_book_title',    '$emap_dlgprod_price', '$emap_author_name', '$emap_author_email',     '$emap_publisher', '$emap_dlg_store', '$em_receipt');";*/
// 1
$string = "";
foreach ($em_emap_rows as $key => $innerArr) {
$result = implode( array_map('quoteItems', $innerArr), ",");
$string .= "(" . $result . ")";

if( $key != count($array) - 1 ){
    $string .= ",";
}
}
function quoteItems($item){
return "'" . $item . "'";
}
//$em_rowss = implode(",", $em_rows); this turns the receipt array     into a string
$em_add_sql  = "INSERT INTO all_author_sales (sku, dlgprod_num,      dlgprod_nam, dlgprod_price, author_name, author_email, publisher,       dlg_store, dlgcustomer_receipt)
VALUES ('$string');";
if ($mysqli->multi_query($em_add_sql) === TRUE) {
} else {
echo "Error: " . $em_add_sql . "
" . $mysqli->error . "
" .           $em_rows;
}

?>

Body:
Thank you for all the help. I couldn't make work what you gave me for my unique situation. However, it inspired me towards my working solution along with a little help from an old friend. Here is the code that now works.

    <?php
//find out current time and 1 hour ago
date_default_timezone_set('America/New_York');
$current_time = strtotime("now");
$hour_ago = strtotime('-1 hour');

//////////////////////////////////////////////////////////////////
/////////////////// Connect to Sales Database  ///////////////////
//////////////////////////////////////////////////////////////////

$mysqli_s = new mysqli("localhost", "user", "password",
"server_sales_data");
if ($mysqli_s->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli_s->connect_errno . ")
" . $mysqli_s->connect_error;
}

//////////////////////////////////////////////////////////////////
///////////////////// Connect to EM Database  ////////////////////
//////////////////////////////////////////////////////////////////

$mysqli_em = new mysqli("localhost", "user", "password",
"server_dlgEM");
if ($mysqli_em->connect_errno) {
echo "Failed to connect to MySQL_EM: (" . $mysqli_em->connect_errno .
") " . $mysqli_em->connect_error;
}

//Grab store name
$dlg_store = "EM";

$em_request = "SELECT * FROM customers WHERE date BETWEEN '$hour_ago'
AND '$current_time'";
$em_result = mysqli_query($mysqli_em, $em_request) or die("Error No
Sales EM");
while ($em_row = mysqli_fetch_array($em_result)) {
$em_prod_num = $em_row["prod_num"];
$em_receipt = $em_row["receipt"];

//////////////////////////////////////////////////////////////////
///////////////////// Grab info for EM Sales  ////////////////////
//////////////////////////////////////////////////////////////////

$request_s = "SELECT * FROM all_products WHERE
dlgprod_num='$em_prod_num' AND dlg_store='$dlg_store'";
$result_s = mysqli_query($mysqli_s, $request_s) or die("Error dlg
prod num EM");
while ($row_s = mysqli_fetch_array($result_s)) {
        $sku_s = $row_s["sku"];
        $dlgprod_num_s = $row_s["dlgprod_num"];
        $book_title_s = addslashes($row_s["book_title"]);
        $dlgprod_price_s = $row_s["dlgprod_price"];
        $author_name_s = addslashes($row_s["author_name"]);
        $author_email_s = $row_s["author_email"];
        $publisher_s = $row_s["publisher"];
        $dlg_store_s = $row_s["dlg_store"];

            $add_sql_s  = "INSERT INTO all_author_sales SET
            `sku`='$sku_s',
            `dlgprod_num`='$dlgprod_num_s',
            `dlgprod_nam`='$book_title_s',
            `dlgprod_price`='$dlgprod_price_s',
            `author_name`='$author_name_s',
            `author_email`='$author_email_s',
            `publisher`='$publisher_s',
            `dlg_store`='$dlg_store_s',
            `dlgcustomer_receipt`='$em_receipt' ";

//create signature
$sig = "The Admin Team at www.website.com";
//to
$admin_email = "admin@website.com";
$to = array($author_email_s, $admin_email);

//setup email headers
$headers='From: ' . $admin_email . "\r\n" .
'Reply-To: ' . $admin_email . "\r\n" .
'X-Mailer: PHP/' . phpversion();
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
$headers .= $emailbody."\n\n";

//email subject and body
$subject = "Your book stats";
$message = "
Hi $author_name_s,<br />
I just wanted to send you a message and let you know that the book or
books below have just been purchased.<br /><br />

Store: $dlg_store_s<br />
Receipt: $em_receipt<br />
Sku Number: $sku_s<br /><br />

Book Title: $book_title_s<br />
Publisher: $publisher_s<br />
Product Number: $dlgprod_num_s<br />
Price: $dlgprod_price_s<br /><br />

Sincerely,<br />
$sig<br /><br />

To remove yourself from this notification, please send an email to
$admin_email with Unsubscribe in the subject line.
";

            if ($mysqli_s->multi_query($add_sql_s) === TRUE) {
            mail (implode(',', $to), $subject, $message, $headers);
            } else {
                echo "Error: " . $add_sql_s . "<br>" . $mysqli_s-
>error . "<br>" . $string;
            }

    }

}

?>


来源: stackexchange

问:
TypeError: Cannot read property 'insertBefore' of null
I have a array like this

```<code>var users = [
    { 'id': 1, 'name': 'user name', 'age': 25, ... },
    { 'id': 2, 'name': 'user name', 'age': 25, ... }
    ...
]
</code>```

I use ng-repeat to display it as a list. like so.

```<code><li ng-repeat="user in users">
    {{user.name}}
    <a href="#" ng-click="UserCTRL.remove_user(user.id)">remove user</a>
</li>
</code>```

And I made the li sortable using jquery sortable. The sortable works and remove_user works. But when I move the last li to any position above it works until i try to remove user then I get the error.

I appreciate any help. what does the error mean?

答:
I dont know if you solve this error for this question was raised 2 years ago. I happened to get the error just like you, and I guess the error might be Cannot read property 'insertBefore' of null. Adding wrap layer div inside the ng-repeat to prevent the angular element been messed and sort it by operate with the div just added list like the following should prevent this error:

```<code><li ng-repeat="user in users">
    <div>
        {{user.name}}
        <a href="#" ng-click="UserCTRL.remove_user(user.id)">remove user</a>
    </div>
</li>
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have a array like this

var users = [
    { 'id': 1, 'name': 'user name', 'age': 25, ... },
    { 'id': 2, 'name': 'user name', 'age': 25, ... }
    ...
]

I use ng-repeat to display it as a list. like so.

    {{user.name}}
    remove user

And I made the li sortable using jquery sortable. The sortable works and remove_user works. But when I move the last li to any position above it works until i try to remove user then I get the error.

I appreciate any help. what does the error mean?

Body:
I dont know if you solve this error for this question was raised 2 years ago. I happened to get the error just like you, and I guess the error might be Cannot read property 'insertBefore' of null. Adding wrap layer div inside the ng-repeat to prevent the angular element been messed and sort it by operate with the div just added list like the following should prevent this error:

<li ng-repeat="user in users">
    <div>
        {{user.name}}
        <a href="#" ng-click="UserCTRL.remove_user(user.id)">remove user</a>
    </div>
</li>


问:
How to create a new variable after comparing values from multiple columns in R?
I have this data frame, q17, below. My goal is replacing "contacts" following these rules:

```<code>ifelse (any values in q17a, q17d, q17f, q17g <5) then contacts is 1

    ifelse (any values in q17a, q17d, q17f, q17g ==5) then contacts is 0

        ifelse (any values in q17a, q17d, q17f, q17g ==8 or 9 or NA) then contacts is 99
</code>```

q17[1:6,]

```<code>   q17a q17d q17f q17g contacts
1     2    5    2   NA       1
2     5    5    5   NA       0
3     1    5    5   NA       1
4     4   NA    5   NA       1
5     1    5    5    5       1
6     3    5   NA   NA       1
</code>```

I tried the following for example, using the answer provided, but the result is not as I expected. Can somebody suggest how to solve this problem?

```<code>apply(q17[,colnames(q17)[1:4]], 1, function(df)
  ifelse(any(df<5), 1,
      ifelse(any(df==5),0,
            ifelse(df == 8 & df == 9 & is.na(df)), 99)))
[1]  1 NA  1  1  1  1
</code>```

I want the result to be: 1  0  1  1  1  1 instead of 1 NA 1 1 1 1

答:
I'm very confused by your question... exactly as you request this is how you do what you ask, as ordered by your example, not your question.

```<code>q17 <- data.frame(q17a = c(1,2,3,4,5,6,7,8,9,10), q17d = c(2,5,1,4,1,3,4,5,4,4), q17f = c(2,5,5,5,5,NA,5,1,NA,4), q17g = c(2,5,5,5,5,NA,5,1,NA,4))
</code>```

q17 looks like

```<code>   q17a q17d q17f q17g
1     1    2    2    2
2     2    5    5    5
3     3    1    5    5
4     4    4    5    5
5     5    1    5    5
6     6    3   NA   NA
7     7    4    5    5
8     8    5    1    1
9     9    4   NA   NA
10   10    4    4    4
</code>```

This is my approach:

```<code>apply(q17[,colnames(q17)[1:4]], 1, function(df)
  ifelse(any(df == 8 | df == 9 | is.na(df)), 99,
         ifelse(any(df == 5), 0,
                ifelse(any(df < 5), 1))))
</code>```

And the result is:

```<code> [1]  1  0  0  0  0 99  0 99 99  1
</code>```

After question edit:

```<code>apply(q17[,colnames(q17)[1:4]], 1, function(df)
  ifelse(any(df < 5, na.rm = T), 1,
         ifelse(any(df == 5, na.rm = T), 0,
                ifelse(df == 8 & df == 9 & is.na(df), 99))))
</code>```

Body:
I have this data frame, q17, below. My goal is replacing "contacts" following these rules:

ifelse (any values in q17a, q17d, q17f, q17g <5) then contacts is 1

    ifelse (any values in q17a, q17d, q17f, q17g ==5) then contacts is 0

        ifelse (any values in q17a, q17d, q17f, q17g ==8 or 9 or NA) then contacts is 99

q17[1:6,]

   q17a q17d q17f q17g contacts
1     2    5    2   NA       1
2     5    5    5   NA       0
3     1    5    5   NA       1
4     4   NA    5   NA       1
5     1    5    5    5       1
6     3    5   NA   NA       1

I tried the following for example, using the answer provided, but the result is not as I expected. Can somebody suggest how to solve this problem?

apply(q17[,colnames(q17)[1:4]], 1, function(df)
  ifelse(any(df<5), 1,
      ifelse(any(df==5),0,
            ifelse(df == 8 & df == 9 & is.na(df)), 99)))
[1]  1 NA  1  1  1  1

I want the result to be: 1  0  1  1  1  1 instead of 1 NA 1 1 1 1

Body:
I'm very confused by your question... exactly as you request this is how you do what you ask, as ordered by your example, not your question.

q17 <- data.frame(q17a = c(1,2,3,4,5,6,7,8,9,10), q17d = c(2,5,1,4,1,3,4,5,4,4), q17f = c(2,5,5,5,5,NA,5,1,NA,4), q17g = c(2,5,5,5,5,NA,5,1,NA,4))

q17 looks like

   q17a q17d q17f q17g
1     1    2    2    2
2     2    5    5    5
3     3    1    5    5
4     4    4    5    5
5     5    1    5    5
6     6    3   NA   NA
7     7    4    5    5
8     8    5    1    1
9     9    4   NA   NA
10   10    4    4    4

This is my approach:

apply(q17[,colnames(q17)[1:4]], 1, function(df)
  ifelse(any(df == 8 | df == 9 | is.na(df)), 99,
         ifelse(any(df == 5), 0,
                ifelse(any(df < 5), 1))))

And the result is:

 [1]  1  0  0  0  0 99  0 99 99  1

After question edit:

apply(q17[,colnames(q17)[1:4]], 1, function(df)
  ifelse(any(df < 5, na.rm = T), 1,
         ifelse(any(df == 5, na.rm = T), 0,
                ifelse(df == 8 & df == 9 & is.na(df), 99))))


问:
Is it okay to pass `this` in the render() method

TL;DR

Is this okay?

```<code>class SideMenu extends React.Component {

  render() {
    // note passing this
    return
        <MenuGroup menu={this}/>
  }
}

class MenuGroup extends React.Component {

  handleClick() {
    this.props.menu.setState({ some: "thing" })
  }

  render() {
   ...
  }
}
</code>```

Background

I am trying to build a side-menu (like the one in sb-admin) using ReactJS.  (I know I could use react-metismenu, but I am doing this to learn how to use ReactJS)

There were two approaches I can think of to do this, but the Context docs kind of warned me enough to not use it for now especially since the experimental API part.

Anyway I had a bunch of components built but no real hierarchy at the moment (since it wasn't needed if I wasn't doing context).  But I needed to pass the object that would store the current state of the menu and allow me to update it.

What I am wondering is if what I did was okay or could it be better or should be avoided.

答:
If your components get too complicated I recommend using some state management tool like mobx or redux. It is not a good idea to pass this down to the child components violates the react one-way flow principle.

You may be looking for this:
https://facebook.github.io/react/docs/lifting-state-up.html

In brief your code should look something like this:

```<code>class SideMenu extends React.Component {
  constructor(props) {
    super(props)
    this.handleMenuChange = this.handleMenuChange.bind(this)
  }

  handleMenuChange(value) { this.setState({something: value })

  render() {
    // note passing this
    return
        <MenuGroup handleMenuChange={this.handleMenuChange}/>
  }
}

class MenuGroup extends React.Component {

  handleClick() {
    this.props.handleMenuChange("thing")
  }

  render() {
   ...
  }
}
</code>```

This structure will allow you for easier reasoning and refactoring, moreover your child components are now reusable.

Body:
TL;DR

Is this okay?

class SideMenu extends React.Component {

  render() {
    // note passing this
    return
        <MenuGroup menu={this}/>
  }
}

class MenuGroup extends React.Component {

  handleClick() {
    this.props.menu.setState({ some: "thing" })
  }

  render() {
   ...
  }
}

Background

I am trying to build a side-menu (like the one in sb-admin) using ReactJS.  (I know I could use react-metismenu, but I am doing this to learn how to use ReactJS)

There were two approaches I can think of to do this, but the Context docs kind of warned me enough to not use it for now especially since the experimental API part.

Anyway I had a bunch of components built but no real hierarchy at the moment (since it wasn't needed if I wasn't doing context).  But I needed to pass the object that would store the current state of the menu and allow me to update it.

What I am wondering is if what I did was okay or could it be better or should be avoided.

Body:
If your components get too complicated I recommend using some state management tool like mobx or redux. It is not a good idea to pass this down to the child components violates the react one-way flow principle.

You may be looking for this:
https://facebook.github.io/react/docs/lifting-state-up.html

In brief your code should look something like this:

class SideMenu extends React.Component {
  constructor(props) {
    super(props)
    this.handleMenuChange = this.handleMenuChange.bind(this)
  }

  handleMenuChange(value) { this.setState({something: value })

  render() {
    // note passing this
    return
        <MenuGroup handleMenuChange={this.handleMenuChange}/>
  }
}

class MenuGroup extends React.Component {

  handleClick() {
    this.props.handleMenuChange("thing")
  }

  render() {
   ...
  }
}

This structure will allow you for easier reasoning and refactoring, moreover your child components are now reusable.


问:
D3 Line Chart Mouseover Coordinates Effect
I am trying to create a line chart, where users can mouse over points to reveal a circle (and also make other things happen on the page, but I'll start with making a circle appear, first).

I've tried several tutorials and all of them have the same results: The circles appear either above the line or off to the side, barely on the chart.

How does one go about getting the circles to appear at the coordinate location to which it corresponds. Here is a Fiddle of the problem and the d3 code below. Also included in the JS Fiddle are my other failed attempts.

Basic chart:

```<code>var data=[{
    "date":"January 1, 2008","total":'73'},
    {"date":"February 1, 2008","total":'40'},
    {"date":"March 1, 2008","total":'43'},
    {"date":"April 1, 2008","total":'28'},
    {"date":"May 1, 2008","total":'35'},
    {"date":"June 1, 2008","total":'20'},
    {"date":"July 1, 2008","total":'48'}
          ];

var chartWidth =650;
    var chartHeight=375;
    var chartMargins ={
            top:20,
            right: 20,
            bottom: 20,
            left: 50};

    var yScaleDomain=[1, 100];

    var chart = d3.select('#chartCanvas'),
        WIDTH=chartWidth,
        HEIGHT=chartHeight,
        MARGINS= chartMargins;

    //SET AXIS SCALES

    xScale = d3.time.scale().range([MARGINS.left, WIDTH - MARGINS.right]).domain(d3.extent(data, function(d) { return new Date(d.date); }));
   var x = d3.time.scale()
    .range([0, WIDTH]);

var y = d3.scale.linear()
    .range([HEIGHT, 0]);
    bisectDate = d3.bisector(function(d) { return d.date; }).left,
    yScale = d3.scale.linear().range([HEIGHT - MARGINS.top, MARGINS.bottom]).domain(yScaleDomain);

    //DRAW AXES

    xAxis = d3.svg.axis()
        .scale(xScale),
    yAxis = d3.svg.axis()
        .scale(yScale)
    .orient("left");

    chart.append("svg:g")
        .attr("transform", "translate(0," + (HEIGHT - MARGINS.bottom) + ")")
        .call(xAxis);
    chart.append("svg:g")
        .attr("transform", "translate(" + (MARGINS.left) + ",0)")
        .call(yAxis);

    //DRAW LINES/ PLOT DATA

   var lineGen = d3.svg.line()
        .x(function(d) {
            //Date() turns string date to numerical value
            return xScale(new Date(d.date));
        })
        .y(function(d) {
            return yScale(d.total);
        })
        //tell d3 what type of lines to draw (straight/linear ones)
        .interpolate('linear');

 chart.append("path")
      .datum(data)
      .attr("class", "line")
      .attr("d", lineGen);
</code>```

MouseOver Attempt 1 (other attempts commented out in Fiddle):

```<code>var Y_value;

    var curve1 = chart.select("path.line").data([data]);

    x = d3.time.scale().range([MARGINS.left, WIDTH - MARGINS.right]);
    y = d3.scale.linear().range([HEIGHT - MARGINS.top, MARGINS.bottom]);

    var circle = chart.append("circle")
            .attr("r", 8)
            .attr("cx", 0)
            .attr("cy", 0)
            .style({fill: '#fff', 'fill-opacity': .2, stroke: '#000', "stroke-width": '1px'})
            .attr("opacity", 0);

    var tooltip = circle.append("chart:title");

    chart.on("mouseover", function() {
        var X_pixel = d3.mouse(this)[0],
            X_date = x.invert(X_pixel);
        var Y_pixel = y(Y_value);

        var pathData = curve1.data()[0]; // recupere donnée de la courbe

        pathData.forEach(function(element, index, array) {
                if ((index+1 < array.length) && (array[index].date <= X_date) && (array[index+1].date >= X_date)) {
                    if (X_date-array[index].date < array[index+1].date-X_date)  Y_value = array[index].val;
                    else Y_value = array[index+1].val;
                }
            });

            circle.attr("opacity", 1)
                .attr("cx", X_pixel)
                .attr("cy", Math.round(y(Y_value)));

            tooltip.text("X = " + (X_date) + "\nY = " + (Y_value));
        });
     chart.append('svg:path')
            .attr('d', lineGen(data))
            .attr('stroke', 'green')
            .attr('stroke-width', 2)
            .attr('fill', 'none');

        stickyChart.append('svg:path')
            .attr('d', lineGen2(data))
            .attr('stroke', 'green')
            .attr('stroke-width', 2)
            .attr('fill', 'none');
</code>```

答:
This gentleman has a pretty good implementation of this:

https://bl.ocks.org/mbostock/3902569

In case it goes away, I've created a standalone version of it here:

var margin = {
    top: 20,
    right: 50,
    bottom: 30,
    left: 50
  },
  width = 400,
  height = 150;

var parseDate = d3.time.format("%d-%b-%y").parse,
  bisectDate = d3.bisector(function(d) {
    return d.date;
  }).left,
  formatValue = d3.format(",.2f"),
  formatCurrency = function(d) {
    return "$" + formatValue(d);
  };

var x = d3.time.scale()
  .range([0, width]);

var y = d3.scale.linear()
  .range([height, 0]);

var xAxis = d3.svg.axis()
  .scale(x)
  .orient("bottom");

var yAxis = d3.svg.axis()
  .scale(y)
  .orient("left");

var line = d3.svg.line()
  .x(function(d) {
    return x(d.date);
  })
  .y(function(d) {
    return y(d.close);
  });

var svg = d3.select("body").append("svg")
  .attr("width", width + margin.left + margin.right)
  .attr("height", height + margin.top + margin.bottom)
  .append("g")
  .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

function process(data) {

  data.sort(function(a, b) {
    return a.date - b.date;
  });

  x.domain([data[0].date, data[data.length - 1].date]);
  y.domain(d3.extent(data, function(d) {
    return d.close;
  }));

  svg.append("g")
    .attr("class", "x axis")
    .attr("transform", "translate(0," + height + ")")
    .call(xAxis);

  svg.append("g")
    .attr("class", "y axis")
    .call(yAxis)
    .append("text")
    .attr("transform", "rotate(-90)")
    .attr("y", 6)
    .attr("dy", ".71em")
    .style("text-anchor", "end")
    .text("Price ($)");

  svg.append("path")
    .datum(data)
    .attr("class", "line")
    .attr("d", line);

  var focus = svg.append("g")
    .attr("class", "focus")
    .style("display", "none");

  focus.append("circle")
    .attr("r", 4.5);

  focus.append("text")
    .attr("x", 9)
    .attr("dy", ".35em");

  svg.append("rect")
    .attr("class", "overlay")
    .attr("width", width)
    .attr("height", height)
    .on("mouseover", function() {
      focus.style("display", null);
    })
    .on("mouseout", function() {
      focus.style("display", "none");
    })
    .on("mousemove", mousemove);

  function mousemove() {
    var x0 = x.invert(d3.mouse(this)[0]),
      i = bisectDate(data, x0, 1),
      d0 = data[i - 1],
      d1 = data[i],
      d = x0 - d0.date > d1.date - x0 ? d1 : d0;
    focus.attr("transform", "translate(" + x(d.date) + "," + y(d.close) + ")");
    focus.select("text").text(formatCurrency(d.close));
  }
}

var data = [];
var close = 95;
for (var i = 0; i < 100; i++) {
  var date = new Date();
  var dateValue = date.getDate() + i;
  date.setDate(dateValue);
  close = close - 1 + 2 * Math.random();
  data[i] = {
    date: date,
    close: close
  };
}
process(data);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
  font: 10px sans-serif;
}

.axis path,
.axis line {
  fill: none;
  stroke: #000;
  shape-rendering: crispEdges;
}

.x.axis path {
  display: none;
}

.line {
  fill: none;
  stroke: steelblue;
  stroke-width: 1.5px;
}

.overlay {
  fill: none;
  pointer-events: all;
}

.focus circle {
  fill: none;
  stroke: steelblue;
}</code>```

```

Body:
I am trying to create a line chart, where users can mouse over points to reveal a circle (and also make other things happen on the page, but I'll start with making a circle appear, first).

I've tried several tutorials and all of them have the same results: The circles appear either above the line or off to the side, barely on the chart.

How does one go about getting the circles to appear at the coordinate location to which it corresponds. Here is a Fiddle of the problem and the d3 code below. Also included in the JS Fiddle are my other failed attempts.

Basic chart:

var data=[{
    "date":"January 1, 2008","total":'73'},
    {"date":"February 1, 2008","total":'40'},
    {"date":"March 1, 2008","total":'43'},
    {"date":"April 1, 2008","total":'28'},
    {"date":"May 1, 2008","total":'35'},
    {"date":"June 1, 2008","total":'20'},
    {"date":"July 1, 2008","total":'48'}
          ];

var chartWidth =650;
    var chartHeight=375;
    var chartMargins ={
            top:20,
            right: 20,
            bottom: 20,
            left: 50};

    var yScaleDomain=[1, 100];

    var chart = d3.select('#chartCanvas'),
        WIDTH=chartWidth,
        HEIGHT=chartHeight,
        MARGINS= chartMargins;

    //SET AXIS SCALES

    xScale = d3.time.scale().range([MARGINS.left, WIDTH - MARGINS.right]).domain(d3.extent(data, function(d) { return new Date(d.date); }));
   var x = d3.time.scale()
    .range([0, WIDTH]);

var y = d3.scale.linear()
    .range([HEIGHT, 0]);
    bisectDate = d3.bisector(function(d) { return d.date; }).left,
    yScale = d3.scale.linear().range([HEIGHT - MARGINS.top, MARGINS.bottom]).domain(yScaleDomain);

    //DRAW AXES

    xAxis = d3.svg.axis()
        .scale(xScale),
    yAxis = d3.svg.axis()
        .scale(yScale)
    .orient("left");

    chart.append("svg:g")
        .attr("transform", "translate(0," + (HEIGHT - MARGINS.bottom) + ")")
        .call(xAxis);
    chart.append("svg:g")
        .attr("transform", "translate(" + (MARGINS.left) + ",0)")
        .call(yAxis);

    //DRAW LINES/ PLOT DATA

   var lineGen = d3.svg.line()
        .x(function(d) {
            //Date() turns string date to numerical value
            return xScale(new Date(d.date));
        })
        .y(function(d) {
            return yScale(d.total);
        })
        //tell d3 what type of lines to draw (straight/linear ones)
        .interpolate('linear');

 chart.append("path")
      .datum(data)
      .attr("class", "line")
      .attr("d", lineGen);

MouseOver Attempt 1 (other attempts commented out in Fiddle):

var Y_value;

    var curve1 = chart.select("path.line").data([data]);

    x = d3.time.scale().range([MARGINS.left, WIDTH - MARGINS.right]);
    y = d3.scale.linear().range([HEIGHT - MARGINS.top, MARGINS.bottom]);

    var circle = chart.append("circle")
            .attr("r", 8)
            .attr("cx", 0)
            .attr("cy", 0)
            .style({fill: '#fff', 'fill-opacity': .2, stroke: '#000', "stroke-width": '1px'})
            .attr("opacity", 0);

    var tooltip = circle.append("chart:title");

    chart.on("mouseover", function() {
        var X_pixel = d3.mouse(this)[0],
            X_date = x.invert(X_pixel);
        var Y_pixel = y(Y_value);

        var pathData = curve1.data()[0]; // recupere donnée de la courbe

        pathData.forEach(function(element, index, array) {
                if ((index+1 < array.length) && (array[index].date <= X_date) && (array[index+1].date >= X_date)) {
                    if (X_date-array[index].date < array[index+1].date-X_date)  Y_value = array[index].val;
                    else Y_value = array[index+1].val;
                }
            });

            circle.attr("opacity", 1)
                .attr("cx", X_pixel)
                .attr("cy", Math.round(y(Y_value)));

            tooltip.text("X = " + (X_date) + "\nY = " + (Y_value));
        });
     chart.append('svg:path')
            .attr('d', lineGen(data))
            .attr('stroke', 'green')
            .attr('stroke-width', 2)
            .attr('fill', 'none');

        stickyChart.append('svg:path')
            .attr('d', lineGen2(data))
            .attr('stroke', 'green')
            .attr('stroke-width', 2)
            .attr('fill', 'none');

Body:
This gentleman has a pretty good implementation of this:

https://bl.ocks.org/mbostock/3902569

In case it goes away, I've created a standalone version of it here:

var margin = {
    top: 20,
    right: 50,
    bottom: 30,
    left: 50
  },
  width = 400,
  height = 150;

var parseDate = d3.time.format("%d-%b-%y").parse,
  bisectDate = d3.bisector(function(d) {
    return d.date;
  }).left,
  formatValue = d3.format(",.2f"),
  formatCurrency = function(d) {
    return "$" + formatValue(d);
  };

var x = d3.time.scale()
  .range([0, width]);

var y = d3.scale.linear()
  .range([height, 0]);

var xAxis = d3.svg.axis()
  .scale(x)
  .orient("bottom");

var yAxis = d3.svg.axis()
  .scale(y)
  .orient("left");

var line = d3.svg.line()
  .x(function(d) {
    return x(d.date);
  })
  .y(function(d) {
    return y(d.close);
  });

var svg = d3.select("body").append("svg")
  .attr("width", width + margin.left + margin.right)
  .attr("height", height + margin.top + margin.bottom)
  .append("g")
  .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

function process(data) {

  data.sort(function(a, b) {
    return a.date - b.date;
  });

  x.domain([data[0].date, data[data.length - 1].date]);
  y.domain(d3.extent(data, function(d) {
    return d.close;
  }));

  svg.append("g")
    .attr("class", "x axis")
    .attr("transform", "translate(0," + height + ")")
    .call(xAxis);

  svg.append("g")
    .attr("class", "y axis")
    .call(yAxis)
    .append("text")
    .attr("transform", "rotate(-90)")
    .attr("y", 6)
    .attr("dy", ".71em")
    .style("text-anchor", "end")
    .text("Price ($)");

  svg.append("path")
    .datum(data)
    .attr("class", "line")
    .attr("d", line);

  var focus = svg.append("g")
    .attr("class", "focus")
    .style("display", "none");

  focus.append("circle")
    .attr("r", 4.5);

  focus.append("text")
    .attr("x", 9)
    .attr("dy", ".35em");

  svg.append("rect")
    .attr("class", "overlay")
    .attr("width", width)
    .attr("height", height)
    .on("mouseover", function() {
      focus.style("display", null);
    })
    .on("mouseout", function() {
      focus.style("display", "none");
    })
    .on("mousemove", mousemove);

  function mousemove() {
    var x0 = x.invert(d3.mouse(this)[0]),
      i = bisectDate(data, x0, 1),
      d0 = data[i - 1],
      d1 = data[i],
      d = x0 - d0.date > d1.date - x0 ? d1 : d0;
    focus.attr("transform", "translate(" + x(d.date) + "," + y(d.close) + ")");
    focus.select("text").text(formatCurrency(d.close));
  }
}

var data = [];
var close = 95;
for (var i = 0; i < 100; i++) {
  var date = new Date();
  var dateValue = date.getDate() + i;
  date.setDate(dateValue);
  close = close - 1 + 2 * Math.random();
  data[i] = {
    date: date,
    close: close
  };
}
process(data);

body {
  font: 10px sans-serif;
}

.axis path,
.axis line {
  fill: none;
  stroke: #000;
  shape-rendering: crispEdges;
}

.x.axis path {
  display: none;
}

.line {
  fill: none;
  stroke: steelblue;
  stroke-width: 1.5px;
}

.overlay {
  fill: none;
  pointer-events: all;
}

.focus circle {
  fill: none;
  stroke: steelblue;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>


问:
RESTful response code for bad preexisting data?
I have a case where sometimes the data in our database is insufficient to process a request (ie, we need an account number or something that hasn't been populated).

If the user's request contained invalid syntax, it'd be a 400.
If the database were down, or a service were failing, it'd be a 500, 502, or 503.

I'm considering 422, which basically means "the request was not malformed, but the semantics of your request have led to an error". The issue here is that it's not something inherent to the request itself, but rather to the state of our pre-existing data.

答:
The behavior you detailed is a server error. Hence, 5xx response codes should be used instead of 4xx (which represent a client error). Now on to which response code in 5xx family; While there does not seem to exist any response code that defines your server behavior correctly, 500 Internal Server Error seems to be the closest one. Take a look at the rfc here: https://www.rfc-editor.org/rfc/rfc2616#section-10.5.1

It also depends on which operation you are doing with your service and which resource.


问:
How can i get data to be pushed from the database to the client, like a messenger service?
I am trying to code a messenger service that will store sent messages in a server and then push the message to all devices connected to the server.

The messenger will be used in a classroom environment and the messages will never be sent to one individual device. At the moment a message can be sent and stored in the database but the app needs to be refreshed for all the messages to be displayed. A simple way would be to continuously run the stored procedure but that would require extra bandwidth and i'm sure there is a better way to do it.

I am currently coding in Android Studio and I'm using MySQL as my database and PHP for my stored procedures. I am very new at Java and this type of coding so any help will be appreciated.

Thanks

答:
You can use google cloud messaging service to send notification in device so please register your application on google service all step are cover below link.
Open below link and follow step

http://www.androidhive.info/2012/10/android-push-notifications-using-google-cloud-messaging-gcm-php-and-mysql/


问:
Client Server Programming in java
I am just working on my assignment of client-server and found an program online of a server.java as:

```<code>import java.io.*;
import java.net.*;

public class MyServer{

    public static void main(String [] args){
        try{
        ServerSocket ssc = new ServerSocket(7500);

        Socket newSsc = ssc.accept();
        DataInputStream din = new DataInputStream(newSsc.getInputStream());
        DataOutputStream dout = new DataOutputStream(newSsc.getOutputStream());

        PrintWriter pw = new PrintWriter(dout);
        pw.println("Hello! Welcome to vinit's server.");
        boolean more_data = true;
        while(more_data){
            String line = din.readLine();
            if(line == null){
                more_data = false;
            }
            else{
                pw.println("From Server "+line + "\n");
                System.out.println("From Client "+line);
                if(line.trim().equals("QUIT"))
                    more_data = false;
            }
        }
            newSsc.close();
        }
        catch(IOException e){
            System.out.println("IO error");

        }

    }
}
</code>```

THen after I used this server by typing the command as

$ telnet 127.0.0.1 7500

Now I want to ask how my server will be getting null from client, i mean what should be entered so that server will get null

Thanks in Advance.

答: Enter Ctrl+C :)</p>

ContentLicense: CC BY-SA 2.5

Title: Client Server Programming in java

Body:
I am just working on my assignment of client-server and found an program online of a server.java as:

import java.io.*;
import java.net.*;

public class MyServer{

    public static void main(String [] args){
        try{
        ServerSocket ssc = new ServerSocket(7500);

        Socket newSsc = ssc.accept();
        DataInputStream din = new DataInputStream(newSsc.getInputStream());
        DataOutputStream dout = new DataOutputStream(newSsc.getOutputStream());

        PrintWriter pw = new PrintWriter(dout);
        pw.println("Hello! Welcome to vinit's server.");
        boolean more_data = true;
        while(more_data){
            String line = din.readLine();
            if(line == null){
                more_data = false;
            }
            else{
                pw.println("From Server "+line + "\n");
                System.out.println("From Client "+line);
                if(line.trim().equals("QUIT"))
                    more_data = false;
            }
        }
            newSsc.close();
        }
        catch(IOException e){
            System.out.println("IO error");

        }

    }
}

THen after I used this server by typing the command as

$ telnet 127.0.0.1 7500

Now I want to ask how my server will be getting null from client, i mean what should be entered so that server will get null

Thanks in Advance.

Body: Enter Ctrl+C :)


问:
How to replace and write multiple strings into a file?
I'm copying data from an original to a new file, and randomly assigning new values to the strings that I'd like to change. For some reason, the code I have will only replace one of my strings. I've tried writing four different filedata.replace lines corresponding to four f.write commands, but that won't work. I've also tried to give filedata.replace multiple arguments in one command, but that creates problems as well. </p>

```<code>import numpy as np
import random
import math
import shutil

for i in range (1,5):
    shutil.copy('template.par', 'a.par')

    a = str(random.uniform(0.00000000000000, 0.0001))                #sigma0
    b = str(random.uniform(0.00000000000000, 1))                     #sigmaslope
    c = str(random.uniform(0.05000000000000, 0.1))                   #viscosity
    d = str(random.uniform(0.00000000000000, 0.00001))                #aspectratio

    f = open('a.par','r')
    filedata = f.read()
    f.close()

    newdata = filedata.replace("6.3661977237e-4", a)
    newdata = filedata.replace("0.0", b)
    newdata = filedata.replace("0.05", c)
    newdata = filedata.replace("1e-5", d)

    f = open('a.par','w')
    f.write(newdata)
    f.close()
</code>```

答:
Bug is in the section:

```<code>newdata = filedata.replace("6.3661977237e-4", a)
newdata = filedata.replace("0.0", b)
newdata = filedata.replace("0.05", c)
newdata = filedata.replace("1e-5", d)
</code>```

Last line will always overwrite the newdata with filedata. So, all previous filedata.replace() will be of no use.

You can fix it by replacing filedata by newdata:

```<code>newdata = filedata.replace("6.3661977237e-4", a)
newdata = newdata.replace("0.0", b)
newdata = newdata.replace("0.05", c)
newdata = newdata.replace("1e-5", d)
</code>```

Let me know if this doesnt fix your issue.

Body:
I'm copying data from an original to a new file, and randomly assigning new values to the strings that I'd like to change. For some reason, the code I have will only replace one of my strings. I've tried writing four different filedata.replace lines corresponding to four f.write commands, but that won't work. I've also tried to give filedata.replace multiple arguments in one command, but that creates problems as well.

import numpy as np
import random
import math
import shutil

for i in range (1,5):
    shutil.copy('template.par', 'a.par')

    a = str(random.uniform(0.00000000000000, 0.0001))                #sigma0
    b = str(random.uniform(0.00000000000000, 1))                     #sigmaslope
    c = str(random.uniform(0.05000000000000, 0.1))                   #viscosity
    d = str(random.uniform(0.00000000000000, 0.00001))                #aspectratio

    f = open('a.par','r')
    filedata = f.read()
    f.close()

    newdata = filedata.replace("6.3661977237e-4", a)
    newdata = filedata.replace("0.0", b)
    newdata = filedata.replace("0.05", c)
    newdata = filedata.replace("1e-5", d)

    f = open('a.par','w')
    f.write(newdata)
    f.close()

Body:
Bug is in the section:

newdata = filedata.replace("6.3661977237e-4", a)
newdata = filedata.replace("0.0", b)
newdata = filedata.replace("0.05", c)
newdata = filedata.replace("1e-5", d)

Last line will always overwrite the newdata with filedata. So, all previous filedata.replace() will be of no use.

You can fix it by replacing filedata by newdata:

newdata = filedata.replace("6.3661977237e-4", a)
newdata = newdata.replace("0.0", b)
newdata = newdata.replace("0.05", c)
newdata = newdata.replace("1e-5", d)

Let me know if this doesnt fix your issue.


问:
How to make the gx command work for URLs in Vim on XFCE4 Desktop?
With GVim on my Windows 7 system, if I press gx while the cursor is on an URL, it launches the URL in Firefox (my default browser on Windows).

However, when I do the same on my XFCE4 Desktop on Debian 8.3 Linux system, pressing gx does nothing at all.

I am using GVim (Vim 7.4) on both systems.

The :let g:netrw_browsex_viewer command returns E121: Undefined variable: g:netrw_browsex_viewer on both systems.

I tried entering the :let g:netrw_browsex_viewer= "xdg-open" command on the Linux system, but it didn't help at all.

I have two questions:

Why does the gx command work for URLs on the Windows system but not on XFCE4 desktop on the Debian Linux system even though g:netrw_browsex_viewer is undefined in both?

How can I make the gx command work for URLs on XFCE4 desktop on the Debian Linux system?

答:
Normally, the following command should work, and it does work when executing Vim 7.4.576 within Xfce terminal (xfce4-terminal 0.6.3).

```<code>:let g:netrw_browsex_viewer="xdg-open"
</code>```

But the above command does not work in GVim 7.4.576 in Xfce 4.10 due to Bug 12251 - exo-open URL does nothing from gvim.

A workaround suggested by Christian Brabandt that works for me is the following.

```<code>:let g:netrw_browsex_viewer="setsid xdg-open"
</code>```

Body:
Normally, the following command should work, and it does work when executing Vim 7.4.576 within Xfce terminal (xfce4-terminal 0.6.3).

:let g:netrw_browsex_viewer="xdg-open"

But the above command does not work in GVim 7.4.576 in Xfce 4.10 due to Bug 12251 - exo-open URL does nothing from gvim.

A workaround suggested by Christian Brabandt that works for me is the following.

:let g:netrw_browsex_viewer="setsid xdg-open"


问:
Reading CSV files using C#
I'm writing a simple import application and need to read a CSV file, show result in a DataGrid and show corrupted lines of the CSV file in another grid. For example, show the lines that are shorter than 5 values in another grid. I'm trying to do that like this:

```<code>StreamReader sr = new StreamReader(FilePath);
importingData = new Account();
string line;
string[] row = new string [5];
while ((line = sr.ReadLine()) != null)
{
    row = line.Split(',');

    importingData.Add(new Transaction
    {
        Date = DateTime.Parse(row[0]),
        Reference = row[1],
        Description = row[2],
        Amount = decimal.Parse(row[3]),
        Category = (Category)Enum.Parse(typeof(Category), row[4])
    });
}
</code>```

but it's very difficult to operate on arrays in this case. Is there a better way to split the values?

答:
First of all need to understand what is CSV and how to write it.

Every next string ( /r/n ) is next "table" row.

"Table" cells is separated by some delimiter symbol. Most often used symbols is \t or ,

Every cell possibly can contain this delimiter symbol (cell must to start with quotes symbol and ends with this symbol in this case)

Every cell possibly can contains /r/n sybols  (cell must to start with quotes symbol and ends with this symbol in this case)

The easiest way for C#/Visual Basic to work with CSV files is to use standard Microsoft.VisualBasic library. You just need to add needed reference, and the following string to your class:

```<code>using Microsoft.VisualBasic.FileIO;
</code>```

Yes, you can use it in C#, don't worry. This library can read relatively big files and supports all of needed rules, so you will be able to work with all of CSV files.

Some time ago I had wrote simple class for CSV read/write based on this library. Using this simple class you will be able to work with CSV like with 2 dimensions array.
You can find my class by the following link:
https://github.com/ukushu/DataExporter

Simple example of using:

```<code>Csv csv = new Csv("\t");//delimiter symbol

csv.FileOpen("c:\\file1.csv");

var row1Cell6Value = csv.Rows[0][5];

csv.AddRow("asdf","asdffffff","5")

csv.FileSave("c:\\file2.csv");
</code>```

ContentLicense: CC BY-SA 4.0

Title: Reading CSV files using C#

Body:
I'm writing a simple import application and need to read a CSV file, show result in a DataGrid and show corrupted lines of the CSV file in another grid. For example, show the lines that are shorter than 5 values in another grid. I'm trying to do that like this:

StreamReader sr = new StreamReader(FilePath);
importingData = new Account();
string line;
string[] row = new string [5];
while ((line = sr.ReadLine()) != null)
{
    row = line.Split(',');

    importingData.Add(new Transaction
    {
        Date = DateTime.Parse(row[0]),
        Reference = row[1],
        Description = row[2],
        Amount = decimal.Parse(row[3]),
        Category = (Category)Enum.Parse(typeof(Category), row[4])
    });
}

but it's very difficult to operate on arrays in this case. Is there a better way to split the values?

Body:
First of all need to understand what is CSV and how to write it.

Every next string ( /r/n ) is next "table" row.

"Table" cells is separated by some delimiter symbol. Most often used symbols is \t or ,

Every cell possibly can contain this delimiter symbol (cell must to start with quotes symbol and ends with this symbol in this case)

Every cell possibly can contains /r/n sybols  (cell must to start with quotes symbol and ends with this symbol in this case)

The easiest way for C#/Visual Basic to work with CSV files is to use standard Microsoft.VisualBasic library. You just need to add needed reference, and the following string to your class:

using Microsoft.VisualBasic.FileIO;

Yes, you can use it in C#, don't worry. This library can read relatively big files and supports all of needed rules, so you will be able to work with all of CSV files.

Some time ago I had wrote simple class for CSV read/write based on this library. Using this simple class you will be able to work with CSV like with 2 dimensions array.
You can find my class by the following link:
https://github.com/ukushu/DataExporter

Simple example of using:

Csv csv = new Csv("\t");//delimiter symbol

csv.FileOpen("c:\\file1.csv");

var row1Cell6Value = csv.Rows[0][5];

csv.AddRow("asdf","asdffffff","5")

csv.FileSave("c:\\file2.csv");


问:
applescript click missing value
```<code>tell application "Google Chrome" to activate
delay 0.5
tell application "System Events"
    tell process "Google Chrome"
        click at {1067, 79}
        click at {1026, 220}
    end tell
end tell
</code>```

here is my applescript, I tried to open and extension by first click in chrome and then second click to download the video inside of the extension, however, only the first command was executed and the second return "missing value". I don't know why. I've also tried add a delay between the two command, it still doesn't work. Any one can help?

答:
```<code>tell application "Google Chrome" to activate
delay 0.5
tell application "System Events"
    tell process "Google Chrome"
        click at {1067, 79}
delay 1
        click at {1026, 220}
    end tell
end tell
</code>```

if this is what you mean^ then try this:

```<code>tell application "Google Chrome" to activate
delay 0.5
tell application "System Events"
    tell process "Google Chrome"
        click at {1067, 79}
    end tell
end tell
delay 0.5
tell application "Google Chrome" to activate
tell application "System Events"
    tell process "Google Chrome"
        click at {1026, 220}
    end tell
end tell
</code>```

Title: applescript click missing value

Body:
tell application "Google Chrome" to activate
delay 0.5
tell application "System Events"
    tell process "Google Chrome"
        click at {1067, 79}
        click at {1026, 220}
    end tell
end tell

here is my applescript, I tried to open and extension by first click in chrome and then second click to download the video inside of the extension, however, only the first command was executed and the second return "missing value". I don't know why. I've also tried add a delay between the two command, it still doesn't work. Any one can help?

Body:
tell application "Google Chrome" to activate
delay 0.5
tell application "System Events"
    tell process "Google Chrome"
        click at {1067, 79}
delay 1
        click at {1026, 220}
    end tell
end tell

if this is what you mean^ then try this:

tell application "Google Chrome" to activate
delay 0.5
tell application "System Events"
    tell process "Google Chrome"
        click at {1067, 79}
    end tell
end tell
delay 0.5
tell application "Google Chrome" to activate
tell application "System Events"
    tell process "Google Chrome"
        click at {1026, 220}
    end tell
end tell


问:
How to show scale labels and set min/max for yAxes?
Using v2.0beta of Chart.js

I'm having trouble displaying the xAxes and yAxes scale labels, as well as setting the yAxes min/max.

I need the yAxes ticks to range from -10 to 120 in increments of 10....this was super easy to do in v1 but I had to switch to v2.0 in order to invert the yAxes...help would be much appreciated :)

Tried setting it up in a jsfiddle but couldn't get it to work, sorry.

Here's my Line object:

```<code>var chart = new Chart(context, {
    type: 'line',
    data: data,
    options: {
        scales: {
            xAxes: [
                {
                    position: "top",
                    scaleLabel: {
                        display: true,
                        labelString: "Frequency (Hz)",
                        fontFamily: "Montserrat",
                        fontColor: "black",
                    },
                    ticks: {
                        fontFamily: "Montserrat",
                    }
                }
            ],
            yAxes: [
                {
                    position: "left",
                    scaleLabel: {
                        display: true,
                        labelString: "dB",
                        fontFamily: "Montserrat",
                        fontColor: "black",
                    },
                    ticks: {
                        fontFamily: "Montserrat",
                        reverse : true,
                        min: -10,
                        max: 120,
                    },
                }
            ],
        },
    }
});
</code>```

答:
A bit late answer but Chart.js v2.0beta doesn't seem to support those tick options well.

I updated your fiddle. I updated Chart.js v2.0beta to Chart.js v2.5, which is the latest Chart.js for now.

Your tick options should look like

```<code>ticks: {
  min: -10,
  max: 110,
  stepSize: 10,
  reverse: true,
},
</code>```

Body:
Using v2.0beta of Chart.js

I'm having trouble displaying the xAxes and yAxes scale labels, as well as setting the yAxes min/max.

I need the yAxes ticks to range from -10 to 120 in increments of 10....this was super easy to do in v1 but I had to switch to v2.0 in order to invert the yAxes...help would be much appreciated :)

Tried setting it up in a jsfiddle but couldn't get it to work, sorry.

Here's my Line object:

var chart = new Chart(context, {
    type: 'line',
    data: data,
    options: {
        scales: {
            xAxes: [
                {
                    position: "top",
                    scaleLabel: {
                        display: true,
                        labelString: "Frequency (Hz)",
                        fontFamily: "Montserrat",
                        fontColor: "black",
                    },
                    ticks: {
                        fontFamily: "Montserrat",
                    }
                }
            ],
            yAxes: [
                {
                    position: "left",
                    scaleLabel: {
                        display: true,
                        labelString: "dB",
                        fontFamily: "Montserrat",
                        fontColor: "black",
                    },
                    ticks: {
                        fontFamily: "Montserrat",
                        reverse : true,
                        min: -10,
                        max: 120,
                    },
                }
            ],
        },
    }
});

Body:
A bit late answer but Chart.js v2.0beta doesn't seem to support those tick options well.

I updated your fiddle. I updated Chart.js v2.0beta to Chart.js v2.5, which is the latest Chart.js for now.

Your tick options should look like

ticks: {
  min: -10,
  max: 110,
  stepSize: 10,
  reverse: true,
},


问:
What's the difference between JPA and Hibernate?
I understand that JPA 2 is a specification and Hibernate is a tool for ORM. Also, I understand that Hibernate has more features than JPA 2. But from a practical point of view, what really is the difference?

I have experience using iBatis and now I'm trying to learn either Hibernate or JPA2. I picked up Pro JPA2 book and it keeps referring to "JPA provider". For example:

If you think a feature should be standardized, you should speak up
  and request it from your JPA provider

This confuses me so I have a few questions:

Using JPA2 alone can I fetch data from DB by simply annotating my POJO's

Is JPA2 supposed to be used with a "JPA Provider" e.g TopLink or Hibernate? If so, then what's the benefit of using JPA2 + Hibernate as compared to JPA2 alone, or compared to Hibernate alone ?

Can you recommend a good practical JPA2 book. "Pro JPA2" seems more like a bible and reference on JPA2 (It doesn't get into Queries until the later half of the book). Is there a book that takes a problem/solution approach to JPA2?

答: JPA is just a specification while Hibernate is one of the JPA provider i.e hibernate is implementing various things mentioned in JPA contract.</p>


问:
What environment variables can be used with a Docker image?
I'm just learning Docker. If I want to use a particular image from Docker Hub, such as mysql, how do I know what environment variables can be used with that Docker image? Any way to get a list of the available variables?</p>

答:
You can simply run it and see. This is what I got when I tried to run</p>

```<code>docker run -it mysql
error: database is uninitialized and password option is not specified
  You need to specify one of MYSQL_ROOT_PASSWORD, MYSQL_ALLOW_EMPTY_PASSWORD and MYSQL_RANDOM_ROOT_PASSWORD
</code>```

Body:
You can simply run it and see. This is what I got when I tried to run

docker run -it mysql
error: database is uninitialized and password option is not specified
  You need to specify one of MYSQL_ROOT_PASSWORD, MYSQL_ALLOW_EMPTY_PASSWORD and MYSQL_RANDOM_ROOT_PASSWORD


问:
Issues in md-select using nested JSON - AngularJs 1.X.X
I having a two drop downs "Department" and "Designation". Initially I loaded the Department and based on Department selection, the Designation will auto populate. Kindly have a look into the JSON object

```<code>{
   "Status":true,
   "Message":"",
   "Result":[
      {
         "DepartmentId":1,
         "Name":"Bala",
         "Designation":[
            {
               "DesignationId":1,
               "DepartmentId":1,
               "Name":"Software Engg"
            },
            {
               "DesignationId":3,
               "DepartmentId":1,
               "Name":"Sr. Human Resouce"
            },
            {
               "DesignationId":2,
               "DepartmentId":1,
               "Name":"Sr. Software Engg"
            }
         ]
      },
      {
         "DepartmentId":2,
         "Name":"Dev",
         "Designation":[

         ]
      },
      {
         "DepartmentId":3,
         "Name":"HR Team",
         "Designation":[

         ]
      },
      {
         "DepartmentId":4,
         "Name":"Sales",
         "Designation":[
            {
               "DesignationId":4,
               "DepartmentId":4,
               "Name":"Sr. Sales Manager"
            }
         ]
      }
   ]
}
</code>```

The final Version of HTML is

<!DOCTYPE html>

<link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/angular_material/1.1.1/angular-material.min.css">

Department:

<md-select ng-model="Select.department" tabindex="9">
        <md-option ng-repeat="key in loadUpData.Department" value="{{key}}">{{key.Name}}</md-option>
    </md-select>

Designation:

<md-select ng-model="Select.department" tabindex="9">
        <md-option ng-repeat="key in Select.department.Designation" value="{{key}}">{{key.Name}}</md-option>
    </md-select>

```

The first drop-down works perfectly but I can't able to populate the second drop-down. Kindly assist me.

答:
You need to add ng-change function to get changes from first md-select, find the updated code.

Working jsfiddel

Html

```<code><div ng-controller="myCtrl">
  <p>Department:</p>
  <md-select ng-model="select.Department" tabindex="9" ng-change="onChange(select.Department)">
    <md-option ng-repeat="key in loadUpData.Department" value="{{key}}">{{key.Name}}</md-option>
  </md-select>
  <br/>
  <p>Designation:</p>
  <md-select ng-model="select.Designation" tabindex="9">
    <md-option ng-repeat="key in designationData" value="{{key}}">{{key.Name}}</md-option>
  </md-select>
</div>
</code>```

Controller

```<code>var app = angular.module('myApp', ['ngMaterial']);

app.controller('myCtrl', function($scope) {
  $scope.loadUpData = {
    Department: angular.fromJson("{" +
      "   \"Status\":true," +
      "   \"Message\":\"\"," +
      "   \"Result\":[" +
      "      {" +
      "         \"DepartmentId\":1," +
      "         \"Name\":\"Bala\"," +
      "         \"Designation\":[" +
      "            {" +
      "               \"DesignationId\":1," +
      "               \"DepartmentId\":1," +
      "               \"Name\":\"Software Engg\"" +
      "            }," +
      "            {" +
      "               \"DesignationId\":3," +
      "               \"DepartmentId\":1," +
      "               \"Name\":\"Sr. Human Resouce\"" +
      "            }," +
      "            {" +
      "               \"DesignationId\":2," +
      "               \"DepartmentId\":1," +
      "               \"Name\":\"Sr. Software Engg\"" +
      "            }" +
      "         ]" +
      "      }," +
      "      {" +
      "         \"DepartmentId\":2," +
      "         \"Name\":\"Dev\"," +
      "         \"Designation\":[" +
      "         ]" +
      "      }," +
      "      {" +
      "         \"DepartmentId\":3," +
      "         \"Name\":\"HR Team\"," +
      "         \"Designation\":[" +
      "         ]" +
      "      }," +
      "      {" +
      "         \"DepartmentId\":4," +
      "         \"Name\":\"Sales\"," +
      "         \"Designation\":[" +
      "            {" +
      "               \"DesignationId\":4," +
      "               \"DepartmentId\":4," +
      "               \"Name\":\"Sr. Sales Manager\"" +
      "            }" +
      "         ]" +
      "      }" +
      "   ]" +
      "}").Result
  };

  $scope.Select = {
    Department: {},
    Designation: {}
  };

  $scope.onChange = function(selected) {
      var Designation = JSON.parse(selected).Designation;
      console.log(Designation);
      $scope.designationData = Designation;
  };

});
</code>```

Body:
I having a two drop downs "Department" and "Designation". Initially I loaded the Department and based on Department selection, the Designation will auto populate. Kindly have a look into the JSON object

{
   "Status":true,
   "Message":"",
   "Result":[
      {
         "DepartmentId":1,
         "Name":"Bala",
         "Designation":[
            {
               "DesignationId":1,
               "DepartmentId":1,
               "Name":"Software Engg"
            },
            {
               "DesignationId":3,
               "DepartmentId":1,
               "Name":"Sr. Human Resouce"
            },
            {
               "DesignationId":2,
               "DepartmentId":1,
               "Name":"Sr. Software Engg"
            }
         ]
      },
      {
         "DepartmentId":2,
         "Name":"Dev",
         "Designation":[

         ]
      },
      {
         "DepartmentId":3,
         "Name":"HR Team",
         "Designation":[

         ]
      },
      {
         "DepartmentId":4,
         "Name":"Sales",
         "Designation":[
            {
               "DesignationId":4,
               "DepartmentId":4,
               "Name":"Sr. Sales Manager"
            }
         ]
      }
   ]
}

The final Version of HTML is

<!DOCTYPE html>

<link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/angular_material/1.1.1/angular-material.min.css">

Department:

<md-select ng-model="Select.department" tabindex="9">
        <md-option ng-repeat="key in loadUpData.Department" value="{{key}}">{{key.Name}}</md-option>
    </md-select>

Designation:

<md-select ng-model="Select.department" tabindex="9">
        <md-option ng-repeat="key in Select.department.Designation" value="{{key}}">{{key.Name}}</md-option>
    </md-select>

The first drop-down works perfectly but I can't able to populate the second drop-down. Kindly assist me.

Body:
You need to add ng-change function to get changes from first md-select, find the updated code.

Working jsfiddel

Html

<div ng-controller="myCtrl">
  <p>Department:</p>
  <md-select ng-model="select.Department" tabindex="9" ng-change="onChange(select.Department)">
    <md-option ng-repeat="key in loadUpData.Department" value="{{key}}">{{key.Name}}</md-option>
  </md-select>
  <br/>
  <p>Designation:</p>
  <md-select ng-model="select.Designation" tabindex="9">
    <md-option ng-repeat="key in designationData" value="{{key}}">{{key.Name}}</md-option>
  </md-select>
</div>

Controller

var app = angular.module('myApp', ['ngMaterial']);

app.controller('myCtrl', function($scope) {
  $scope.loadUpData = {
    Department: angular.fromJson("{" +
      "   \"Status\":true," +
      "   \"Message\":\"\"," +
      "   \"Result\":[" +
      "      {" +
      "         \"DepartmentId\":1," +
      "         \"Name\":\"Bala\"," +
      "         \"Designation\":[" +
      "            {" +
      "               \"DesignationId\":1," +
      "               \"DepartmentId\":1," +
      "               \"Name\":\"Software Engg\"" +
      "            }," +
      "            {" +
      "               \"DesignationId\":3," +
      "               \"DepartmentId\":1," +
      "               \"Name\":\"Sr. Human Resouce\"" +
      "            }," +
      "            {" +
      "               \"DesignationId\":2," +
      "               \"DepartmentId\":1," +
      "               \"Name\":\"Sr. Software Engg\"" +
      "            }" +
      "         ]" +
      "      }," +
      "      {" +
      "         \"DepartmentId\":2," +
      "         \"Name\":\"Dev\"," +
      "         \"Designation\":[" +
      "         ]" +
      "      }," +
      "      {" +
      "         \"DepartmentId\":3," +
      "         \"Name\":\"HR Team\"," +
      "         \"Designation\":[" +
      "         ]" +
      "      }," +
      "      {" +
      "         \"DepartmentId\":4," +
      "         \"Name\":\"Sales\"," +
      "         \"Designation\":[" +
      "            {" +
      "               \"DesignationId\":4," +
      "               \"DepartmentId\":4," +
      "               \"Name\":\"Sr. Sales Manager\"" +
      "            }" +
      "         ]" +
      "      }" +
      "   ]" +
      "}").Result
  };

  $scope.Select = {
    Department: {},
    Designation: {}
  };

  $scope.onChange = function(selected) {
      var Designation = JSON.parse(selected).Designation;
      console.log(Designation);
      $scope.designationData = Designation;
  };

});


问:
Finding a paragraph containing a word in MS word
I would like to find and possibly highlight all paragraphs in a .doc or docx document which contain one or more keywords.

I started with this regex (using MS Word's Find with wildcards) which simply finds all paragraphs:

([^13^l]){1}*(^13){1}

This works well in my document, i.e. it goes from paragraph to paragraph. Then I tried to replace the * with one possible search term *sust* like so:

([^13^l]){1}*sust*(^13){1}

This however highlights lots of paragraphs up to the end of a paragraph which includes *sust*. I find this very strange because the first attempt simply parsed the document paragraph by paragraph even in the parts that are returned by my second attempt.

I also tried
([^13^l]){1}(*sust*)(^13){1} as well as ([^13^l]){1} (*sust*) (^13){1} which all highlight lots of paragraphs rather than only one.

What am I doing wrong here?

答:
You need 5 "regex" searches to find all possible occurrences in normal paragraphes.

This catches every paragraph with keyword inside it:

```<code>[^11-^13]{1}([!^11-^13]@sust[!^11-^13]@[^11-^13]{1})
</code>```

...with keyword being first word in the paragraph:

```<code>[^11-^13]{1}(sust[!^11-^13]@[^11-^13]{1})
</code>```

...with keyword being last word in the paragraph:

```<code>[^11-^13]{1}([!^11-^13]@sust[^11-^13]{1})
</code>```

...with keyword in first paragraph in the document (it will catch more):

```<code>([!^11-^13]@sust[!^11-^13]@[^11-^13]{1})
</code>```

...with keyword being first word in the document  (or just check by yourself, it also catches more):

```<code>(sust[!^11-^13]@[^11-^13]{1})
</code>```

According to documentation, for cases 1-3 might work:

```<code>[^11-^13]{1}([!^11-^13]{0,}sust[!^11-^13]{0,}[^11-^13]{1})
</code>```

but (for Word 2010) it doesn't.

Body:
You need 5 "regex" searches to find all possible occurrences in normal paragraphes.

This catches every paragraph with keyword inside it:

[^11-^13]{1}([!^11-^13]@sust[!^11-^13]@[^11-^13]{1})

...with keyword being first word in the paragraph:

[^11-^13]{1}(sust[!^11-^13]@[^11-^13]{1})

...with keyword being last word in the paragraph:

[^11-^13]{1}([!^11-^13]@sust[^11-^13]{1})

...with keyword in first paragraph in the document (it will catch more):

([!^11-^13]@sust[!^11-^13]@[^11-^13]{1})

...with keyword being first word in the document  (or just check by yourself, it also catches more):

(sust[!^11-^13]@[^11-^13]{1})

According to documentation, for cases 1-3 might work:

[^11-^13]{1}([!^11-^13]{0,}sust[!^11-^13]{0,}[^11-^13]{1})

but (for Word 2010) it doesn't.


问:
Converting function signature from compiler language to c++
Hey guys, I need to make a list of some functions that are listed in the linker output. The syntax i get is as follows:

```<code>int foo(int num,double dnum, Temp & temp) (in namespace "funcsns")
</code>```

Turns into:

```<code>.text._ZN7funcsns3fooEidRNS_4TempE
</code>```

(You might know it from the "undefined symbol" and some other linking errors that print functions names)

Now, i can write a script that somehow turns it into something readable but i wonder if there is a smart way of doing it.

Please share your ideas!

thanks.

答:
As indicated by other, c++filt is the way to go for the GNU toolchain.

This can also be done programmaticaly (even from a C program) : see abi::__cxa_demangle (which is actually what c++filt does).

Body:
Hey guys, I need to make a list of some functions that are listed in the linker output. The syntax i get is as follows:

int foo(int num,double dnum, Temp & temp) (in namespace "funcsns")

Turns into:

.text._ZN7funcsns3fooEidRNS_4TempE

(You might know it from the "undefined symbol" and some other linking errors that print functions names)

Now, i can write a script that somehow turns it into something readable but i wonder if there is a smart way of doing it.

Please share your ideas!

thanks.


问:
why does python change the original parameter
I want to send a http request,but have a problem with the params,The following is my code:

```<code>my_url="mysite.com/api"
payload = {'start':"2017-04-01%2000:00:00",'end':"017-04-01%2023:59:59"}
r=requests.get(my_url,params=payload)
print r.request.url
</code>```

The url sent is "mysite.com/api?start=2017-04-01%252000%3A00%3A00&end=2017-04-01%252023%3A59%3A59', the params is changed. Could anyone help me?

答:
Python is URL encoding the information for you.  Certain characters aren't allowed during HTTP transmission (because they serve specific functions in the protocol).  If you want to use illegal characters like : and (space) then you can URL encode them to %3A and %20.  URL encoding is standardized, so you can send your information (post encoding) then a server will receive it and decode it, resulting in them receiving your original message.

Here's a more in depth analysis of it:
https://www.thoughtco.com/encoding-urls-3467463

Body:
I want to send a http request,but have a problem with the params,The following is my code:

my_url="mysite.com/api"
payload = {'start':"2017-04-01%2000:00:00",'end':"017-04-01%2023:59:59"}
r=requests.get(my_url,params=payload)
print r.request.url

The url sent is "mysite.com/api?start=2017-04-01%252000%3A00%3A00&end=2017-04-01%252023%3A59%3A59', the params is changed. Could anyone help me?


问:
Parsing CSV files in C#, with header
Is there a default/official/recommended way to parse CSV files in C#? I don't want to roll my own parser.

Also, I've seen instances of people using ODBC/OLE DB to read CSV via the Text driver, and a lot of people discourage this due to its "drawbacks." What are these drawbacks?

Ideally, I'm looking for a way through which I can read the CSV by column name, using the first record as the header / field names. Some of the answers given are correct but work to basically deserialize the file into classes.

答:
Some time ago I had wrote simple class for CSV read/write based on Microsoft.VisualBasic library. Using this simple class you will be able to work with CSV like with 2 dimensions array. You can find my class by the following link: https://github.com/ukushu/DataExporter

Simple example of usage:

```<code>Csv csv = new Csv("\t");//delimiter symbol

csv.FileOpen("c:\\file1.csv");

var row1Cell6Value = csv.Rows[0][5];

csv.AddRow("asdf","asdffffff","5")

csv.FileSave("c:\\file2.csv");
</code>```

For reading header only you need is to read csv.Rows[0] cells :)

Title: Parsing CSV files in C#, with header

Body:
Some time ago I had wrote simple class for CSV read/write based on Microsoft.VisualBasic library. Using this simple class you will be able to work with CSV like with 2 dimensions array. You can find my class by the following link: https://github.com/ukushu/DataExporter

Simple example of usage:

Csv csv = new Csv("\t");//delimiter symbol

csv.FileOpen("c:\\file1.csv");

var row1Cell6Value = csv.Rows[0][5];

csv.AddRow("asdf","asdffffff","5")

csv.FileSave("c:\\file2.csv");

For reading header only you need is to read csv.Rows[0] cells :)


问:
read lines in txt file [java]
I'll try to be as clear as possible but pardon me if my question is not perfect.
I have a txt file with several lines of data. example:

123 ralph bose 20000 200 1 2

256 ed shane 30000 100 2 4

...

I need to read each line sequentially and pass it back to a method in a separate class for processing. I know how to break down each line into elements by using StringTokenizer.

However, i'm not sure how to read one line at a time, pass back the elements to the other class and then, once the processing is done, to read the NEXT line. Method cooperation between my classes works fine (tested) but how do i read one line at a time?

I was thinking of creating an array where each line would be an array element but as the number of lines will be unknown i cannot create an array as i don't know its final length.

Thanks

Baba

EDIT

rough setup :

Class A

```<code>end_of_file = f1.readRecord(emp);

        if(!end_of_file)
        {
           slip.printPay(slipWrite);
        }
</code>```

Class B

```<code>public boolean readRecord(Employee pers) throws IOException {

        boolean eof = false ;

        String line = in.readLine() ;

                ???

                }
</code>```

filename is never passed around

so up until here i can read the first line but i think i need a way to loop through the lines to read them one by one with back and forth between classes.

tricky...

答:
There are lots of ways to read an entire line at a time; Scanner is probably easiest:

```<code>final Scanner s = new Scanner(yourFile);
while(s.hasNextLine()) {
    final String line = s.nextLine();
    YourClass.processLine(line);
}
</code>```

Title: read lines in txt file [java]

Body:
I'll try to be as clear as possible but pardon me if my question is not perfect.
I have a txt file with several lines of data. example:

123 ralph bose 20000 200 1 2

256 ed shane 30000 100 2 4

...

I need to read each line sequentially and pass it back to a method in a separate class for processing. I know how to break down each line into elements by using StringTokenizer.

However, i'm not sure how to read one line at a time, pass back the elements to the other class and then, once the processing is done, to read the NEXT line. Method cooperation between my classes works fine (tested) but how do i read one line at a time?

I was thinking of creating an array where each line would be an array element but as the number of lines will be unknown i cannot create an array as i don't know its final length.

Thanks

Baba

EDIT

rough setup :

Class A

end_of_file = f1.readRecord(emp);

        if(!end_of_file)
        {
           slip.printPay(slipWrite);
        }

Class B

public boolean readRecord(Employee pers) throws IOException {

        boolean eof = false ;

        String line = in.readLine() ;

                ???

                }

filename is never passed around

so up until here i can read the first line but i think i need a way to loop through the lines to read them one by one with back and forth between classes.

tricky...

Body:
There are lots of ways to read an entire line at a time; Scanner is probably easiest:

final Scanner s = new Scanner(yourFile);
while(s.hasNextLine()) {
    final String line = s.nextLine();
    YourClass.processLine(line);
}


问:
Swift 3 unwind segue from view controller C to A also executes code of view controller B
ViewController A has the function:

@IBAction fund backToViewControllerA (segue: UIStoryboardSegue) {}

ViewController C: via storyboard a unwind segue was created (view controller to exit, with an identifier and action)

When going from A to B to C and then pressing the button in C to start the unwind, the ViewController C unwinds to A. So far so good...

Problem: in the meantime, during the unwind, also the viewDidAppear() of B is executed.

Question: how do I prevent the code of ViewController B to be executed?

答:
FYI. I test a example.
If A is in UINavigationController. A > B > C > A will good.
But if A is just a UIViewController. The code of B.viewDidAppear will be executed.</p>


问:
How to stop scrapy spider after certain number of requests?
I am developing an simple scraper to get 9 gag posts and its images but due to some technical difficulties iam unable to stop the scraper and it keeps on scraping which i dont want.I want to increase the counter value and stop after 100 posts.
But the 9gag page was designed in a fashion in each response it gives only 10 posts and after each iteration my counter value resets to 10 in this case my loop runs infintely long and never stops.

```<code># -*- coding: utf-8 -*-
import scrapy
from _9gag.items import GagItem

class FirstSpider(scrapy.Spider):
    name = "first"
    allowed_domains = ["9gag.com"]
    start_urls = (
        'http://www.9gag.com/',
    )

    last_gag_id = None
    def parse(self, response):
        count = 0
        for article in response.xpath('//article'):
            gag_id = article.xpath('@data-entry-id').extract()
            count +=1
            if gag_id:
                if (count != 100):
                    last_gag_id = gag_id[0]
                    ninegag_item = GagItem()
                    ninegag_item['entry_id'] = gag_id[0]
                    ninegag_item['url'] = article.xpath('@data-entry-url').extract()[0]
                    ninegag_item['votes'] = article.xpath('@data-entry-votes').extract()[0]
                    ninegag_item['comments'] = article.xpath('@data-entry-comments').extract()[0]
                    ninegag_item['title'] = article.xpath('.//h2/a/text()').extract()[0].strip()
                    ninegag_item['img_url'] = article.xpath('.//div[1]/a/img/@src').extract()

                    yield ninegag_item

                else:
                    break

        next_url = 'http://9gag.com/?id=%s&c=200' % last_gag_id
        yield scrapy.Request(url=next_url, callback=self.parse)
        print count
</code>```

Code for items.py is here

```<code>from scrapy.item import Item, Field

class GagItem(Item):
    entry_id = Field()
    url = Field()
    votes = Field()
    comments = Field()
    title = Field()
    img_url = Field()
</code>```

So i want to increase a global count value and tried this by passing 3 arguments to parse function it gives error

```<code>TypeError: parse() takes exactly 3 arguments (2 given)
</code>```

So is there a way to pass a global count value and return it after each iteration and stop after 100 posts(suppose).

Entire project is available here Github
Even if i set POST_LIMIT =100 the infinite loop happens,see here command i executed

```<code>scrapy crawl first -s POST_LIMIT=10 --output=output.json
</code>```

答:
There's a built-in setting CLOSESPIDER_PAGECOUNT that can be passed via command-line -s argument or changed in settings: scrapy crawl <spider> -s CLOSESPIDER_PAGECOUNT=100

One small caveat is that if you've enabled caching, it will count cache hits as page counts as well.

Body:
I am developing an simple scraper to get 9 gag posts and its images but due to some technical difficulties iam unable to stop the scraper and it keeps on scraping which i dont want.I want to increase the counter value and stop after 100 posts.
But the 9gag page was designed in a fashion in each response it gives only 10 posts and after each iteration my counter value resets to 10 in this case my loop runs infintely long and never stops.

# -*- coding: utf-8 -*-
import scrapy
from _9gag.items import GagItem

class FirstSpider(scrapy.Spider):
    name = "first"
    allowed_domains = ["9gag.com"]
    start_urls = (
        'http://www.9gag.com/',
    )

    last_gag_id = None
    def parse(self, response):
        count = 0
        for article in response.xpath('//article'):
            gag_id = article.xpath('@data-entry-id').extract()
            count +=1
            if gag_id:
                if (count != 100):
                    last_gag_id = gag_id[0]
                    ninegag_item = GagItem()
                    ninegag_item['entry_id'] = gag_id[0]
                    ninegag_item['url'] = article.xpath('@data-entry-url').extract()[0]
                    ninegag_item['votes'] = article.xpath('@data-entry-votes').extract()[0]
                    ninegag_item['comments'] = article.xpath('@data-entry-comments').extract()[0]
                    ninegag_item['title'] = article.xpath('.//h2/a/text()').extract()[0].strip()
                    ninegag_item['img_url'] = article.xpath('.//div[1]/a/img/@src').extract()

                    yield ninegag_item

                else:
                    break

        next_url = 'http://9gag.com/?id=%s&c=200' % last_gag_id
        yield scrapy.Request(url=next_url, callback=self.parse)
        print count

Code for items.py is here

from scrapy.item import Item, Field

class GagItem(Item):
    entry_id = Field()
    url = Field()
    votes = Field()
    comments = Field()
    title = Field()
    img_url = Field()

So i want to increase a global count value and tried this by passing 3 arguments to parse function it gives error

TypeError: parse() takes exactly 3 arguments (2 given)

So is there a way to pass a global count value and return it after each iteration and stop after 100 posts(suppose).

Entire project is available here Github
Even if i set POST_LIMIT =100 the infinite loop happens,see here command i executed

scrapy crawl first -s POST_LIMIT=10 --output=output.json