问:
Link within a text in another column php
I am trying to create a link within a text, I have 2 columns in my table (updates1) and (link1) updates 1 contains a text while link 1 contains a link. The problem is whenever im trying to call it the data or the link itself is being an output besides the text. I need it to be stored inside the text.</p>

```<code> echo "<b><h4>{$list["updates1"]}<a>{$list["link1"]}</a></b></h4><hr>";
</code>```

答:
you can also try it using "\"</p>

```<code>echo "<b><h4><a href=\"{$list['link1']}\"> {$list['updates1']}</a></h4></b><hr>";
</code>```

Body:
I am trying to create a link within a text, I have 2 columns in my table (updates1) and (link1) updates 1 contains a text while link 1 contains a link. The problem is whenever im trying to call it the data or the link itself is being an output besides the text. I need it to be stored inside the text.

 echo "
{$list["updates1"]}{$list["link1"]}

";

Body:
you can also try it using "\"

echo "<b><h4><a href=\"{$list['link1']}\"> {$list['updates1']}</a></h4></b><hr>";


来源: stackexchange

问:
How can I read/write a value in a shared memory using two programs(one in C and the other in C#)
Can someone help me with some info and some code example if it's possible?
I need to read/write a value in a shared memory using two programs(one in C and the other in C#). I have to use a buffer in which I write the value. Also that buffer is a struct.

The Client should be written in C# and the server in C.

Thanks.

答:
You have 3 solutions:

You can use shared memory if two apps are running on the same computer. There are many examples on the web about using shared memory both in C# and C/C++. In C#, shared memory functions are well wrapped in .Net Framework. In C/C++ you may use windows API directly or use a library such as boost.

You may use network communication between these processes. If both apps are running on the same computer, you can use up address 127.0.0.1 (localhost) for inter-network communication without need to know ip address. For network communication, again there are many source code examples on the web both for C# and C/C++. You'd better to use TCP sockets, and use a serializer/deserializer such as json, or use your custom format for communication between these processes.

If the amount of data and the number of times these apps need to communicate with each other is very low, and the apps are running on the same computer, you can use file-based communication which is very simple, but NOT RECOMMENDED for performance issues. You can define a file on a specific path on the computer, and periodically (say 1 per second) check for file existence. When first app wants to send data to second app, first app creates that file and writes data into it. Second app becomes aware of that file existence, reads its contents and deletes the file. First app waits for the file to be deleted, and then starts for sending another data to the second app by doing the same job. The same can be applied for sending data from second app to the first app. This approach needs only use of file i/o functions!

ContentLicense: CC BY-SA 3.0


问:
how to make text over images in a row using bootstrap?
Now it is not responsive, the two images should be in one row. I want to make text like painting and photography over these images. how can it be possible?

.caption {
  position: absolute;
  top: 9%;
  left: 11px;
  width: 100%;
  color: #fff;
  font-family: Myriad Pro regular;
  font-size: 15.31px;
}

.caption1 {
  position: absolute;
  top: -51px;
  left: 11px;
  width: 100%;
  color: #fff;
  font-family: Myriad Pro regular;
  font-size: 15.31px;
}

.imageandtext {
  position: relative;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="grid-two imageandtext">
  <figure>

    <img src="http://lorempixel.com/300/300/" class="img-thumbnail">
    <div class="caption">
      <p>Painting</p>
    </div>
    <div class="imageandtext image_grid">
      <img src="http://lorempixel.com/300/300/?r" class="img-thumbnail">
      <div class="caption1">
        <p>Photography</p>
      </div>
    </div>
  </figure>
</div></code>```

答:
You need to cover your image and caption  text in a relative element

```<code>figure{
    position: relative;
}
</code>```

Check the below snippet -

figure{
 position: relative;
}
.caption {
  position: absolute;
  top: 10px;
  left: 11px;
  width: 100%;
  color: #fff;
  font-family: Myriad Pro regular;
  font-size: 15.31px;
}

.caption1 {
  position: absolute;
  top: 10px;
  left: 11px;
  width: 100%;
  color: #fff;
  font-family: Myriad Pro regular;
  font-size: 15.31px;
}

.imageandtext {
  position: relative;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="grid-two imageandtext">
   <figure>
     <img src="http://res.cloudinary.com/demo/image/upload/w_200,h_200,c_crop,g_center/fat_cat.jpg" class="img-thumbnail">
     <div class="caption">
       <p>Painting</p>
     </div>
    </figure>
    <figure>
     <div class="imageandtext image_grid">
       <img src="http://res.cloudinary.com/demo/image/upload/w_200,h_200,c_crop,g_center/fat_cat.jpg" class="img-thumbnail">
       <div class="caption1">
         <p>Photography</p>
       </div>
     </div>
   </figure>
</div></code>```

Body:
Now it is not responsive, the two images should be in one row. I want to make text like painting and photography over these images. how can it be possible?

.caption {
  position: absolute;
  top: 9%;
  left: 11px;
  width: 100%;
  color: #fff;
  font-family: Myriad Pro regular;
  font-size: 15.31px;
}

.caption1 {
  position: absolute;
  top: -51px;
  left: 11px;
  width: 100%;
  color: #fff;
  font-family: Myriad Pro regular;
  font-size: 15.31px;
}

.imageandtext {
  position: relative;
}

Painting

Photography

Body:
You need to cover your image and caption  text in a relative element

figure{
    position: relative;
}

Check the below snippet -

figure{
 position: relative;
}
.caption {
  position: absolute;
  top: 10px;
  left: 11px;
  width: 100%;
  color: #fff;
  font-family: Myriad Pro regular;
  font-size: 15.31px;
}

.caption1 {
  position: absolute;
  top: 10px;
  left: 11px;
  width: 100%;
  color: #fff;
  font-family: Myriad Pro regular;
  font-size: 15.31px;
}

.imageandtext {
  position: relative;
}

<div class="grid-two imageandtext">
   <figure>
     <img src="http://res.cloudinary.com/demo/image/upload/w_200,h_200,c_crop,g_center/fat_cat.jpg" class="img-thumbnail">
     <div class="caption">
       <p>Painting</p>
     </div>
    </figure>
    <figure>
     <div class="imageandtext image_grid">
       <img src="http://res.cloudinary.com/demo/image/upload/w_200,h_200,c_crop,g_center/fat_cat.jpg" class="img-thumbnail">
       <div class="caption1">
         <p>Photography</p>
       </div>
     </div>
   </figure>
</div>


问:
Pushing keys to an array or javascript object?
I need to create an array or js object with specific keys, which should be pushed to an empty array or js object. After that, I need to push some specific values according to that keys, something like this:

```<code>var arr = ["john":["jval1","jval2"], "matt":["mval1","mval2","mval3"]]
</code>```

I know that's not the rigt notation for a js object or an array, but that's the idea.

This is basically what I'm trying to do:

```<code>var keys = ["john","matt"];             //my keys
var jvals = ["jval1","jval2"];          //my values for key john
var mvals = ["mval1","mval2","mval3"];  //my values for key matt

var arr = [];

for(var i in keys) arr.push(keys[i])  //pushing the names (I need to push this names as keys so next lines should work)

for(var i in jvals) arr["john"].push(jvals[i])  //Trying to push john values, which doesn't work because "john is not a key"
for(var i in mvals) arr["matt"].push(mvals[i])  //Same.
</code>```

This doesn't work at all, so how should I do this?

答:
Is this you wanted?

Declare arr as object and add keys with empty array.and then push to your keys.

var keys = ["john","matt"];             //my keys
var jvals = ["jval1","jval2"];          //my values for key john
var mvals = ["mval1","mval2","mval3"];  //my values for key matt

var arr = {};

for(var i in keys) arr[keys[i]]=[];

for(var i in jvals) arr["john"].push(jvals[i]);
for(var i in mvals) arr["matt"].push(mvals[i]);

console.log(arr);```

Body:
I need to create an array or js object with specific keys, which should be pushed to an empty array or js object. After that, I need to push some specific values according to that keys, something like this:

var arr = ["john":["jval1","jval2"], "matt":["mval1","mval2","mval3"]]

I know that's not the rigt notation for a js object or an array, but that's the idea.

This is basically what I'm trying to do:

var keys = ["john","matt"];             //my keys
var jvals = ["jval1","jval2"];          //my values for key john
var mvals = ["mval1","mval2","mval3"];  //my values for key matt

var arr = [];

for(var i in keys) arr.push(keys[i])  //pushing the names (I need to push this names as keys so next lines should work)

for(var i in jvals) arr["john"].push(jvals[i])  //Trying to push john values, which doesn't work because "john is not a key"
for(var i in mvals) arr["matt"].push(mvals[i])  //Same.

This doesn't work at all, so how should I do this?


问:
How can I convert a fully qualified file path to URL in Laravel
I have a complete file path (/var/www/project/public/csv/Info.csv) stored in a variable $file

How can I convert this variable into a server friendly URL. I tried to use the url($file) helper function but it returns http://127.0.0.1/var/www/soccer/public/csv/Info.csv

The expected output is: http://127.0.0.1/csv/Info.csv

One approach is to cut the string from public and pass it to url() function. Does anyone have a more eloquent approach?

答:
You can try explode and use asset like this </p>

```<code>$file = '/var/www/project/public/csv/Info.csv';
$file = explode('/public/', $file);
echo asset($file[1]);
 Or Manually prepare path
echo config('app.url') . $file[1];

Both ways you can get excepted output http://127.0.0.1/csv/Info.csv
</code>```

Body:
You can try explode and use asset like this

$file = '/var/www/project/public/csv/Info.csv';
$file = explode('/public/', $file);
echo asset($file[1]);
 Or Manually prepare path
echo config('app.url') . $file[1];

Both ways you can get excepted output http://127.0.0.1/csv/Info.csv


问:
Get file url schema
How do I show the user a previously uploaded file that is stored on the website's server (I am aware uploaded files should be stored on a different server) when I know the path? To explain; below in my code I have created a button inside an  element and I am trying to get it to display the relevant file to the user by putting the relevant url in the  element shows the user the file they need to see. </p>

```<code><!DOCTYPE html>
<html>

<head>
   <meta charset="utf-8">
    <title>Total </title>
      <link type="text/css" rel="stylesheet" href="course.css">
       <script src="../jquery.js"></script>
        <script src="../jquery-ui.js"></script>

</head>
<body>

<?php
    if ($handle = opendir('../uploads'))
    {
      while (false !== ($entry = readdir($handle)))
     {

      if ($entry != "." && $entry != "..")
      {

          $real=realpath("../uploads/".$entry);

            echo  "<button class='files accordian'>$entry $real</button>
                     <div class='panel'>
                        <p>$real</p>";
            echo '<a href="WHAT WOULD GO IN HERE?"><button class="current-file" name="sent" value="View-Current-File"><img class="view-file-img" src="../images/magnify.png">View Current File</button></a>';
      }

    }
 }

 ?>

</body>
</html>
</code>```

答:
I think this should be enough for you,</p>

```<code>echo '<a href="../uploads/'.$entry.'">
        <button class="current-file" name="sent" value="View-Current-File">
           <img class="view-file-img" src="../images/magnify.png">View Current File
        </button>
      </a>';
</code>```

Title: Get file url schema

Body:
How do I show the user a previously uploaded file that is stored on the website's server (I am aware uploaded files should be stored on a different server) when I know the path? To explain; below in my code I have created a button inside an  element and I am trying to get it to display the relevant file to the user by putting the relevant url in the  element shows the user the file they need to see.

<!DOCTYPE html>

   <meta charset="utf-8">
    <title>Total </title>
      <link type="text/css" rel="stylesheet" href="course.css">

<?php
    if ($handle = opendir('../uploads'))
    {
      while (false !== ($entry = readdir($handle)))
     {

      if ($entry != "." && $entry != "..")
      {

          $real=realpath("../uploads/".$entry);

            echo  "<button class='files accordian'>$entry $real</button>

$real
";
            echo '<button class="current-file" name="sent" value="View-Current-File">View Current File</button>';
      }

    }
 }

 ?>

Body:
I think this should be enough for you,

echo '<a href="../uploads/'.$entry.'">
        <button class="current-file" name="sent" value="View-Current-File">
           <img class="view-file-img" src="../images/magnify.png">View Current File
        </button>
      </a>';


问:
Outlook using python win32com to iterate subfolders
I have the following code which gets me the inbox of my shared folder, and all of the emails inside. This code works great and will print the subject of the last email.

```<code>outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")
recip = outlook.CreateRecipient("foo@bar.com")
inbox = outlook.GetSharedDefaultFolder(recip, 6)
messages = inbox.Items
message = messages.GetLast()
print (message.Subject)
</code>```

I can access other parent folders in foo@bar.com's mailbox (like Sent), but I can't get any subfolders of a folder within the inbox, or deeper than that. So if I want inbox\subfolder1, how do I access that? Using Outlook 2013 if that matters.
My main goal is to do:

```<code>message.Move(inbox\subfolder1)
</code>```

答:
Yeah its better to write it as the name of the folder instead of writing the folder numbers

Like my folder hierarchy is : Outlook_Mails > Inbox > Important

```<code>outlook = win32.com.client.Dispatch("Outlook.Application")
mapi = outlook.GetNamespace("MAPI")

your_folder = mapi.Folders['Outlook_Mails'].Folders['Inbox'].Folders['Important']
for message in your_folder.Items:
    print(message.Subject)
</code>```

Body:
I have the following code which gets me the inbox of my shared folder, and all of the emails inside. This code works great and will print the subject of the last email.

outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")
recip = outlook.CreateRecipient("foo@bar.com")
inbox = outlook.GetSharedDefaultFolder(recip, 6)
messages = inbox.Items
message = messages.GetLast()
print (message.Subject)

I can access other parent folders in foo@bar.com's mailbox (like Sent), but I can't get any subfolders of a folder within the inbox, or deeper than that. So if I want inbox\subfolder1, how do I access that? Using Outlook 2013 if that matters.
My main goal is to do:

message.Move(inbox\subfolder1)

Body:
Yeah its better to write it as the name of the folder instead of writing the folder numbers

Like my folder hierarchy is : Outlook_Mails > Inbox > Important

outlook = win32.com.client.Dispatch("Outlook.Application")
mapi = outlook.GetNamespace("MAPI")

your_folder = mapi.Folders['Outlook_Mails'].Folders['Inbox'].Folders['Important']
for message in your_folder.Items:
    print(message.Subject)


问:
How to get specific values of each field using php DOM Script ? for the below format?
I want to get the value of each field like "Delhi" , "Kolkatta".

How can i do this using php DOM Script ?

here is the source of the page to parsed.

```<code><tbody><tr>
<td>Delhi</td>
<td>66.91</td>
</tr>
<tr>
<td>Kolkata</td>
<td>69.52</td>
</tr>
<tr>
<td>Mumbai</td>
<td>78.44</td>
</tr>
<tr>
<td>Chennai</td>
<td>69.93</td>
</tr></tbody>
</code>```

答:
See question here: How do you parse and process HTML/XML in PHP?

How to use the DOM extension has been covered extensively on StackOverflow, so if you choose to use it, you can be sure most of the issues you run into can be solved by searching/browsing Stack Overflow

Here an example:

```<code>$html = <<<HTML
<tbody><tr>
<td>Delhi</td>
<td>66.91</td>
</tr>
<tr>
<td>Kolkata</td>
<td>69.52</td>
</tr>
<tr>
<td>Mumbai</td>
<td>78.44</td>
</tr>
<tr>
<td>Chennai</td>
<td>69.93</td>
</tr></tbody>
HTML;

$dom = new DOMDocument();
$dom->loadHTML($html);

$elements = $dom->getElementsByTagName('tr');
$data = [];
foreach($elements as $node) {
    $childElements = $node->getElementsByTagName('td');
    $data[$childElements->item(0)->nodeValue] = $childElements->item(1)->nodeValue;
}
</code>```

Body:
I want to get the value of each field like "Delhi" , "Kolkatta".

How can i do this using php DOM Script ?

here is the source of the page to parsed.

Delhi
66.91

Kolkata
69.52

Mumbai
78.44

Chennai
69.93

Body:
See question here: How do you parse and process HTML/XML in PHP?

How to use the DOM extension has been covered extensively on StackOverflow, so if you choose to use it, you can be sure most of the issues you run into can be solved by searching/browsing Stack Overflow

Here an example:

$html = <<<HTML
<tbody><tr>
<td>Delhi</td>
<td>66.91</td>
</tr>
<tr>
<td>Kolkata</td>
<td>69.52</td>
</tr>
<tr>
<td>Mumbai</td>
<td>78.44</td>
</tr>
<tr>
<td>Chennai</td>
<td>69.93</td>
</tr></tbody>
HTML;

$dom = new DOMDocument();
$dom->loadHTML($html);

$elements = $dom->getElementsByTagName('tr');
$data = [];
foreach($elements as $node) {
    $childElements = $node->getElementsByTagName('td');
    $data[$childElements->item(0)->nodeValue] = $childElements->item(1)->nodeValue;
}


问:
echo specific part of array in php
I'm still learning php arrays and I'm trying to echo a

```<code>array(8) { [0]=> string(9) "site_name" [1]=> string(3) "url" [2]=> string(5) "title" [3]=> string(11) "description" [4]=> string(4) "type" [5]=> string(5) "image" [6]=> string(11) "image:width" [7]=> string(12) "image:height" } NULL site_name => Playbuzzurl => http://www.playbuzz.com/jordonr10/what-modern-societal-archetype-fits-your-personalitytitle => What Modern Societal Archetype Fits Your Personality?description => It's 2017, so it's about time we update the books!type => articleimage => http://cdn.playbuzz.com/cdn/aef166e1-1574-4d57-9823-3f38f30bcfc4/810f1d3e-0a97-4797-8235-b4c988562a1c.jpgimage:width => 1600image:height => 842
</code>```

array(8) { [0]=> string(9) "site_name" [1]=> string(3) "url" [2]=>
  string(5) "title" [3]=> string(11) "description" [4]=> string(4)
  "type" [5]=> string(5) "image" [6]=> string(11) "image:width" [7]=>
  string(12) "image:height" } NULL site_name => Playbuzzurl =>
  http://www.playbuzz.com/jordonr10/what-modern-societal-archetype-fits-your-personalitytitle
  => What Modern Societal Archetype Fits Your Personality?description => It's 2017, so it's about time we update the books!type => articleimage
  => http://cdn.playbuzz.com/cdn/aef166e1-1574-4d57-9823-3f38f30bcfc4/810f1d3e-0a97-4797-8235-b4c988562a1c.jpgimage:width => 1600image:height => 842

I'm trying to echo just the value for description which is It's 2017, so it's about time we update the books!

I've tried several different things, but nothing works. Any help is greatly appreciated.

```<code>echo $array[0]['description'];      // returns nothing
var_dump($key);                     // returns string(12) "image:height"
</code>```

Current Code

```<code><?php
require_once('OpenGraph.php');

$graph = OpenGraph::fetch('http://www.playbuzz.com/jordonr10/what-modern-societal-archetype-fits-your-personality');
var_dump($graph->keys());
var_dump($graph->schema);

foreach ($graph as $key => $value) {
    echo "$key => $value<br><hr>";
}
echo "Value Below<hr>";
echo $array['description'];

?>
</code>```

答:
From your code its seems that you can directly get value of description from $graph if key is already there.
 Also you are trying to diplay $array['description'];  here I can see $array is define any where

try to

```<code> echo $graph['description']; // if $graph is array
</code>```

OR

```<code>echo $graph->description; // If its an object
</code>```

Title: echo specific part of array in php

Body:
I'm still learning php arrays and I'm trying to echo a

array(8) { [0]=> string(9) "site_name" [1]=> string(3) "url" [2]=> string(5) "title" [3]=> string(11) "description" [4]=> string(4) "type" [5]=> string(5) "image" [6]=> string(11) "image:width" [7]=> string(12) "image:height" } NULL site_name => Playbuzzurl => http://www.playbuzz.com/jordonr10/what-modern-societal-archetype-fits-your-personalitytitle => What Modern Societal Archetype Fits Your Personality?description => It's 2017, so it's about time we update the books!type => articleimage => http://cdn.playbuzz.com/cdn/aef166e1-1574-4d57-9823-3f38f30bcfc4/810f1d3e-0a97-4797-8235-b4c988562a1c.jpgimage:width => 1600image:height => 842

array(8) { [0]=> string(9) "site_name" [1]=> string(3) "url" [2]=>
  string(5) "title" [3]=> string(11) "description" [4]=> string(4)
  "type" [5]=> string(5) "image" [6]=> string(11) "image:width" [7]=>
  string(12) "image:height" } NULL site_name => Playbuzzurl =>
  http://www.playbuzz.com/jordonr10/what-modern-societal-archetype-fits-your-personalitytitle
  => What Modern Societal Archetype Fits Your Personality?description => It's 2017, so it's about time we update the books!type => articleimage
  => http://cdn.playbuzz.com/cdn/aef166e1-1574-4d57-9823-3f38f30bcfc4/810f1d3e-0a97-4797-8235-b4c988562a1c.jpgimage:width => 1600image:height => 842

I'm trying to echo just the value for description which is It's 2017, so it's about time we update the books!

I've tried several different things, but nothing works. Any help is greatly appreciated.

echo $array[0]['description'];      // returns nothing
var_dump($key);                     // returns string(12) "image:height"

Current Code

<?php
require_once('OpenGraph.php');

$graph = OpenGraph::fetch('http://www.playbuzz.com/jordonr10/what-modern-societal-archetype-fits-your-personality');
var_dump($graph->keys());
var_dump($graph->schema);

foreach ($graph as $key => $value) {
    echo "$key => $value

";
}
echo "Value Below
";
echo $array['description'];

?>

Body:
From your code its seems that you can directly get value of description from $graph if key is already there.
 Also you are trying to diplay $array['description'];  here I can see $array is define any where

try to

 echo $graph['description']; // if $graph is array

OR

echo $graph->description; // If its an object


问:
UDAF merge rows where are first orderdby in a Spark DataSet/Dataframe
Let's say we have a dataset/dataframe in Spark where has 3 columns
ID, Word, Timestamp

I want to write a UDAF function where I can do something like this

```<code>df.show()

ID | Word | Timestamp
1  | I    | "2017-1-1 00:01"
1  | am   | "2017-1-1 00:02"
1  | Chris | "2017-1-1 00:03"
2  | I    | "2017-1-1 00:01"
2  | am   | "2017-1-1 00:02"
2  | Jessica | "2017-1-1 00:03"

val df_merged = df.groupBy("ID")
  .sort("ID", "Timestamp")
  .agg(custom_agg("ID", "Word", "Timestamp")

df_merged.show

ID | Words         | StartTime        |      EndTime     |
1  | "I am Chris"  | "2017-1-1 00:01" | "2017-1-1 00:03" |
1  | "I am Jessica"  | "2017-1-1 00:01" | "2017-1-1 00:03" |
</code>```

The question is how can ensure that the column Words will be merged in the right order inside my UDAF?

答:
Here is a sollution with Spark 2's groupByKey (used with an untyped Dataset).The advantage of groupByKey is that you have access to the group (you get an Iterator[Row] in mapGroups):

```<code> df.groupByKey(r => r.getAs[Int]("ID"))
      .mapGroups{case(id,rows) => {
        val sorted = rows
          .toVector
          .map(r => (r.getAs[String]("Word"),r.getAs[java.sql.Timestamp]("Timestamp")))
          .sortBy(_._2.getTime)

        (id,
         sorted.map(_._1).mkString(" "),
         sorted.map(_._2).head,
         sorted.map(_._2).last
         )
        }
      }.toDF("ID","Words","StartTime","EndTime")
</code>```

Body:
Let's say we have a dataset/dataframe in Spark where has 3 columns
ID, Word, Timestamp

I want to write a UDAF function where I can do something like this

df.show()

ID | Word | Timestamp
1  | I    | "2017-1-1 00:01"
1  | am   | "2017-1-1 00:02"
1  | Chris | "2017-1-1 00:03"
2  | I    | "2017-1-1 00:01"
2  | am   | "2017-1-1 00:02"
2  | Jessica | "2017-1-1 00:03"

val df_merged = df.groupBy("ID")
  .sort("ID", "Timestamp")
  .agg(custom_agg("ID", "Word", "Timestamp")

df_merged.show

ID | Words         | StartTime        |      EndTime     |
1  | "I am Chris"  | "2017-1-1 00:01" | "2017-1-1 00:03" |
1  | "I am Jessica"  | "2017-1-1 00:01" | "2017-1-1 00:03" |

The question is how can ensure that the column Words will be merged in the right order inside my UDAF?

Body:
Here is a sollution with Spark 2's groupByKey (used with an untyped Dataset).The advantage of groupByKey is that you have access to the group (you get an Iterator[Row] in mapGroups):

 df.groupByKey(r => r.getAs[Int]("ID"))
      .mapGroups{case(id,rows) => {
        val sorted = rows
          .toVector
          .map(r => (r.getAs[String]("Word"),r.getAs[java.sql.Timestamp]("Timestamp")))
          .sortBy(_._2.getTime)

        (id,
         sorted.map(_._1).mkString(" "),
         sorted.map(_._2).head,
         sorted.map(_._2).last
         )
        }
      }.toDF("ID","Words","StartTime","EndTime")


问:
Listening to dynamically created toggle button in android
Hello all I am implementing a control board with dynamically created toggle buttons where the number of toggle buttons is also dynamic, I am having a hard time appending a function to the dynamically created buttons, </p>

```<code> for (int i = 0; i < len; i++) {
 ToggleButton tb[i] = new ToggleButton(this);
            LinearLayout.LayoutParams tbparams = new LinearLayout.LayoutParams
                    (90, LinearLayout.LayoutParams.WRAP_CONTENT);
            tbparams.setMargins(120, 0, 0, 0);
            tb[i].setBackgroundResource(R.drawable.bgtoggle);
            tb[i].setId(i+1);
            tb[i].setText("toggle_btn"+i+1);
            tb[i].setPadding(4, 4, 4, 4);
            tb[i].setLayoutParams(tbparams);
}
</code>```

答:
Implement a CheckedChangeListener as:

```<code>    OnCheckedChangeListener listener = new
    CompoundButton.OnCheckedChangeListener(){
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        if (isChecked) {
            // The toggle is enabled
        } else {
            // The toggle is disabled
        }
}
</code>```

and set it as:

```<code>tb.setOnCheckedChangeListener(listener);
</code>```

You can retrieve the id of the toggled button by invoking buttonView.getId() in onCheckedChanged method and do specific task based on Id.

Body:
Hello all I am implementing a control board with dynamically created toggle buttons where the number of toggle buttons is also dynamic, I am having a hard time appending a function to the dynamically created buttons,

 for (int i = 0; i < len; i++) {
 ToggleButton tb[i] = new ToggleButton(this);
            LinearLayout.LayoutParams tbparams = new LinearLayout.LayoutParams
                    (90, LinearLayout.LayoutParams.WRAP_CONTENT);
            tbparams.setMargins(120, 0, 0, 0);
            tb[i].setBackgroundResource(R.drawable.bgtoggle);
            tb[i].setId(i+1);
            tb[i].setText("toggle_btn"+i+1);
            tb[i].setPadding(4, 4, 4, 4);
            tb[i].setLayoutParams(tbparams);
}

Body:
Implement a CheckedChangeListener as:

    OnCheckedChangeListener listener = new
    CompoundButton.OnCheckedChangeListener(){
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        if (isChecked) {
            // The toggle is enabled
        } else {
            // The toggle is disabled
        }
}

and set it as:

tb.setOnCheckedChangeListener(listener);

You can retrieve the id of the toggled button by invoking buttonView.getId() in onCheckedChanged method and do specific task based on Id.


问:
classwork - shellsort in c#?
i need an easy way to sort an array using ShellSort in c#, please help me</p>

答:
Nobody is going to write your code for you. You're there to learn. I'd take the following steps:

Go to Wikipedia's Shell Sort Page

Find the psuedocode for the algorithm. Read it until you understand what it does.

Port the psuedocode to C#.

If you have a problem during implementation feel free to come back and ask specific questions.

ContentLicense: CC BY-SA 2.5

Title: classwork - shellsort in c#?


问:
Role does not exist and unable to create database when using PostgreSQL
I am using Heroku for my application and it requires PostgreSQL but you can still use SQLite3 for development. Since Heroku strongly advised against having 2 different databases I decided to change to PostgreSQL for development. I installed the gem pg and also went to the official PostgreSQL site to get the Windows installer and also changed my database.yml. During installation it requires a password for PostgreSQL so I made one.
I had to change the pg_hba.conf file from using md5 to trust in order get past: fe_sendauth: no password supplied when trying to create the database.

```<code># TYPE  DATABASE        USER            ADDRESS                 METHOD

# IPv4 local connections:
host    all             all             127.0.0.1/32            trust # was md5
# IPv6 local connections:
host    all             all             ::1/128                 trust # was md5
# Allow replication connections from localhost, by a user with the
# replication privilege.
#host    replication     postgres        127.0.0.1/32            trust
#host    replication     postgres        ::1/128                 trust
</code>```

After getting rid of that though, I now get this:

```<code>$ rake db:create
(in C:/app)
FATAL:  role "User" does not exist
Couldn't create database for {"adapter"=>"postgresql", "encoding"=>"utf8",
"database"=>"app_test", "pool"=>5, "username"=>nil, "password"=>nil}
</code>```

I do still have my development.sqlite3 and text.sqlite3 present, could that be the issue? What must be done?

Here is my full gist: https://gist.github.com/1522188

答:
If you have a specific account/user on your machine for postgres called postgres for example.

Then executing this command will bring a prompt for you to enter a role name.

```<code>sudo -u postgres createuser --interactive
</code>```

Then doing

```<code>rake db:create
</code>```

Should work!

Body:
I am using Heroku for my application and it requires PostgreSQL but you can still use SQLite3 for development. Since Heroku strongly advised against having 2 different databases I decided to change to PostgreSQL for development. I installed the gem pg and also went to the official PostgreSQL site to get the Windows installer and also changed my database.yml. During installation it requires a password for PostgreSQL so I made one.
I had to change the pg_hba.conf file from using md5 to trust in order get past: fe_sendauth: no password supplied when trying to create the database.

# TYPE  DATABASE        USER            ADDRESS                 METHOD

# IPv4 local connections:
host    all             all             127.0.0.1/32            trust # was md5
# IPv6 local connections:
host    all             all             ::1/128                 trust # was md5
# Allow replication connections from localhost, by a user with the
# replication privilege.
#host    replication     postgres        127.0.0.1/32            trust
#host    replication     postgres        ::1/128                 trust

After getting rid of that though, I now get this:

$ rake db:create
(in C:/app)
FATAL:  role "User" does not exist
Couldn't create database for {"adapter"=>"postgresql", "encoding"=>"utf8",
"database"=>"app_test", "pool"=>5, "username"=>nil, "password"=>nil}

I do still have my development.sqlite3 and text.sqlite3 present, could that be the issue? What must be done?

Here is my full gist: https://gist.github.com/1522188

Body:
If you have a specific account/user on your machine for postgres called postgres for example.

Then executing this command will bring a prompt for you to enter a role name.

sudo -u postgres createuser --interactive

Then doing

rake db:create

Should work!


问:
How Cassandra choose clustering key when we only specify Primary key in a table
We can specify compound primary key in cassandra. When we specify only one column as Primary key then how Cassandra will generate clustering key.
In cassandra primary key automatically becomes partition key.

Example :-
CASE 1 - K1: primary key has only one partition key and no cluster key.

CASE 2 - (K1, K2): column K1 is a partition key and column K2 is a cluster key.

CASE 3 - (K1,K2,K3,...): column K1 is a partition key and columns K2, K3 and so on make cluster key.

In Case 1 how cassandra will choose the Clustering key for a given table with only Specifying Primary Key

Thank you

答:
In case no clustering key is provided (CASE 1), then cassandra will not choose any clustering key.

How CQL3 maps to cassandra internal data structure

If you describe a table with such a primary key, you will not get WITH CLUSTERING ORDER BY option.

ContentLicense: CC BY-SA 4.0


答:
```<code>var keys = ["john","matt"];             //my keys
var jvals = ["jval1","jval2"];          //my values for key john
var mvals = ["mval1","mval2","mval3"];  //my values for key matt

var arr = {}; // not []

for(var i in keys) arr.[keys[i]] = [];  //pushing the names (I need to push this names as keys so next lines should work)

for(var i in jvals) arr["john"].push(jvals[i])  //Trying to push john values, which doesn't work because "john is not a key"
for(var i in mvals) arr["matt"].push(mvals[i])  //Same.
</code>```

Title: Pushing keys to an array or javascript object?


问:
Decode JSON where value can be a string or an array of different values
Yet another question on how to decode things with Elm...

So the problem is that I need to decode a value which can be either a string, for example

"price_unknown"

or it can be an array of 2 elements, where first one is a string and the second is a float:

["price", 50.5]

And for the eventual value I have a type:

```<code>type Something
  = PriceUnknown
  = Price Float
</code>```

into which I need to convert the value from the json response.

I tried to use a bunch of things using somewhat between the lines of:

```<code>decode MyString
  |> required "other_value" Json.Decode.string
  |> required "price" JD.oneOf [JD.string, JD.list (JD.oneOf [JD.string, JD.float])] |> JD.map mapper
</code>```

( I use json_decode_pipeline package here )

But obviously it complains about different values in the lists and whatnot so I am stuck.

Thank you in advance.

答:
You are pretty close, but all of the Decoders in oneOf have to have the same type. Also, destructuring mixed lists can be a pain. This uses elm-community/json-extra to make a manual decoding step easier.

```<code>myDecoder : Decoder SomethingElse
myDecoder =
    decode MyString
        |> required "other_value" Json.Decode.string
        |> required "price" priceDecoder

priceDecoder : Decoder Something
priceDecoder =
    JD.oneOf
        [ priceUnknownDecoder
        , priceKnownDecoder
        ]

priceUnknownDecoder : Decoder Something
priceUnknownDecoder =
    JD.string
        |> JD.andThen
            (\string ->
                if string == "price_unknown" then
                    JD.succeed PriceUnknown
                else
                    JD.fail "Invalid unknown price string."
            )

priceKnownDecoder : Decoder Something
priceKnownDecoder =
    listTupleDecoder
        JD.string
        JD.float
        |> JD.andThen
            (\(tag, price) ->
                if tag == "price" then
                    JD.succeed (Price price)
                else
                    JD.fail "Invalid tag string."
            )

listTupleDecoder : Decoder a -> Decoder b -> Decoder (a, b)
listTupleDecoder firstD secondD =
    JD.list JD.value
        |> JD.andThen
            (\values ->
                case values of
                    [first, second] ->
                        Result.map2
                            (,)
                            JD.decodeValue firstD first
                            JD.decodeValue secondD second
                            |> JD.Extra.fromResult

                    _ ->
                        JD.fail "There aren't two values in the list."
            )
</code>```

Body:
Yet another question on how to decode things with Elm...

So the problem is that I need to decode a value which can be either a string, for example

"price_unknown"

or it can be an array of 2 elements, where first one is a string and the second is a float:

["price", 50.5]

And for the eventual value I have a type:

type Something
  = PriceUnknown
  = Price Float

into which I need to convert the value from the json response.

I tried to use a bunch of things using somewhat between the lines of:

decode MyString
  |> required "other_value" Json.Decode.string
  |> required "price" JD.oneOf [JD.string, JD.list (JD.oneOf [JD.string, JD.float])] |> JD.map mapper

( I use json_decode_pipeline package here )

But obviously it complains about different values in the lists and whatnot so I am stuck.

Thank you in advance.

Body:
You are pretty close, but all of the Decoders in oneOf have to have the same type. Also, destructuring mixed lists can be a pain. This uses elm-community/json-extra to make a manual decoding step easier.

myDecoder : Decoder SomethingElse
myDecoder =
    decode MyString
        |> required "other_value" Json.Decode.string
        |> required "price" priceDecoder

priceDecoder : Decoder Something
priceDecoder =
    JD.oneOf
        [ priceUnknownDecoder
        , priceKnownDecoder
        ]

priceUnknownDecoder : Decoder Something
priceUnknownDecoder =
    JD.string
        |> JD.andThen
            (\string ->
                if string == "price_unknown" then
                    JD.succeed PriceUnknown
                else
                    JD.fail "Invalid unknown price string."
            )

priceKnownDecoder : Decoder Something
priceKnownDecoder =
    listTupleDecoder
        JD.string
        JD.float
        |> JD.andThen
            (\(tag, price) ->
                if tag == "price" then
                    JD.succeed (Price price)
                else
                    JD.fail "Invalid tag string."
            )

listTupleDecoder : Decoder a -> Decoder b -> Decoder (a, b)
listTupleDecoder firstD secondD =
    JD.list JD.value
        |> JD.andThen
            (\values ->
                case values of
                    [first, second] ->
                        Result.map2
                            (,)
                            JD.decodeValue firstD first
                            JD.decodeValue secondD second
                            |> JD.Extra.fromResult

                    _ ->
                        JD.fail "There aren't two values in the list."
            )


问:
Generating insert, update and delete statement from Change Data Capture data
I am using Change Data Capture to capture the change of data from software application. I am trying to generate the SQL statements (insert, update, delete) from the data captured.

Is there any proper way to get this done?

答: The way I have is/which I have worked on is, get all the change records from CDC tables along with the action (update/delete/insert) and pass the batch of records to a stored procedure which accepts table type as a input parameter. In the stored procedure you can basically write a cursor/ group by action to perform the operation on destination table. This way you don't need to generate dynamic SQL queries and run it on data base and we have seen this as a very efficient way when compared to generating dynamic sql and run it on DB.</p>


问:
MYSQL: ORDER BY table selected on the fly by user
I have a table like this:

Table: Cols

```<code> col1   col2    col3    col4
------ ------  ------  -------
  1       2       5       8
  5       4       2       7
  5       3       7       4
  7       5       4       1
</code>```

its very important what sort column be selected by user, i try something like:

```<code>    SELECT col1,Col2,Col3
    FROM Cols
    order by cast(:ORDER_ID_COL as integer)
</code>```

or

```<code>    SELECT col1,Col2,Col3
    FROM Cols
    order by cast(:ORDER_ID_COL as varchar(20))
</code>```

Both without errors but none correct.

If I'm out of the way, please enlighten me to get back on track.

答:
When you pass :ORDER_ID_COL to sql, it will be taken as a value not a column, so it won't produce the order what you want, in other words your query like following:

```<code>SELECT col1,Col2,Col3
FROM Cols
order by 'col1'
</code>```

You can use a ugly way to do that:

```<code>SELECT col1,Col2,Col3
FROM Cols
order by case when :ORDER_ID_COL = 'col1' then col1
              when :ORDER_ID_COL = 'col2' then col2
              when :ORDER_ID_COL = 'col3' then col3
              when :ORDER_ID_COL = 'col4' then col4
         end
</code>```

Or use dynamic sql:

```<code>SET @sql = concat('select col1,Col2,Col3 from cols order by ', :ORDER_ID_COL);
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
</code>```

Body:
I have a table like this:

Table: Cols

 col1   col2    col3    col4
------ ------  ------  -------
  1       2       5       8
  5       4       2       7
  5       3       7       4
  7       5       4       1

its very important what sort column be selected by user, i try something like:

    SELECT col1,Col2,Col3
    FROM Cols
    order by cast(:ORDER_ID_COL as integer)

or

    SELECT col1,Col2,Col3
    FROM Cols
    order by cast(:ORDER_ID_COL as varchar(20))

Both without errors but none correct.

If I'm out of the way, please enlighten me to get back on track.

Body:
When you pass :ORDER_ID_COL to sql, it will be taken as a value not a column, so it won't produce the order what you want, in other words your query like following:

SELECT col1,Col2,Col3
FROM Cols
order by 'col1'

You can use a ugly way to do that:

SELECT col1,Col2,Col3
FROM Cols
order by case when :ORDER_ID_COL = 'col1' then col1
              when :ORDER_ID_COL = 'col2' then col2
              when :ORDER_ID_COL = 'col3' then col3
              when :ORDER_ID_COL = 'col4' then col4
         end

Or use dynamic sql:

SET @sql = concat('select col1,Col2,Col3 from cols order by ', :ORDER_ID_COL);
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;


问:
jQuery code works for last iteration of php loop generated button
I'm creating a forum where people can vote on posts. The vote is called 'consents'.

```<code><?php
$postshow = "SELECT * FROM ideas_1 ORDER BY consents DESC LIMIT 10";
$done = mysqli_query($conn, $postshow);
//$show = mysqli_fetch_assoc($done);

while ($show = mysqli_fetch_assoc($done)) {
    echo"<div class = 'comments'>";
    echo"<br>";
    echo"<br>";
    echo $show['post'];
    echo"<br>";
    echo"<p class = 'counter'>";
    echo $show['consents'];
    echo"</p>";
    echo"<br>";
    $postid = $show['postid'];
    $userid = $show['userid'];
    $consents = $show['consents'];
      $asd = "SELECT * FROM consents WHERE dept = 'ideas' and task = '1' and postid = '$postid' and voterid = '$id'";
      $doit = mysqli_query($conn, $asd);
      $exist = mysqli_num_rows($doit);
      if ($exist == 0){
    echo"<button id = \"consents$postid\">Consent This</button>";
      }
    echo"</div>";

}
?>
<script>
    var posterid = "<?php echo $userid;?>"
    var postid = "<?php echo $postid;?>"
    var voterid = "<?php echo $id;?>"
    var consents = "<?php echo $consents;?>"

$(document).ready(function () {
   $('#consents' + postid).click(function(){
    $(this).hide();
    $.post ("consentsideas.php", {
        dept: "ideas",
        task: "1",
        postid: postid,
        voterid: voterid,
        consents: consents,
        posterid: posterid
    });
    $(".counter").html(++consents);
   });
   $(".answer").mousedown(function(){
            $(".post_answer").show();
            });
   $(document).click(function(event) {
    if(!$(event.target).closest('.post_answer').length) {
        if($('.post_answer').is(":visible")) {
            $('.post_answer').hide();
        }
    }
});
  $(".post_answer").click(function(){
    var answer = $(".answer").val();
    $.post ("answerideas.php", {
        answer: answer,
        id: voterid
            });
    $(".answer").val('');
    });
}
  );
</script>
</code>```

But any button looped by the while loop, when clicked, only updates the CONSENTS counter for the last iteration of the while loop.
As you can see, I've made the button's id unique(I hope I did that correctly). So could anyone tell me where's the problem?

答:
@musicnothing
Hey, I've edited my code a bit. Now it works. Thanks man!</p>

```<code>while ($show = mysqli_fetch_assoc($done)) {
    $postid = $show['postid'];
    $userid = $show['userid'];
    $consents = $show['consents'];?>
   <div class = 'comments'>
    <?php echo$show['post'];?><br>
    <?php echo$show['consents'];?> <span>Consents</span>

     <?php $asd = "SELECT * FROM consents WHERE dept = 'ideas' and task = '1' and postid = '$postid' and voterid = '$id'";
      $doit = mysqli_query($conn, $asd);
      $exist = mysqli_num_rows($doit);
      if ($exist == 0){ ?>
    <button class = 'consents' data-postid = '<?php echo$postid;?>' data-posterid ='<?php echo$userid;?>'
    data-voterid = '<?php echo$id;?>' data-consents = '<?php echo$consents;?>' >Consent This</button>
     <?php } ?>
   </div>

<?php }
?>
<script>

    var voterid = "<?php echo $id;?>"

$(document).ready(function () {
   $('.consents').click(function(){
    var postid = $(this).data('postid');
    var consents = $(this).data('consents');
    var posterid = $(this).data('posterid');
    $(this).hide();
    $.post ("consentsideas.php", {
        dept: "ideas",
        task: "1",
        postid: postid,
        voterid: voterid,
        consents: consents,
        posterid: posterid
    });
    $(".counter").html(++consents);
   });
   $(".answer").mousedown(function(){
            $(".post_answer").show();
            });
   $(document).click(function(event) {
    if(!$(event.target).closest('.post_answer').length) {
        if($('.post_answer').is(":visible")) {
            $('.post_answer').hide();
        }
    }
});
  $(".post_answer").click(function(){
    var answer = $(".answer").val();
    $.post ("answerideas.php", {
        answer: answer,
        id: voterid
            });
    $(".answer").val('');
    });
}
  );
</script>
</code>```

Body:
I'm creating a forum where people can vote on posts. The vote is called 'consents'.

<?php
$postshow = "SELECT * FROM ideas_1 ORDER BY consents DESC LIMIT 10";
$done = mysqli_query($conn, $postshow);
//$show = mysqli_fetch_assoc($done);

while ($show = mysqli_fetch_assoc($done)) {
    echo"
";
    echo"
";
    echo"
";
    echo $show['post'];
    echo"
";
    echo"
";
    echo $show['consents'];
    echo"
";
    echo"
";
    $postid = $show['postid'];
    $userid = $show['userid'];
    $consents = $show['consents'];
      $asd = "SELECT * FROM consents WHERE dept = 'ideas' and task = '1' and postid = '$postid' and voterid = '$id'";
      $doit = mysqli_query($conn, $asd);
      $exist = mysqli_num_rows($doit);
      if ($exist == 0){
    echo"<button id = \"consents$postid\">Consent This</button>";
      }
    echo"
";

}
?>

But any button looped by the while loop, when clicked, only updates the CONSENTS counter for the last iteration of the while loop.
As you can see, I've made the button's id unique(I hope I did that correctly). So could anyone tell me where's the problem?

Body:
@musicnothing
Hey, I've edited my code a bit. Now it works. Thanks man!

while ($show = mysqli_fetch_assoc($done)) {
    $postid = $show['postid'];
    $userid = $show['userid'];
    $consents = $show['consents'];?>
   <div class = 'comments'>
    <?php echo$show['post'];?><br>
    <?php echo$show['consents'];?> <span>Consents</span>

     <?php $asd = "SELECT * FROM consents WHERE dept = 'ideas' and task = '1' and postid = '$postid' and voterid = '$id'";
      $doit = mysqli_query($conn, $asd);
      $exist = mysqli_num_rows($doit);
      if ($exist == 0){ ?>
    <button class = 'consents' data-postid = '<?php echo$postid;?>' data-posterid ='<?php echo$userid;?>'
    data-voterid = '<?php echo$id;?>' data-consents = '<?php echo$consents;?>' >Consent This</button>
     <?php } ?>
   </div>

<?php }
?>
<script>

    var voterid = "<?php echo $id;?>"

$(document).ready(function () {
   $('.consents').click(function(){
    var postid = $(this).data('postid');
    var consents = $(this).data('consents');
    var posterid = $(this).data('posterid');
    $(this).hide();
    $.post ("consentsideas.php", {
        dept: "ideas",
        task: "1",
        postid: postid,
        voterid: voterid,
        consents: consents,
        posterid: posterid
    });
    $(".counter").html(++consents);
   });
   $(".answer").mousedown(function(){
            $(".post_answer").show();
            });
   $(document).click(function(event) {
    if(!$(event.target).closest('.post_answer').length) {
        if($('.post_answer').is(":visible")) {
            $('.post_answer').hide();
        }
    }
});
  $(".post_answer").click(function(){
    var answer = $(".answer").val();
    $.post ("answerideas.php", {
        answer: answer,
        id: voterid
            });
    $(".answer").val('');
    });
}
  );
</script>


问:
Paste data from Excel to Word
I have been searching this site and there appears to be numerous articles on datatype:=wdpastetext. However, I couldn't still find solution for issue that I have encountered with part of my code.

I'm copying data from excel to word L19 to L38 as text. However, some of the rows from L19 to L38 are bold and underlined and I would like to retain that formatting. Code below is simply pasting it as normal text without bold or underline.

Any help would be appreciated.

```<code>Range("L19:L38").Copy
With objWord
    .Selection.PasteSpecial Link:=False, DataType:=wdPasteText, _
     Placement:=wdInLine, DisplayAsIcon:=False
</code>```

答:
wdPasteText is supposed to copy across just text. It doesn't copy across any formatting. Bold and Underline are part of formatting. If you want the formatting to be copied across then you can use wdPasteHTML.

```<code>With objWord
    .Selection.PasteSpecial Link:=False, DataType:=wdPasteHTML, _
    Placement:=wdInLine, DisplayAsIcon:=False
End With
</code>```

Screenshot

For other option see this KB article

WdPasteDataType Enumeration (Word)

Title: Paste data from Excel to Word

Body:
I have been searching this site and there appears to be numerous articles on datatype:=wdpastetext. However, I couldn't still find solution for issue that I have encountered with part of my code.

I'm copying data from excel to word L19 to L38 as text. However, some of the rows from L19 to L38 are bold and underlined and I would like to retain that formatting. Code below is simply pasting it as normal text without bold or underline.

Any help would be appreciated.

Range("L19:L38").Copy
With objWord
    .Selection.PasteSpecial Link:=False, DataType:=wdPasteText, _
     Placement:=wdInLine, DisplayAsIcon:=False

Body:
wdPasteText is supposed to copy across just text. It doesn't copy across any formatting. Bold and Underline are part of formatting. If you want the formatting to be copied across then you can use wdPasteHTML.

With objWord
    .Selection.PasteSpecial Link:=False, DataType:=wdPasteHTML, _
    Placement:=wdInLine, DisplayAsIcon:=False
End With

Screenshot

For other option see this KB article

WdPasteDataType Enumeration (Word)


问:
Why utf8 encoding of the string gives the string that is unchanged in return
My code is as shown below:

```<code>let createCipher = (req, res) => {
    const text = req.body.text;
    let hash = crypto.createHash('md5').update(utf8.encode(text)).digest('hex');
    res.json({
        status: '200',
        data: hash,
        utf: utf8.encode(text)
    });
}
</code>```

Here, whatever I give as text input parameter, the same will be return in the response field utf. so is there anything missing from utf8 process?

答:
```<code>let createCipher = (req, res) => {
    const text = req.body.text;
    //text = "Hello World";

    let hash = crypto.createHash('md5');
    hash.update(utf8.encode(text));

    //or you try
    //let hash = crypto.createHash('md5').update(utf8.encode(text));

    let data = hash.digest('hex');
    //console.log(data + '  ' + text);
    //console.log("utf8 - byte data : " + utf8.encode(data)+ '  ' + utf8.encode(text));
    res.json({
        status: '200',
        data: hash,
        utf: utf8.encode(data) //data
    });
}

//Output
//b10a8db164e0754105b7a99be72e3fe5  Hello World
//utf8 - byte data : b10a8db164e0754105b7a99be72e3fe5  Hello World
</code>```

Body:
My code is as shown below:

let createCipher = (req, res) => {
    const text = req.body.text;
    let hash = crypto.createHash('md5').update(utf8.encode(text)).digest('hex');
    res.json({
        status: '200',
        data: hash,
        utf: utf8.encode(text)
    });
}

Here, whatever I give as text input parameter, the same will be return in the response field utf. so is there anything missing from utf8 process?


问:
Can someone explain, what does the webhook do in api.ai?
I am new to api.ai. I want to send data to the web server and receive it and then give it to the users? From the documentation that I read, I understood that I have to use a webhook. But I am not sure how will api.ai send and receive the data?

Can the webhook be developed in any language?

答:
You can visualize the working of a webhook like a block where data request comes in JSON format somewhat like this:

```<code>{
  "id": "7aef9329-4a32-4d59-b661-8bf380a0f35b",
  "timestamp": "2017-06-07T05:36:12.641Z",
  "lang": "en",
  "result": {
    "source": "agent",
    "resolvedQuery": "hi",
    "action": "order.pizza",
    "actionIncomplete": true,
    "parameters": {
      "address": "",
      "crust": "",
      "sauce": "",
      "size": "",
      "time": "",
      "topping": "",
      "type": ""
    }
  }
}
</code>```

and another json file is returned to it according to the prescribed settings.

Body:
You can visualize the working of a webhook like a block where data request comes in JSON format somewhat like this:

{
  "id": "7aef9329-4a32-4d59-b661-8bf380a0f35b",
  "timestamp": "2017-06-07T05:36:12.641Z",
  "lang": "en",
  "result": {
    "source": "agent",
    "resolvedQuery": "hi",
    "action": "order.pizza",
    "actionIncomplete": true,
    "parameters": {
      "address": "",
      "crust": "",
      "sauce": "",
      "size": "",
      "time": "",
      "topping": "",
      "type": ""
    }
  }
}

and another json file is returned to it according to the prescribed settings.


答:
Here we are using DOMDocument to achieve desired output.

Try this code snippet here

```<code>$domDocument = new DOMDocument();
$domDocument->loadHTML($string);

$domXPath = new DOMXPath($domDocument);
$results = $domXPath->query("//tbody/tr/td");
$data=array();
for($x=0;$x<$results->length;$x+=2)
{
    $instance=$results->item($x);
    if($instance instanceof DOMElement)
    {
        $data[]=$results->item($x)->textContent;
    }
}
print_r($data);
</code>```

Title: How to get specific values of each field using php DOM Script ? for the below format?

Body:
I want to get the value of each field like "Delhi" , "Kolkatta".

How can i do this using php DOM Script ?

here is the source of the page to parsed.

Delhi
66.91

Kolkata
69.52

Mumbai
78.44

Chennai
69.93

Body:
Here we are using DOMDocument to achieve desired output.

Try this code snippet here

$domDocument = new DOMDocument();
$domDocument->loadHTML($string);

$domXPath = new DOMXPath($domDocument);
$results = $domXPath->query("//tbody/tr/td");
$data=array();
for($x=0;$x<$results->length;$x+=2)
{
    $instance=$results->item($x);
    if($instance instanceof DOMElement)
    {
        $data[]=$results->item($x)->textContent;
    }
}
print_r($data);


问:
How to save STDOUT outputs to a text file?
I have a program which utilizes a 3rd party command line tool to generate logs. The 3rd party generates all its output to the STDOUT which the user must then use the " > test.txt" command to save the file.

However the program somehow generates a certain amount of report generated but not the entire report. This was test by using the command

C:\Test\ftk\ripxp>ripxp.exe -r C:\test\ftk\ntuser.dat -d "C:\System Volume\_rest
ore{BB12863B-2C77-46C9-BCDA-1810E52F1089}" -p runmru > C:\test\test05.txt

on the command line console which works and on the program which works only partially.

The errors were narrowed down to either the arguments error or the file saving error part (streamReader). Therefore the error could be due to the STDOUT not being properly saved.

Therefore may someone please advise on the codes? Thanks!

The Arguments for the 3rd party tool(2008 H. Carvey):

```<code>RipXP v.20081001 - CLI RegRipper tool
RipXP [-r Reg hive file] [-p plugin module][-d RP dir][-lgh]
Parse Windows Registry files, using either a single module from the plugins folder.
Then parse all corresponding hive files from the XP Restore Points (extracted from
image) using the same plugin.

-r Reg hive file...Registry hive file to parse
-g ................Guess the hive file (experimental)
-d RP directory....Path to the Restore Point directory
-p plugin module...use only this module
-l ................list all plugins
-h.................Help (print this information)

Ex: C:\>rip -g
C:\>rip -r d:\cases\ntuser.dat -d d:\cases\svi -p userassist

All output goes to STDOUT; use redirection (ie, > or >>) to output to a file.

copyright 2008 H. Carvey
</code>```

The Codes:

```<code>static void Main(string[] args)
    {
        // Automatically finds folder that starts with _restore
        DirectoryInfo directoryInfo = new DirectoryInfo(@"C:\System Volume\");
        DirectoryInfo restoreFolder = directoryInfo.GetDirectories().FirstOrDefault(d => d.Name.StartsWith("_restore"));

        // Gets the folder name
        String baka = restoreFolder.Name;

        if (restoreFolder == null)
            throw new DirectoryNotFoundException();

            Process process = new Process();
            process.StartInfo.FileName = @"C:\test\ftk\ripxp\ripxp.exe";
            process.StartInfo.Arguments = @"-r C:\test\ftk\ntuser.dat -d C:\System Volume\" + restoreFolder.Name + " -p runmru";
            process.StartInfo.CreateNoWindow = false;
            process.StartInfo.UseShellExecute = false;
            process.StartInfo.RedirectStandardOutput = true;
            process.StartInfo.RedirectStandardInput = true;
            process.StartInfo.RedirectStandardError = true;
            process.Start();

            String text = @"-r C:\test\ftk\ntuser.dat -d C:\System Volume\" +restoreFolder.Name  + " -p runmru";
            Console.WriteLine(baka);
            Console.WriteLine(text);

            // Strangely the program only outputs the first section "-r C:\test\ftk\ntuser.dat" argument results.....
            System.IO.StreamReader reader = process.StandardOutput;
            String sRes = reader.ReadToEnd();
            StreamWriter SW;
            SW = File.CreateText(@"C:\test\test01.txt");
            SW.WriteLine(sRes);
            SW.Close();
            Console.WriteLine("File Created Successfully");
            reader.Close();

    }
</code>```

答:
The System.Console class has a SetOut method that should do what you need.

You should call Console.SetOut(yourTextWriter) at the beginning of your program's execution.

Just add this at the first line of the program:

```<code>Console.SetOut(File.CreateText(locationToSaveLogs));
</code>```

Body:
I have a program which utilizes a 3rd party command line tool to generate logs. The 3rd party generates all its output to the STDOUT which the user must then use the " > test.txt" command to save the file.

However the program somehow generates a certain amount of report generated but not the entire report. This was test by using the command

C:\Test\ftk\ripxp>ripxp.exe -r C:\test\ftk\ntuser.dat -d "C:\System Volume\_rest
ore{BB12863B-2C77-46C9-BCDA-1810E52F1089}" -p runmru > C:\test\test05.txt

on the command line console which works and on the program which works only partially.

The errors were narrowed down to either the arguments error or the file saving error part (streamReader). Therefore the error could be due to the STDOUT not being properly saved.

Therefore may someone please advise on the codes? Thanks!

The Arguments for the 3rd party tool(2008 H. Carvey):

RipXP v.20081001 - CLI RegRipper tool
RipXP [-r Reg hive file] [-p plugin module][-d RP dir][-lgh]
Parse Windows Registry files, using either a single module from the plugins folder.
Then parse all corresponding hive files from the XP Restore Points (extracted from
image) using the same plugin.

-r Reg hive file...Registry hive file to parse
-g ................Guess the hive file (experimental)
-d RP directory....Path to the Restore Point directory
-p plugin module...use only this module
-l ................list all plugins
-h.................Help (print this information)

Ex: C:\>rip -g
C:\>rip -r d:\cases\ntuser.dat -d d:\cases\svi -p userassist

All output goes to STDOUT; use redirection (ie, > or >>) to output to a file.

copyright 2008 H. Carvey

The Codes:

static void Main(string[] args)
    {
        // Automatically finds folder that starts with _restore
        DirectoryInfo directoryInfo = new DirectoryInfo(@"C:\System Volume\");
        DirectoryInfo restoreFolder = directoryInfo.GetDirectories().FirstOrDefault(d => d.Name.StartsWith("_restore"));

        // Gets the folder name
        String baka = restoreFolder.Name;

        if (restoreFolder == null)
            throw new DirectoryNotFoundException();

            Process process = new Process();
            process.StartInfo.FileName = @"C:\test\ftk\ripxp\ripxp.exe";
            process.StartInfo.Arguments = @"-r C:\test\ftk\ntuser.dat -d C:\System Volume\" + restoreFolder.Name + " -p runmru";
            process.StartInfo.CreateNoWindow = false;
            process.StartInfo.UseShellExecute = false;
            process.StartInfo.RedirectStandardOutput = true;
            process.StartInfo.RedirectStandardInput = true;
            process.StartInfo.RedirectStandardError = true;
            process.Start();

            String text = @"-r C:\test\ftk\ntuser.dat -d C:\System Volume\" +restoreFolder.Name  + " -p runmru";
            Console.WriteLine(baka);
            Console.WriteLine(text);

            // Strangely the program only outputs the first section "-r C:\test\ftk\ntuser.dat" argument results.....
            System.IO.StreamReader reader = process.StandardOutput;
            String sRes = reader.ReadToEnd();
            StreamWriter SW;
            SW = File.CreateText(@"C:\test\test01.txt");
            SW.WriteLine(sRes);
            SW.Close();
            Console.WriteLine("File Created Successfully");
            reader.Close();

    }

Body:
The System.Console class has a SetOut method that should do what you need.

You should call Console.SetOut(yourTextWriter) at the beginning of your program's execution.

Just add this at the first line of the program:

Console.SetOut(File.CreateText(locationToSaveLogs));


问:
Best way to convert ArrayList to string
I have a scenario in which if the user select any option from drop-down then that value is going to server as ArrayList. And if the user does not select anything then the default value is going to server as String.  In java I have to convert the value to string(if i get ArrayList I have to convert that into string if i get string I have to store as it is. What is the best way to do this with minimal code?

I am trying below code :

```<code>String encoding =  myMap.get("encoding").toString();

encoding = encoding.replaceAll("\\[\\]", ""); \\removing brackets
</code>```

答:
You should never ever rely on things like list.toString().replaceAll("[\\[\\]]", "") because they are just an specific implementation of the toString method for the list and can be changed any moment making your code to crash...

Using join since java8

```<code>List<Object> olist = Arrays.asList(1, 2, 3, 4, 5);
List<String> sList = olist.stream().map(String::valueOf).collect(Collectors.toList());
String results = String.join(",", sList);
System.out.println(results);
</code>```

Title: Best way to convert ArrayList to string

Body:
I have a scenario in which if the user select any option from drop-down then that value is going to server as ArrayList. And if the user does not select anything then the default value is going to server as String.  In java I have to convert the value to string(if i get ArrayList I have to convert that into string if i get string I have to store as it is. What is the best way to do this with minimal code?

I am trying below code :

String encoding =  myMap.get("encoding").toString();

encoding = encoding.replaceAll("\\[\\]", ""); \\removing brackets

Body:
You should never ever rely on things like list.toString().replaceAll("[\\[\\]]", "") because they are just an specific implementation of the toString method for the list and can be changed any moment making your code to crash...

Using join since java8

List<Object> olist = Arrays.asList(1, 2, 3, 4, 5);
List<String> sList = olist.stream().map(String::valueOf).collect(Collectors.toList());
String results = String.join(",", sList);
System.out.println(results);


问:
How to do session based filtering servlet authentication
I am currently using filter to authenticate credentials given in the REST and servlet calls done in the servlet.

Everytime when a request made it fetches the credentials from the database which is expensive operation everytime.

Is there any way to authenticate based on session so that need not go everytime to retrieve details from db.

Thanks.

答:
I see two options you have

Keep the session token in memory. Each app server has a way to replicate in-memory session cache. Indeed it requires some cache management around.

Most of the solutions I've seen and done used this option.

You can use a self-containing token (such as JWT) the filter should be able to validate without accessing DB every time. Then you will need a token service to exchange the client credentials for the token.

If your clients use directly their credentials (basic authentication), you may consider some way to use tokens which are more secure to cache (OAuth 2.0)

When someone has improvent or disagreement, feel free to comment


问:
OpenAI Gym: Understanding `action_space` notation (spaces.Box)
I want to setup an RL agent on the OpenAI CarRacing-v0 environment, but before that I want to understand the action space. In the code on github line 119 says:

```<code>self.action_space = spaces.Box( np.array([-1,0,0]), np.array([+1,+1,+1]))  # steer, gas, brake
</code>```

How do I read this line? Although my problem is concrete wrt CarRacing-v0 I would like to understand the spaces.Box() notation in general

答:
Box means that you are dealing with real valued quantities.

The first array np.array([-1,0,0] are the lowest accepted values, and the second np.array([+1,+1,+1]) are the highest accepted values. In this case (using the comment) we see that we have 3 available actions:

Steering: Real valued in [-1, 1]

Gas: Real valued in [0, 1]

Brake: Real valued in [0, 1]

Body:
I want to setup an RL agent on the OpenAI CarRacing-v0 environment, but before that I want to understand the action space. In the code on github line 119 says:

self.action_space = spaces.Box( np.array([-1,0,0]), np.array([+1,+1,+1]))  # steer, gas, brake

How do I read this line? Although my problem is concrete wrt CarRacing-v0 I would like to understand the spaces.Box() notation in general


问:
Online resources for Introduction to computer and computer sciences for absolute beginner
In our office, we have an office boy(completed high school(10+2 years)) with average academic record so far). He wants to learn programming. I have started coaching him in Computer Science basics (history of computer science, number systems, etc.), but I am not able to put in enough time with him(because I have very limited free time and more importantly I do not want to spoon feed him). Now I am not sure how to fill in the gap of theoretical reading.

Now my question is, could anyone point me to some online resources(preferably in simple English) for Introduction to Computer Sciences.

Moreover, I am planning to start him with on programming with book Think Like A Computer Scientist - Python version. If any body knows a better book or an online resource - preferably in Python, please point out.

Thanks

答: I learnt to program by myself with nothing more than the web to aid me. If he's serious about learning then he shouldn't need much teaching. You might start by pointing him to http://docs.python.org/tutorial/</p>


问:
Failed to invoke the service. Possible causes: The service is offline or inaccessible; Relations in tables
I came across a weird situation in WCF Service. I don't know what exactly the reason behind this. The screen shots are self explanatory.

Below screen shots shows - 1. Project structure, 2. DB Structure, 3. Table relations etc.

Now closely observe the result i got -

This is weird. I don't understand why WCF generating error here.

Later on I have done some R&D and removed the relation between tables.

Now see the result -

Surprisingly, the WCF is functioning.
This is really weird.
Can anybody explain me why this behavior, and what changes should i make to make my service working with relational tables.

Thank you for sharing your time and wisdom.

答:
If you're doing this with code first, write it into the context in constructor</p>

```<code>Base.Configuration.ProxyCreationEnabled = false;
</code>```

Body:
If you're doing this with code first, write it into the context in constructor

Base.Configuration.ProxyCreationEnabled = false;


问:
Android Using incompatible plugins for the annotation processing
after more work on my project and install ro remove some libraries. i get this error as:

```<code>Warning:Using incompatible plugins for the annotation processing:
android-apt. This may result in an unexpected behavior.
</code>```

i search more sites about this problem but i can't resolve that

this is my application build.gradle content file

```<code>apply plugin: 'com.android.application'
apply plugin: 'android-apt'
apply plugin: 'com.neenbedankt.android-apt'

android {
    compileSdkVersion 25
    buildToolsVersion "25.0.2"
    defaultConfig {
        applicationId "ir.pishguy.cafealachiqpro"
        minSdkVersion 15
        targetSdkVersion 25
        versionCode 1
        versionName "1.0"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
    dataBinding {
        enabled = true
    }
}

repositories {
    jcenter()
    maven { url "https://jitpack.io" }
    maven { url "https://clojars.org/repo/" }
}

def dbflow_version = "4.0.0-beta5"
def sqlcipher_version = "3.5.4"

dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    compile 'com.android.support:appcompat-v7:25.3.1'
    compile 'com.android.support:support-v13:25.3.1'
    compile 'com.android.support:cardview-v7:25.3.1'
    compile 'com.android.support:recyclerview-v7:25.3.1'

    compile 'org.greenrobot:eventbus:3.0.0'

    compile('io.socket:socket.io-client:0.8.3') {
        exclude group: 'org.json', module: 'json'
    }
    compile 'com.bugsnag:bugsnag-android:+'
    compile 'com.facebook.rebound:rebound:0.3.8'
    compile 'com.tumblr:backboard:0.1.0'
    compile 'com.readystatesoftware.systembartint:systembartint:1.0.3'

    compile 'com.squareup.retrofit2:retrofit:2.0.2'
    compile 'com.squareup.retrofit2:converter-gson:2.0.2'
    compile 'com.squareup.picasso:picasso:2.5.2'

    apt "com.github.Raizlabs.DBFlow:dbflow-processor:${dbflow_version}"
    // use kapt for kotlin apt
    compile "com.github.Raizlabs.DBFlow:dbflow-core:${dbflow_version}"
    compile "com.github.Raizlabs.DBFlow:dbflow:${dbflow_version}"
    // sql-cipher database encryption (optional)
    compile "com.github.Raizlabs.DBFlow:dbflow-sqlcipher:${dbflow_version}"
    compile "net.zetetic:android-database-sqlcipher:${sqlcipher_version}@aar"

    compile 'io.reactivex.rxjava2:rxandroid:2.0.1'
    compile 'io.reactivex.rxjava2:rxjava:2.0.1'
}
</code>```

and this content is for project build.gradle

```<code>buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:2.3.0'
        classpath 'com.neenbedankt.gradle.plugins:android-apt:1.8'
    }
}

allprojects {
    repositories {
        jcenter()
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}
</code>```

what i get error: i get this result on LogCat

```<code>Warning:Using incompatible plugins for the annotation processing: android-apt. This may result in an unexpected behavior.
/Users/mahdi/Desktop/Home/Projects/Android/CafeAlachiqPro/app/src/main/java/ir/pishguy/cafealachiqpro/Ui/Register/Activity/View/ActivityRegister.java
Error:(48, 45) error: package ir.pishguy.cafealachiqpro.databinding does not exist
Error:(75, 13) error: cannot find symbol class ActivityRegisterBinding
/Users/mahdi/Desktop/Home/Projects/Android/CafeAlachiqPro/app/src/main/java/ir/pishguy/cafealachiqpro/Ui/Register/Robot/RobotMessagesAdapter.java
Error:(12, 45) error: package ir.pishguy.cafealachiqpro.databinding does not exist
Error:(13, 45) error: package ir.pishguy.cafealachiqpro.databinding does not exist
/Users/mahdi/Desktop/Home/Projects/Android/CafeAlachiqPro/app/src/main/java/ir/pishguy/cafealachiqpro/Ui/Register/Robot/RobotViewHolder.java
Error:(6, 45) error: package ir.pishguy.cafealachiqpro.databinding does not exist
Error:(13, 13) error: cannot find symbol class RobotDataBinding
Error:(15, 28) error: cannot find symbol class RobotDataBinding
/Users/mahdi/Desktop/Home/Projects/Android/CafeAlachiqPro/app/src/main/java/ir/pishguy/cafealachiqpro/Ui/Register/Robot/UserViewHolder.java
Error:(6, 45) error: package ir.pishguy.cafealachiqpro.databinding does not exist
Error:(13, 13) error: cannot find symbol class UserMessagesDataBinding
Error:(15, 27) error: cannot find symbol class UserMessagesDataBinding
</code>```

all of binding classes are correct i checked them by click on each binded classes

答:
An annotation processor was included in the Gradle version 2.2, so there is no reason to provide an extra one.

Check my updated answer here.

Body:
after more work on my project and install ro remove some libraries. i get this error as:

Warning:Using incompatible plugins for the annotation processing:
android-apt. This may result in an unexpected behavior.

i search more sites about this problem but i can't resolve that

this is my application build.gradle content file

apply plugin: 'com.android.application'
apply plugin: 'android-apt'
apply plugin: 'com.neenbedankt.android-apt'

android {
    compileSdkVersion 25
    buildToolsVersion "25.0.2"
    defaultConfig {
        applicationId "ir.pishguy.cafealachiqpro"
        minSdkVersion 15
        targetSdkVersion 25
        versionCode 1
        versionName "1.0"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
    dataBinding {
        enabled = true
    }
}

repositories {
    jcenter()
    maven { url "https://jitpack.io" }
    maven { url "https://clojars.org/repo/" }
}

def dbflow_version = "4.0.0-beta5"
def sqlcipher_version = "3.5.4"

dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    compile 'com.android.support:appcompat-v7:25.3.1'
    compile 'com.android.support:support-v13:25.3.1'
    compile 'com.android.support:cardview-v7:25.3.1'
    compile 'com.android.support:recyclerview-v7:25.3.1'

    compile 'org.greenrobot:eventbus:3.0.0'

    compile('io.socket:socket.io-client:0.8.3') {
        exclude group: 'org.json', module: 'json'
    }
    compile 'com.bugsnag:bugsnag-android:+'
    compile 'com.facebook.rebound:rebound:0.3.8'
    compile 'com.tumblr:backboard:0.1.0'
    compile 'com.readystatesoftware.systembartint:systembartint:1.0.3'

    compile 'com.squareup.retrofit2:retrofit:2.0.2'
    compile 'com.squareup.retrofit2:converter-gson:2.0.2'
    compile 'com.squareup.picasso:picasso:2.5.2'

    apt "com.github.Raizlabs.DBFlow:dbflow-processor:${dbflow_version}"
    // use kapt for kotlin apt
    compile "com.github.Raizlabs.DBFlow:dbflow-core:${dbflow_version}"
    compile "com.github.Raizlabs.DBFlow:dbflow:${dbflow_version}"
    // sql-cipher database encryption (optional)
    compile "com.github.Raizlabs.DBFlow:dbflow-sqlcipher:${dbflow_version}"
    compile "net.zetetic:android-database-sqlcipher:${sqlcipher_version}@aar"

    compile 'io.reactivex.rxjava2:rxandroid:2.0.1'
    compile 'io.reactivex.rxjava2:rxjava:2.0.1'
}

and this content is for project build.gradle

buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:2.3.0'
        classpath 'com.neenbedankt.gradle.plugins:android-apt:1.8'
    }
}

allprojects {
    repositories {
        jcenter()
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

what i get error: i get this result on LogCat

Warning:Using incompatible plugins for the annotation processing: android-apt. This may result in an unexpected behavior.
/Users/mahdi/Desktop/Home/Projects/Android/CafeAlachiqPro/app/src/main/java/ir/pishguy/cafealachiqpro/Ui/Register/Activity/View/ActivityRegister.java
Error:(48, 45) error: package ir.pishguy.cafealachiqpro.databinding does not exist
Error:(75, 13) error: cannot find symbol class ActivityRegisterBinding
/Users/mahdi/Desktop/Home/Projects/Android/CafeAlachiqPro/app/src/main/java/ir/pishguy/cafealachiqpro/Ui/Register/Robot/RobotMessagesAdapter.java
Error:(12, 45) error: package ir.pishguy.cafealachiqpro.databinding does not exist
Error:(13, 45) error: package ir.pishguy.cafealachiqpro.databinding does not exist
/Users/mahdi/Desktop/Home/Projects/Android/CafeAlachiqPro/app/src/main/java/ir/pishguy/cafealachiqpro/Ui/Register/Robot/RobotViewHolder.java
Error:(6, 45) error: package ir.pishguy.cafealachiqpro.databinding does not exist
Error:(13, 13) error: cannot find symbol class RobotDataBinding
Error:(15, 28) error: cannot find symbol class RobotDataBinding
/Users/mahdi/Desktop/Home/Projects/Android/CafeAlachiqPro/app/src/main/java/ir/pishguy/cafealachiqpro/Ui/Register/Robot/UserViewHolder.java
Error:(6, 45) error: package ir.pishguy.cafealachiqpro.databinding does not exist
Error:(13, 13) error: cannot find symbol class UserMessagesDataBinding
Error:(15, 27) error: cannot find symbol class UserMessagesDataBinding

all of binding classes are correct i checked them by click on each binded classes


问:
Error in make controller in laravel
I want learn larvel please help.

Using laravel version 5.0.16.

```<code>php artisan make:controller Admin\Controller --resource
</code>```

It shows this error:

[RuntimeException]   The "--resource" option does not exist.

What is the problem?

What is different between?

```<code>php artisan make:controller Admin\Controller --resource

php artisan make:controller Admin\Controller --plain

php artisan make:controller Admin\Controller
</code>```

答:
1st of all --resource does not exist in 5.0 and don't use / in controller name as you write above Admin/Controller make it as AdminController

Short

Now in Laravel 5.2 make:controller command creates plain controller, if you want to make resource controller you need to add --resource

Resource Controller

Resource controller gives four built-in methods of CRUD with routes as well, for example you run:

```<code>php artisan make:controller AdminController --resource
</code>```

Then the routes can be registered as:

```<code>Route::resource('admin', 'AdminController');
</code>```

It will give you four methods.

Create Retrieve Update Delete

Laravel resource routing assigns the typical "CRUD" routes to a controller with a single line of code.

Plain Controller and without --plain.

Before, Laravel 5.2 --plain was used to make a simple controller without builtin routes and methods. Now:

php artisan make:controller AdminController

Works the same as --plain.

Reference: https://laravel.com/docs/5.4/controllers

Title: Error in make controller in laravel

Body:
I want learn larvel please help.

Using laravel version 5.0.16.

php artisan make:controller Admin\Controller --resource

It shows this error:

[RuntimeException]   The "--resource" option does not exist.

What is the problem?

What is different between?

php artisan make:controller Admin\Controller --resource

php artisan make:controller Admin\Controller --plain

php artisan make:controller Admin\Controller

Body:
1st of all --resource does not exist in 5.0 and don't use / in controller name as you write above Admin/Controller make it as AdminController

Short

Now in Laravel 5.2 make:controller command creates plain controller, if you want to make resource controller you need to add --resource

Resource Controller

Resource controller gives four built-in methods of CRUD with routes as well, for example you run:

php artisan make:controller AdminController --resource

Then the routes can be registered as:

Route::resource('admin', 'AdminController');

It will give you four methods.

Create Retrieve Update Delete

Laravel resource routing assigns the typical "CRUD" routes to a controller with a single line of code.

Plain Controller and without --plain.

Before, Laravel 5.2 --plain was used to make a simple controller without builtin routes and methods. Now:

php artisan make:controller AdminController

Works the same as --plain.

Reference: https://laravel.com/docs/5.4/controllers


问:
Android Studio WebView Youtube Video BlackScreen
I want to play a video in the WebView but somehow I get an blackscreen on the video but I can hear the sound of it. Would be really glad if someone can help me</p>

```<code>public class MainActivity extends AppCompatActivity {

WebView displayYoutubeVideo;
TextView button;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    String frameVideo = "<html><body>Video From YouTube<br><iframe
    width=\"560\" height=\"315\"
    src=\"https://www.youtube.com/embed/WtO3_tF8niU\" frameborder=\"0\"
    allowfullscreen></iframe></body></html>";

    WebView displayYoutubeVideo = (WebView) findViewById(R.id.youtube_view);

    displayYoutubeVideo.getSettings().setUserAgentString("Mozilla/5.0
           (Windows NT 10.0; WOW64; rv:53.0) Gecko/20100101 Firefox/53.0");

    displayYoutubeVideo.setWebViewClient(new WebViewClient() {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            return false;
        }
    });
    WebSettings webSettings = displayYoutubeVideo.getSettings();
    webSettings.setJavaScriptEnabled(true);
    displayYoutubeVideo.loadData(frameVideo, "text/html", "utf-8");
}
}
</code>```

答:
This link may help you.It seems you missed some properties for the web view.

https://inducesmile.com/android/embed-and-play-youtube-video-in-android-webview/

Body:
I want to play a video in the WebView but somehow I get an blackscreen on the video but I can hear the sound of it. Would be really glad if someone can help me

public class MainActivity extends AppCompatActivity {

WebView displayYoutubeVideo;
TextView button;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    String frameVideo = "Video From YouTube
";

    WebView displayYoutubeVideo = (WebView) findViewById(R.id.youtube_view);

    displayYoutubeVideo.getSettings().setUserAgentString("Mozilla/5.0
           (Windows NT 10.0; WOW64; rv:53.0) Gecko/20100101 Firefox/53.0");

    displayYoutubeVideo.setWebViewClient(new WebViewClient() {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            return false;
        }
    });
    WebSettings webSettings = displayYoutubeVideo.getSettings();
    webSettings.setJavaScriptEnabled(true);
    displayYoutubeVideo.loadData(frameVideo, "text/html", "utf-8");
}
}


问:
How perform one final action when user android app completely closes - Android Studio
so currently I'm developing an app for Android in Android studio. Basically, when the user presses the home button, tabs button or shuts off the screen (while the app runs in the background ) a string of text gets encrypted, stored and the app logs out. Problem is, it takes a couple seconds for the encryption to go through, so if the user closes the app by going to tabs mode and swiping it away before the encryption is complete the whole process gets cancelled. Is there a way where even though the user shuts off the app it can process the final encryption or a final function?</p>

答:
Basically you have to do something like this in your MainActivity( DashboardActivity) of app

```<code>        private Boolean exit = false;

        @Override
        public void onBackPressed() {

            if (exit) {
                super.onBackPressed();
            } else {
                FragmentManager manager = getSupportFragmentManager();
                if (manager.getBackStackEntryCount() <= 0) {
                    Utilities.showToastCompulsary(DashboardActivity.this, "Press Back again to Exit.");
                    exit = true;
                    encryptionProccess();
                    new Handler().postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            exit = false;

                        }
                    }, 3 * 1000); //manage your time as per process
                } else {
                    super.onBackPressed();
                }
            }
        }
