问:
mysql remove duplicate month
I want to remove duplicate month

this is my data

i want remove duplicate and show like this

this is my code

```<code><?php
    include "connect.php";
    $query = "select * from mydata";
    $result = mysqli_query($con,$query);
    while($data  = mysqli_fetch_array($result)){
        $dbasearray[] = $data['month_data'].",".$data['week_data'].",".$data['total_data'];
    }
    $s1 = array();
    $s2 = array();
    $a  = array();
    $b  = array();

    echo "<table border='1'>

            <tr>
                <th>Month</th>
                <th>Week</th>
                <th>Total</th>
                <th>s1</th>
                <th>s2</th>
                <th>a</th>
                <th>b</th>
            </tr>
            ";
        foreach ($dbasearray as $index => $datah){

            $data = explode(",", $datah);

            echo "<tr>";
            echo "<td align='center'>".$data[0]."</td>";
            echo "<td align='center'>".$data[1]."</td>";
            echo "<td align='center'>".$data[2]."</td>";
                if($index==0){
                    echo "<td>".$s1[$index] = $data[2]."</td>";
                    echo "<td>".$s2[$index] = $data[2]."</td>";
                }
                else {
                    echo "<td>".$s1[$index] = 0.1*$data[2]+0.9*$s1[$index-1]."</td>";
                    echo "<td>".$s2[$index] = 0.1*$s1[$index]+0.9*$s2[$index-1]."</td>";
                }
                echo "<td>".$a[$index] = 2*$s1[$index]-$s2[$index]."</td>";
                echo "<td>".$b[$index] = (0.1/0.9)*($s1[$index]-$s2[$index])."</td>";
            echo "</tr>";
        }
    echo "</table>";
    ?>
</code>```

i don't know to remove/hidden my code, i'm cannot using group by
help me. Thank's

答:
One suggestion, try printing the stuff inside the while loop itself , instead of storing in another variable and iterating multiple times. After you complete that,

Just do the following. You don't want duplicate months printed.
So, before the while loop add this.

```<code>$prev_month = '';
</code>```

then inside the while loop you need to input the correct month.

```<code>   if ($prev_month == $row['month'])
   {
       $month = '';
   }
   $prev_month = $row['month'];
</code>```

Use $month inside your html printing.

The complete code is written below. Check and see if it works.

```<code>$month = '';
$prev_month = '';
echo "<table border='3'>";
while($row=mysqli_fetch_array($result,MYSQLI_ASSOC)){
   echo "<tr>";
   $month = $row['month'];

   if ($prev_month == $row['month'])
   {
       $month = '';
   }
   $week = $row['week'];
   $total = $row['total'];
   $s1 = $row['s1'];
   $s2 = $row['s2'];
   $a = $row['a'];
   $b = $row['b'];

   echo "<td>";
   echo $month ;
   echo "</td>";

   echo "<td>";
   echo $week ;
   echo "</td>";

   echo "<td>";
   echo $total ;
   echo "</td>";

   echo "<td>";
   echo  $s1 ;
   echo "</td>";

   echo "<td>";
   echo $s2 ;
   echo "</td>";

   echo "<td>";
   echo $a ;
   echo "</td>";

   echo "<td>";
   echo $b ;
   echo "</td>";

   // Fill up the rest of fields and the print them
   echo "</tr>";
   $prev_month = $row['month'];

}
echo "</table>";
</code>```

Title: mysql remove duplicate month

Body:
I want to remove duplicate month

this is my data

i want remove duplicate and show like this

this is my code

<?php
    include "connect.php";
    $query = "select * from mydata";
    $result = mysqli_query($con,$query);
    while($data  = mysqli_fetch_array($result)){
        $dbasearray[] = $data['month_data'].",".$data['week_data'].",".$data['total_data'];
    }
    $s1 = array();
    $s2 = array();
    $a  = array();
    $b  = array();

    echo "

                Month
                Week
                Total
                s1
                s2
                a
                b

            ";
        foreach ($dbasearray as $index => $datah){

            $data = explode(",", $datah);

            echo "
";
            echo "".$data[0]."	";
            echo "".$data[1]."	";
            echo "".$data[2]."	";
                if($index==0){
                    echo "".$s1[$index] = $data[2]."	";
                    echo "".$s2[$index] = $data[2]."	";
                }
                else {
                    echo "".$s1[$index] = 0.1*$data[2]+0.9*$s1[$index-1]."	";
                    echo "".$s2[$index] = 0.1*$s1[$index]+0.9*$s2[$index-1]."	";
                }
                echo "".$a[$index] = 2*$s1[$index]-$s2[$index]."	";
                echo "".$b[$index] = (0.1/0.9)*($s1[$index]-$s2[$index])."	";
            echo "
";
        }
    echo "
";
    ?>

i don't know to remove/hidden my code, i'm cannot using group by
help me. Thank's

Body:
One suggestion, try printing the stuff inside the while loop itself , instead of storing in another variable and iterating multiple times. After you complete that,

Just do the following. You don't want duplicate months printed.
So, before the while loop add this.

$prev_month = '';

then inside the while loop you need to input the correct month.

   if ($prev_month == $row['month'])
   {
       $month = '';
   }
   $prev_month = $row['month'];

Use $month inside your html printing.

The complete code is written below. Check and see if it works.

$month = '';
$prev_month = '';
echo "<table border='3'>";
while($row=mysqli_fetch_array($result,MYSQLI_ASSOC)){
   echo "<tr>";
   $month = $row['month'];

   if ($prev_month == $row['month'])
   {
       $month = '';
   }
   $week = $row['week'];
   $total = $row['total'];
   $s1 = $row['s1'];
   $s2 = $row['s2'];
   $a = $row['a'];
   $b = $row['b'];

   echo "<td>";
   echo $month ;
   echo "</td>";

   echo "<td>";
   echo $week ;
   echo "</td>";

   echo "<td>";
   echo $total ;
   echo "</td>";

   echo "<td>";
   echo  $s1 ;
   echo "</td>";

   echo "<td>";
   echo $s2 ;
   echo "</td>";

   echo "<td>";
   echo $a ;
   echo "</td>";

   echo "<td>";
   echo $b ;
   echo "</td>";

   // Fill up the rest of fields and the print them
   echo "</tr>";
   $prev_month = $row['month'];

}
echo "</table>";


来源: stackexchange

问:
Levenstein distance substring
Is there a good way to use levenstein distance to match one particular string to any region within a second longer string?

Example:

```<code>str1='aaaaa'
str2='bbbbbbaabaabbbb'

if str1 in str2 with a distance < 2:
    return True
</code>```

So in the above example part of string 2 is aabaa and distance(str1,str2) < 2 so the statement should return True.

The only way I can think to do this is take 5 chars from str2 at a time, compare that with str1 and then repeat this moving through str2. Unfortunately this seems really inefficient and I need to process a large amount of data this way.

答:
The trick is to generate all the substrings of appropriate length of b, then compare each one.

```<code>def lev_dist(a,b):
    length_cost = abs(len(a) - len(b))
    diff_cost = sum(1 for (aa, bb) in zip(a,b) if aa != bb)
    return diff_cost + length_cost

def all_substr_of_length(n, s):
    if n > len(s):
        return [s]
    else:
        return [s[i:i+n] for i in range(0, len(s)-n+1)]

def lev_substr(a, b):
    """Gives minimum lev distance of all substrings of b and
    the single string a.
    """

    return min(lev_dist(a, bb) for bb in all_substr_of_length(len(a), b))

if lev_substr(str1, str2) < 2:
    # it works!
</code>```

ContentLicense: CC BY-SA 3.0

Title: Levenstein distance substring

Body:
Is there a good way to use levenstein distance to match one particular string to any region within a second longer string?

Example:

str1='aaaaa'
str2='bbbbbbaabaabbbb'

if str1 in str2 with a distance < 2:
    return True

So in the above example part of string 2 is aabaa and distance(str1,str2) < 2 so the statement should return True.

The only way I can think to do this is take 5 chars from str2 at a time, compare that with str1 and then repeat this moving through str2. Unfortunately this seems really inefficient and I need to process a large amount of data this way.

Body:
The trick is to generate all the substrings of appropriate length of b, then compare each one.

def lev_dist(a,b):
    length_cost = abs(len(a) - len(b))
    diff_cost = sum(1 for (aa, bb) in zip(a,b) if aa != bb)
    return diff_cost + length_cost

def all_substr_of_length(n, s):
    if n > len(s):
        return [s]
    else:
        return [s[i:i+n] for i in range(0, len(s)-n+1)]

def lev_substr(a, b):
    """Gives minimum lev distance of all substrings of b and
    the single string a.
    """

    return min(lev_dist(a, bb) for bb in all_substr_of_length(len(a), b))

if lev_substr(str1, str2) < 2:
    # it works!


问:
How can save (multiple) entries from a html form to an array in php?
I have an HTML form with three fields, first name surname and mid. name and I want to save this information in a php page. The problem is I don't know how to save multiple entries in array without a connection of database.

HTML form

```<code><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <title>Εργασία 11 - Βασίλης Τρίγκας</title>
    </head>
    <body>
        <h4>Καταχώριση βιβλίου</h4>
        <form action="form_action.php" method="get">
            Συγγραφέας <br/><input type="text" name="fnwriter" /><br/>
            Τίτλος <br/><input type="text" name="title" /><br/>
            Εκδότης<br/> <input type="text" name="editor" /><br />
            <input type="submit" value="Submit" />
        </form>

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

PHP File

```<code>    <?php

function display_welcome(){
    print("Σωστή εισαγωγή,  ");
    print($_GET['fnwriter','title','editor'])
}

function display_empty_form(){
    print <<<_HTML_
    <FORM method="post" action="$SERVER['PHP_SELF']">
    <BR/>
    <INPUT type="submit" value="SUBMIT NAME">
    </FORM>
    _HTML_;
}

if ($_GET['fnwriter','title']) {
    display_welcome();
}
else {
    display_empty_form();
}

$Book=array("fnwriter","title","editor");

$fwriter=$_GET['$fnwriter']
$title=$_GET['$title']
$editor=$_GET['$editor']

echo $fnwriter;
echo $title;
echo $editor;

for ($i = 0; $i < count($fnwriter,$title,$editor); ++$i) {
        echo "Book $i= $fnwriter[$i],$title[$i],$editor[$i]<br />";
    }

