问:
on check save data in database and remove on uncheck
I am trying do is save/delete data in (mysql) database on checkbox check/uncheck respectively. i have dynamically generated checkboxes from that i want to save data of particular checkbox in database. simultaneously if uncheck that particular checkbox data will erase from database.
can anybody tell me is this possible using jquery or any other scripting language in php.
thanks in advance.

i am adding some code what i tried
this my "table_edit_ajax.php" code

```<code><?php
$mysql_hostname = "localhost";
$mysql_user = "root";
$mysql_password = "";
$mysql_database = "test";
$bd = mysql_connect($mysql_hostname, $mysql_user, $mysql_password)
or die("Opps some thing went wrong");
mysql_select_db($mysql_database, $bd) or die("Opps some thing went wrong");

if($_POST[first_input_.$i])
{
$firstname=mysql_escape_String($_POST[first_input_.$i]);
$sql = "INSERT INTO fullnames(firstname)VALUES('$firstname')";
mysql_query($sql);
}
?>
</code>```

this is my main file in which i am generating checkboxes called "test.php"

```<code><?php
$mysql_hostname = "localhost";
$mysql_user = "root";
$mysql_password = "";
$mysql_database = "test";
$bd = mysql_connect($mysql_hostname, $mysql_user, $mysql_password)
or die("Opps some thing went wrong");
mysql_select_db($mysql_database, $bd) or die("Opps some thing went wrong");
?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script>
<script type="text/javascript">
$('.edit_tr').on('change', function(){
    // saving or deleting?
    var savedelete;
    if ($(this).is(':checked')) savedelete='save';
    alert ("save test");
    else savedelete='delete';
    alert ("delete test");
    // what am I changing?
    var name=$(this).attr('first_input_<?php echo $i; ?>');

    // call the server
    $.ajax({
      type: "POST",
      url: 'table_edit_ajax.php'
      data: {"do": "saveordelete", "whichone": savedelete,  "name": name   },
      success: function(data){
        if (data=='true'){ // is string not boolean
            // it worked
            alert ("true");
        }else{
            // didn't work
            alert ("false");
        }
      }
    });

});
</script>
<style>
body
{
font-family:Arial, Helvetica, sans-serif;
font-size:14px;
}

td
{
padding:7px;
}
.editbox
{
font-size:14px;
width:270px;
/*background-color:#ffffcc;*/

border:solid 1px #000;
padding:4px;
}

th
{
font-weight:bold;
text-align:left;
padding:4px;
}
.head
{
background-color:#333;
color:#FFFFFF

}

</style>
</head>

<body bgcolor="#dedede">
<div style="margin:0 auto; width:750px; padding:10px; background-color:#fff; height:800px;">

<table width="100%">
<tr class="head">
<th>First Name</th>
</tr>
<?php
$i=1;
while($i<=5)
{
if($i%2)
{
?>
<tr id="lovetr<?php echo $i; ?>" class="edit_tr">
<?php } else { ?>
<tr id="trlove<?php echo $i; ?>" bgcolor="#f2f2f2" class="edit_tr">
<?php } ?>
<td width="50%" class="edit_td">
<input type="checkbox" value="firstname<?php echo $i; ?>" class="editbox" name="first_input_<?php echo $i; ?>" />
</td>
</tr>

<?php
$i++;
}
?>

</table>
</div>
</body>
</html>
</code>```

答:
```<code> <?php
 include('../dbcon.php');
 $id = $_POST['id'];
 mysql_query("delete from files where file_id = '$id' ")or die(mysql_error());
 ?>
</code>```

you cak make id selector using checbox and add to $_POST['selector'];

```<code>   <?php
        include('../dbcon.php');
        if (isset($_POST['backup_delete'])){
        $id=$_POST['selector'];
        $N = count($id);
        for($i=0; $i < $N; $i++)
        {
            $result = mysql_query("DELETE FROM teacher_backpack where file_id='$id[$i]'");
        }
        header("location: backack.php");
        }
        ?>
</code>```

Body:
I am trying do is save/delete data in (mysql) database on checkbox check/uncheck respectively. i have dynamically generated checkboxes from that i want to save data of particular checkbox in database. simultaneously if uncheck that particular checkbox data will erase from database.
can anybody tell me is this possible using jquery or any other scripting language in php.
thanks in advance.

i am adding some code what i tried
this my "table_edit_ajax.php" code

<?php
$mysql_hostname = "localhost";
$mysql_user = "root";
$mysql_password = "";
$mysql_database = "test";
$bd = mysql_connect($mysql_hostname, $mysql_user, $mysql_password)
or die("Opps some thing went wrong");
mysql_select_db($mysql_database, $bd) or die("Opps some thing went wrong");

if($_POST[first_input_.$i])
{
$firstname=mysql_escape_String($_POST[first_input_.$i]);
$sql = "INSERT INTO fullnames(firstname)VALUES('$firstname')";
mysql_query($sql);
}
?>

this is my main file in which i am generating checkboxes called "test.php"

<?php
$mysql_hostname = "localhost";
$mysql_user = "root";
$mysql_password = "";
$mysql_database = "test";
$bd = mysql_connect($mysql_hostname, $mysql_user, $mysql_password)
or die("Opps some thing went wrong");
mysql_select_db($mysql_database, $bd) or die("Opps some thing went wrong");
?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>

First Name

<?php
$i=1;
while($i<=5)
{
if($i%2)
{
?>
<tr id="lovetr<?php echo $i; ?>" class="edit_tr">
<?php } else { ?>
<tr id="trlove<?php echo $i; ?>" bgcolor="#f2f2f2" class="edit_tr">
<?php } ?>

<input type="checkbox" value="firstname<?php echo $i; ?>" class="editbox" name="first_input_<?php echo $i; ?>" />

<?php
$i++;
}
?>

Body:
 <?php
 include('../dbcon.php');
 $id = $_POST['id'];
 mysql_query("delete from files where file_id = '$id' ")or die(mysql_error());
 ?>

you cak make id selector using checbox and add to $_POST['selector'];

   <?php
        include('../dbcon.php');
        if (isset($_POST['backup_delete'])){
        $id=$_POST['selector'];
        $N = count($id);
        for($i=0; $i < $N; $i++)
        {
            $result = mysql_query("DELETE FROM teacher_backpack where file_id='$id[$i]'");
        }
        header("location: backack.php");
        }
        ?>


来源: stackexchange

问:
How do I pass commands serially without using pipe through telnet
I am doing automation by sending commands through telnet serial port in command line.
My question is, I have two telnet ports where I send commands in parallel to each one and copy the result to a text file.

But here is the thing! The commands I pass are in only one session, It's like I am passing the arguments one after another.

For example, I do each step in parallel and then do cat c1 and cat c2:

```<code>In telnet 1                        telnet 2

#touch c1                          #touch c2
>cat c1                            >cat c2
</code>```

Now after I run cat c1 I  get some result in telnet 1 and when I run cat c2, then I get some more result added in c1 and not in c2. I have to copy the cat c1 result to a text file and then run last commands in parallel:

```<code>>the                                >the
</code>```

As you can see after I run touch c1, I don't get # but> which continues.

Can you tell me how to proceed in parallel?

I used a pipe but it didn't work as I don't get result from cat c1 after cat c2 is executed, but I get only cat c1 result.

I may not have explained very clearly, but tried. if anyone can help me out that would be great.

答:
May be you are looking for asynchronous processing of commands. Asynchronous commands execute in parallel.

The command should be terminated with '&', then the shell executes the command in background....

ex:

```<code>touch c1 & touch c2
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am doing automation by sending commands through telnet serial port in command line.
My question is, I have two telnet ports where I send commands in parallel to each one and copy the result to a text file.

But here is the thing! The commands I pass are in only one session, It's like I am passing the arguments one after another.

For example, I do each step in parallel and then do cat c1 and cat c2:

In telnet 1                        telnet 2

#touch c1                          #touch c2
>cat c1                            >cat c2

Now after I run cat c1 I  get some result in telnet 1 and when I run cat c2, then I get some more result added in c1 and not in c2. I have to copy the cat c1 result to a text file and then run last commands in parallel:

>the                                >the

As you can see after I run touch c1, I don't get # but> which continues.

Can you tell me how to proceed in parallel?

I used a pipe but it didn't work as I don't get result from cat c1 after cat c2 is executed, but I get only cat c1 result.

I may not have explained very clearly, but tried. if anyone can help me out that would be great.

Body:
May be you are looking for asynchronous processing of commands. Asynchronous commands execute in parallel.

The command should be terminated with '&', then the shell executes the command in background....

ex:

touch c1 & touch c2


问:
access 3D Mat cell position uting pointer
I am trying to access a 3D Mat object, but I don't know how to do it.

In the 2D case i can access any matrix position in a double for cycle over "i" and "j" simply with the following command:

```<code>float a = M.ptr<float>(i)[j];
</code>```

Do you know how I can do it in the case I have a 3D matrix? I have tried with

```<code>float a = M.ptr<float>(i)(j)[k];
</code>```

and

```<code>float a = M.ptr<float>(i)[j][k];
</code>```

but they are not working. I don't want to use .at(i,j,k) because it is very slow.

答:
I have solved it this way: </p>

```<code>float a = M.ptr<float>(i)[j,k];
</code>```

Body:
I am trying to access a 3D Mat object, but I don't know how to do it.

In the 2D case i can access any matrix position in a double for cycle over "i" and "j" simply with the following command:

float a = M.ptr<float>(i)[j];

Do you know how I can do it in the case I have a 3D matrix? I have tried with

float a = M.ptr<float>(i)(j)[k];

and

float a = M.ptr<float>(i)[j][k];

but they are not working. I don't want to use .at(i,j,k) because it is very slow.

Body:
I have solved it this way:

float a = M.ptr<float>(i)[j,k];


问:
Increment forEachFeatureAtPixel OpenLayers 3
I draw some markers in my Map. Those markers, have a User Icon (It is a image in png) I would like, that, when I use forEachFeatureAtPixel, I can click in all area of this user Icon.

So, my question is, How can I increment the area to "forEachFeatureAtPixel"?

It is my function:

```<code>// display popup on click
map.on('click', function(evt) {
 var feature = map.forEachFeatureAtPixel(evt.pixel,
  function(feature, layer) {
    return feature;
  });
 if (feature) {

  //..................
 }
 });
</code>```

答:
Not sure if I'm understanding your question correctly but...

You shouldn't have to increment anything in your code..

Try this:

```<code>// display popup on click
map.on('click', function(evt) {
  var features = [];
  map.forEachFeatureAtPixel(evt.pixel, function(feature, layer) {
    features.push(feature);
  });
  for (var i = 0; i < features.length; i++) {
    console.dir(features[i]); //Displays object in browser console log
  }
});
</code>```

Body:
I draw some markers in my Map. Those markers, have a User Icon (It is a image in png) I would like, that, when I use forEachFeatureAtPixel, I can click in all area of this user Icon.

So, my question is, How can I increment the area to "forEachFeatureAtPixel"?

It is my function:

// display popup on click
map.on('click', function(evt) {
 var feature = map.forEachFeatureAtPixel(evt.pixel,
  function(feature, layer) {
    return feature;
  });
 if (feature) {

  //..................
 }
 });

Body:
Not sure if I'm understanding your question correctly but...

You shouldn't have to increment anything in your code..

Try this:

// display popup on click
map.on('click', function(evt) {
  var features = [];
  map.forEachFeatureAtPixel(evt.pixel, function(feature, layer) {
    features.push(feature);
  });
  for (var i = 0; i < features.length; i++) {
    console.dir(features[i]); //Displays object in browser console log
  }
});


问:
MySQL InnoDB - create CASCADE foreign key constraint when data already exists that violates it?
I have a database that was originally in MyISAM and so had no foreign key constraints. As a result, there are quite a few orphaned rows where the record the foreign key refers to has since been deleted.

To fix this I decided to convert to InnoDB and add the foreign keys, with CASCADE for both updating and deleting. However, when I try to add the foreign key, I get errors like this (from Navicat 8 console):

```<code>1452 - Cannot add or update a child row: a foreign key constraint fails
(`database`.`#sql-1358_38d`, CONSTRAINT `#sql-1358_38d_ibfk_1` FOREIGN KEY
(`manufacturerID`) REFERENCES `manufacturer` (`ID`) ON DE)
</code>```

I know why it's doing this - because of the orphaned rows. Is there a way though to have the creation of the constrain automatically clear out those rows? It will take ages to go through all of the tables and find orphaned rows.

This is one of the queries I'm running just in case it is suspect:

```<code>ALTER TABLE part_number ADD CONSTRAINT
FOREIGN KEY(manufacturerID)
REFERENCES manufacturer(ID)
ON DELETE CASCADE
ON UPDATE CASCADE;
</code>```

答:
You need to get rid of all irrelevant records before you can add a constraint.

You can do it two ways.

1 Using not exists()

```<code>DELETE FROM part_number
 WHERE NOT EXISTS (
           select id from manufacturer
            where part_number.manufacturerID = manufacturer.ID
       )