</code>```

one another approch is you can try with onDistroyed method

```<code>@Override
protected void onDestroy() {
    startLoader();
    encriptionProcess();
    stopLoader();
    super.onDestroy();
}
</code>```

Body:
Basically you have to do something like this in your MainActivity( DashboardActivity) of app

        private Boolean exit = false;

        @Override
        public void onBackPressed() {

            if (exit) {
                super.onBackPressed();
            } else {
                FragmentManager manager = getSupportFragmentManager();
                if (manager.getBackStackEntryCount() <= 0) {
                    Utilities.showToastCompulsary(DashboardActivity.this, "Press Back again to Exit.");
                    exit = true;
                    encryptionProccess();
                    new Handler().postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            exit = false;

                        }
                    }, 3 * 1000); //manage your time as per process
                } else {
                    super.onBackPressed();
                }
            }
        }

one another approch is you can try with onDistroyed method

@Override
protected void onDestroy() {
    startLoader();
    encriptionProcess();
    stopLoader();
    super.onDestroy();
}


问:
How to center an image inside a list with other elements
I have an unordered list that contains several list elements inside. Also inside is an image element which is to be centered. I tried to center it using the margin: auto; property but since there are list elements on the side, it takes that into account when centering itself. How do I center the image in respect to it's container?

.nav {
  width: 1280px;
  margin: 0 auto;
  font-size: 16px;
  font-weight: 500;
  border: 1px solid black;
}

.nav li {
  float: left;
  vertical-align: top;
  margin: 5px 10px;
}

nav li:first-child {
  margin-left: 75px;
}

.nav img {
  display: block;
  margin: auto;
  height: 21px;
  width: 24px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><nav class="nav">
  <ul class="clearfix">
    <li>Home</li>
    <li>Moments</li>
    <li>Notifications</li>
    <li>Messages</li>
    <img src="assets/image/twitter-icon.png" alt="Twitter Icon">
  </ul>
</nav></code>```