//echo $Book[$_GET];
//print_r($);
?>
</code>```

答:
I don't really get your question, is that about saving data to a file, or about processing $_POST data?

If it's the first one, you have a plenty of possibilities, from simple CSV (or any other separator) to XML ;)

ContentLicense: CC BY-SA 2.5

Body:
I have an HTML form with three fields, first name surname and mid. name and I want to save this information in a php page. The problem is I don't know how to save multiple entries in array without a connection of database.

HTML form

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">

        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <title>Εργασία 11 - Βασίλης Τρίγκας</title>

Καταχώριση βιβλίου

        <form action="form_action.php" method="get">
            Συγγραφέας
<input type="text" name="fnwriter" />

            Τίτλος
<input type="text" name="title" />

            Εκδότης
 <input type="text" name="editor" />

            <input type="submit" value="Submit" />
        </form>

PHP File

    <?php

function display_welcome(){
    print("Σωστή εισαγωγή,  ");
    print($_GET['fnwriter','title','editor'])
}

function display_empty_form(){
    print <<<_HTML_
    <FORM method="post" action="$SERVER['PHP_SELF']">

    <INPUT type="submit" value="SUBMIT NAME">
    </FORM>
    _HTML_;
}

if ($_GET['fnwriter','title']) {
    display_welcome();
}
else {
    display_empty_form();
}

$Book=array("fnwriter","title","editor");

$fwriter=$_GET['$fnwriter']
$title=$_GET['$title']
$editor=$_GET['$editor']

echo $fnwriter;
echo $title;
echo $editor;

for ($i = 0; $i < count($fnwriter,$title,$editor); ++$i) {
        echo "Book $i= $fnwriter[$i],$title[$i],$editor[$i]
";
    }

//echo $Book[$_GET];
//print_r($);
?>


问:
How to iterate through a STL set till the second last element?
I want to iterate through a STL set to do operations on elements pairwise in the set. For eg. if set S={1,2,3), I need to be able to check {1,2},{2,3},{1,3}.

So a very wrong C++ code for this would be as follows-

```<code>set<bitset<2501> > arr;
unsigned sz = arr.size();

rep(i,sz-1)
{
    for(j=i+1;j<sz;j++)
    {
        //do processing and in my case is an OR operation
        if(((arr[i])|(arr[j])) == num)
        {
            cnt++;
        }
    }
}
</code>```

I wrote the above wrong code to give you a better idea of what I want to do.
A better version (should have worked but did not) is as follows-

```<code>set<bitset<2501> >::iterator secondlast = arr.end();
advance(secondlast,-1);

for(set<bitset<2501> >::iterator it1 = arr.begin();it1!=secondlast;++it1)
{
    for(set<bitset<2501> >::iterator it2 = it1+1;it2!=arr.end();++it2)
    {
        //do processing, I didn't show the OR operation
    }
}
</code>```

The above code is giving the following errors-

```<code>error: no match for 'operator+' in 'it1 + 1'|
error: no match for 'operator<' in '__x < __y'|
</code>```

There were a lot of other notes, warnings also but I think the main culprits are these two errors. If you require the whole clipboard of errors, I'll edit it later on your say.

So I can you please solve the errors and help me do what I need to do :)

EDIT:
Even if I remove the inner loop from the code then also I'm getting errors.

```<code>set<bitset<2501> >::iterator secondlast = arr.end();
advance(secondlast,-1);

for(set<bitset<2501> >::iterator it1 = arr.begin();it1!=secondlast;++it1)
{

}
</code>```

答:
You may use the following in C++11:</p>

```<code>std::set<std::bitset<2501>> arr;
std::set<std::bitset<2501>>::iterator end= arr.end();

for(std::set<std::bitset<2501> >::iterator it1 = arr.begin();it1 != end; ++it1)
{
    for(std::set<std::bitset<2501> >::iterator it2 = std::next(it1); it2 != end; ++it2)
    {
        //do processing, I didn't show the OR operation
    }
}
</code>```

Body:
I want to iterate through a STL set to do operations on elements pairwise in the set. For eg. if set S={1,2,3), I need to be able to check {1,2},{2,3},{1,3}.

So a very wrong C++ code for this would be as follows-

set<bitset<2501> > arr;
unsigned sz = arr.size();

rep(i,sz-1)
{
    for(j=i+1;j<sz;j++)
    {
        //do processing and in my case is an OR operation
        if(((arr[i])|(arr[j])) == num)
        {
            cnt++;
        }
    }
}

I wrote the above wrong code to give you a better idea of what I want to do.
A better version (should have worked but did not) is as follows-

set<bitset<2501> >::iterator secondlast = arr.end();
advance(secondlast,-1);

for(set<bitset<2501> >::iterator it1 = arr.begin();it1!=secondlast;++it1)
{
    for(set<bitset<2501> >::iterator it2 = it1+1;it2!=arr.end();++it2)
    {
        //do processing, I didn't show the OR operation
    }
}

The above code is giving the following errors-

error: no match for 'operator+' in 'it1 + 1'|
error: no match for 'operator<' in '__x < __y'|

There were a lot of other notes, warnings also but I think the main culprits are these two errors. If you require the whole clipboard of errors, I'll edit it later on your say.

So I can you please solve the errors and help me do what I need to do :)

EDIT:
Even if I remove the inner loop from the code then also I'm getting errors.

set<bitset<2501> >::iterator secondlast = arr.end();
advance(secondlast,-1);

for(set<bitset<2501> >::iterator it1 = arr.begin();it1!=secondlast;++it1)
{

}

Body:
You may use the following in C++11:

std::set<std::bitset<2501>> arr;
std::set<std::bitset<2501>>::iterator end= arr.end();

for(std::set<std::bitset<2501> >::iterator it1 = arr.begin();it1 != end; ++it1)
{
    for(std::set<std::bitset<2501> >::iterator it2 = std::next(it1); it2 != end; ++it2)
    {
        //do processing, I didn't show the OR operation
    }
}


答:
You can achieve this with an case class and an UDF:</p>

```<code>case class MyStruct(x:Option[Int], y:Map[Double,Int])

import org.apache.spark.sql.functions.{udf, first,coalesce}

val emptyStruct = udf(() => MyStruct(None,Map.empty[Double,Int]))

df.groupBy($"a").pivot("a")
  .agg(first(coalesce($"b",emptyStruct())))
  .show(false)
</code>```

Title: Spark - named_struct for empty Map

Body:
I use Spark 2.0.1 Scala 2.11, and this question is related to this

Below is the setup:

val ss = new StructType().add("x", IntegerType).add("y", MapType(DoubleType, IntegerType))

val s = new StructType()
    .add("a", IntegerType)
    .add("b", ss)

val d = Seq(Row(1, Row(1,Map(1.0->1, 2.0->2))),
    Row(2, Row(2,Map(2.0->2, 3.0->3))),
    Row(3, null ),
    Row(4, Row(4, Map())))

val rd = sc.parallelize(d)
val df = spark.createDataFrame(rd, s)

df.select($"a", $"b").show(false)

// +---+---------------------------+
// |a  |b                          |
// +---+---------------------------+
// |1  |[1,Map(1.0 -> 1, 2.0 -> 2)]|
// |2  |[2,Map(2.0 -> 2, 3.0 -> 3)]|
// |3  |null                       |
// |4  |[4,Map()]                  |
// +---+---------------------------+
//

The below statement works when I have to provide a default to coalesce (row 2 col 3 cell has the default value):

df.groupBy($"a").pivot("a").
  agg(expr("first(coalesce(b, named_struct('x', cast(null as Int), 'y', Map(0.0D, 0) )))" ) )
  .show(false)

// +---+---------------------------+---------------------------+--------------------+---------+
// |a  |1                          |2                          |3                   |4        |
// +---+---------------------------+---------------------------+--------------------+---------+
// |1  |[1,Map(1.0 -> 1, 2.0 -> 2)]|null                       |null                |null     |
// |3  |null                       |null                       |[null,Map(0.0 -> 0)]|null     |
// |4  |null                       |null                       |null                |[4,Map()]|
// |2  |null                       |[2,Map(2.0 -> 2, 3.0 -> 3)]|null                |null     |
// +---+---------------------------+---------------------------+--------------------+---------+

But how to create an empty Map() (like what's seen in a=4) using named_struct or otherwise?

Body:
You can achieve this with an case class and an UDF:

case class MyStruct(x:Option[Int], y:Map[Double,Int])

import org.apache.spark.sql.functions.{udf, first,coalesce}

val emptyStruct = udf(() => MyStruct(None,Map.empty[Double,Int]))

df.groupBy($"a").pivot("a")
  .agg(first(coalesce($"b",emptyStruct())))
  .show(false)


问:
SQL error in laravel
I am trying to change a field in my users table to a varchar of 200.  Currently it is 60 and not long enough.  I tried using ->change() but because the table has an enum I get an error Unknown database type enum requested, Doctrine\DBAL\Platforms\MySQL57Platform may not support it.
As a result I am trying to change the column using a raw sql statement.
Here is the line I am trying to use.

```<code>DB::statement('ALTER TABLE users CHANGE COLUMN subrole VARCHAR(200)');
</code>```

When I try this I get an error

```<code>[Illuminate\Database\QueryException]
  SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the
  right syntax to use near 'VARCHAR(200)' at line 1 (SQL: ALTER TABLE users CHANGE COLUMN subrole VARCHAR(200))
</code>```

What do I need to change?  I am trying to change the column of subrole to size varchar 200.

答:
CHANGE is meant more for renaming columns and changing the definition:

```<code>CHANGE [COLUMN] old_col_name new_col_name column_definition
    [FIRST|AFTER col_name]
</code>```

You want MODIFY to change just the definition:

```<code>MODIFY [COLUMN] col_name column_definition
    [FIRST | AFTER col_name]
</code>```

MySQL Reference

Title: SQL error in laravel

Body:
I am trying to change a field in my users table to a varchar of 200.  Currently it is 60 and not long enough.  I tried using ->change() but because the table has an enum I get an error Unknown database type enum requested, Doctrine\DBAL\Platforms\MySQL57Platform may not support it.
As a result I am trying to change the column using a raw sql statement.
Here is the line I am trying to use.

DB::statement('ALTER TABLE users CHANGE COLUMN subrole VARCHAR(200)');

When I try this I get an error

[Illuminate\Database\QueryException]
  SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the
  right syntax to use near 'VARCHAR(200)' at line 1 (SQL: ALTER TABLE users CHANGE COLUMN subrole VARCHAR(200))

What do I need to change?  I am trying to change the column of subrole to size varchar 200.

Body:
CHANGE is meant more for renaming columns and changing the definition:

CHANGE [COLUMN] old_col_name new_col_name column_definition
    [FIRST|AFTER col_name]

You want MODIFY to change just the definition:

MODIFY [COLUMN] col_name column_definition
    [FIRST | AFTER col_name]

MySQL Reference


问:
Center a flex item when its siblings have different widths
I know flexbox offers a great solution for centering items. But I run into an issue when I have 3 items and I'd like the center (2nd) item to be centered with respect to the window, regardless of the size of the other 2 items.

In my pen you can see the second item "Client Index" is off-center because the content on the right is larger than the content on the left.  How can I force it to center itself?

.flex {
  display: flex;
  align-items: center;
  justify-content: space-between;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="flex">
  <span style="font-size:12px;">small</span>
  <span style="font-size:20px;">Client Index</span>
  <span style="font-size:18px;">Lots of content that moves the center</span>
</div></code>```

My Codepen

答:
One way would be to set flex-grow: 1; flex-basis: 0 so the 3 columns are distributed evenly, then you can center the text or the content in the middle one.