</code>```

2. Using a temporary table (a bit ugly, but i'll post it too)

```<code>-- create a temporary table
CREATE TEMPORARY TABLE `temp_ids`
(
  `id` INTEGER
);

-- store all id's that need to be deleted
INSERT INTO `temp_ids`
SELECT part_number.id FROM part_number LEFT JOIN manufacturer ON (manufacturer.ID = part_number.manufacturerID)
WHERE ISNULL(`manufacturer.ID);

-- delete them
DELETE
FROM part_number
WHERE id IN (
  SELECT `id` FROM `temp_ids`
);

-- drop the table
DROP TEMPORARY TABLE `temp_ids`;
</code>```

See my related question: Handling database integrity

After all "dead" records are deleted, you will be able to add a constraint.

Hope this works for you :)

ContentLicense: CC BY-SA 2.5

Body:
I have a database that was originally in MyISAM and so had no foreign key constraints. As a result, there are quite a few orphaned rows where the record the foreign key refers to has since been deleted.

To fix this I decided to convert to InnoDB and add the foreign keys, with CASCADE for both updating and deleting. However, when I try to add the foreign key, I get errors like this (from Navicat 8 console):

1452 - Cannot add or update a child row: a foreign key constraint fails
(`database`.`#sql-1358_38d`, CONSTRAINT `#sql-1358_38d_ibfk_1` FOREIGN KEY
(`manufacturerID`) REFERENCES `manufacturer` (`ID`) ON DE)

I know why it's doing this - because of the orphaned rows. Is there a way though to have the creation of the constrain automatically clear out those rows? It will take ages to go through all of the tables and find orphaned rows.

This is one of the queries I'm running just in case it is suspect:

ALTER TABLE part_number ADD CONSTRAINT
FOREIGN KEY(manufacturerID)
REFERENCES manufacturer(ID)
ON DELETE CASCADE
ON UPDATE CASCADE;

Body:
You need to get rid of all irrelevant records before you can add a constraint.

You can do it two ways.

1 Using not exists()

DELETE FROM part_number
 WHERE NOT EXISTS (
           select id from manufacturer
            where part_number.manufacturerID = manufacturer.ID
       )