答:
1) All Elements be Center

```<code>.nav {
  width: 1280px;
  margin: 0 auto;
  font-size: 16px;
  font-weight: 500;
  border: 1px solid black;
}

.nav li {
  float: left;<------Remove
  display: inline-block;<-----------Add
  vertical-align: top;
  margin: 5px 10px;
}

nav li:first-child {
  margin-left: 75px;<---------Change to margin-left: 0px;------
}

.nav img {
  display: block;<----------Change to display: inline-block;---
  margin: auto;<---------Remove
  height: 21px;
  width: 24px;
}

.clearfix{<-----------Add this Selector
  text-align: center;
  width: 100%;
  padding-left: 0;
}
</code>```

Full Code:

.nav {
  width: 1280px;
  margin: 0 auto;
  font-size: 16px;
  font-weight: 500;
  border: 1px solid black;
}

.nav li {
  display: inline-block;
  vertical-align: top;
  margin: 5px 10px;
}

nav li:first-child {
  margin-left: 0px;
}

.nav img {
  display: inline-block;
  height: 21px;
  width: 24px;
}

.clearfix{
  text-align: center;
  width: 100%;
  padding-left: 0;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code>  <nav class="nav">
    <ul class="clearfix">
      <li>Home</li>
      <li>Moments</li>
      <li>Notifications</li>
      <li>Messages</li>
      <img src="http://www.mrwallpaper.com/wallpapers/cute-bunny-1600x900.jpg" alt="Twitter Icon">
    </ul>
  </nav></code>```

2) Just image be Center

```<code>.nav {
  width: 1280px;
  margin: 0 auto;
  font-size: 16px;
  font-weight: 500;
  border: 1px solid black;
  position: relative;<---------Add
}

.nav li {
  float: left;<---------remove
  vertical-align: top;
  margin: 5px 10px;
}

nav li:first-child {
  margin-left: 75px;
}

.nav img {
  display: block;<-------Change To  display: inline-block;---
  margin: auto;<----------remove---------
  right: 0;<--------------Add
  position: absolute;<-------------Add
  height: 21px;
  width: 24px;
}

.clearfix { <----------------Add
  width: 50%;
  padding-left: 0;
  position: relative;
}
</code>```

Full Code:

.nav {
  width: 1280px;
  margin: 0 auto;
  font-size: 16px;
  font-weight: 500;
  border: 1px solid black;
  position: relative;
}

.nav li {
  display: inline-block;
  vertical-align: top;
  margin: 5px 10px;

}

nav li:first-child {
  margin-left: 75px;
}

.nav img {
  display: inline-block;
  height: 21px;
  width: 24px;
  right: 0;
  position: absolute;
}

.clearfix {
      width: 50%;
      padding-left: 0;
      position: relative;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><nav class="nav">
    <ul class="clearfix">
      <li>Home</li>
      <li>Moments</li>
      <li>Notifications</li>
      <li>Messages</li>
      <img src="http://www.mrwallpaper.com/wallpapers/cute-bunny-1600x900.jpg" alt="Twitter Icon">
    </ul>
  </nav></code>```

Body:
I have an unordered list that contains several list elements inside. Also inside is an image element which is to be centered. I tried to center it using the margin: auto; property but since there are list elements on the side, it takes that into account when centering itself. How do I center the image in respect to it's container?

.nav {
  width: 1280px;
  margin: 0 auto;
  font-size: 16px;
  font-weight: 500;
  border: 1px solid black;
}

.nav li {
  float: left;
  vertical-align: top;
  margin: 5px 10px;
}

nav li:first-child {
  margin-left: 75px;
}

.nav img {
  display: block;
  margin: auto;
  height: 21px;
  width: 24px;
}

Home

Moments

Notifications

Messages

Body:
1) All Elements be Center