I'm using text-align to center the middle column. You could also use display: flex; justify-content: center; to do the same thing.

.flex {
  display: flex;
  align-items: center;
  justify-content: space-between;
}
.flex > span {
  flex: 1 0 0;
}
.flex > span:nth-child(2) {
  text-align: center;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="flex">
  <span style="font-size:12px;">small</span>
  <span style="font-size:20px;">Client Index</span>
  <span style="font-size:18px;">Lots of content that moves the center</span>
</div></code>```

Body:
I know flexbox offers a great solution for centering items. But I run into an issue when I have 3 items and I'd like the center (2nd) item to be centered with respect to the window, regardless of the size of the other 2 items.

In my pen you can see the second item "Client Index" is off-center because the content on the right is larger than the content on the left.  How can I force it to center itself?

.flex {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

  small
  Client Index
  Lots of content that moves the center

My Codepen

Body:
One way would be to set flex-grow: 1; flex-basis: 0 so the 3 columns are distributed evenly, then you can center the text or the content in the middle one.

I'm using text-align to center the middle column. You could also use display: flex; justify-content: center; to do the same thing.

.flex {
  display: flex;
  align-items: center;
  justify-content: space-between;
}
.flex > span {
  flex: 1 0 0;
}
.flex > span:nth-child(2) {
  text-align: center;
}

<div class="flex">
  <span style="font-size:12px;">small</span>
  <span style="font-size:20px;">Client Index</span>
  <span style="font-size:18px;">Lots of content that moves the center</span>
</div>


问:
Finding the longest border of a string
First, let me tell you what the border of a string is,

```<code>let x = "abacab"
let y = "ababab"
</code>```

The border of a string is a substring which is both a proper prefix and proper suffix of the string — "proper" meaning that the whole string does not count as a substring. The longest border of x is "ab". The longest border of y is "abab" (the prefix and suffix can overlap).

Another example:

In string "abcde hgrab abcde", then "abcde" is a prefix as well as suffix. Thus it is also the longest border of the string above.

How can I find the longest border of a string?

答:
Here is a JS solution with commentary that uses the prefix function that DAIe mentioned:

function getPrefixBorders(string) {
    // This will contain the border length for each
    // prefix in ascending order by prefix length.
    var borderLengthByPrefix = [0];

    // This is the length of the border on the current prefix.
    var curBorderLength = 0;

    // Loop from the 2nd character to the last.
    for (var i = 1; i < string.length; i++) {

        // As long as a border exists but the character
        // after it doesn't match the current character,
        while (curBorderLength > 0 && string[curBorderLength] !== string[i])
            // set the border length to the length of the current border's border.
            curBorderLength = borderLengthByPrefix[curBorderLength - 1];

        // If the characters do match,
        if (string[curBorderLength] === string[i])
            // the new border is 1 character longer.
            curBorderLength++;

        // Note the border length of the current prefix.
        borderLengthByPrefix[i] = curBorderLength;
    }

    return borderLengthByPrefix;
}
```

<p>It returns the longest border lengths of every prefix in a string (which is a lot more than asked for, but it does so in linear time). So to get the length of the longest border in the full string:</p>

```var string = "ababab";
var borderLengthsByPrefix = getPrefixBorders(); // [0,0,1,2,3,4]
var stringBorderLength = borderLengthsByPrefix[borderLengthsByPrefix.length - 1];
```

Another great resource for understanding how this works is this video (and the one before it) on Coursera.

Title: Finding the longest border of a string

Body:
First, let me tell you what the border of a string is,

let x = "abacab"
let y = "ababab"

The border of a string is a substring which is both a proper prefix and proper suffix of the string — "proper" meaning that the whole string does not count as a substring. The longest border of x is "ab". The longest border of y is "abab" (the prefix and suffix can overlap).

Another example:

In string "abcde hgrab abcde", then "abcde" is a prefix as well as suffix. Thus it is also the longest border of the string above.

How can I find the longest border of a string?

Body:
Here is a JS solution with commentary that uses the prefix function that DAIe mentioned:

function getPrefixBorders(string) {
    // This will contain the border length for each
    // prefix in ascending order by prefix length.
    var borderLengthByPrefix = [0];

    // This is the length of the border on the current prefix.
    var curBorderLength = 0;

    // Loop from the 2nd character to the last.
    for (var i = 1; i < string.length; i++) {

        // As long as a border exists but the character
        // after it doesn't match the current character,
        while (curBorderLength > 0 && string[curBorderLength] !== string[i])
            // set the border length to the length of the current border's border.
            curBorderLength = borderLengthByPrefix[curBorderLength - 1];

        // If the characters do match,
        if (string[curBorderLength] === string[i])
            // the new border is 1 character longer.
            curBorderLength++;

        // Note the border length of the current prefix.
        borderLengthByPrefix[i] = curBorderLength;
    }

    return borderLengthByPrefix;
}

It returns the longest border lengths of every prefix in a string (which is a lot more than asked for, but it does so in linear time). So to get the length of the longest border in the full string:

var string = "ababab";
var borderLengthsByPrefix = getPrefixBorders(); // [0,0,1,2,3,4]
var stringBorderLength = borderLengthsByPrefix[borderLengthsByPrefix.length - 1];

Another great resource for understanding how this works is this video (and the one before it) on Coursera.


问:
Can I redistribute the Microsoft T4 Engine with my product?
I'm generating code dynamically, currently using String.Format and embedding placeholders - but reformatting the C# code for use as a template is a pain, and I think using a T4 template would be better.

However, the code generation will be happening on a running system, so I need to know that I can safely and legally redistribute the Microsoft T4 Engine with my product.

Anyone else done this? Or know the (legal) answer?

答: I recalled this came up back in 2006 (before I knew what T4 was!) and went searching and found this http://social.msdn.microsoft.com/Forums/en-US/vsx/thread/1ab0bf3f-2810-4adf-bf75-900b98dee8e2/ Unfortunately the gotdotnet link is broken. Tricky to say whethere in that thread they are agreeing that you can legally host T4 outsid of VS and redistribute - or not.</p>

LastEditorDisplayName: Craig Stuntz

OwnerDisplayName: Eric Nelson


答:
You are using operator+ to get the next element through an iterator, use the preincrement operator, std::advance or std::next instead

```<code>#include <iostream>
#include <iterator>
#include <set>

using std::cout;
using std::endl;

int main() {
    std::set<int> s{1, 2, 3, 4};

    for (std::set<int>::iterator i = s.begin(); i != s.end(); ++i) {
        for (std::set<int>::iterator j = std::next(i); j != s.end(); ++j) {
            cout << *i << " and " << *j << endl;
        }
    }
}
</code>```

Title: How to iterate through a STL set till the second last element?

Body:
You are using operator+ to get the next element through an iterator, use the preincrement operator, std::advance or std::next instead

#include <iostream>
#include <iterator>
#include <set>

using std::cout;
using std::endl;

int main() {
    std::set<int> s{1, 2, 3, 4};

    for (std::set<int>::iterator i = s.begin(); i != s.end(); ++i) {
        for (std::set<int>::iterator j = std::next(i); j != s.end(); ++j) {
            cout << *i << " and " << *j << endl;
        }
    }
}


问:
Assigning event to subscribe with new
I'm making QuestSystem in unity.

what i want to do is assigning to my questData an event so it can know when the quest objective has been completed.

Lets say there is a class named A and action called a.

and i want Class B, Action b want to have reference to A.a

So if i do

b = A.a;,

b+= someAction;, it actually does a+=someAction;

but when if i do that. It will just simply b+=someAction and A.a will remain null

what should i do to perform what i want?

here are some tags. (i don't know what the answer would be. so..)

```<code># event
# subscribing event
# assigning event
# referencing event
# action
# delegate
</code>```

====== Edited =======
here is my code.

QuestData.cs

```<code>public class QuestData
{
    public string questName;
    public string qusetID;
    public string questDescription;
    public SceneType questSceneType;

    private string isActivePrefsKey { get { return $"QuestKey{qusetID}"; } }
    public bool isActive {
        get {
            return Convert.ToBoolean (PlayerPrefs.GetInt (isActivePrefsKey));
        }
        set { PlayerPrefs.SetInt (isActivePrefsKey, Convert.ToInt16 (value)); }
    }
    public QuestObjective questObjective;
    public QuestReward questReward;

    public void Activate ()
    {
        if (AppController.CurrentScene == questSceneType) {
            questObjective.ActivateObjective ();

        }
    }

}
</code>```

QuestObjective.cs

```<code>public class QuestObjective
{
    // TODO rename all
    public int goalObjectiveCount;
    public int currentObjectiveCount;

    public Action questAction;

    public void OnConditionMatch ()
    {
        Debug.Log ("OnConditionMatch");
        currentObjectiveCount += 1;
    }

    public void ActivateObjective ()
    {
        questAction += OnConditionMatch;
    }

}
</code>```

QuestManager.cs

```<code>public class QuestManager : MonoBehaviour
{

    List<QuestData> questDatas;

    void Awake ()
    {
        PrepareQuestDatas ();
        ActivateActiveQuests ();
    }

    void ActivateActiveQuests ()
    {
        var activeQuests = GetActiveQuests ();
        foreach (var activeQuest in activeQuests) {
            activeQuest.Activate ();
        }
    }

    List<QuestData> GetActiveQuests ()
    {
        // for debuging
        return questDatas;

        // real code
        return questDatas.Where (q => q.isActive == true).ToList ();
    }

    public void PrepareQuestDatas ()
    {
        questDatas = new List<QuestData> {
            new QuestData {
                questName = "Foot Print",
                questDescription  = "win the game for first time",
                questSceneType = SceneType.Main,
                questObjective = new QuestObjective {
                    goalObjectiveCount = 1,
                    questAction = GamePlayController.instance.endGameCon.onWinGame
                },
                questReward = new QuestCoinReward{
                    rewardAmount = 100,
                },
            }
        };
    }

}
</code>```

答:
One potential solution is to create a new set of EventArgs, like this:

```<code>public class QuestCompletedEventArgs : System.EventArgs
{
    public QuestObjective FinishedObjective { get; }
    public QuestCompletedEventArgs(QuestObjective objectiveIn) {
        this.FinishedObjective = objectiveIn;
    }
}
</code>```

(probably in a different file)
... and use it like this:

First, create an event delegate:

```<code>public delegate void QuestObjectiveCompleteHandler(object sender, QuestCompletedEventArgs e);
</code>```

Instantiate the event delegate:

```<code>public event QuestObjectiveCompletedHandler CompletedObjective;
</code>```

Define the method that will do something when the objective is completed:

```<code>public void ObjectiveCompleted(object sender, QuestCompletedEventArgs e)
{
    // do something
}
</code>```

Assign that method to the event:

```<code>this.CompletedObjective += this.ObjectiveCompleted;
</code>```

From here, you can make the FinishedObjective object within the QuestCompletedEventArgs a List<QuestObjective>, and FinishedObjective.add(objectiveIn) whenever appropriate.

You should also be able to make the event handling method act differently when a certain amount of objectives have been completed, or whatever you want to do with that information.

Of course, you can also add multiple different methods to respond to this event by adding more this.CompletedObjective += this.methodName; lines, as long as the signature of the new method(s) carry that same signature.

ContentLicense: CC BY-SA 4.0

Title: Assigning event to subscribe with new

Body:
I'm making QuestSystem in unity.

what i want to do is assigning to my questData an event so it can know when the quest objective has been completed.

Lets say there is a class named A and action called a.

and i want Class B, Action b want to have reference to A.a

So if i do

b = A.a;,

b+= someAction;, it actually does a+=someAction;

but when if i do that. It will just simply b+=someAction and A.a will remain null

what should i do to perform what i want?

here are some tags. (i don't know what the answer would be. so..)

# event
# subscribing event
# assigning event
# referencing event
# action
# delegate

====== Edited =======
here is my code.

QuestData.cs

public class QuestData
{
    public string questName;
    public string qusetID;
    public string questDescription;
    public SceneType questSceneType;

    private string isActivePrefsKey { get { return $"QuestKey{qusetID}"; } }
    public bool isActive {
        get {
            return Convert.ToBoolean (PlayerPrefs.GetInt (isActivePrefsKey));
        }
        set { PlayerPrefs.SetInt (isActivePrefsKey, Convert.ToInt16 (value)); }
    }
    public QuestObjective questObjective;
    public QuestReward questReward;

    public void Activate ()
    {
        if (AppController.CurrentScene == questSceneType) {
            questObjective.ActivateObjective ();

        }
    }

}

QuestObjective.cs

public class QuestObjective
{
    // TODO rename all
    public int goalObjectiveCount;
    public int currentObjectiveCount;

    public Action questAction;

    public void OnConditionMatch ()
    {
        Debug.Log ("OnConditionMatch");
        currentObjectiveCount += 1;
    }

    public void ActivateObjective ()
    {
        questAction += OnConditionMatch;
    }

}

QuestManager.cs

public class QuestManager : MonoBehaviour
{

    List<QuestData> questDatas;

    void Awake ()
    {
        PrepareQuestDatas ();
        ActivateActiveQuests ();
    }

    void ActivateActiveQuests ()
    {
        var activeQuests = GetActiveQuests ();
        foreach (var activeQuest in activeQuests) {
            activeQuest.Activate ();
        }
    }

    List<QuestData> GetActiveQuests ()
    {
        // for debuging
        return questDatas;

        // real code
        return questDatas.Where (q => q.isActive == true).ToList ();
    }

    public void PrepareQuestDatas ()
    {
        questDatas = new List<QuestData> {
            new QuestData {
                questName = "Foot Print",
                questDescription  = "win the game for first time",
                questSceneType = SceneType.Main,
                questObjective = new QuestObjective {
                    goalObjectiveCount = 1,
                    questAction = GamePlayController.instance.endGameCon.onWinGame
                },
                questReward = new QuestCoinReward{
                    rewardAmount = 100,
                },
            }
        };
    }

}

Body:
One potential solution is to create a new set of EventArgs, like this:

public class QuestCompletedEventArgs : System.EventArgs
{
    public QuestObjective FinishedObjective { get; }
    public QuestCompletedEventArgs(QuestObjective objectiveIn) {
        this.FinishedObjective = objectiveIn;
    }
}

(probably in a different file)
... and use it like this:

First, create an event delegate:

public delegate void QuestObjectiveCompleteHandler(object sender, QuestCompletedEventArgs e);

Instantiate the event delegate:

public event QuestObjectiveCompletedHandler CompletedObjective;

Define the method that will do something when the objective is completed:

public void ObjectiveCompleted(object sender, QuestCompletedEventArgs e)
{
    // do something
}

Assign that method to the event:

this.CompletedObjective += this.ObjectiveCompleted;

From here, you can make the FinishedObjective object within the QuestCompletedEventArgs a List<QuestObjective>, and FinishedObjective.add(objectiveIn) whenever appropriate.

You should also be able to make the event handling method act differently when a certain amount of objectives have been completed, or whatever you want to do with that information.

Of course, you can also add multiple different methods to respond to this event by adding more this.CompletedObjective += this.methodName; lines, as long as the signature of the new method(s) carry that same signature.


问:
Lagom: Asynchronous Operations in Command Handlers
In Lagom, what do you do when a command handler must perform some asynchronous operations? For example:

```<code>override def behavior = Actions().onCommand[MyCommand, Done] {
  case (cmd, ctx, state) =>
    // some complex code that performs asynchronous operations
    // (for example, querying other persistent entities or the read-side
    // by making calls that return Future[...] and composing those),
    // as summarized in a placeholder below:
    val events: Future[Seq[Event]] = ???
    events map {
      xs => ctx.thenPersistAll(xs: _*) { () => ctx.reply(Done) }
    }
}
</code>```

The problem with the code like that is that the compiler expects the command handler to return Persist, not Future[Persist].

Is this done on purpose, to make sure that the events are persisted in the correct order (that is, the events generated by a prior command must be saved before the events generated by a later command)? But can't that be handled by proper management of the event offsets, so that the journal always orders them correctly, regardless of when they are actually saved?

And what does one do in situations like this, when the command handling is complex enough to require making asynchronous calls from the command handler?

答:
There is a similar question on the mailing list with an answer from James.
https://groups.google.com/forum/?utm_medium=email&utm_source=footer#!topic/lagom-framework/Z6lynjNTqgE

In short, your entity in a CQRS application is a consistency boundary and should only depend on data that it's immediately available inside it, not outside (no call to external services).

What you are probably looking for a what it's called Command Enrichment. You receive an request, collect some data from external services and build a command containing everything you need to send to your Entity.

You certainly should not query the read-side to make business decisions inside your write-side entity. You also should not make business decisions on data coming from other entities.

Your entity should be able to make all the decision because it is the consistency boundary of your model.

Body:
In Lagom, what do you do when a command handler must perform some asynchronous operations? For example:

override def behavior = Actions().onCommand[MyCommand, Done] {
  case (cmd, ctx, state) =>
    // some complex code that performs asynchronous operations
    // (for example, querying other persistent entities or the read-side
    // by making calls that return Future[...] and composing those),
    // as summarized in a placeholder below:
    val events: Future[Seq[Event]] = ???
    events map {
      xs => ctx.thenPersistAll(xs: _*) { () => ctx.reply(Done) }
    }
}

The problem with the code like that is that the compiler expects the command handler to return Persist, not Future[Persist].

Is this done on purpose, to make sure that the events are persisted in the correct order (that is, the events generated by a prior command must be saved before the events generated by a later command)? But can't that be handled by proper management of the event offsets, so that the journal always orders them correctly, regardless of when they are actually saved?

And what does one do in situations like this, when the command handling is complex enough to require making asynchronous calls from the command handler?


问:
How to create a sub array from another array in Java?
How to create a sub-array from another array? Is there a method that takes the indexes from the first array such as:

```<code>methodName(object array, int start, int end)
</code>```

I don't want to go over making loops and making my program suffer.

I keep getting error:

cannot find symbol method copyOfRange(int[],int,int)

This is my code:

```<code>import java.util.*;

public class testing
{
    public static void main(String [] arg)
    {
        int[] src = new int[] {1, 2, 3, 4, 5};
        int b1[] = Arrays.copyOfRange(src, 0, 2);
    }
}
</code>```

答:
```<code>int newArrayLength = 30;

int[] newArray = new int[newArrayLength];

System.arrayCopy(oldArray, 0, newArray, 0, newArray.length);
</code>```

Body:
How to create a sub-array from another array? Is there a method that takes the indexes from the first array such as:

methodName(object array, int start, int end)

I don't want to go over making loops and making my program suffer.

I keep getting error:

cannot find symbol method copyOfRange(int[],int,int)

This is my code:

import java.util.*;

public class testing
{
    public static void main(String [] arg)
    {
        int[] src = new int[] {1, 2, 3, 4, 5};
        int b1[] = Arrays.copyOfRange(src, 0, 2);
    }
}


问:
I want to use the getUserMedia in Android Lollipop 5.0 WebView
I want to start a web camera using the getUserMedia in WebView of Android.
The following has written the code, but, errorCallback will have is called.
why not?

Incidentally, The following web site was implemented by reference to.

Android, WebViews, & getUserMedia: Putting it all together

```<code>myWebView = (WebView) findViewById(R.id.webview);

// Settings
WebSettings webSettings = myWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
webSettings.setAllowFileAccessFromFileURLs(true);
webSettings.setAllowUniversalAccessFromFileURLs(true);
myWebView.addJavascriptInterface(new WebAppInterface(this), “Android”);

// Set a web view client and a chrome client
myWebView.setWebViewClient(new WebViewClient());
myWebView.setWebChromeClient(new WebChromeClient() {
  // Need to accept permissions to use the camera and audio
  @Override
  public void onPermissionRequest(final PermissionRequest request) {
    Log.d(TAG, “onPermissionRequest”);
    MainActivity.this.runOnUiThread(new Runnable() {
      @TargetApi(Build.VERSION_CODES.LOLLIPOP)
      @Override
      public void run() {
        if(request.getOrigin().toString().equals(LOCAL_FILE)) {
          request.grant(request.getResources());
        }
        else {
            request.deny();
        }
      }
    });
  }
});
// Load the local HTML file into the webview
myWebView.loadUrl(LOCAL_FILE);
</code>```

[permissions]

```<code><uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" />
</code>```

[JavaScript]

```<code> var constraints = {video: true, audio: true};
 var localStream = null;
 function init() {
    console.log(‘Getting user media with constraints’, constraints);
    navigator.webkitGetUserMedia(constraints, handleUserMediaSuccess, handleUserMediaError);
 };

 function handleUserMediaSuccess(stream) {
    console.log(‘[+] Successfully got local video stream!’);
    attachMediaStream = function(element, stream) {
          element.src = window.webkitURL.createObjectURL(stream);
    };
    attachMediaStream(document.getElementById(“localVideo”), stream);
 };

 function handleUserMediaError(error) {
    alert(‘[!] getUserMedia error: ‘, error);
 };

 window.onload = function() {
    init();
 };
</code>```

答:
This was also failing for me following the same doc. The solution in my case: I needed to manually enable the permissions which the manifest was attempting to set. My device was not prompting me to accept them on installation.

On my Android device > Settings > Applications > Application Manager > MyAppName > Permissions > Turn on Camera & Microphone

Body:
I want to start a web camera using the getUserMedia in WebView of Android.
The following has written the code, but, errorCallback will have is called.
why not?

Incidentally, The following web site was implemented by reference to.

Android, WebViews, & getUserMedia: Putting it all together

myWebView = (WebView) findViewById(R.id.webview);

// Settings
WebSettings webSettings = myWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
webSettings.setAllowFileAccessFromFileURLs(true);
webSettings.setAllowUniversalAccessFromFileURLs(true);
myWebView.addJavascriptInterface(new WebAppInterface(this), “Android”);

// Set a web view client and a chrome client
myWebView.setWebViewClient(new WebViewClient());
myWebView.setWebChromeClient(new WebChromeClient() {
  // Need to accept permissions to use the camera and audio
  @Override
  public void onPermissionRequest(final PermissionRequest request) {
    Log.d(TAG, “onPermissionRequest”);
    MainActivity.this.runOnUiThread(new Runnable() {
      @TargetApi(Build.VERSION_CODES.LOLLIPOP)
      @Override
      public void run() {
        if(request.getOrigin().toString().equals(LOCAL_FILE)) {
          request.grant(request.getResources());
        }
        else {
            request.deny();
        }
      }
    });
  }
});
// Load the local HTML file into the webview
myWebView.loadUrl(LOCAL_FILE);

[permissions]

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" />

[JavaScript]

 var constraints = {video: true, audio: true};
 var localStream = null;
 function init() {
    console.log(‘Getting user media with constraints’, constraints);
    navigator.webkitGetUserMedia(constraints, handleUserMediaSuccess, handleUserMediaError);
 };

 function handleUserMediaSuccess(stream) {
    console.log(‘[+] Successfully got local video stream!’);
    attachMediaStream = function(element, stream) {
          element.src = window.webkitURL.createObjectURL(stream);
    };
    attachMediaStream(document.getElementById(“localVideo”), stream);
 };

 function handleUserMediaError(error) {
    alert(‘[!] getUserMedia error: ‘, error);
 };

 window.onload = function() {
    init();
 };


问:
Video play on hover
I have a selection of video thumbnails that I want to trigger to play/pause on hover. I have managed to get one of them to work, but I run into a problem with the others on the list. Attached is the fiddle of my code. There will be a div covering each html5 video so the hover needs to delegate to the video, which I'm unsure as to how to do.

https://jsfiddle.net/meh1aL74/

Preview of the html here -

```<code><div class="video">
            <div class="videoListCopy">
                <a href="videodetail.html" class="buttonMore">
                        <div class="breaker"><div class="line"></div></div>
                        <div class="buttonContent">
                            <div class="linkArrowContainer">
                                <div class="iconArrowRight"></div>
                                <div class="iconArrowRightTwo"></div>
                            </div>
                            <span>Others</span>
                        </div>
                    </a>
            </div>
            <div class="videoSlate">
                <video class="thevideo" loop>
                  <source src="http://www.w3schools.com/html/movie.ogg" type="video/ogg">
                Your browser does not support the video tag.
                </video>
            </div>
        </div>

          <div class="video">
            <div class="videoListCopy">
                <a href="videodetail.html" class="buttonMore">
                        <div class="breaker"><div class="line"></div></div>
                        <div class="buttonContent">
                            <div class="linkArrowContainer">
                                <div class="iconArrowRight"></div>
                                <div class="iconArrowRightTwo"></div>
                            </div>
                            <span>Others</span>
                        </div>
                    </a>
            </div>
            <div class="videoSlate">
                <video class="thevideo" loop>
                  <source src="http://www.w3schools.com/html/movie.ogg" type="video/ogg">
                Your browser does not support the video tag.
                </video>
            </div>
        </div>
</code>```

Preview of the JavaScript here -

```<code>    var figure = $(".video");
    var vid = $("video");

    [].forEach.call(figure, function (item) {
            item.addEventListener('mouseover', hoverVideo, false);
            item.addEventListener('mouseout', hideVideo, false);
    });

    function hoverVideo(e) {
            $('.thevideo')[0].play();
    }

    function hideVideo(e) {
            $('.thevideo')[0].pause();
    }
</code>```

Thank you very much for your help.

答:
Shortest version would be this one. No need for any fancy jQuery, just plain HTML:

```<code><div>
    <video onmouseover="this.play()" onmouseout="this.pause();this.currentTime=0;">
    <source src="yourVideo.ogg" type="video/ogg"></source>
    </video>
</div>
</code>```

This way it's a tad cleaner.

Title: Video play on hover

Body:
I have a selection of video thumbnails that I want to trigger to play/pause on hover. I have managed to get one of them to work, but I run into a problem with the others on the list. Attached is the fiddle of my code. There will be a div covering each html5 video so the hover needs to delegate to the video, which I'm unsure as to how to do.

https://jsfiddle.net/meh1aL74/

Preview of the html here -

                            Others

                <video class="thevideo" loop>
                  <source src="http://www.w3schools.com/html/movie.ogg" type="video/ogg">
                Your browser does not support the video tag.
                </video>

                            Others

                <video class="thevideo" loop>
                  <source src="http://www.w3schools.com/html/movie.ogg" type="video/ogg">
                Your browser does not support the video tag.
                </video>

Preview of the JavaScript here -

    var figure = $(".video");
    var vid = $("video");

    [].forEach.call(figure, function (item) {
            item.addEventListener('mouseover', hoverVideo, false);
            item.addEventListener('mouseout', hideVideo, false);
    });

    function hoverVideo(e) {
            $('.thevideo')[0].play();
    }

    function hideVideo(e) {
            $('.thevideo')[0].pause();
    }

Thank you very much for your help.

Body:
Shortest version would be this one. No need for any fancy jQuery, just plain HTML:

<div>
    <video onmouseover="this.play()" onmouseout="this.pause();this.currentTime=0;">
    <source src="yourVideo.ogg" type="video/ogg"></source>
    </video>
</div>

This way it's a tad cleaner.


问:
Printing in thread not working for python 3
For some reason I keep failing to create a simple thread using python 3, the code below prints "test" once and then leaves the program running without printing anymore lines.

```<code>import time, threading

def test():
    print("test")
    threading.Timer(1, test).start()

test()
</code>```

This code seems to work for millions of others, but not for me.

I'm not sure if this is just a printing failure or if the thread is not running at all. I've found and tried dozens of examples like the one above but they all give me the same issue (also time.sleep() has the same issue). I figure I might have to cancel the threading before I start a new one, but this has proven to be kind of difficult during a loop and I am not even sure that will work.

答: I found the solution to my problem, I was using git bash and apperently it doesn't show values when printing them in a loop so it would only print the first time the function was called. It works fine using windows CMD.</p>

Body:
For some reason I keep failing to create a simple thread using python 3, the code below prints "test" once and then leaves the program running without printing anymore lines.

import time, threading

def test():
    print("test")
    threading.Timer(1, test).start()

test()

This code seems to work for millions of others, but not for me.

I'm not sure if this is just a printing failure or if the thread is not running at all. I've found and tried dozens of examples like the one above but they all give me the same issue (also time.sleep() has the same issue). I figure I might have to cancel the threading before I start a new one, but this has proven to be kind of difficult during a loop and I am not even sure that will work.


问:
How to aggregate prices in OHLC-data
I have a SQL Server table with columns:

```<code>ID, START_DTTM, OPEN, HIGH, LOW, CLOSE
</code>```

I have to aggregate data hourly.

So, I tried this query:

```<code>SELECT
    ID,
    MIN(START_DTTM) START_DTTM,
    MAX(HIGH) AS HIGH,
    MIN(LOW) AS LOW
FROM
    MY_TABLE
GROUP BY
    ID, DATEPART(DAY, START_DTTM), DATEPART(HOUR, START_DTTM)
</code>```

and it works, but I can't pull OPEN and CLOSE.

I tried something like this:

```<code>FIRST_VALUE(OPEN_PRICE) OVER (PARTITION BY
DATEPART(DAY, START_DTTM), DATEPART(HOUR, START_DTTM) ORDER BY START_DTTM)
</code>```

And, of course, it doesn't work. What can I do?

答:
You can use a subquery for that:</p>

```<code>SELECT ID, MIN(START_DTTM) START_DTTM, MAX(HIGH) AS HIGH, MIN(LOW) AS LOW,
       MAX(CASE WHEN seqnum_asc = 1 THEN OPEN_PRICE END) as open_price,
       MAX(CASE WHEN seqnum_desc = 1 THEN CLOSE_PRICE END) as close_price
FROM (SELECT t.*,
             ROW_NUMBER() OVER (PARTITION BY ID, DATEPART(DAY, START_DTTM), DATEPART(HOUR, START_DTTM) ORDER BY STRT_DTTM) as seqnum_asc,
             ROW_NUMBER() OVER (PARTITION BY ID, DATEPART(DAY, START_DTTM), DATEPART(HOUR, START_DTTM) ORDER BY STRT_DTTM) as seqnum_desc
      FROM MY_TABLE
     ) t
GROUP BY ID, DATEPART(DAY, START_DTTM), DATEPART(HOUR, START_DTTM);
</code>```

Title: How to aggregate prices in OHLC-data

Body:
I have a SQL Server table with columns:

ID, START_DTTM, OPEN, HIGH, LOW, CLOSE

I have to aggregate data hourly.

So, I tried this query:

SELECT
    ID,
    MIN(START_DTTM) START_DTTM,
    MAX(HIGH) AS HIGH,
    MIN(LOW) AS LOW
FROM
    MY_TABLE
GROUP BY
    ID, DATEPART(DAY, START_DTTM), DATEPART(HOUR, START_DTTM)

and it works, but I can't pull OPEN and CLOSE.

I tried something like this:

FIRST_VALUE(OPEN_PRICE) OVER (PARTITION BY
DATEPART(DAY, START_DTTM), DATEPART(HOUR, START_DTTM) ORDER BY START_DTTM)

And, of course, it doesn't work. What can I do?

Body:
You can use a subquery for that:

SELECT ID, MIN(START_DTTM) START_DTTM, MAX(HIGH) AS HIGH, MIN(LOW) AS LOW,
       MAX(CASE WHEN seqnum_asc = 1 THEN OPEN_PRICE END) as open_price,
       MAX(CASE WHEN seqnum_desc = 1 THEN CLOSE_PRICE END) as close_price
FROM (SELECT t.*,
             ROW_NUMBER() OVER (PARTITION BY ID, DATEPART(DAY, START_DTTM), DATEPART(HOUR, START_DTTM) ORDER BY STRT_DTTM) as seqnum_asc,
             ROW_NUMBER() OVER (PARTITION BY ID, DATEPART(DAY, START_DTTM), DATEPART(HOUR, START_DTTM) ORDER BY STRT_DTTM) as seqnum_desc
      FROM MY_TABLE
     ) t
GROUP BY ID, DATEPART(DAY, START_DTTM), DATEPART(HOUR, START_DTTM);


问:
How to add this Javascript to my AMP webpage?
This script is a countdown for Christmas

Is it possible to display in an AMP HTML web page or not? If possible, how to do it? What is the minify Javascript that I should add to the AMP web page, please help me.

```<code><script type="text/javascript">// <![CDATA[
var today=new Date()

//Enter the occasion's MONTH (1-12) and DAY (1-31):
var theoccasion=new Date(today.getFullYear(), 12, 25)

//Customize text to show before and on occasion. Follow grammer below:
var beforeOccasionText="left until Christmas :) "
var onOccasiontext="Today is Christmas. Happy Holidays!"

var monthtext=new
Array("Jan","Feb","Mar","April","May","June","July","Aug","Sep","Oct","Nov","Dec")
theoccasion.setMonth(theoccasion.getMonth()-1) //change to 0-11 month format
var showdate="("+monthtext[theoccasion.getMonth()]+" "+theoccasion.getDate()+")" //show date of occasion

var one_day=1000*60*60*24
var calculatediff=""

calculatediff=Math.ceil((theoccasion.getTime()-today.getTime())/(one_day))
if (calculatediff<0){ //if bday already passed
var nextyeartoday=new Date()
nextyeartoday.setFullYear(today.getFullYear()+1)
calculatediff=Math.ceil((nextyeartoday.getTime()-
today.getTime())/(one_day)+calculatediff)
}

//Display message accordingly
var pluraldayornot=(calculatediff==1)? "day" : "days"
if (calculatediff>0)
    document.write("<b>"+calculatediff+" "+pluraldayornot+" "+beforeOccasionText+" "+showdate+"!</b>")
else if (calculatediff==0)
document.write("<b>"+onOccasiontext+" "+showdate+"!</b>")
// ]]></script>
</code>```

答:
You can't use custom javascript in AMP html. Instead, you should use one of AMP custom components to imitate whatever your script is supposed to do. If you tell me what you're trying to do with that script, I might be able to point you in the right direction.

Edit: you might be able to achieve what you're trying to do by using an HTML templating language that can do some math for you.


问:
I am searching extensible mail plugin for Hudson
I want to send reports about every Hudson job build ito mail. Mail address must be get by certain rule, for example: committer - vpupkin, his mail - vasya.pupkin@co.com. I have script which makes this transformation. Is there way to do this?</p>

答: If you are using an LDAP directory. You should be able to resolve the email address for a user through an email property of the user in the LDAP. Don't know if that also works with Active Directory (but you should be able to access your AD with the LDAP protocol).</p>


问:
Is there a registry setting I can change to make the default drag and drop to move not copy
I have a user that keeps whining that a file keeps copying and not moving.  After showing them multiple times what they need to do they still persist on complaining that "this needs to be fixed"

There is a program that does it but I dont' really want to download it
http://www.winmatrix.com/forums/index.php?/topic/34601-dragndrop-editor/

Inside they  said that the registry setting was

HKCR\AllFileSystemObject\DefaultDropEffect

and
HKCR*\DefaultDropEffect - dword, values are 1,2 or 4

However I can't find that registry setting in Windows 7.

答:
Simplified Instructions

1. Start Button -> Regedit <enter>

2. Navigate to HKEY_CLASSES_ROOT-->AllFileSystemObject

3. Right Click inside the right panel and select NEW ->DWORD

4. Name it DefaultDropEffect

5. Set the Value to 2 (decimal or hexadecimal does not matter)

6. Save

7. Test immediately, no reboot required.

Values:

0 or delete = default action

1 = Always copy

2 = Always move

4 = Always create shortcut


问:
How to run Alexa skill with the alexa-sdk on own server with Node.js without Lambda drop-in?
The Alexa skill docs will eventually allow you to send webhooks to https endpoints. However the SDK only documents lambda style alexa-sdk usage. How would one go about running Alexa applications on one's own server without anything abstracting Lambda? Is it possible to wrap the event and context objects?

答: You can already use your own endpoint. When you create a new skill, in the configuration tab, just choose HTTPS and provide your https endpoint. ASK will call your endpoint where you can run anything you want (tip, check ngrok.com to tunnel to your own dev machine). Regarding the event and context objects; your endpoint will receive the event object information. You don't need the context object for anything, that just lets you interact with Lambda-specific stuff (http://docs.aws.amazon.com/lambda/latest/dg/python-context-object.html). Just make sure that you comply with the (undocumented) timeouts by ASK and you are good to go.


问:
Debugging "Element is not clickable at point" error
I see this only in Chrome.

The full error message reads:

"org.openqa.selenium.WebDriverException: Element is not clickable at point (411, 675). Other element would receive the click: ..."

The element that 'would receive the click' is to the side of the element in question, not on top of it and not overlapping it, not moving around the page.

I have tried adding an offset, but that does not work either.  The item is on the displayed window without any need for scrolling.

答:
If you have jQuery loaded on the page, you can execute the following javascript command:

```<code>"$('#" + element_id + "').click()"
</code>```

Example using python executor:

```<code>driver.execute_script("$('#%s').click()" % element_id)
</code>```

Body:
If you have jQuery loaded on the page, you can execute the following javascript command:

"$('#" + element_id + "').click()"

Example using python executor:

driver.execute_script("$('#%s').click()" % element_id)


问:
How to get the list of application names and uninstall strings from JSON file and pass them as parameters to uninstall an application using powershell
I would like to read JSON file to get the list of application names and their respective uninstall strings and pass them as arguments in power shell to uninstall the apps irrespective of whether the apps are Windows Installer(MSI) or setup. Can someone please suggest me how to do this. Thanks</p>

答:
Use the ConvertFrom-JSON.
This will create a PSObject out of the JSON</p>

```<code>$TEST2 = $TEST | ConvertFrom-Json
</code>```

Body:
Use the ConvertFrom-JSON.
This will create a PSObject out of the JSON

$TEST2 = $TEST | ConvertFrom-Json


问:
Trigger events that are loaded via AJAX
The issue: when retrieving data from an Ajax request that contains components to be used in jQuery calls. The jQuery isn't working.

Solution: as answered by  Bikash Waiba the reason this happens is because the jQuery functionality needs to know the page has loaded.

答:
If you have several lines you must use a class attribute instead of an id attribute for the case of #likeClick, use the class .community-post-like-button ids should not be repeated in a same HTML document.
Your code would look like this then.

HTML

```<code><div class='community-post-like-button' id='likeClick' data-value='{$id}'>Like Me</div>
</code>```

JavaScript

```<code> $(document).ready(function() {
      $('.community-post-like-button').click(function(){
         var id = $(this).data('value');
         $.ajax({
         url: '../resources/handlers/like.php',
         type: 'POST',
         data: {id: id},
         cache:false,
          success: function(data) {
            $('#likeNumber').html(data);
          }
        });
       });
   });
</code>```

Title: Trigger events that are loaded via AJAX

Body:
If you have several lines you must use a class attribute instead of an id attribute for the case of #likeClick, use the class .community-post-like-button ids should not be repeated in a same HTML document.
Your code would look like this then.

HTML

<div class='community-post-like-button' id='likeClick' data-value='{$id}'>Like Me</div>

JavaScript

 $(document).ready(function() {
      $('.community-post-like-button').click(function(){
         var id = $(this).data('value');
         $.ajax({
         url: '../resources/handlers/like.php',
         type: 'POST',
         data: {id: id},
         cache:false,
          success: function(data) {
            $('#likeNumber').html(data);
          }
        });
       });
   });


问:
How to loop over form field choices and display associated model instance fields
I have a ModelForm with a multiple choice field. The choices are populated instances of Hikers belonging to a specific Club.

I want to customize the way my form displays, by displaying the choices in a table where the 1st column contains checkboxes, and a few more columns display the details of each hiker. So for example the columns are (checboxes, name, age, favourite hiking trail).

I'm not sure how to approach this. How  do I access and display the form field choices with it's associated model instance fields in my template. Anybody know of the Django way to do this?

```<code>#models.py
class Club(models.Model):
    title = models.CharField()
    hikers = models.ManyToManyField(Hikers)

class Hiker(models.Model):
    name = models.CharField()
    age = models.PositiveIntegerField()
    favourite_trail = models.CharField()

#forms.py
class ClubForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        club_pk = kwargs['club_pk']
        del kwargs['club_pk']
        super(ClubForm, self).__init__(*args, **kwargs)
        choices = [(ts.pk, ts.name) for hiker in Club.objects.filter(pk=club_pk)]
        self.fields['hikers'].choices = choices

    class Meta:
        model = Club
        fields = ('hikers',)
        widgets = {'hikers': forms.CheckboxSelectMultiple}
</code>```

答:
Easiest would be if you define the whole form in a HTML template. You should be able to iterate over a field's values in a template like that:</p>

```<code>{% for value, text in form.hikers.field.choices %}
    {{ value }}: {{ text }}
{% endfor %}
</code>```

Body:
I have a ModelForm with a multiple choice field. The choices are populated instances of Hikers belonging to a specific Club.

I want to customize the way my form displays, by displaying the choices in a table where the 1st column contains checkboxes, and a few more columns display the details of each hiker. So for example the columns are (checboxes, name, age, favourite hiking trail).

I'm not sure how to approach this. How  do I access and display the form field choices with it's associated model instance fields in my template. Anybody know of the Django way to do this?

#models.py
class Club(models.Model):
    title = models.CharField()
    hikers = models.ManyToManyField(Hikers)

class Hiker(models.Model):
    name = models.CharField()
    age = models.PositiveIntegerField()
    favourite_trail = models.CharField()

#forms.py
class ClubForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        club_pk = kwargs['club_pk']
        del kwargs['club_pk']
        super(ClubForm, self).__init__(*args, **kwargs)
        choices = [(ts.pk, ts.name) for hiker in Club.objects.filter(pk=club_pk)]
        self.fields['hikers'].choices = choices

    class Meta:
        model = Club
        fields = ('hikers',)
        widgets = {'hikers': forms.CheckboxSelectMultiple}

Body:
Easiest would be if you define the whole form in a HTML template. You should be able to iterate over a field's values in a template like that:

{% for value, text in form.hikers.field.choices %}
    {{ value }}: {{ text }}
{% endfor %}


问:
Converting Facebook post ID from String to int
I am making a news feed where I retrieve Facebook posts from a specific Facebook page. I retrieve those posts with help of the Facebook Graph API. I have a FeedItem which has an ID (int). The ID is also used to check which item is at the current position (Recyclerview).

The problem is that Facebook gives the posts a String ID. I have no idea how I can possibly convert this so that it will work with my application.

My Adapter:

```<code>public class FeedListAdapter extends RecyclerView.Adapter<FeedListAdapter.ViewHolder> {

private ImageLoader imageLoader = AppController.getInstance().getImageLoader();
private List<FeedItem> mFeedItems;
private Context mContext;

public FeedListAdapter(List<FeedItem> pFeedItems, Context pContext) {
    this.mFeedItems = pFeedItems;
    this.mContext = pContext;
}

/* Create methods for further adapter use.*/
@Override
public ViewHolder onCreateViewHolder(final ViewGroup parent, final int viewType) {
    View feedView = LayoutInflater.from(parent.getContext())
                                  .inflate(R.layout.feed_item, parent, false);
    return new ViewHolder(feedView);
}

@Override
public void onBindViewHolder(final ViewHolder holder, final int position) {
    holder.populateRow(getFeedItem(position));
}

@Override
public long getItemId(int position) {
    return mFeedItems.get(position).getId();
}

@Override
public int getItemCount() {
    return mFeedItems.size();
}

private FeedItem getFeedItem(int position) {
    return mFeedItems.get(position);
}

class ViewHolder extends RecyclerView.ViewHolder implements OnClickListener {

    private ImageView mProfilePic;
    private TextView mName;
    private TextView mTimestamp;
    private TextView mTxtStatusMsg;
    private FeedImageView mFeedImage;

    //initialize the variables
    ViewHolder(View view) {
        super(view);
        mProfilePic = (ImageView) view.findViewById(R.id.feedProfilePic);
        mName = (TextView) view.findViewById(R.id.feedName);
        mTimestamp = (TextView) view.findViewById(R.id.feedTimestamp);
        mTxtStatusMsg = (TextView) view.findViewById(R.id.feedStatusMessage);
        mFeedImage = (FeedImageView) view.findViewById(R.id.feedImage);
        view.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {

    }

    private void populateRow(FeedItem pFeedItem) {
        getProfilePic(pFeedItem);

        mName.setText(pFeedItem.getName());

        mTimestamp.setText(pFeedItem.getTimeStamp());

        mTxtStatusMsg.setText(pFeedItem.getStatus());

        getStatusImg(pFeedItem);
    }

    private void getProfilePic(FeedItem pFeedItem) {
        imageLoader.get(pFeedItem.getProfilePic(), new ImageListener() {
            @Override
            public void onResponse(ImageContainer response, boolean arg1) {
                if (response.getBitmap() != null) {
                    // load image into imageview
                    mProfilePic.setImageBitmap(response.getBitmap());
                }
            }

            @Override
            public void onErrorResponse(final VolleyError pVolleyError) {

            }
        });
    }

    private void getStatusImg(FeedItem pFeedItem) {
        if (pFeedItem.getImage() != null) {
            mFeedImage.setImageUrl(pFeedItem.getImage(), imageLoader);
            mFeedImage.setVisibility(View.VISIBLE);
            mFeedImage
                    .setResponseObserver(new FeedImageView.ResponseObserver() {
                        @Override
                        public void onError() {
                        }

                        @Override
                        public void onSuccess() {
                        }
                    });
        } else {
            mFeedImage.setVisibility(View.GONE);
        }
    }
}
</code>```

My FeedFragment:

```<code>public class FeedFragment extends android.support.v4.app.Fragment {

private static final String TAG = FeedFragment.class.getSimpleName();
private FeedListAdapter mListAdapter;
private List<FeedItem> mFeedItems;
private RecyclerView mRecyclerView;
private String FACEBOOKURL = "**URL OF MY FB-POSTDATA**";

// newInstance constructor for creating fragment with arguments
public static FeedFragment newInstance() {
    FeedFragment fragment = new FeedFragment();
    return fragment;
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    // Inflate the layout resource file
    View view = getActivity().getLayoutInflater().inflate(R.layout.fragment_feed, container, false);

    initRecyclerView(view);
    initCache();

    return view;
}

@Override
public void onStart() {
    super.onStart();
}

@Override
public void onResume() {
    super.onResume();
}

private void initRecyclerView(View pView) {
    mRecyclerView = (RecyclerView) pView.findViewById(R.id.fragment_feed_recyclerview);
    LayoutManager mLayoutManager = new LinearLayoutManager(getActivity());
    mRecyclerView.setLayoutManager(mLayoutManager);
    mRecyclerView.setHasFixedSize(false);

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        mRecyclerView.setNestedScrollingEnabled(true);
    }

    mFeedItems = new ArrayList<>();

    mListAdapter = new FeedListAdapter(mFeedItems, getActivity());
    mRecyclerView.setAdapter(mListAdapter);
}

private void initCache() {
    // We first check for cached request
    Cache cache = AppController.getInstance().getRequestQueue().getCache();
    Entry entry = cache.get(FACEBOOKURL);
    if (entry != null) {
        // fetch the data from cache
        try {
            String data = new String(entry.data, "UTF-8");
            try {
                parseJsonFeed(new JSONObject(data));
            } catch (JSONException e) {
                e.printStackTrace();
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

    } else {
        // making fresh volley request and getting json
        JsonObjectRequest jsonReq = new JsonObjectRequest(Method.GET,
                FACEBOOKURL, null, new Response.Listener<JSONObject>() {

            @Override
            public void onResponse(JSONObject response) {
                VolleyLog.d(TAG, "Response: " + response.toString());
                if (response != null) {
                    parseJsonFeed(response);
                }
            }
        }, new Response.ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError error) {
                VolleyLog.d(TAG, "Error: " + error.getMessage());
            }
        });

        // Adding request to volley request queue
        AppController.getInstance().addToRequestQueue(jsonReq);
    }
}
private void parseJsonFeed(JSONObject response) {
    try {
        JSONArray feedArray = response.getJSONArray("data");

        for (int i = 0; i < feedArray.length(); i++) {
            JSONObject feedObj = (JSONObject) feedArray.get(i);

            FeedItem item = new FeedItem();
            item.setId(Integer.parseInt(feedObj.getString("id")));
            item.setName("name of page");

            // Image might be null sometimes
            String image = feedObj.isNull("full_picture") ? null : feedObj
                    .getString("full_picture");
            item.setImage(image);
            // Status message might be null sometimes
            String status = feedObj.isNull("message") ? null : feedObj
                    .getString("message");
            item.setStatus(status);

            item.setProfilePic("**profile picture url**");
            item.setTimeStamp(feedObj.getString("created_time"));

            mFeedItems.add(item);
        }

        // notify data changes to list adapter
        mListAdapter.notifyDataSetChanged();
    } catch (JSONException e) {
        e.printStackTrace();
    }
} }
</code>```

As I said; I have no idea how to handle this and I figured someone here would maybe have an idea on how to convert this, so that I can use the String that the graph api gives me, and use it as an integer.

答:
If the id is all numeric, you should be able to do this: int id = Integer.valueOf(facebookId)

If you have an undescore you can try this:

```<code>public int getIdFromString(String postId) {
    String finalId;
    while (postId.indexOf("_") > 0) {
        finalId = postId.substring(0, postId.indexOf("_"));
        postId = finalId.concat(postId.substring(postId.indexOf("_") + 1));
    }
    return Integer.valueOf(postId);
}
</code>```

Body:
I am making a news feed where I retrieve Facebook posts from a specific Facebook page. I retrieve those posts with help of the Facebook Graph API. I have a FeedItem which has an ID (int). The ID is also used to check which item is at the current position (Recyclerview).

The problem is that Facebook gives the posts a String ID. I have no idea how I can possibly convert this so that it will work with my application.

My Adapter:

public class FeedListAdapter extends RecyclerView.Adapter<FeedListAdapter.ViewHolder> {

private ImageLoader imageLoader = AppController.getInstance().getImageLoader();
private List<FeedItem> mFeedItems;
private Context mContext;

public FeedListAdapter(List<FeedItem> pFeedItems, Context pContext) {
    this.mFeedItems = pFeedItems;
    this.mContext = pContext;
}

/* Create methods for further adapter use.*/
@Override
public ViewHolder onCreateViewHolder(final ViewGroup parent, final int viewType) {
    View feedView = LayoutInflater.from(parent.getContext())
                                  .inflate(R.layout.feed_item, parent, false);
    return new ViewHolder(feedView);
}

@Override
public void onBindViewHolder(final ViewHolder holder, final int position) {
    holder.populateRow(getFeedItem(position));
}

@Override
public long getItemId(int position) {
    return mFeedItems.get(position).getId();
}

@Override
public int getItemCount() {
    return mFeedItems.size();
}

private FeedItem getFeedItem(int position) {
    return mFeedItems.get(position);
}

class ViewHolder extends RecyclerView.ViewHolder implements OnClickListener {

    private ImageView mProfilePic;
    private TextView mName;
    private TextView mTimestamp;
    private TextView mTxtStatusMsg;
    private FeedImageView mFeedImage;

    //initialize the variables
    ViewHolder(View view) {
        super(view);
        mProfilePic = (ImageView) view.findViewById(R.id.feedProfilePic);
        mName = (TextView) view.findViewById(R.id.feedName);
        mTimestamp = (TextView) view.findViewById(R.id.feedTimestamp);
        mTxtStatusMsg = (TextView) view.findViewById(R.id.feedStatusMessage);
        mFeedImage = (FeedImageView) view.findViewById(R.id.feedImage);
        view.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {

    }

    private void populateRow(FeedItem pFeedItem) {
        getProfilePic(pFeedItem);

        mName.setText(pFeedItem.getName());

        mTimestamp.setText(pFeedItem.getTimeStamp());

        mTxtStatusMsg.setText(pFeedItem.getStatus());

        getStatusImg(pFeedItem);
    }

    private void getProfilePic(FeedItem pFeedItem) {
        imageLoader.get(pFeedItem.getProfilePic(), new ImageListener() {
            @Override
            public void onResponse(ImageContainer response, boolean arg1) {
                if (response.getBitmap() != null) {
                    // load image into imageview
                    mProfilePic.setImageBitmap(response.getBitmap());
                }
            }

            @Override
            public void onErrorResponse(final VolleyError pVolleyError) {

            }
        });
    }

    private void getStatusImg(FeedItem pFeedItem) {
        if (pFeedItem.getImage() != null) {
            mFeedImage.setImageUrl(pFeedItem.getImage(), imageLoader);
            mFeedImage.setVisibility(View.VISIBLE);
            mFeedImage
                    .setResponseObserver(new FeedImageView.ResponseObserver() {
                        @Override
                        public void onError() {
                        }

                        @Override
                        public void onSuccess() {
                        }
                    });
        } else {
            mFeedImage.setVisibility(View.GONE);
        }
    }
}

My FeedFragment:

public class FeedFragment extends android.support.v4.app.Fragment {

private static final String TAG = FeedFragment.class.getSimpleName();
private FeedListAdapter mListAdapter;
private List<FeedItem> mFeedItems;
private RecyclerView mRecyclerView;
private String FACEBOOKURL = "**URL OF MY FB-POSTDATA**";

// newInstance constructor for creating fragment with arguments
public static FeedFragment newInstance() {
    FeedFragment fragment = new FeedFragment();
    return fragment;
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    // Inflate the layout resource file
    View view = getActivity().getLayoutInflater().inflate(R.layout.fragment_feed, container, false);

    initRecyclerView(view);
    initCache();

    return view;
}

@Override
public void onStart() {
    super.onStart();
}

@Override
public void onResume() {
    super.onResume();
}

private void initRecyclerView(View pView) {
    mRecyclerView = (RecyclerView) pView.findViewById(R.id.fragment_feed_recyclerview);
    LayoutManager mLayoutManager = new LinearLayoutManager(getActivity());
    mRecyclerView.setLayoutManager(mLayoutManager);
    mRecyclerView.setHasFixedSize(false);

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        mRecyclerView.setNestedScrollingEnabled(true);
    }

    mFeedItems = new ArrayList<>();

    mListAdapter = new FeedListAdapter(mFeedItems, getActivity());
    mRecyclerView.setAdapter(mListAdapter);
}

private void initCache() {
    // We first check for cached request
    Cache cache = AppController.getInstance().getRequestQueue().getCache();
    Entry entry = cache.get(FACEBOOKURL);
    if (entry != null) {
        // fetch the data from cache
        try {
            String data = new String(entry.data, "UTF-8");
            try {
                parseJsonFeed(new JSONObject(data));
            } catch (JSONException e) {
                e.printStackTrace();
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

    } else {
        // making fresh volley request and getting json
        JsonObjectRequest jsonReq = new JsonObjectRequest(Method.GET,
                FACEBOOKURL, null, new Response.Listener<JSONObject>() {

            @Override
            public void onResponse(JSONObject response) {
                VolleyLog.d(TAG, "Response: " + response.toString());
                if (response != null) {
                    parseJsonFeed(response);
                }
            }
        }, new Response.ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError error) {
                VolleyLog.d(TAG, "Error: " + error.getMessage());
            }
        });

        // Adding request to volley request queue
        AppController.getInstance().addToRequestQueue(jsonReq);
    }
}
private void parseJsonFeed(JSONObject response) {
    try {
        JSONArray feedArray = response.getJSONArray("data");

        for (int i = 0; i < feedArray.length(); i++) {
            JSONObject feedObj = (JSONObject) feedArray.get(i);

            FeedItem item = new FeedItem();
            item.setId(Integer.parseInt(feedObj.getString("id")));
            item.setName("name of page");

            // Image might be null sometimes
            String image = feedObj.isNull("full_picture") ? null : feedObj
                    .getString("full_picture");
            item.setImage(image);
            // Status message might be null sometimes
            String status = feedObj.isNull("message") ? null : feedObj
                    .getString("message");
            item.setStatus(status);

            item.setProfilePic("**profile picture url**");
            item.setTimeStamp(feedObj.getString("created_time"));

            mFeedItems.add(item);
        }

        // notify data changes to list adapter
        mListAdapter.notifyDataSetChanged();
    } catch (JSONException e) {
        e.printStackTrace();
    }
} }

As I said; I have no idea how to handle this and I figured someone here would maybe have an idea on how to convert this, so that I can use the String that the graph api gives me, and use it as an integer.

Body:
If the id is all numeric, you should be able to do this: int id = Integer.valueOf(facebookId)

If you have an undescore you can try this:

public int getIdFromString(String postId) {
    String finalId;
    while (postId.indexOf("_") > 0) {
        finalId = postId.substring(0, postId.indexOf("_"));
        postId = finalId.concat(postId.substring(postId.indexOf("_") + 1));
    }
    return Integer.valueOf(postId);
}


问:
Joomla - Fatal error: Class 'JParameter' not found
I'm trying to upgrade Joomla 2.5.22 to 3.5.1, and last time I checked the progress bar, it was 86 %. I looked away for a moment and when I came back to check I saw the below error message.

Fatal error: Class 'JParameter' not found in
  /home/mywebsite/public_html/plugins/system/bigshotgoogleanalytics/bigshotgoogleanalytics.php on line 24

What is the cause of this error and how would it be fixed?

答:
bigshotanalytics is one of those plugins that cause a blank page or, at best, a fatal error when updating Joomla. This is because of its old code. I suggest you move the tracking code to your template. You can also add the tracking code to a custom HTML module (after removing the encapsulating div through an override) and then assign the module to a position in your template (the position should be in the  section of the HTML).

Now to answer your question, Joomla no longer uses JParameter - it uses JRegistry instead. So something like:

```<code>$jparameter = new JParameter('param1');
</code>```

Should be changed to:

```<code>$jregistry= new JRegistry();
$jparameter = $jregistry->get('param1');
</code>```

Body:
bigshotanalytics is one of those plugins that cause a blank page or, at best, a fatal error when updating Joomla. This is because of its old code. I suggest you move the tracking code to your template. You can also add the tracking code to a custom HTML module (after removing the encapsulating div through an override) and then assign the module to a position in your template (the position should be in the  section of the HTML).

Now to answer your question, Joomla no longer uses JParameter - it uses JRegistry instead. So something like:

$jparameter = new JParameter('param1');

Should be changed to:

$jregistry= new JRegistry();
$jparameter = $jregistry->get('param1');


问:
Is there a way to configure a view of builds that I started in Jenkins?
We have 'try' build jobs that developers can initiate with parameterized variables to point to a particular branch for pulling the code and trial running the build in jenkins. Is there a way I can customize a custom personal view showing only the builds that I have started? </p>

答:
The custom way

I think there's a way to customize a personal view by coding / modifying your Jenkins installation, jan-molak worked on that feature here.

You can check the commits and maybe implement something by your own, especially this and this.

The plugin

Take a look on View Job Filter If you configure it, there are options which seems to acomplish what you want:

Logged-in User Relevance Filter: This adds/removes jobs based on their
  relevance to the logged in user. For example: matching jobs that were
  started by the user, or where the user committed changes to the source
  code of the job; matching jobs with a name that contains the user’s
  name or login id.


问:
Access to svg from D3 library
So I have an SVG image(3 circles) generated from data with D3 library.

```<code>var myData = [1,2,3];
var svgViewport = d3.select("body").append("svg").attr("width","600").attr("height","600");
var circleSelection = svgViewport.selectAll("circle").data(myData);
var circleElements = circleSelection.enter().append("circle");

circleElements.attr("cx",function(d,i) {
    return d * 100;
})
    .attr("cy",function(d,i) {
        return d * 50;
    })
    .attr("r","35");

function greenBlue(d,i) {
    if (i % 2 === 0) {
        return "green";
    }
    else {
        return "blue";
    };
}

greenBlue(1,2);
var circleStyle = circleElements.style("fill",greenBlue);
</code>```

I want to when I mouse over an element it will change color. I know how to do it when elements are in HTML file, but I want to know how it

```<code>document.getElementById("info").onmouseover = function() {
mouseOver()};
</code>```

can be replaced in this case.

答:
Sure, start by reading the d3 documentation on event handling, which will bring you to the documentation for the .on method. So, if you'd like to change the color on mouseover, you'd use on, and this:

```<code>circleElements.on("mouseover", function() {
  d3.select(this).style("fill", "green");
});
</code>```

This example is nearly verbatim the example in the documentation.

Title: Access to svg from D3 library

Body:
So I have an SVG image(3 circles) generated from data with D3 library.

var myData = [1,2,3];
var svgViewport = d3.select("body").append("svg").attr("width","600").attr("height","600");
var circleSelection = svgViewport.selectAll("circle").data(myData);
var circleElements = circleSelection.enter().append("circle");

circleElements.attr("cx",function(d,i) {
    return d * 100;
})
    .attr("cy",function(d,i) {
        return d * 50;
    })
    .attr("r","35");

function greenBlue(d,i) {
    if (i % 2 === 0) {
        return "green";
    }
    else {
        return "blue";
    };
}

greenBlue(1,2);
var circleStyle = circleElements.style("fill",greenBlue);

I want to when I mouse over an element it will change color. I know how to do it when elements are in HTML file, but I want to know how it

document.getElementById("info").onmouseover = function() {
mouseOver()};

can be replaced in this case.

Body:
Sure, start by reading the d3 documentation on event handling, which will bring you to the documentation for the .on method. So, if you'd like to change the color on mouseover, you'd use on, and this:

circleElements.on("mouseover", function() {
  d3.select(this).style("fill", "green");
});

This example is nearly verbatim the example in the documentation.


问:
SAS-How to calculate observations with certain lags
Suppose the dataset has two columns

```<code>Date   Time     Price
01-03  11:00      1
01-03  11:02      2
01-03  11:02      3
01-03  11:03      4
01-03  11:07      5
01-04  11:00      4
01-04  11:01      6
01-04  11:01      7
</code>```

I need to add a new column that equals to the posted price in the most recently minutes in the same day. If this minutes has multiple price, it should select the first one. For example

```<code>Date   Time     Price   New
01-03  11:00      1      2
01-03  11:02      2      4
01-03  11:02      3      4
01-03  11:03      4      5
01-03  11:07      5      .
01-04  11:00      4      6
01-04  11:01      6      .
01-04  11:01      7      .
</code>```

I use the code (by date; if first.time;) to solve the problem of multiple date. Since the gap between time is not fixed, I cannot use lag function in this case. So I don't know how to select the first price in next most recently minute. Could anyone give me some solutions? THX

答:
With just base SAS, this isn't particularly hard, though this isn't the most efficient method if you have very large datasets, this should perform okay in general.

We iterate over the dataset starting at the following row, until we find a row that has either a different time OR a different date.  If different time, save that price as the new price, and if different date (or EOF) clear the new price variable.

```<code>data have;
input Date :$5. Time :time5. Price;
format time time5.;
datalines;
01-03  11:00      1
01-03  11:02      2
01-03  11:02      3
01-03  11:03      4
01-03  11:07      5
01-04  11:00      4
01-04  11:01      6
01-04  11:01      7
;;;;
run;

data want;
  set have nobs=nobs;
  do _i = _n_ to nobs until (new_date ne date or new_time > time);
    set have(rename=(date=new_date price=new_price time=new_time)) point=_i;
  end;
  if (date ne new_date) or (_i > nobs) then call missing(new_price);  *times that it searched beyond limits;
run;
</code>```

Body:
Suppose the dataset has two columns

Date   Time     Price
01-03  11:00      1
01-03  11:02      2
01-03  11:02      3
01-03  11:03      4
01-03  11:07      5
01-04  11:00      4
01-04  11:01      6
01-04  11:01      7

I need to add a new column that equals to the posted price in the most recently minutes in the same day. If this minutes has multiple price, it should select the first one. For example

Date   Time     Price   New
01-03  11:00      1      2
01-03  11:02      2      4
01-03  11:02      3      4
01-03  11:03      4      5
01-03  11:07      5      .
01-04  11:00      4      6
01-04  11:01      6      .
01-04  11:01      7      .

I use the code (by date; if first.time;) to solve the problem of multiple date. Since the gap between time is not fixed, I cannot use lag function in this case. So I don't know how to select the first price in next most recently minute. Could anyone give me some solutions? THX

Body:
With just base SAS, this isn't particularly hard, though this isn't the most efficient method if you have very large datasets, this should perform okay in general.

We iterate over the dataset starting at the following row, until we find a row that has either a different time OR a different date.  If different time, save that price as the new price, and if different date (or EOF) clear the new price variable.

data have;
input Date :$5. Time :time5. Price;
format time time5.;
datalines;
01-03  11:00      1
01-03  11:02      2
01-03  11:02      3
01-03  11:03      4
01-03  11:07      5
01-04  11:00      4
01-04  11:01      6
01-04  11:01      7
;;;;
run;

data want;
  set have nobs=nobs;
  do _i = _n_ to nobs until (new_date ne date or new_time > time);
    set have(rename=(date=new_date price=new_price time=new_time)) point=_i;
  end;
  if (date ne new_date) or (_i > nobs) then call missing(new_price);  *times that it searched beyond limits;
run;