2. Using a temporary table (a bit ugly, but i'll post it too)

-- create a temporary table
CREATE TEMPORARY TABLE `temp_ids`
(
  `id` INTEGER
);

-- store all id's that need to be deleted
INSERT INTO `temp_ids`
SELECT part_number.id FROM part_number LEFT JOIN manufacturer ON (manufacturer.ID = part_number.manufacturerID)
WHERE ISNULL(`manufacturer.ID);

-- delete them
DELETE
FROM part_number
WHERE id IN (
  SELECT `id` FROM `temp_ids`
);

-- drop the table
DROP TEMPORARY TABLE `temp_ids`;

See my related question: Handling database integrity

After all "dead" records are deleted, you will be able to add a constraint.

Hope this works for you :)


问:
16 bit word lc-3 BR and JMP instruction
I have a issue that I cannot seem to figure out, when it comes to 16 bit words. Below i have attached the corresponding code and the the imagine that gives a bit of a description of what I am asking help for.

```<code> .orig x3000
 ld r1,n
 lea r5,data
 add r1,r1,#-1
loop:
 str r1,r5,0
 add r5,r5,r2
 add r1,r1,#-1
 brp loop
 trap x25
data: .blkw 2
n: .fill 10
 .end
</code>```

Here is the image

I get the nzp codes but im not sure how to calculate the pcoffset9 so it would be greatly appreciated if someone could help with this example.

答:
The formula to calculate the PCOffset is as follows

ADDRESS_OF_SYMBOL - (INSTRUCTION_ADDRESS + 1)

```<code>.orig x3000
  LEA R0, HELLO_WORLD                ; x3000
  PUTS                               ; x3001
  HALT                               ; x3002
  HELLO_WORLD .stringz "HELLO WORLD" ; x3003
.end
</code>```

so the PCOffset in the LEA instruction is as follows

ADDRESS_HELLO_WORLD - (ADDRESS_LEA + 1)

x3003 - (x3000 + 1) = 2

When the LEA instruction executes remember that the PC is already incremented as part of Fetch so PC will be at x3001.  We add the 2 to it to get x3003 the address of where the label HELLO_WORLD is.

Title: 16 bit word lc-3 BR and JMP instruction

Body:
I have a issue that I cannot seem to figure out, when it comes to 16 bit words. Below i have attached the corresponding code and the the imagine that gives a bit of a description of what I am asking help for.

 .orig x3000
 ld r1,n
 lea r5,data
 add r1,r1,#-1
loop:
 str r1,r5,0
 add r5,r5,r2
 add r1,r1,#-1
 brp loop
 trap x25
data: .blkw 2
n: .fill 10
 .end

Here is the image

I get the nzp codes but im not sure how to calculate the pcoffset9 so it would be greatly appreciated if someone could help with this example.

Body:
The formula to calculate the PCOffset is as follows

ADDRESS_OF_SYMBOL - (INSTRUCTION_ADDRESS + 1)

.orig x3000
  LEA R0, HELLO_WORLD                ; x3000
  PUTS                               ; x3001
  HALT                               ; x3002
  HELLO_WORLD .stringz "HELLO WORLD" ; x3003
.end

so the PCOffset in the LEA instruction is as follows

ADDRESS_HELLO_WORLD - (ADDRESS_LEA + 1)

x3003 - (x3000 + 1) = 2

When the LEA instruction executes remember that the PC is already incremented as part of Fetch so PC will be at x3001.  We add the 2 to it to get x3003 the address of where the label HELLO_WORLD is.


问:
Access object from outer select clause in LINQ statement
Suppose I have the following LINQ Statement. I would like to find a way to use "r.Portfolio" while I am in the 3rd select clause (see comment in the code):

```<code>positionsToOptimize
    .Select(p => p)
    .SelectMany(r => r.Positions)
    .Select(pos => new OptimizedPosition() {
        CalculationType = TCalculationType.Absolute,
        Position = pos.NetPositionAmount,
        SecurityID = pos.SecurityID,
        Portfolio = r.Portfolio        // <- How do I do this? (Portfolio is not in 'pos')
    });
</code>```

Essentially I am trying to replace the following foreach nested loop:

```<code>var lst = new List<OptimizedPosition>();
foreach (var r in positionsToOptimize) {
    foreach (var pos in r.Positions) {
        lst.Add(new OptimizedPosition() {
            CalculationType = TCalculationType.Absolute,
            Position = pos.NetPositionAmount,
            SecurityID = pos.SecurityID,
            SystemCode = r.SystemCode
        });
    }
}

return lst;
</code>```

答:
Just use the SelectMany select the final objects. r is already in scope in that lambda, no need to get clever. And you don't need to select p => p; p was already p.

```<code>var results =
    positionsToOptimize
    .SelectMany(r =>
        r.Positions.Select(pos => new OptimizedPosition()
        {
            CalculationType = TCalculationType.Absolute,
            Position = pos.NetPositionAmount,
            SecurityID = pos.SecurityID,
            Portfolio = r.Portfolio
        }
    ));
</code>```

Body:
Suppose I have the following LINQ Statement. I would like to find a way to use "r.Portfolio" while I am in the 3rd select clause (see comment in the code):

positionsToOptimize
    .Select(p => p)
    .SelectMany(r => r.Positions)
    .Select(pos => new OptimizedPosition() {
        CalculationType = TCalculationType.Absolute,
        Position = pos.NetPositionAmount,
        SecurityID = pos.SecurityID,
        Portfolio = r.Portfolio        // <- How do I do this? (Portfolio is not in 'pos')
    });

Essentially I am trying to replace the following foreach nested loop:

var lst = new List<OptimizedPosition>();
foreach (var r in positionsToOptimize) {
    foreach (var pos in r.Positions) {
        lst.Add(new OptimizedPosition() {
            CalculationType = TCalculationType.Absolute,
            Position = pos.NetPositionAmount,
            SecurityID = pos.SecurityID,
            SystemCode = r.SystemCode
        });
    }
}

return lst;

Body:
Just use the SelectMany select the final objects. r is already in scope in that lambda, no need to get clever. And you don't need to select p => p; p was already p.

var results =
    positionsToOptimize
    .SelectMany(r =>
        r.Positions.Select(pos => new OptimizedPosition()
        {
            CalculationType = TCalculationType.Absolute,
            Position = pos.NetPositionAmount,
            SecurityID = pos.SecurityID,
            Portfolio = r.Portfolio
        }
    ));


问:
Laravel Dusk Test can't trigger Vue 13 keyCode in a text field using jQuery
Struggling with this for a couple of days.

I need to create a laravel dusk test that uses Vuejs framework. There is a method that triggers when the user press the ENTER key. I just found out that the jQuery can trigger Enter Key programmatically by using .trigger() method:

$('.text-input').trigger($.Event("keypress", {keyCode: 13}))

It works fine but it doesn't trigger the vue method binded with the .text-input. Any idea why it doesn't work and is there any other approach to meet the requirements?

Any help from you guys is really appreciated.

答:
I guess $.Event is jQuery Event wrapper around native event and it seems to trigger actual event we need native event in some cases.

```<code>var e = document.createEvent('HTMLEvents');
e.keyCode = 13;
e.initEvent('keypress', false, true);
$('.text-input').get(0).dispatchEvent(e);
</code>```

<!DOCTYPE html>

  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>

    {{ message }}
    <input type='text' @keypress="test" id='ok' value='2 sec wait for it' />

 ```

can you try this and let us know if works or not.

Body:
I guess $.Event is jQuery Event wrapper around native event and it seems to trigger actual event we need native event in some cases.

var e = document.createEvent('HTMLEvents');
e.keyCode = 13;
e.initEvent('keypress', false, true);
$('.text-input').get(0).dispatchEvent(e);

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
  <script src="https://code.jquery.com/jquery-3.1.0.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.0.3/vue.js"></script>
</head>
<body>
  <div id="app">
    {{ message }}
    <input type='text' @keypress="test" id='ok' value='2 sec wait for it' />
  </div>
  <script>

new Vue({
  el: '#app',
  data: { message : 'testing man' },
  methods: {
    test(e) {
      console.log('wait for it enter triggered : ' + e.keyCode)
    }
  }
});

setTimeout( () => {
  // modern browsers, IE9+
  var e = document.createEvent('HTMLEvents');
  e.keyCode = 13;
  e.initEvent('keypress', false, true);
  $('#ok').get(0).dispatchEvent(e);

},2000)
  </script>
</body>
 </html>

can you try this and let us know if works or not.


问:
Can't make drop-down hover work
I am trying to make a drop-down menu that drops from image but I can't seem to make it work. How should I target the hover? Because everything I am trying is not working. How I am trying to initiate hover effect is shown at the end of CSS.

.area-left {
  float: left;
}

.menu-icon {
  width: 28px;
  display: inline-block;
  vertical-align: middle;
  margin-top: 5px;
}

.menu-icon hr {
  border: 2px solid #A5CF4C;
  border-radius: 100px;
  margin-top: 3px;
  margin-bottom: 4px;
  margin-right: 5px;
  margin-left: 3px;
}

.area-left .menu li:hover {
  background-color: rgba(165, 207, 76, 0.4);
}

.logo img {
  vertical-align: middle;
  margin-top: 2px;
}

.sub-menu ul {
  background-color: rgba(255, 255, 255, 0.8);
}

.sub-menu li {
  border: 1px solid green;
  padding: 0px 5px;
}

.sub-menu .menu li:first-child {
  margin-top: 3px;
}

.sub-menu ul li {
  display: none;
}

.logo img:hover .sub-menu ul li {
  display: block;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="area-left">
  <ul id="htc-menu" class="parent-menu">
    <li class="logo ico-container">
      <div class="menu-icon">
        <hr/>
        <hr/>
        <hr/>
      </div><img src="images/logo.png" alt="HTC Logo"></li>
    <li class="sub-menu">
      <ul class="menu">
        <li>smartphones</li>
        <li>accessories</li>
        <li>virtual reality</li>
        <li>fitness</li>
      </ul>
    </li>
  </ul>
</div></code>```

答:
You're trying to access the .sub-menu as a child of .logo, despite them being siblings of each other.

Try:

.logo:hover + .sub-menu ul li  {
    display: block;
}
```

<p>Or just:</p>

<pre class="lang-css prettyprint-override"><code>#htc-menu:hover .sub-menu ul li  {
    display: block;
}
</code>```

Title: Can't make drop-down hover work

Body:
I am trying to make a drop-down menu that drops from image but I can't seem to make it work. How should I target the hover? Because everything I am trying is not working. How I am trying to initiate hover effect is shown at the end of CSS.

.area-left {
  float: left;
}

.menu-icon {
  width: 28px;
  display: inline-block;
  vertical-align: middle;
  margin-top: 5px;
}

.menu-icon hr {
  border: 2px solid #A5CF4C;
  border-radius: 100px;
  margin-top: 3px;
  margin-bottom: 4px;
  margin-right: 5px;
  margin-left: 3px;
}

.area-left .menu li:hover {
  background-color: rgba(165, 207, 76, 0.4);
}

.logo img {
  vertical-align: middle;
  margin-top: 2px;
}

.sub-menu ul {
  background-color: rgba(255, 255, 255, 0.8);
}

.sub-menu li {
  border: 1px solid green;
  padding: 0px 5px;
}

.sub-menu .menu li:first-child {
  margin-top: 3px;
}

.sub-menu ul li {
  display: none;
}

.logo img:hover .sub-menu ul li {
  display: block;
}

smartphones

accessories

virtual reality

fitness

Body:
You're trying to access the .sub-menu as a child of .logo, despite them being siblings of each other.

Try:

.logo:hover + .sub-menu ul li  {
    display: block;
}

Or just:

#htc-menu:hover .sub-menu ul li  {
    display: block;
}


问:
How to use more qualifiers, like Shift, with Appskey (Menu key)
Using the Windows Menu key (between Right Windows key and Control) on usual keyboards provides a nice qualifier key for defining macros in AutoHotKey. This is called Appskey in AutoHotKey, so e.g. Menu T can send "Hello Menu T" with:

```<code>Appskey & T::Send Hello Menu T
</code>```

Is there a way to use additional qualifier, like Shift (referenced as +), with Appskey ?

I tried some obvious possibilities without luck, like:

```<code>Appskey & + T::Send Hello Menu Shift T
+ Appskey & T::Send Hello Menu Shift T
</code>```

However, these fail.

答:
Use the #If directive to make the combination context-sensitive:

```<code>Appskey & T::Send Hello Menu T

#If GetKeyState("Shift","P")

    Appskey & T::Send Hello Menu Shift T

#If  ; turn off context sensitivity
</code>```

or this:

```<code>Appskey & T::
    If GetKeyState("Shift","P")
        Send Hello Menu Shift T
    else
    If GetKeyState("Ctrl","P")
        Send Hello Menu Ctrl T
    else
        Send Hello Menu T
return
</code>```

Body:
Using the Windows Menu key (between Right Windows key and Control) on usual keyboards provides a nice qualifier key for defining macros in AutoHotKey. This is called Appskey in AutoHotKey, so e.g. Menu T can send "Hello Menu T" with:

Appskey & T::Send Hello Menu T

Is there a way to use additional qualifier, like Shift (referenced as +), with Appskey ?

I tried some obvious possibilities without luck, like:

Appskey & + T::Send Hello Menu Shift T
+ Appskey & T::Send Hello Menu Shift T

However, these fail.

Body:
Use the #If directive to make the combination context-sensitive:

Appskey & T::Send Hello Menu T

#If GetKeyState("Shift","P")

    Appskey & T::Send Hello Menu Shift T

#If  ; turn off context sensitivity

or this:

Appskey & T::
    If GetKeyState("Shift","P")
        Send Hello Menu Shift T
    else
    If GetKeyState("Ctrl","P")
        Send Hello Menu Ctrl T
    else
        Send Hello Menu T
return


问:
Internal and External Links Test using Selenium
Want to know how to test internal and external links using webpage. I did the following code to get the links from a page.

```<code>    driver.get("http://newtours.demoaut.com/");
    driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);

    List<WebElement> links = driver.findElements(By.tagName("a"));

    for(int i=0;i<links.size();i++)
    {

        System.out.println(links.get(i).getText());
    }
</code>```

From the above code, getting displayed the link text... Please guide me...

Thanks

答:
I'm guessing by your question that the text is not what you're wanting to see, but instead get a list of the actual URL's.  In that case, you need to instead get the "href" attribute:</p>

```<code>for (int i=0; i < links.size(); i++)
    System.out.println(links.get(i).getAttribute("href"));
</code>```

Body:
Want to know how to test internal and external links using webpage. I did the following code to get the links from a page.

    driver.get("http://newtours.demoaut.com/");
    driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);

    List<WebElement> links = driver.findElements(By.tagName("a"));

    for(int i=0;i<links.size();i++)
    {

        System.out.println(links.get(i).getText());
    }

From the above code, getting displayed the link text... Please guide me...

Thanks

Body:
I'm guessing by your question that the text is not what you're wanting to see, but instead get a list of the actual URL's.  In that case, you need to instead get the "href" attribute:

for (int i=0; i < links.size(); i++)
    System.out.println(links.get(i).getAttribute("href"));


问:
About inctanceof in java
I would ask about.. do we use instanceof
If there's  a class has an array of super class and the super class  has two sub-classes ..or more

For example: class team  has an array of person (aggregation relation)
And the class person is super
The sub classes are   class player and  class couch )
Should I use increaseof in this method
Void add_person( person p){

答:
Assuming that your Team class is in the following form:

```<code>class Team{

Person[] personArr;

...
}
</code>```

And your Player and Coach classes have the following relation with the Person class:

```<code>class Player extends Person{
...
}

class Coach extends Person{
...
}
</code>```

and you have the following objects:

```<code>Coach tom = new Coach();
Player dick = new Player();
Person harry = new Player();

Team wolves = new Team ([tom, dick, harry]); //assume constructor
</code>```

the following is the behavior of instanceof:

```<code>tom instanceof Coach //returns true
dick instanceof Player //returns true
tom instanceof Person //returns true
wolves instanceof Team //returns true
harry instanceof Person //returns true
harry instanceof Player //returns true
harry instanceof Coach //returns false
</code>```

Title: About inctanceof in java

Body:
Assuming that your Team class is in the following form:

class Team{

Person[] personArr;

...
}

And your Player and Coach classes have the following relation with the Person class:

class Player extends Person{
...
}

class Coach extends Person{
...
}

and you have the following objects:

Coach tom = new Coach();
Player dick = new Player();
Person harry = new Player();

Team wolves = new Team ([tom, dick, harry]); //assume constructor

the following is the behavior of instanceof:

tom instanceof Coach //returns true
dick instanceof Player //returns true
tom instanceof Person //returns true
wolves instanceof Team //returns true
harry instanceof Person //returns true
harry instanceof Player //returns true
harry instanceof Coach //returns false


问:
How to get a list of friends the user invited in a Facebook app?
When users invite friends to my Facebook application with e.g. fb:multi-friend-selector, how can the application get a list of friends (uids) the user just invited? My application has internal "groups" and I need to connect the invites to these groups and therefore have this possibility.

We all know Facebook's documentation isn't very verbose and I've spent some considerable time researching this to no avail yet. Creative ideas to solve my problem are also appreciated.

答:
Kyberias is correct, however a bit more information is good.

One of the attributes for <fb:request-form> (which must surround the <fb:multi-friend-request>) is action.  This is the URL where the form will POST the data, and in that request will be an array of invited user ids, named 'ids'.

http://developers.facebook.com/docs/reference/fbml/request-form


问:
how to prevent cpu usage from changing timing in labview?
I'm trying to write a code in which every 1 ms a number plused one , should be replaced the old number . (something  like a chronometer !  )  .

the problem is whenever the cpu usage increases because of some other programs running on the pc,  this 1 milliseconds  is also increased and timing in my program changes !

is there any way to prevent cpu load changes affecting timing in my program ?

答:
There is no way to prevent cpu load changes from affecting timing in your program unless the computer has a realtime clock.

If it doesn't have a realtime clock, there is no reason to expect it to behave deterministically. Do you need for your program to run at that pace?


问:
Python Pandas Set Value in DataFrame where Index has Multiple Identical Label Values
I want to set a value in a row in a pandas dataframe where the row index has duplicate values and the value of a date column is the max value for the selected index value.

My dataframe:

```<code>Index  Start_Date   End_Date

  A      2017-10-01   2017-10-13
  B      2017-10-07   2017-10-15
  B      2017-10-18    np.Nat
  C      2017-10-09   2017-10-30
</code>```

so I want to set the End_Date for index value 'B' where the Start_Date is the Max for 'B'

What is the best way to do this?

EDIT:

My dataframe:

```<code>Index  Start_Date   End_Date

  A      2017-10-01   2017-10-13
  B      2017-10-07   2017-10-15
  B      2017-10-18    np.Nat
  C      2017-10-09   2017-10-30
  D      2017-11-01    np.Nat
  E      2017-11-03   2017-11-09
  E      2017-11-13    np.Nat
</code>```

Through separate processes I come to learn that the End_Date corresponding to row #3 (Index == 'B', Start_Date == '2017-10-18 is 2017-10-25.  I also separately find that row #5(Index == 'D', Start_Date == '2017-11-01'  is 2017-11-03.  So I want to fill those values into End_Date one at a time.  Since I don't have an End_Date value for the last row (Index = 'E', Start_Date == '2017-11-13') that will stay empty.

Note that 'D' is unique while 'B' is not.

Output:

My dataframe:

```<code>Index  Start_Date   End_Date

  A      2017-10-01   2017-10-13
  B      2017-10-07   2017-10-15
  B      2017-10-18   2017-10-25
  C      2017-10-09   2017-10-30
  D      2017-11-01   2017-11-03
  E      2017-11-03   2017-11-09
  E      2017-11-13    np.Nat
</code>```

Not that the values 2017-10-25 in row 3 and 2017-11-03 came from another process and we can assume they are stored in variables - that can then be used to populate the initial dataframe to obtain the output.

答:
```<code># get the row indexes
row_idx = df.sort_values(['Index', 'Start_Date']).duplicated(keep='last')

# set values
df.loc[row_idx, 'End_Date'] = 'Your desired value'
</code>```

Hope it helps!

Body:
I want to set a value in a row in a pandas dataframe where the row index has duplicate values and the value of a date column is the max value for the selected index value.

My dataframe:

Index  Start_Date   End_Date

  A      2017-10-01   2017-10-13
  B      2017-10-07   2017-10-15
  B      2017-10-18    np.Nat
  C      2017-10-09   2017-10-30

so I want to set the End_Date for index value 'B' where the Start_Date is the Max for 'B'

What is the best way to do this?

EDIT:

My dataframe:

Index  Start_Date   End_Date

  A      2017-10-01   2017-10-13
  B      2017-10-07   2017-10-15
  B      2017-10-18    np.Nat
  C      2017-10-09   2017-10-30
  D      2017-11-01    np.Nat
  E      2017-11-03   2017-11-09
  E      2017-11-13    np.Nat

Through separate processes I come to learn that the End_Date corresponding to row #3 (Index == 'B', Start_Date == '2017-10-18 is 2017-10-25.  I also separately find that row #5(Index == 'D', Start_Date == '2017-11-01'  is 2017-11-03.  So I want to fill those values into End_Date one at a time.  Since I don't have an End_Date value for the last row (Index = 'E', Start_Date == '2017-11-13') that will stay empty.

Note that 'D' is unique while 'B' is not.

Output:

My dataframe:

Index  Start_Date   End_Date

  A      2017-10-01   2017-10-13
  B      2017-10-07   2017-10-15
  B      2017-10-18   2017-10-25
  C      2017-10-09   2017-10-30
  D      2017-11-01   2017-11-03
  E      2017-11-03   2017-11-09
  E      2017-11-13    np.Nat

Not that the values 2017-10-25 in row 3 and 2017-11-03 came from another process and we can assume they are stored in variables - that can then be used to populate the initial dataframe to obtain the output.

Body:
# get the row indexes
row_idx = df.sort_values(['Index', 'Start_Date']).duplicated(keep='last')

# set values
df.loc[row_idx, 'End_Date'] = 'Your desired value'

Hope it helps!


问:
JavaFX- MouseEvents converting the shapes from circle to a rectangle
I have been trying to convert the pre-made program on netbeans called MouseEvents shape from a circle to a rectangle. I tried it out but this is where I got a red line:

```<code> private Rectangle createRectangle(final String name, final Color color, int width, int height) {
    //create a rectangle with desired name,  color and radius
    final Rectangle rectangle = new Rectangle(width, new RadialGradient(0, 0, 0.2, 0.3, 1, true, CycleMethod.NO_CYCLE, new Stop[] {
        new Stop(0, Color.rgb(250,250,255)),
        new Stop(1, color)
    }));
</code>```

Here is another bit of code that may help you answer:

```<code> final Rectangle rectangleSmall = createRectangle("Blue rectangle", Color.DODGERBLUE, 25,10);
</code>```

答:
First of all, it's not clear whether you are converting a circle to rectangle or the vice versa, and what do u mean by 'converting' .

And also, you aren't creating a Rectangle at all, because, you didn't use the height variable at all. Try this instead:

```<code>final Rectangle rectangle = new Rectangle(width, height, new RadialGradient(0, 0, 0.2, 0.3, 1, true, CycleMethod.NO_CYCLE, new Stop[] {
        new Stop(0, Color.rgb(250,250,255)),
        new Stop(1, color)
    });
</code>```

Body:
I have been trying to convert the pre-made program on netbeans called MouseEvents shape from a circle to a rectangle. I tried it out but this is where I got a red line:

 private Rectangle createRectangle(final String name, final Color color, int width, int height) {
    //create a rectangle with desired name,  color and radius
    final Rectangle rectangle = new Rectangle(width, new RadialGradient(0, 0, 0.2, 0.3, 1, true, CycleMethod.NO_CYCLE, new Stop[] {
        new Stop(0, Color.rgb(250,250,255)),
        new Stop(1, color)
    }));

Here is another bit of code that may help you answer:

 final Rectangle rectangleSmall = createRectangle("Blue rectangle", Color.DODGERBLUE, 25,10);

Body:
First of all, it's not clear whether you are converting a circle to rectangle or the vice versa, and what do u mean by 'converting' .

And also, you aren't creating a Rectangle at all, because, you didn't use the height variable at all. Try this instead:

final Rectangle rectangle = new Rectangle(width, height, new RadialGradient(0, 0, 0.2, 0.3, 1, true, CycleMethod.NO_CYCLE, new Stop[] {
        new Stop(0, Color.rgb(250,250,255)),
        new Stop(1, color)
    });


问:
Waiting for a method execution
Suppose, I have a class SomeClass with a method void process(). The implementation of this method is smth like new Thread(this::someOtherMethod).start (need to execute only someOtherMethod in a particular thread).

Having written down a unit test for this method:

SomeClass class= new SomeClass(anObjectToWorkWith);
class.process();
assertEquals(expectedObj, anObjectToWorkWith)

I have realised, that as the process method executes in a particular thread, an assertEquals instruction is called before the process method is completed.

Therefore, I have a question: is there some way to wait for the process method execution, to make assertEquals be called necessarily after the process.

Thank you in advance.

P.S. Don't propose solutions that use Thread.sleep method or solutions that imply making SomeClass implement Runnable interface, as these solutions don't conform to the tasking.

答:
You simply have hard to test code here.

When your code under test creates a new thread instance and uses that - then there is simply no good way to write reasonable unit tests.

Instead: consider changing your code under test.

For example: instead of using low level threads, turn to an ExecutorService. And then use a same thread executor for your tests. Because that allows you to turn your multi-threaded problem into a single-threaded one. Just by using a different kind of executor.

Title: Waiting for a method execution


问:
How do I sort array of pairs based on the greater value in first or second
```<code>bool custome_compare(const pair<int, int>& p1, const pair<int, int>& p2){
    if (p1.first > p1.second || p1.second > p1.first) return true;
    else return false;
}
int main()
{
    pair<int, int> arr[4];
    arr[0].first = 4, arr[0].second = 10;
    arr[1].first = 7, arr[1].second = 6;
    arr[2].first = 3, arr[2].second = 8;
    arr[3].first = 9, arr[3].second = 1;

    sort(arr, arr + 4 , custome_compare);
    //---------------------------------------
    return 0;
}
</code>```

My goal to sort the array of pairs based on the greater value.

I don't care the greater value is the first or the second element in the pair.

For example i have this pairs:

4,10

7,6

3,8

9,1

After sort them :

4,10

9,1

3,8

7,6

So i'm not sorting based on first or second i sorting based on both.

How can I edit this compare function to do this task ?

Thanks in advance.

答:
It sounds like you want to compare the max of the two pairs.</p>

```<code>bool custom_compare(const pair<int, int>& p1, const pair<int, int>& p2){
    return std::max(p1.first, p1.second) < std::max(p2.first, p2.second);
    }
</code>```

Body:
bool custome_compare(const pair<int, int>& p1, const pair<int, int>& p2){
    if (p1.first > p1.second || p1.second > p1.first) return true;
    else return false;
}
int main()
{
    pair<int, int> arr[4];
    arr[0].first = 4, arr[0].second = 10;
    arr[1].first = 7, arr[1].second = 6;
    arr[2].first = 3, arr[2].second = 8;
    arr[3].first = 9, arr[3].second = 1;

    sort(arr, arr + 4 , custome_compare);
    //---------------------------------------
    return 0;
}

My goal to sort the array of pairs based on the greater value.

I don't care the greater value is the first or the second element in the pair.

For example i have this pairs:

4,10

7,6

3,8

9,1

After sort them :

4,10

9,1

3,8

7,6

So i'm not sorting based on first or second i sorting based on both.

How can I edit this compare function to do this task ?

Thanks in advance.

Body:
It sounds like you want to compare the max of the two pairs.

bool custom_compare(const pair<int, int>& p1, const pair<int, int>& p2){
    return std::max(p1.first, p1.second) < std::max(p2.first, p2.second);
    }


问:
Thread safety on Immutable object
I was reading about Immutable objects in java.

There is a statement which states - "Immutable objects are thread-safe".
I need more clarification for the above statement:

If I have a shared resource of type 'String' which is shared with multiple threads (say 3)
And if one of the thread make changes to the shared reference, it will create a new String object and that will available only with that Thread object and other threads will not get to know about the changes made by one of the thread.

Will it not lead to data inconsistency?

So could anyone please help me understand this?

Thanks in advance.

答:
An object of an immutable class is always thread-safe. However, the reference to such an object doesn't have anything to do with that. It might be or it might not be thread-safe, depending on how the class that contains the reference to this thread-safe object (a String object, for example) and the methods to manipulate such a reference.

See this example below, to illustrate the explanation:

```<code>public class User {
   private string name;

   public User(String name) {
      this.name=name;
   }

   public String getName() {
      return name;
   }

   public void setName(String name) {
      this.name=name;
   }
}
</code>```

So, even though String is an immutable and thread-safe class, the reference to it in the class User above isn't thread-safe because its methods could be concurrently changing this reference to new String objects.

If you wanted it to be thread-safe, there would be many options. One of them would be to set all methods that can change the name object as synchronized.

Title: Thread safety on Immutable object

Body:
An object of an immutable class is always thread-safe. However, the reference to such an object doesn't have anything to do with that. It might be or it might not be thread-safe, depending on how the class that contains the reference to this thread-safe object (a String object, for example) and the methods to manipulate such a reference.

See this example below, to illustrate the explanation:

public class User {
   private string name;

   public User(String name) {
      this.name=name;
   }

   public String getName() {
      return name;
   }

   public void setName(String name) {
      this.name=name;
   }
}

So, even though String is an immutable and thread-safe class, the reference to it in the class User above isn't thread-safe because its methods could be concurrently changing this reference to new String objects.

If you wanted it to be thread-safe, there would be many options. One of them would be to set all methods that can change the name object as synchronized.


问:
Android NavigationView MenuItem Icon Animation
I'm trying to understand if menu icon animation should work in the new
Navigationview, the same way action items animation works or any other view for that matter, that is used on any app layout.

The code below doesn't work for me.
I'm using for testing the code sample released by Android for the new support
library.
Same animation code works nicely on the toolbar. Also tried the older API for
animation (followed that link: Animated Icon for ActionItem)

I guess I'm missing something...

thanks ahead.

Code:

Xml:

```<code><android.support.v4.widget.DrawerLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/drawer_layout"
    android:layout_height="match_parent"
    android:layout_width="match_parent"
    android:fitsSystemWindows="true"
    android:background="@color/lightPrimaryColor">

    <include layout="@layout/include_list_viewpager"/>

    <android.support.design.widget.NavigationView
        android:id="@+id/nav_view"
        android:layout_height="match_parent"
        android:layout_width="wrap_content"
        android:layout_gravity="start"
        android:fitsSystemWindows="true"
        android:background="@color/lightPrimaryColor"
        app:headerLayout="@layout/nav_header"
        app:theme="@style/menu_item_style"
        app:menu="@menu/drawer_view"/>

</android.support.v4.widget.DrawerLayout>
</code>```

drawer_view:

```<code><?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:class="http://schemas.android.com/tools"
    class:actionViewClass="android.widget.ProgressBar">

    <group android:checkableBehavior="single"
        android:id="@+id/drawer_menu">
        <!--   <item
           android:id="@+id/nav_my_lists"
           android:title="@string/title_shopping_lists"
           android:icon="@drawable/ic_event"
           app:showAsAction="always"/> -->
        <item
            android:id="@+id/nav_examp_lists"
            android:icon="@drawable/refresh1"
            android:title="@string/example"
            app:showAsAction="always"
            android:layoutDirection="rtl"/>
        <item
            android:id="@+id/nav_split_lists"
            android:title="@string/split"
            android:icon="@drawable/refresh2"
            app:showAsAction="always"
            app:actionViewClass="android.widget.ImageView"/>
        <item
            android:id="@+id/nav_change_net"
            android:title="@string/change"
            android:icon="@drawable/refresh3"
            app:showAsAction="always"
            android:layoutDirection="rtl"/>

    </group>

</menu>
</code>```

java:

```<code>navigationView.setNavigationItemSelectedListener(
                new NavigationView.OnNavigationItemSelectedListener() {
            @Override
            public boolean onNavigationItemSelected(MenuItem menuItem) {

               menuItem.setChecked(true);
               mDrawerLayout.closeDrawers();

                switch (menuItem.getItemId()) {

                    case R.id.nav_my_lists:

                        anim = AnimatorInflater.loadAnimator(getApplication(), R.animator.rotation);
                        anim.setTarget(menuItem.getIcon());
                        anim.setDuration(2000);
                        //anim.setStartDelay(10);
                        anim.addListener(new AnimatorListenerAdapter() {
                            @Override
                            public void onAnimationStart(Animator animation) {
                                Toast.makeText(getApplication(), "Started...", Toast.LENGTH_SHORT).show();
                            }

                        });

                        anim.start();
                        boolean run = anim.isRunning();

                        String title = menuItem.getTitle().toString();
                        loadShoppingList(title);

                        return true;
</code>```

答:
It is possible. You don't need set custom View for that.

```<code>private AnimationDrawableWrapper drawableWrapper;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    //...

    Menu menu = navigationView.getMenu();
    MenuItem menuItem = menu.findItem(R.id.your_icon);
    Drawable icon = menuItem.getIcon();
    drawableWrapper = new AnimationDrawableWrapper(getResources(), icon);
    menuItem.setIcon(drawableWrapper);
}

public void startRotateIconAnimation() {
    ValueAnimator animator = ObjectAnimator.ofInt(0, 360);
    animator.addUpdateListener(animation -> {
        int rotation = (int) animation.getAnimatedValue();
        drawableWrapper.setRotation(rotation);
    });
    animator.start();
}
</code>```

We can't animate drawable directly, so use DrawableWrapper(from android.support.v7 for API<21):

```<code>public class AnimationDrawableWrapper extends DrawableWrapper {

    private float rotation;
    private Rect bounds;

    public AnimationDrawableWrapper(Resources resources, Drawable drawable) {
        super(vectorToBitmapDrawableIfNeeded(resources, drawable));
        bounds = new Rect();
    }

    @Override
    public void draw(Canvas canvas) {
        copyBounds(bounds);
        canvas.save();
        canvas.rotate(rotation, bounds.centerX(), bounds.centerY());
        super.draw(canvas);
        canvas.restore();
    }

    public void setRotation(float degrees) {
        this.rotation = degrees % 360;
        invalidateSelf();
    }

    /**
     * Workaround for issues related to vector drawables rotation and scaling:
     * https://code.google.com/p/android/issues/detail?id=192413
     * https://code.google.com/p/android/issues/detail?id=208453
     */
    private static Drawable vectorToBitmapDrawableIfNeeded(Resources resources, Drawable drawable) {
        if (drawable instanceof VectorDrawable) {
            Bitmap b = Bitmap.createBitmap(drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight(), Bitmap.Config.ARGB_8888);
            Canvas c = new Canvas(b);
            drawable.setBounds(0, 0, c.getWidth(), c.getHeight());
            drawable.draw(c);
            drawable = new BitmapDrawable(resources, b);
        }
        return drawable;
    }
}
</code>```

I took the idea for DrawableWrapper from here: https://stackoverflow.com/a/39108111/5541688

Body:
I'm trying to understand if menu icon animation should work in the new
Navigationview, the same way action items animation works or any other view for that matter, that is used on any app layout.

The code below doesn't work for me.
I'm using for testing the code sample released by Android for the new support
library.
Same animation code works nicely on the toolbar. Also tried the older API for
animation (followed that link: Animated Icon for ActionItem)

I guess I'm missing something...

thanks ahead.

Code:

Xml:

<android.support.v4.widget.DrawerLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/drawer_layout"
    android:layout_height="match_parent"
    android:layout_width="match_parent"
    android:fitsSystemWindows="true"
    android:background="@color/lightPrimaryColor">

    <include layout="@layout/include_list_viewpager"/>

    <android.support.design.widget.NavigationView
        android:id="@+id/nav_view"
        android:layout_height="match_parent"
        android:layout_width="wrap_content"
        android:layout_gravity="start"
        android:fitsSystemWindows="true"
        android:background="@color/lightPrimaryColor"
        app:headerLayout="@layout/nav_header"
        app:theme="@style/menu_item_style"
        app:menu="@menu/drawer_view"/>

</android.support.v4.widget.DrawerLayout>

drawer_view:

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:class="http://schemas.android.com/tools"
    class:actionViewClass="android.widget.ProgressBar">

    <group android:checkableBehavior="single"
        android:id="@+id/drawer_menu">

        <item
            android:id="@+id/nav_examp_lists"
            android:icon="@drawable/refresh1"
            android:title="@string/example"
            app:showAsAction="always"
            android:layoutDirection="rtl"/>
        <item
            android:id="@+id/nav_split_lists"
            android:title="@string/split"
            android:icon="@drawable/refresh2"
            app:showAsAction="always"
            app:actionViewClass="android.widget.ImageView"/>
        <item
            android:id="@+id/nav_change_net"
            android:title="@string/change"
            android:icon="@drawable/refresh3"
            app:showAsAction="always"
            android:layoutDirection="rtl"/>

    </group>

</menu>

java:

navigationView.setNavigationItemSelectedListener(
                new NavigationView.OnNavigationItemSelectedListener() {
            @Override
            public boolean onNavigationItemSelected(MenuItem menuItem) {

               menuItem.setChecked(true);
               mDrawerLayout.closeDrawers();

                switch (menuItem.getItemId()) {

                    case R.id.nav_my_lists:

                        anim = AnimatorInflater.loadAnimator(getApplication(), R.animator.rotation);
                        anim.setTarget(menuItem.getIcon());
                        anim.setDuration(2000);
                        //anim.setStartDelay(10);
                        anim.addListener(new AnimatorListenerAdapter() {
                            @Override
                            public void onAnimationStart(Animator animation) {
                                Toast.makeText(getApplication(), "Started...", Toast.LENGTH_SHORT).show();
                            }

                        });

                        anim.start();
                        boolean run = anim.isRunning();

                        String title = menuItem.getTitle().toString();
                        loadShoppingList(title);

                        return true;

Body:
It is possible. You don't need set custom View for that.

private AnimationDrawableWrapper drawableWrapper;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    //...

    Menu menu = navigationView.getMenu();
    MenuItem menuItem = menu.findItem(R.id.your_icon);
    Drawable icon = menuItem.getIcon();
    drawableWrapper = new AnimationDrawableWrapper(getResources(), icon);
    menuItem.setIcon(drawableWrapper);
}

public void startRotateIconAnimation() {
    ValueAnimator animator = ObjectAnimator.ofInt(0, 360);
    animator.addUpdateListener(animation -> {
        int rotation = (int) animation.getAnimatedValue();
        drawableWrapper.setRotation(rotation);
    });
    animator.start();
}

We can't animate drawable directly, so use DrawableWrapper(from android.support.v7 for API<21):

public class AnimationDrawableWrapper extends DrawableWrapper {

    private float rotation;
    private Rect bounds;

    public AnimationDrawableWrapper(Resources resources, Drawable drawable) {
        super(vectorToBitmapDrawableIfNeeded(resources, drawable));
        bounds = new Rect();
    }

    @Override
    public void draw(Canvas canvas) {
        copyBounds(bounds);
        canvas.save();
        canvas.rotate(rotation, bounds.centerX(), bounds.centerY());
        super.draw(canvas);
        canvas.restore();
    }

    public void setRotation(float degrees) {
        this.rotation = degrees % 360;
        invalidateSelf();
    }

    /**
     * Workaround for issues related to vector drawables rotation and scaling:
     * https://code.google.com/p/android/issues/detail?id=192413
     * https://code.google.com/p/android/issues/detail?id=208453
     */
    private static Drawable vectorToBitmapDrawableIfNeeded(Resources resources, Drawable drawable) {
        if (drawable instanceof VectorDrawable) {
            Bitmap b = Bitmap.createBitmap(drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight(), Bitmap.Config.ARGB_8888);
            Canvas c = new Canvas(b);
            drawable.setBounds(0, 0, c.getWidth(), c.getHeight());
            drawable.draw(c);
            drawable = new BitmapDrawable(resources, b);
        }
        return drawable;
    }
}

I took the idea for DrawableWrapper from here: https://stackoverflow.com/a/39108111/5541688


问:
Handling POST request on a GET route (express.js)
I am new to express and node together and seem to be stuck, with what seems to be, a simple issue. I have an API route that uses GET. Route:

```<code>app.get('/api/v1/all', getAllWords);
</code>```

Then inside of the getAllWords callback function, I want to check if the request that was sent was of GET or POST. This is the code I have to check the request method:

```<code>function getAllWords(request, response) {
   let reply;
   if (request.method === 'GET') {
      console.log('This was a GET request');
      // handle GET here...
   }
   if (request.method === 'POST') {
      console.log('This was a POST request');
      reply = {
          "msg": "HTTP Method not allowed"
      };
      response.send(reply)
   }
}
</code>```

When I use Postman to send off a GET request it works just fine. But when sending a POST request I get the generic express.js "Cannot POST /api/v1/all".

Why did it the response.send(reply) not work for the POST method?

答: You can make use of app.all(...) to handle both GET and POST requests but it also accepts other kind of requests such as PUT and DELETE. I prefer separating the GETand POST request though.

Body:
I am new to express and node together and seem to be stuck, with what seems to be, a simple issue. I have an API route that uses GET. Route:

app.get('/api/v1/all', getAllWords);

Then inside of the getAllWords callback function, I want to check if the request that was sent was of GET or POST. This is the code I have to check the request method:

function getAllWords(request, response) {
   let reply;
   if (request.method === 'GET') {
      console.log('This was a GET request');
      // handle GET here...
   }
   if (request.method === 'POST') {
      console.log('This was a POST request');
      reply = {
          "msg": "HTTP Method not allowed"
      };
      response.send(reply)
   }
}

When I use Postman to send off a GET request it works just fine. But when sending a POST request I get the generic express.js "Cannot POST /api/v1/all".

Why did it the response.send(reply) not work for the POST method?


问:
Make generic definition optional in Swift 4
My class definition looks like

```<code>class Response<T : Decodable> {
    var responseData : T?
}

class Test {
    func someFunction() {
        let serverResponse = Response<Employee>();
        let errorResponse = Response(); //Compilation error here
    }
}
</code>```

How I can make the Response class to be initialized either through a Decodable class or nil representation?

答:
Response is usually written like this:</p>

```<code>enum Response<T : Decodable> {
    case success(T)
    case failure(Error)
}
</code>```

Body:
My class definition looks like

class Response<T : Decodable> {
    var responseData : T?
}

class Test {
    func someFunction() {
        let serverResponse = Response<Employee>();
        let errorResponse = Response(); //Compilation error here
    }
}

How I can make the Response class to be initialized either through a Decodable class or nil representation?

Body:
Response is usually written like this:

enum Response<T : Decodable> {
    case success(T)
    case failure(Error)
}


问:
jquery animate opacity has an impact of other divs? weird behavior
I've got a really strange jquery behavior. I want to make a grid like background with animated tiles (opacity to .8 and back to .25 on mouseover and mouseleave).

As this should be my background it should'n have an impact on my content div.

Unfortunately it doesn't work as expected. THe content div(Which i colored red for testing purposes) gets animated, too.

Here's a link the the site.

答: The content div is not animated, but the page-bg div is on the top of the content (because of absolute position), so when you change opacity, the content div (in the background) is getting visible...</p>


问:
how to display uploaded picture . php ,mysql
hey guys i am stuck at very end point of my code , my aim was to Store image path to database and store the image to a directory. and than i want to show those images.
i am successfully done uploading part but now i am stuck how can i show those images on my webpage, here is my code </p>

```<code><?php
  $sql    = "SELECT * FROM pictures";
  $result = mysqli_query($conn, $sql);
  $data   = mysqli_fetch_array($result,MYSQLI_ASSOC);

  while($row = mysqli_fetch_array($result))
  {
   $image_path=$row["folder_name"];
   $image_name=$row["picture_name"];

   echo "img src=".$image_path."/".$image_name." width=100 height=100";
  }
?>
</code>```

答:
If you want to fetch associative arrays, use fetch_assoc instead, your $data is not needed here, it's simpler at the end. Also, only select the fields you need in your query. To fix your problem, You are simply missing the HTML , try this:</p>

```<code><?php
  $sql    = "SELECT folder_name, picture_name FROM pictures";
  $result = mysqli_query($conn, $sql);
  if(!$result) {
      die("Error with your Query: " . mysqli_error($conn));
  }
  while($row = mysqli_fetch_assoc($result)) {
      $image_path = $row["folder_name"];
      $image_name = $row["picture_name"];
      echo "<img src=\"" . $image_path . "/" . $image_name . "\" width=\"100\" height=\"100\"></img>\n";
  }
?>
</code>```

Body:
hey guys i am stuck at very end point of my code , my aim was to Store image path to database and store the image to a directory. and than i want to show those images.
i am successfully done uploading part but now i am stuck how can i show those images on my webpage, here is my code

<?php
  $sql    = "SELECT * FROM pictures";
  $result = mysqli_query($conn, $sql);
  $data   = mysqli_fetch_array($result,MYSQLI_ASSOC);

  while($row = mysqli_fetch_array($result))
  {
   $image_path=$row["folder_name"];
   $image_name=$row["picture_name"];

   echo "img src=".$image_path."/".$image_name." width=100 height=100";
  }
?>

Body:
If you want to fetch associative arrays, use fetch_assoc instead, your $data is not needed here, it's simpler at the end. Also, only select the fields you need in your query. To fix your problem, You are simply missing the HTML , try this:

<?php
  $sql    = "SELECT folder_name, picture_name FROM pictures";
  $result = mysqli_query($conn, $sql);
  if(!$result) {
      die("Error with your Query: " . mysqli_error($conn));
  }
  while($row = mysqli_fetch_assoc($result)) {
      $image_path = $row["folder_name"];
      $image_name = $row["picture_name"];
      echo "<img src=\"" . $image_path . "/" . $image_name . "\" width=\"100\" height=\"100\"></img>\n";
  }
?>


问:
Sharepoint online - automatic filename based on metadata
I would like to name the documents in the document library based on meta tags and the document ID sharepoint give the document. Is there any way to achieve this without using sharepoint designer?</p>

答: You'd need some sort of workflow or event receiver that will handle that when triggered by an item adding/updated event. Since you're using SharePoint Online, Microsoft Flow may be a simple solution. </p>


问:
Pulse effect CSS around button not working
I am trying to create a pulse effect around this button.
Unfortunately its not working... and I can't find the error.

#pulse {
  width: 50px;
  height: 100%;
}

#show {
  float: left;
  margin-top: -200px;
  margin-left: 10px;
  border: none;
  height: 40px;
  width: 40px;
  box-shadow: 0 0 0 0 rgba(232, 76, 61, 0.7);
  border-radius: 50%;
  background: none;
  cursor: pointer;
  background-image: url('bilder/showleftside.svg');
  background-repeat: no-repeat;
  background-size: cover;
  -webkit-animation: pulse 1.25s infinite cubic-bezier(0.66, 0, 0, 1);
  -moz-animation: pulse 1.25s infinite cubic-bezier(0.66, 0, 0, 1);
  -ms-animation: pulse 1.25s infinite cubic-bezier(0.66, 0, 0, 1);
  animation: pulse 1.25s infinite cubic-bezier(0.66, 0, 0, 1);
}

@keyframes pulse {
  0% {
    transform: scale(1, 1);
  }
  50% {
    opacity: 0.3;
  }
  100% {
    transform: scale(1.5);
    opacity: 0;
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="pulse">
  <button id="show" type="button" onclick=""></button>
</div></code>```

答:
You defined a animation with name pulse. What this pulse animation is supposed to do is missing in your code. Add keyframes to define your animation.

https://developer.mozilla.org/en-US/docs/Web/CSS/@keyframes

#pulse {
    width: 50px;
    height: 100%;
}

#show {
    float: left;
    margin: 20px;

    border: 1px solid #ddd;
    height: 40px;
    width: 40px;
    box-shadow: 0 0 0 0 rgba(232, 76, 61, 0.7);
    border-radius: 50%;
    background: none;
    cursor: pointer;

    background-image: url('bilder/showleftside.svg');
    background-repeat: no-repeat;
    background-size: cover;

    -webkit-animation: pulse 1.25s infinite cubic-bezier(0.66, 0, 0, 1);
    -moz-animation: pulse 1.25s infinite cubic-bezier(0.66, 0, 0, 1);
    -ms-animation: pulse 1.25s infinite cubic-bezier(0.66, 0, 0, 1);
    animation: pulse 1.25s infinite cubic-bezier(0.66, 0, 0, 1);
}

@keyframes pulse {
  0% {
    transform: scale(1);
  }
  50% {
    transform: scale(1.2);
  }
  100% {
    transform: scale(1);
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="pulse">
    <button id="show" type="button">X</button>
 </div></code>```

Body:
I am trying to create a pulse effect around this button.
Unfortunately its not working... and I can't find the error.

#pulse {
  width: 50px;
  height: 100%;
}

#show {
  float: left;
  margin-top: -200px;
  margin-left: 10px;
  border: none;
  height: 40px;
  width: 40px;
  box-shadow: 0 0 0 0 rgba(232, 76, 61, 0.7);
  border-radius: 50%;
  background: none;
  cursor: pointer;
  background-image: url('bilder/showleftside.svg');
  background-repeat: no-repeat;
  background-size: cover;
  -webkit-animation: pulse 1.25s infinite cubic-bezier(0.66, 0, 0, 1);
  -moz-animation: pulse 1.25s infinite cubic-bezier(0.66, 0, 0, 1);
  -ms-animation: pulse 1.25s infinite cubic-bezier(0.66, 0, 0, 1);
  animation: pulse 1.25s infinite cubic-bezier(0.66, 0, 0, 1);
}

@keyframes pulse {
  0% {
    transform: scale(1, 1);
  }
  50% {
    opacity: 0.3;
  }
  100% {
    transform: scale(1.5);
    opacity: 0;
  }
}

  <button id="show" type="button" onclick=""></button>

Body:
You defined a animation with name pulse. What this pulse animation is supposed to do is missing in your code. Add keyframes to define your animation.

https://developer.mozilla.org/en-US/docs/Web/CSS/@keyframes

#pulse {
    width: 50px;
    height: 100%;
}

#show {
    float: left;
    margin: 20px;

    border: 1px solid #ddd;
    height: 40px;
    width: 40px;
    box-shadow: 0 0 0 0 rgba(232, 76, 61, 0.7);
    border-radius: 50%;
    background: none;
    cursor: pointer;

    background-image: url('bilder/showleftside.svg');
    background-repeat: no-repeat;
    background-size: cover;

    -webkit-animation: pulse 1.25s infinite cubic-bezier(0.66, 0, 0, 1);
    -moz-animation: pulse 1.25s infinite cubic-bezier(0.66, 0, 0, 1);
    -ms-animation: pulse 1.25s infinite cubic-bezier(0.66, 0, 0, 1);
    animation: pulse 1.25s infinite cubic-bezier(0.66, 0, 0, 1);
}

@keyframes pulse {
  0% {
    transform: scale(1);
  }
  50% {
    transform: scale(1.2);
  }
  100% {
    transform: scale(1);
  }
}

<div id="pulse">
    <button id="show" type="button">X</button>
 </div>


答:
Here you are

```<code>bool custome_compare(const std::pair<int, int> &p1, const std::pair<int, int> &p2)
{
    return std::max( p1.first, p1.second ) > std::max( p2.first, p2.second );
}
</code>```

Here is a demonstrative program

```<code>#include <iostream>
#include <utility>
#include <algorithm>
#include <iterator>

bool custome_compare(const std::pair<int, int> &p1, const std::pair<int, int> &p2)
{
    return std::max( p1.first, p1.second ) > std::max( p2.first, p2.second );
}

int main()
{
    std::pair<int, int> arr[] =
    {
        { 4, 10 }, { 7, 6 }, { 3, 8 }, { 9, 1 }
    };

    for ( const auto &p : arr )
    {
        std::cout << p.first << ", " << p.second << '\n';
    }

    std::cout << std::endl;

    std::sort( std::begin( arr ), std::end( arr ), custome_compare );

    for ( const auto &p : arr )
    {
        std::cout << p.first << ", " << p.second << '\n';
    }

    std::cout << std::endl;

    return 0;
}
</code>```

Its output is

```<code>4, 10
7, 6
3, 8
9, 1

4, 10
9, 1
3, 8
7, 6
</code>```

Title: How do I sort array of pairs based on the greater value in first or second

Body:
Here you are

bool custome_compare(const std::pair<int, int> &p1, const std::pair<int, int> &p2)
{
    return std::max( p1.first, p1.second ) > std::max( p2.first, p2.second );
}

Here is a demonstrative program

#include <iostream>
#include <utility>
#include <algorithm>
#include <iterator>

bool custome_compare(const std::pair<int, int> &p1, const std::pair<int, int> &p2)
{
    return std::max( p1.first, p1.second ) > std::max( p2.first, p2.second );
}

int main()
{
    std::pair<int, int> arr[] =
    {
        { 4, 10 }, { 7, 6 }, { 3, 8 }, { 9, 1 }
    };

    for ( const auto &p : arr )
    {
        std::cout << p.first << ", " << p.second << '\n';
    }

    std::cout << std::endl;

    std::sort( std::begin( arr ), std::end( arr ), custome_compare );

    for ( const auto &p : arr )
    {
        std::cout << p.first << ", " << p.second << '\n';
    }

    std::cout << std::endl;

    return 0;
}

Its output is

4, 10
7, 6
3, 8
9, 1

4, 10
9, 1
3, 8
7, 6


问:
Get simple recursive from table with id_parent
I guess my brain starts to slow down, but I want to get a recursive array of my results from this table :

```<code>|id|int(11)|
|name|varchar(150)|
|type|tinyint(4)|
|id_parent|mediumint(9)|

|1|Marque forte|1|0|
|2|Communication|2|1|
|3|Respect du CI|0|2|
|4|Stratégie digitale|0|2
|5|Expérience de marque|2|1|
|6|Gastronomie|0|5|
</code>```

I want an array like :

```<code>array('id' => array('name' => $name, 'childs' => array( ... ), 'id' => ...)
</code>```

I just want to order my dataset in one array.

I tried this so far :

```<code>// returns array of objects - codeigniter result
$dbResult = $this->db->get_where('table')->result();

// will contains the array
$this->data['tree'] = array();
$this->getRecursive(0, 0, $dbResult);
....

private function getRecursive($parent, $niveau, $result)
{
    foreach ($result AS $row)
    {
        if ($parent == $row->id_parent)
        {
            $this->data['tree'][] = array($row->name => $this->getRecursive($row->id, ($niveau + 1), $result));
        }
    }
}
</code>```

Which gives me weird result ...

答:
You don't need a recursion here - the following should do the job</p>

```<code>$arrTreeById = [];
//$arrData = $this->db->get_where('table')->result_array();

$arrData = [
    [
        'id' => 1,
        'name' => 'Marque forte',
        'type' => 2,
        'id_parent' => 0
    ],
    [
        'id' => 2,
        'name' => 'Communication',
        'type' => 2,
        'id_parent' => 1
    ],
    [
        'id' => 3,
        'name' => 'Respect du CI',
        'type' => 0,
        'id_parent' => 2
    ],
    [
        'id' => 4,
        'name' => 'Stratégie digitale',
        'type' => 0,
        'id_parent' => 2
    ],
    [
        'id' => 5,
        'name' => 'Expérience de marque',
        'type' => 2,
        'id_parent' => 1
    ],
    [
        'id' => 6,
        'name' => 'Gastronomie',
        'type' => 0,
        'id_parent' => 5
    ],
];

foreach($arrData AS $arrItem)
{
    $arrTreeById[$arrItem['id']] = $arrItem;
}

foreach($arrTreeById AS &$arrItem)
{
    if (isset($arrTreeById[$arrItem['id_parent']]))
    {
        $arrTreeById[$arrItem['id_parent']]['arrChilds'][] = &$arrItem;
    }
    if ($arrItem['id_parent'] == 0) $intStartingKey = $arrItem['id'];
}

print_r($arrTreeById[$intStartingKey]);
</code>```

Body:
I guess my brain starts to slow down, but I want to get a recursive array of my results from this table :

|id|int(11)|
|name|varchar(150)|
|type|tinyint(4)|
|id_parent|mediumint(9)|

|1|Marque forte|1|0|
|2|Communication|2|1|
|3|Respect du CI|0|2|
|4|Stratégie digitale|0|2
|5|Expérience de marque|2|1|
|6|Gastronomie|0|5|

I want an array like :

array('id' => array('name' => $name, 'childs' => array( ... ), 'id' => ...)

I just want to order my dataset in one array.

I tried this so far :

// returns array of objects - codeigniter result
$dbResult = $this->db->get_where('table')->result();

// will contains the array
$this->data['tree'] = array();
$this->getRecursive(0, 0, $dbResult);
....

private function getRecursive($parent, $niveau, $result)
{
    foreach ($result AS $row)
    {
        if ($parent == $row->id_parent)
        {
            $this->data['tree'][] = array($row->name => $this->getRecursive($row->id, ($niveau + 1), $result));
        }
    }
}

Which gives me weird result ...

Body:
You don't need a recursion here - the following should do the job

$arrTreeById = [];
//$arrData = $this->db->get_where('table')->result_array();

$arrData = [
    [
        'id' => 1,
        'name' => 'Marque forte',
        'type' => 2,
        'id_parent' => 0
    ],
    [
        'id' => 2,
        'name' => 'Communication',
        'type' => 2,
        'id_parent' => 1
    ],
    [
        'id' => 3,
        'name' => 'Respect du CI',
        'type' => 0,
        'id_parent' => 2
    ],
    [
        'id' => 4,
        'name' => 'Stratégie digitale',
        'type' => 0,
        'id_parent' => 2
    ],
    [
        'id' => 5,
        'name' => 'Expérience de marque',
        'type' => 2,
        'id_parent' => 1
    ],
    [
        'id' => 6,
        'name' => 'Gastronomie',
        'type' => 0,
        'id_parent' => 5
    ],
];

foreach($arrData AS $arrItem)
{
    $arrTreeById[$arrItem['id']] = $arrItem;
}

foreach($arrTreeById AS &$arrItem)
{
    if (isset($arrTreeById[$arrItem['id_parent']]))
    {
        $arrTreeById[$arrItem['id_parent']]['arrChilds'][] = &$arrItem;
    }
    if ($arrItem['id_parent'] == 0) $intStartingKey = $arrItem['id'];
}

print_r($arrTreeById[$intStartingKey]);


问:
Unable to join to domain hosted on Azure VM
So I've created a VM Win Server 2016 on Azure. I've created a VPN connection between Azure VM (Which is AD DC) and a test windows machine. I can ping AD IP (but not domain, only IP), RDP into machine etc.. however when I try to join domain it's not recognized. So it's probably DNS issue on Azure but I've been unable to resolve it? What to do? How to proceed? The idea is to be able to connect remote machines via Point to Site VPN to AD DC on Azure.
Thanks</p>

答: You need to have your DC listed as a DNS server if you are doing AD integrated DNS Or have a public record so that the Azure DNS servers can advertise it. Make sure you have done the step - Reset the DNS server for the Azure virtual network. You can also refer to http://msdn.microsoft.com/en-us/library/azure/jj156090.aspx for guidance and http://azure.microsoft.com/en-us/documentation/articles/virtual-networks-install-replica-active-directory-domain-controller/ for steps.</p>


问:
Catch MySQL error when record does not exist in NodeJS
I am trying to figure out how I can catch an error when a requested id is not found in the Database records.

My code is:

```<code>router.get('/users/:id', function(req, res) {

    getId = req.params.id

    db.con.query('SELECT * FROM employees where id=?', getId, function(err, results) {

       if (err) {
            console.log('error in query')
            return

        } else {
            obj = {
                id: results[0].id,
                name: results[0].name,
                location: results[0].location
                // error should be cached here when a requested results[0].id is not found
            }
            res.render('showuser');
        }
    })

});
</code>```

In the console, I get the following error when a non-existed id is requested as it should be, however I cannot catch this error programmatically.

```<code>throw err; // Rethrow non-MySQL errors
^
ReferenceError: id is not defined
at Query._callback (C:\NodeJS\CRUD\CRUD-4\routes\add.js:21:13)
</code>```

Node: v8.8.0

Express: v4.15.5

答:
```<code>// Error handler
app.use(function(err, req, res, next) {
  res.status(500).end(err.message);
});
...
router.get('/users/:id(\\d+)', function(req, res, next) {
    var id = req.params.id;

    db.con.query('SELECT * FROM employees where id= ?', id, function (err, results) {
       if (err)
          return next(err);

       if (results.length == 0)
          return next(new Error('Incorrect id: ' + id));

        obj = {
            id: results[0].id,
            name: results[0].name,
            location: results[0].location
        }
        res.render('showuser', obj);
    });
})
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am trying to figure out how I can catch an error when a requested id is not found in the Database records.

My code is:

router.get('/users/:id', function(req, res) {

    getId = req.params.id

    db.con.query('SELECT * FROM employees where id=?', getId, function(err, results) {

       if (err) {
            console.log('error in query')
            return

        } else {
            obj = {
                id: results[0].id,
                name: results[0].name,
                location: results[0].location
                // error should be cached here when a requested results[0].id is not found
            }
            res.render('showuser');
        }
    })

});

In the console, I get the following error when a non-existed id is requested as it should be, however I cannot catch this error programmatically.

throw err; // Rethrow non-MySQL errors
^
ReferenceError: id is not defined
at Query._callback (C:\NodeJS\CRUD\CRUD-4\routes\add.js:21:13)

Node: v8.8.0

Express: v4.15.5


问:
How to create dataflow pipeline from JSON file on cloud storage to datastore
Im new to GCP and needed some help on the following:
I have a .json file uploaded to cloud storage and need to move the data into cloud datastore for parsing/queries.

I think a large dataset may take too long to import natively, so was interesting in using dataflow to transform and load.
Any ideas or help would be much appreciated.

答:
This is a fairly straightforward problem.  You'll need to:

Review the basics of writing dataflow pipelines here:
https://beam.apache.org/documentation/pipelines/design-your-pipeline/

Read from GCS:
https://beam.apache.org/documentation/sdks/javadoc/0.2.0-incubating/org/apache/beam/sdk/io/TextIO.html

Transform JSON to entities:
https://cloud.google.com/dataflow/java-sdk/JavaDoc/com/google/cloud/dataflow/sdk/coders/TableRowJsonCoder
(or similar)

Write to Datastore
https://github.com/apache/beam/tree/master/sdks/java/io/google-cloud-platform/src/main/java/org/apache/beam/sdk/io/gcp/datastore

Hope this helps!


问:
Checkbox to select various months
Within a userform, I'm coding a checkbox to select multiple other checkboxes (months). This is to enable the user to select all 12 months rather than clicking through each of them. Following is the code I've written. What have I done wrong now?</p>

```<code>Private Sub Selectbox_AfterUpdate()
Dim x As Integer

If Me.Selectbox.Value = True Then
For x = 0 To 12
Me.Controls("Month" & x).Value = True
Next x
Me.Selectbox.Caption = "Deselect All"

ElseIf Me.Selectbox.Value = False Then
For x = 0 To 12
Me.Controls("Month" & x).Value = False

Next x
Me.Selectbox.Caption = "Select All"

End If

End Sub
</code>```

答:
Don't check against True or False, check against vbChecked or vbUnchecked.  You also have 1 too many iterations on your loop.  Your code would look like this:</p>

```<code>Private Sub Selectbox_AfterUpdate()
   Dim x As Integer

   If Me.Selectbox.Value = vbChecked Then
      For x = 1 To 12
         Me.Controls("Month" & x).Value = vbChecked
      Next x

      Me.Selectbox.Caption = "Deselect All"
   ElseIf Me.Selectbox.Value = vbUnchecked Then
      For x = 1 To 12
         Me.Controls("Month" & x).Value = vbUnchecked
      Next x

      Me.Selectbox.Caption = "Select All"
   End If
End Sub
</code>```

Title: Checkbox to select various months

Body:
Within a userform, I'm coding a checkbox to select multiple other checkboxes (months). This is to enable the user to select all 12 months rather than clicking through each of them. Following is the code I've written. What have I done wrong now?

Private Sub Selectbox_AfterUpdate()
Dim x As Integer

If Me.Selectbox.Value = True Then
For x = 0 To 12
Me.Controls("Month" & x).Value = True
Next x
Me.Selectbox.Caption = "Deselect All"

ElseIf Me.Selectbox.Value = False Then
For x = 0 To 12
Me.Controls("Month" & x).Value = False

Next x
Me.Selectbox.Caption = "Select All"

End If

End Sub

Body:
Don't check against True or False, check against vbChecked or vbUnchecked.  You also have 1 too many iterations on your loop.  Your code would look like this:

Private Sub Selectbox_AfterUpdate()
   Dim x As Integer

   If Me.Selectbox.Value = vbChecked Then
      For x = 1 To 12
         Me.Controls("Month" & x).Value = vbChecked
      Next x

      Me.Selectbox.Caption = "Deselect All"
   ElseIf Me.Selectbox.Value = vbUnchecked Then
      For x = 1 To 12
         Me.Controls("Month" & x).Value = vbUnchecked
      Next x

      Me.Selectbox.Caption = "Select All"
   End If
End Sub


问:
NetSuite external form
I need to present a form to customers to allow interaction with regard to back orders ... Cancel, wait, fill or Add to, etc. What facility does NetSuite offer for things like online forms or Suitelets and if so, do I need a site external to NetSuite? </p>

<p>thanks in advance for any help </p>

答:
Customer Center is included in Netsuite. It is possible to inject links to Suitelets into this to provide any missing functionality.

The devil is in the details though in terms of achieving any particular level of functionality and design.

External customer forms are meant as marketing tools.

Title: NetSuite external form

Body:
I need to present a form to customers to allow interaction with regard to back orders ... Cancel, wait, fill or Add to, etc. What facility does NetSuite offer for things like online forms or Suitelets and if so, do I need a site external to NetSuite?

thanks in advance for any help


问:
How to detect the presence of a default recording device in the system?
How do I detect if the system has a default recording device installed?
I bet this can be done through some calls to the Win32 API, anyone has any experience with this?

I'm talking about doing this through code, not by opening the control panel and taking a look under sound options.

答: The win32 api has a function called waveInGetNumDevs for it.</p>

OwnerDisplayName: Rotem

OwnerDisplayName: Lars Truijens


问:
How to use joptimizer for linear programming
I am working on solving a linear programming problem using joptimizer.

My problem is:

```<code>Maximize (x1*f1 + x2*f2 + x3*f3)

such that (x1*v1 + x2*v2 + x3*v3) <= h
</code>```

I need to find x1, x2 and x3.

I do not know how to create a joptimizer input from the above equation.

答:
Maybe you would like to have a look at the following sample code too.

Don't forget to import the dependecies from http://www.joptimizer.com/downloadWithAdd.html.

You should download and import external three jar files ( /joptimizer-4.0.0.jar, /joptimizer-4.0.0-dependencies.zip, /joptimizer-4.0.0-sources.jar) into your project manually. The .zip file demands unzipping too.

```<code>import java.util.Arrays;
import com.joptimizer.optimizers.*;

public class LCLP {
    // min (x) for J = C'*X;
    // s.t.
    // A*X = b;
    // X <= 0;
    // X = [x1;x2;x3;...xN]
    public static void main(String[] args) throws Exception {

        // Example from http://www.joptimizer.com/linearProgramming.html

        //Objective function
        double[] c = new double[] { -1., -1. };
        //Inequalities constraints
        double[][] G = new double[][] {{4./3., -1}, {-1./2., 1.}, {-2., -1.}, {1./3., 1.}};
        double[] h = new double[] {2., 1./2., 2., 1./2.};
        //Bounds on variables
        double[] lb = new double[] {0 , 0};
        double[] ub = new double[] {10, 10};
        //optimization problem
        LPOptimizationRequest or = new LPOptimizationRequest();
        or.setC(c);
        or.setG(G);
        or.setH(h);
        or.setLb(lb);
        or.setUb(ub);
        or.setDumpProblem(true);
        //optimization
        LPPrimalDualMethod opt = new LPPrimalDualMethod();
        opt.setLPOptimizationRequest(or);
        opt.optimize();
        double[] sol = opt.getOptimizationResponse().getSolution();
        System.out.println("Solution = " + Arrays.toString(sol));
    }
}
</code>```

Body:
I am working on solving a linear programming problem using joptimizer.

My problem is:

Maximize (x1*f1 + x2*f2 + x3*f3)

such that (x1*v1 + x2*v2 + x3*v3) <= h

I need to find x1, x2 and x3.

I do not know how to create a joptimizer input from the above equation.

Body:
Maybe you would like to have a look at the following sample code too.

Don't forget to import the dependecies from http://www.joptimizer.com/downloadWithAdd.html.

You should download and import external three jar files ( /joptimizer-4.0.0.jar, /joptimizer-4.0.0-dependencies.zip, /joptimizer-4.0.0-sources.jar) into your project manually. The .zip file demands unzipping too.

import java.util.Arrays;
import com.joptimizer.optimizers.*;

public class LCLP {
    // min (x) for J = C'*X;
    // s.t.
    // A*X = b;
    // X <= 0;
    // X = [x1;x2;x3;...xN]
    public static void main(String[] args) throws Exception {

        // Example from http://www.joptimizer.com/linearProgramming.html

        //Objective function
        double[] c = new double[] { -1., -1. };
        //Inequalities constraints
        double[][] G = new double[][] {{4./3., -1}, {-1./2., 1.}, {-2., -1.}, {1./3., 1.}};
        double[] h = new double[] {2., 1./2., 2., 1./2.};
        //Bounds on variables
        double[] lb = new double[] {0 , 0};
        double[] ub = new double[] {10, 10};
        //optimization problem
        LPOptimizationRequest or = new LPOptimizationRequest();
        or.setC(c);
        or.setG(G);
        or.setH(h);
        or.setLb(lb);
        or.setUb(ub);
        or.setDumpProblem(true);
        //optimization
        LPPrimalDualMethod opt = new LPPrimalDualMethod();
        opt.setLPOptimizationRequest(or);
        opt.optimize();
        double[] sol = opt.getOptimizationResponse().getSolution();
        System.out.println("Solution = " + Arrays.toString(sol));
    }
}


问:
gradle could not find other gradle script
```<code>/--common
/--common/build.gradle
/--common/deploy.gradle
/--project1
/--project1/build.gradle
</code>```

I have a multi-project structure and have extracted repeating code from my build.gradle file and placed this into another file deploy.gradle.

I have placed the deploy.gradle file into the common project at the same folder level as the build.gradle file. The folder structure is shown above.

In the build.gradle file of the common project I can reference the file using the statement,

```<code>apply from: 'deploy.gradle'
</code>```

This works like a dream and the common project build works perfectly calling in the tasks from the deploy.gradle file.

The problem comes when I try to reference deploy.gradle file from one of the other projects. When I add the apply... statement to the build.gradle of  project1 I get the compilation error,

Error:(23, 0) Could not read script
  'C:\path-to-project1-script-file\deploy.gradle' as it does not exist.

So Gradle is looking for the deploy.gradle file in project1 only even though I have a dependency set to the common project in the project1 build.gradle file.

Question is how can I make deploy.gradle from common project visible to project1.

答:
Here is an example project1/build.gradle that references common/deploy.gradle:

```<code>// import myDeploy task
apply from: "${rootDir}/common/deploy.gradle"

task myProject1Task(dependsOn: 'myDeploy') {
    doLast {
        println 'TRACER myProject1Task'
    }
}
</code>```

It is often important to distinguish projectDir from rootDir in multi-project builds. projectDir is the specific subproject; rootDir is where settings.gradle lives.

Body:
/--common
/--common/build.gradle
/--common/deploy.gradle
/--project1
/--project1/build.gradle

I have a multi-project structure and have extracted repeating code from my build.gradle file and placed this into another file deploy.gradle.

I have placed the deploy.gradle file into the common project at the same folder level as the build.gradle file. The folder structure is shown above.

In the build.gradle file of the common project I can reference the file using the statement,

apply from: 'deploy.gradle'

This works like a dream and the common project build works perfectly calling in the tasks from the deploy.gradle file.

The problem comes when I try to reference deploy.gradle file from one of the other projects. When I add the apply... statement to the build.gradle of  project1 I get the compilation error,

Error:(23, 0) Could not read script
  'C:\path-to-project1-script-file\deploy.gradle' as it does not exist.

So Gradle is looking for the deploy.gradle file in project1 only even though I have a dependency set to the common project in the project1 build.gradle file.

Question is how can I make deploy.gradle from common project visible to project1.

Body:
Here is an example project1/build.gradle that references common/deploy.gradle:

// import myDeploy task
apply from: "${rootDir}/common/deploy.gradle"

task myProject1Task(dependsOn: 'myDeploy') {
    doLast {
        println 'TRACER myProject1Task'
    }
}

It is often important to distinguish projectDir from rootDir in multi-project builds. projectDir is the specific subproject; rootDir is where settings.gradle lives.


问:
Dialogflow, How to url encode json as part of the text param?
Im trying to create a script, either by Python or PHP, that can receive JSON from Dialogflow webhooks.

The data value will be from resolvedQuery.

I want to parse the data then send to the below URL:

```<code>https://joinjoaomgcd.appspot.com/_ah/api/messaging/v1/sendPush?text=***JSON GOES HERE ***&deviceId=18c972b753ad&apikey=5b48aed7
</code>```

The data from resolvedQuery needs to be sent to the about URL where *JSON GOES HERE * is.

Here is the Python code I have been trying:

```<code>from flask import Flask
from flask import request
from flask import make_response
import json
import logging as l
import requests

app = Flask(__name__)

@app.route('/')
def hello():
    """Return a friendly HTTP greeting."""
    l.info("reached the hello() module...")

    return 'Hello  Beautiful World!\n'

@app.route('/apiai', methods=['POST'])
def apiai_response():

requests_session = requests.session()
requests_session.headers.update({'Content-Type': 'application/json'})
requests_session.headers.update({'charset':'utf-8'})

post_data = '[{ "resolvedQuery": "" }]'

requests_response = requests_session.post(url="https://joinjoaomgcd.appspot.com/_ah/api/messaging/v1/sendPush?text=***JSON GOES HERE ***&deviceId=18c972b753ad&apikey=5b48aed7", data=post_data)

print requests_response.content

@app.errorhandler(404)
def page_not_found(e):
    """Return a custom 404 error."""
    return 'Sorry, nothing at this URL.', 404
</code>```

答:
I would try something like this:

```<code>import json
import requests

json_string = json.dumps({"hello": "world"})
these_params = {"text": json_string,
                "deviceId": "18c972b753ad&apikey=5b48aed7"}
this_url = "https://joinjoaomgcd.appspot.com/_ah/api/messaging/v1/sendPush"

r.get(url=this_url, params=these_params)
</code>```

notice it is a get request and not a post request

It is a matter of opinion however using url encoded params on a GET request differ in how stuff gets read. As far as the data field is concerned on a post request, the handling is a bit different.

On a get request it will look something like part of the url as :

```<code>text=%7B%22hello%22%3A%22world%22%7D
</code>```

Where as a post request the server will try to read in a application/json encoded body which expects the "data" to be valid json text.

also note:

How to urlencode a querystring in Python?

Body:
Im trying to create a script, either by Python or PHP, that can receive JSON from Dialogflow webhooks.

The data value will be from resolvedQuery.

I want to parse the data then send to the below URL:

https://joinjoaomgcd.appspot.com/_ah/api/messaging/v1/sendPush?text=***JSON GOES HERE ***&deviceId=18c972b753ad&apikey=5b48aed7

The data from resolvedQuery needs to be sent to the about URL where *JSON GOES HERE * is.

Here is the Python code I have been trying:

from flask import Flask
from flask import request
from flask import make_response
import json
import logging as l
import requests

app = Flask(__name__)

@app.route('/')
def hello():
    """Return a friendly HTTP greeting."""
    l.info("reached the hello() module...")

    return 'Hello  Beautiful World!\n'

@app.route('/apiai', methods=['POST'])
def apiai_response():

requests_session = requests.session()
requests_session.headers.update({'Content-Type': 'application/json'})
requests_session.headers.update({'charset':'utf-8'})

post_data = '[{ "resolvedQuery": "" }]'

requests_response = requests_session.post(url="https://joinjoaomgcd.appspot.com/_ah/api/messaging/v1/sendPush?text=***JSON GOES HERE ***&deviceId=18c972b753ad&apikey=5b48aed7", data=post_data)

print requests_response.content

@app.errorhandler(404)
def page_not_found(e):
    """Return a custom 404 error."""
    return 'Sorry, nothing at this URL.', 404

Body:
I would try something like this:

import json
import requests

json_string = json.dumps({"hello": "world"})
these_params = {"text": json_string,
                "deviceId": "18c972b753ad&apikey=5b48aed7"}
this_url = "https://joinjoaomgcd.appspot.com/_ah/api/messaging/v1/sendPush"

r.get(url=this_url, params=these_params)

notice it is a get request and not a post request

It is a matter of opinion however using url encoded params on a GET request differ in how stuff gets read. As far as the data field is concerned on a post request, the handling is a bit different.

On a get request it will look something like part of the url as :

text=%7B%22hello%22%3A%22world%22%7D

Where as a post request the server will try to read in a application/json encoded body which expects the "data" to be valid json text.

also note:

How to urlencode a querystring in Python?


问:
Ipad bug: automatic switching of keyboard mode
I am not able solve a strange bug in my iPad game, "Sometimes keyboard switches automatically
from alphabet characters to numeric characters while entering numbers on it".

Also please note that I am only allowing  numeric input by using - (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string. I have not done anything else to switch keyboard mode.

Any idea?

答:
Use the "keyboardType" property of the UITextField.</p>

```<code>myTextField.keyboardType = UIKeyboardTypeNumberPad;
</code>```

Body:
Use the "keyboardType" property of the UITextField.

myTextField.keyboardType = UIKeyboardTypeNumberPad;