.nav {
  width: 1280px;
  margin: 0 auto;
  font-size: 16px;
  font-weight: 500;
  border: 1px solid black;
}

.nav li {
  float: left;<------Remove
  display: inline-block;<-----------Add
  vertical-align: top;
  margin: 5px 10px;
}

nav li:first-child {
  margin-left: 75px;<---------Change to margin-left: 0px;------
}

.nav img {
  display: block;<----------Change to display: inline-block;---
  margin: auto;<---------Remove
  height: 21px;
  width: 24px;
}

.clearfix{<-----------Add this Selector
  text-align: center;
  width: 100%;
  padding-left: 0;
}

Full Code:

.nav {
  width: 1280px;
  margin: 0 auto;
  font-size: 16px;
  font-weight: 500;
  border: 1px solid black;
}

.nav li {
  display: inline-block;
  vertical-align: top;
  margin: 5px 10px;
}

nav li:first-child {
  margin-left: 0px;
}

.nav img {
  display: inline-block;
  height: 21px;
  width: 24px;
}

.clearfix{
  text-align: center;
  width: 100%;
  padding-left: 0;
}

  <nav class="nav">
    <ul class="clearfix">
      <li>Home</li>
      <li>Moments</li>
      <li>Notifications</li>
      <li>Messages</li>
      <img src="http://www.mrwallpaper.com/wallpapers/cute-bunny-1600x900.jpg" alt="Twitter Icon">
    </ul>
  </nav>

2) Just image be Center

.nav {
  width: 1280px;
  margin: 0 auto;
  font-size: 16px;
  font-weight: 500;
  border: 1px solid black;
  position: relative;<---------Add
}

.nav li {
  float: left;<---------remove
  vertical-align: top;
  margin: 5px 10px;
}

nav li:first-child {
  margin-left: 75px;
}

.nav img {
  display: block;<-------Change To  display: inline-block;---
  margin: auto;<----------remove---------
  right: 0;<--------------Add
  position: absolute;<-------------Add
  height: 21px;
  width: 24px;
}

.clearfix { <----------------Add
  width: 50%;
  padding-left: 0;
  position: relative;
}

Full Code:

.nav {
  width: 1280px;
  margin: 0 auto;
  font-size: 16px;
  font-weight: 500;
  border: 1px solid black;
  position: relative;
}

.nav li {
  display: inline-block;
  vertical-align: top;
  margin: 5px 10px;

}

nav li:first-child {
  margin-left: 75px;
}

.nav img {
  display: inline-block;
  height: 21px;
  width: 24px;
  right: 0;
  position: absolute;
}

.clearfix {
      width: 50%;
      padding-left: 0;
      position: relative;
}

<nav class="nav">
    <ul class="clearfix">
      <li>Home</li>
      <li>Moments</li>
      <li>Notifications</li>
      <li>Messages</li>
      <img src="http://www.mrwallpaper.com/wallpapers/cute-bunny-1600x900.jpg" alt="Twitter Icon">
    </ul>
  </nav>


问:
Signalr ConnectedUsers
i am new with asp.net mvc and signalr. I send message to all clients in my message app but i want private messaging and in this article under the title "private chat" codes are like belove:

```<code>public void SendPrivateMessage(string toUserId, string message)
{

    string fromUserId = Context.ConnectionId;
    var toUser = ConnectedUsers.FirstOrDefault(x => x.ConnectionId == toUserId) ;
    var fromUser = ConnectedUsers.FirstOrDefault(x => x.ConnectionId == fromUserId);

    if (toUser != null && fromUser!=null)
    {
       // send to
       Clients.Client(toUserId).sendPrivateMessage(fromUserId, fromUser.UserName, message);

       // send to caller user
       Clients.Caller.sendPrivateMessage(toUserId, fromUser.UserName, message);
    }
}
</code>```

question.1: Does fromUserId have to be a number or id not a name?
question.2: Where did Connectedusers defined?because i am getting error about it.
And here is my code that sends messages to all clients:

```<code>public void Send(string alici,string name,string message)
{
    Clients.All.addNewMessageToPage(name, message);
    //alici:name of receiver, name:name of sender
}
</code>```

Can i use alici to send message to a specific user and how?
thanks

答:
Answer for Question 1:

toUserId must me ID that will be almost similar to GUID (Uniqueidentifier), this will help you identify each user separately even if there will be two Users with same name.

Question 2 is answered by radu-matei and thats correct by far my knowledge.

Title: Signalr ConnectedUsers

Body:
i am new with asp.net mvc and signalr. I send message to all clients in my message app but i want private messaging and in this article under the title "private chat" codes are like belove:

public void SendPrivateMessage(string toUserId, string message)
{

    string fromUserId = Context.ConnectionId;
    var toUser = ConnectedUsers.FirstOrDefault(x => x.ConnectionId == toUserId) ;
    var fromUser = ConnectedUsers.FirstOrDefault(x => x.ConnectionId == fromUserId);

    if (toUser != null && fromUser!=null)
    {
       // send to
       Clients.Client(toUserId).sendPrivateMessage(fromUserId, fromUser.UserName, message);

       // send to caller user
       Clients.Caller.sendPrivateMessage(toUserId, fromUser.UserName, message);
    }
}

question.1: Does fromUserId have to be a number or id not a name?
question.2: Where did Connectedusers defined?because i am getting error about it.
And here is my code that sends messages to all clients:

public void Send(string alici,string name,string message)
{
    Clients.All.addNewMessageToPage(name, message);
    //alici:name of receiver, name:name of sender
}

Can i use alici to send message to a specific user and how?
thanks