问:
How do I use the d3 selection/join methods to change a line graph?
I'm using v4.

I want to dynamically change the data for a line graph, but I can't figure out how to get the data to the d attribute of the path element.  This does not work (no line is drawn):

```<code>    draw_line(data) {
        let selection = this.svg.select('path.line').datum(data);
        selection.enter()
             .append('path')
             .attr('class', 'line')
             .attr('d', this.line);
        selection
            .transition(this.transition)
            .attr('d', this.line);
    }
</code>```

The following does work, but it doesn't seem idiomatic (doesn't use enter(), exit(), etc.

```<code>    draw_line(data) {
        let path = this.svg.select('path.line');
        if (path.empty()) {
            this.svg
                .append('path')
                .datum(data)
                .attr('class', 'line')
                .attr('d', this.line);
        } else {
             path
                .datum(data)
                .transition(this.transition)
                .attr('d', this.line);
        }
    }
</code>```

I'm sure I'm missing something obvious..?

The following shouldn't be relevant for the question, but is included for reference.
The constructor and calling method look like:

```<code>class LineGraph {
    constructor(w, h, location) {
        this.margin = {top: 50, right: 50, bottom: 50, left: 50};
        this.outer_width = w;
        this.outer_heigth = h;
        this.width = this.outer_width - this.margin.left - this.margin.right;
        this.height = this.outer_heigth - this.margin.top - this.margin.bottom;

        this.svg = d3.select(location)
                     .append("svg")             // append the svg object to location
                       .attr("width", w)
                       .attr("height", h)
                     .append("g")               // appends a 'group' element to 'svg'
                        .attr("transform", `translate(${this.margin.left}, ${this.margin.top})`);
    }

    draw(data) {
        this.transition = d3.transition()
                            .duration(2000);

        // set the ranges
        this.x = d3.scaleTime().range([0, this.width]);
        this.bottomAxis = d3.axisBottom(this.x).ticks(d3.timeWeek);

        this.y = d3.scaleLinear().range([this.height, 0]);
        this.leftAxis = d3.axisLeft(this.y);

        this.line = d3.line()
          .x(d => this.x(d.date))
          .y(d => this.y(d.value));

        // this.draw_axes(data);
        this.draw_line(data);
    }
</code>```

and the invocation looks like:

```<code>let graph = new LineGraph(500, 500, '#content');
let parse_time = d3.timeParse('%d-%b-%y');
let data1 = [
    {date: parse_time('1-May-12'), value: 158.13},
    {date: parse_time('30-Apr-12'), value: 153.98},
    {date: parse_time('27-Apr-12'), value: 167.00}
];
let data2 = [
    {date: parse_time('2-May-12'), value: 242.42},
    {date: parse_time('1-May-12'), value: 158.13},
    {date: parse_time('30-Apr-12'), value: 153.98},
    {date: parse_time('27-Apr-12'), value: 167.00}
];
graph.draw(data1.sort((a, b) => a.date - b.date));

setTimeout(() => {
    graph.draw(data2.sort((a, b) => a.date - b.date));
}, 2000);
</code>```

答:
Unlike the data() method, datum() does not compute a join. According to the API:

Unlike selection.data, this method does not compute a join and does not affect indexes or the enter and exit selections.

Also, select and selectAll behave differently regarding grouping and data propagation. You should use selectAll, even if you have just one line in the chart. Have a look at this table:

Method
select()
selectAll()

Selection
selects the first element that matches the selector string
selects all elements that match the selector string

Grouping
Does not affect grouping
Affects grouping

Data propagation
Propagates data
Doesn't propagate data

Therefore, your first snippet should be:

```<code>draw_line(data) {

    let selection = this.svg.selectAll('path.line')
    //'selectAll' here ----------^
        .data([data]);
        // ^--- 'data' instead of 'datum'

    selection.enter()
         .append('path')
         .attr('class', 'line')
         .attr('d', this.line);

    selection.transition(this.transition)
        .attr('d', this.line);

}
</code>```

Body:
I'm using v4.

I want to dynamically change the data for a line graph, but I can't figure out how to get the data to the d attribute of the path element.  This does not work (no line is drawn):

    draw_line(data) {
        let selection = this.svg.select('path.line').datum(data);
        selection.enter()
             .append('path')
             .attr('class', 'line')
             .attr('d', this.line);
        selection
            .transition(this.transition)
            .attr('d', this.line);
    }

The following does work, but it doesn't seem idiomatic (doesn't use enter(), exit(), etc.

    draw_line(data) {
        let path = this.svg.select('path.line');
        if (path.empty()) {
            this.svg
                .append('path')
                .datum(data)
                .attr('class', 'line')
                .attr('d', this.line);
        } else {
             path
                .datum(data)
                .transition(this.transition)
                .attr('d', this.line);
        }
    }

I'm sure I'm missing something obvious..?

The following shouldn't be relevant for the question, but is included for reference.
The constructor and calling method look like:

class LineGraph {
    constructor(w, h, location) {
        this.margin = {top: 50, right: 50, bottom: 50, left: 50};
        this.outer_width = w;
        this.outer_heigth = h;
        this.width = this.outer_width - this.margin.left - this.margin.right;
        this.height = this.outer_heigth - this.margin.top - this.margin.bottom;

        this.svg = d3.select(location)
                     .append("svg")             // append the svg object to location
                       .attr("width", w)
                       .attr("height", h)
                     .append("g")               // appends a 'group' element to 'svg'
                        .attr("transform", `translate(${this.margin.left}, ${this.margin.top})`);
    }

    draw(data) {
        this.transition = d3.transition()
                            .duration(2000);

        // set the ranges
        this.x = d3.scaleTime().range([0, this.width]);
        this.bottomAxis = d3.axisBottom(this.x).ticks(d3.timeWeek);

        this.y = d3.scaleLinear().range([this.height, 0]);
        this.leftAxis = d3.axisLeft(this.y);

        this.line = d3.line()
          .x(d => this.x(d.date))
          .y(d => this.y(d.value));

        // this.draw_axes(data);
        this.draw_line(data);
    }

and the invocation looks like:

let graph = new LineGraph(500, 500, '#content');
let parse_time = d3.timeParse('%d-%b-%y');
let data1 = [
    {date: parse_time('1-May-12'), value: 158.13},
    {date: parse_time('30-Apr-12'), value: 153.98},
    {date: parse_time('27-Apr-12'), value: 167.00}
];
let data2 = [
    {date: parse_time('2-May-12'), value: 242.42},
    {date: parse_time('1-May-12'), value: 158.13},
    {date: parse_time('30-Apr-12'), value: 153.98},
    {date: parse_time('27-Apr-12'), value: 167.00}
];
graph.draw(data1.sort((a, b) => a.date - b.date));

setTimeout(() => {
    graph.draw(data2.sort((a, b) => a.date - b.date));
}, 2000);

Body:
Unlike the data() method, datum() does not compute a join. According to the API:

Unlike selection.data, this method does not compute a join and does not affect indexes or the enter and exit selections.

Also, select and selectAll behave differently regarding grouping and data propagation. You should use selectAll, even if you have just one line in the chart. Have a look at this table:

Method
select()
selectAll()

Selection
selects the first element that matches the selector string
selects all elements that match the selector string

Grouping
Does not affect grouping
Affects grouping

Data propagation
Propagates data
Doesn't propagate data

Therefore, your first snippet should be:

draw_line(data) {

    let selection = this.svg.selectAll('path.line')
    //'selectAll' here ----------^
        .data([data]);
        // ^--- 'data' instead of 'datum'

    selection.enter()
         .append('path')
         .attr('class', 'line')
         .attr('d', this.line);

    selection.transition(this.transition)
        .attr('d', this.line);

}


来源: stackexchange

问:
how to read Dc:creator tag in xml?
the rss feed export is:

<item>
<title>◀تنبلی گروهی چیست؟</title>
<link>
http://forum.mlmarketing.ir/showthread.php/241-◀تنبلی-گروهی-چیست؟?goto=newpost
</link>
<pubDate>Wed, 08 Feb 2017 07:37:19 GMT</pubDate>
<description>
*✏مهندس فرانسوی به نام رینگلمن که روی کارایی اسبها کار می کرد دریافت که قدرت حمل بار دو اسب با دو برابر قدرت حمل بار یک اسب برابر نیست. او این...
</description>
<content:encoded>
<![CDATA[

✏مهندس فرانسوی به نام رینگلمن که روی کارایی اسبها کار می کرد دریافت که قدرت حمل بار دو اسب با دو برابر قدرت حمل بار یک اسب برابر نیست. او این مطالعه را به رفتار گروهی انسانها نیز تعمیم داد. نتایج جالب توجه بود. اگر دو نفر در یک تیم طناب کشی حاضر شوند هر یک تا 93% توان خود را به کار خواهند گرفت. اگر طناب کشی بین گروههای سه نفره انجام شود هر یک از اعضاء تیم 85% توان خود را به کار خواهد گرفت، این عدد در مورد یک تیم هشت نفره برای هر فرد تنها 49% خواهد بود!

 ✏در روانشناسی اجتماعی ثابت شده است که کارایی گروهها و تیمهای کاری از جمع کارایی تک تک اعضاء گروه کمتر است. کاهش تلاش فرد در یک تیم ناشی از دیده نشدن است. در واقع افراد هنگامی حداکثر توان ذهنی و جسمی خود را به کار می گیرند که این تلاش به طور مشخص قابل سنجش و ارزیابی باشد. اگر صرف توان و تلاش یک فرد عضو یک تیم در عملکرد کلی گروه به طور مشخص قابل اندازه گیری نباشد، تنبلی کردن رفتار نرمال اعضاء گروه خواهد بود. به این پدیده تنبلی گروهی (Social Loafing) گفته می شود.

 ✏وقتی افراد با هم کار می کنند کارایی کاهش می یابد و این خیلی غیر عادی نیست. این کاهش کارایی تا حدی است که عملکرد کلی تیم به طور کامل مختل نشود چون در شرایطی که تیم ببازد هیچ یک از افراد از عواقب آن ایمن نخواهد بود. افراد در تیم سطح تنبلی خود را طوری تنظیم می کنند که به طور مشخص بازنده بودن تیم به چشم نیاید.

 ✏تنبلی گروهی پیامدهای جالب توجهی دارد. هیچ کس در یک گروه به تصور خود نمی خواهد پیامدهای منفی تصمیم گیریها و عملکرد گروهی را بپذیرد و مایل است(به ویژه زمانی که تیم باخته است) خود را پشت تصمیمات گروه پنهان کند(Diffusion of Responsibility).

 ✏از طرفی معمولا ریسک پذیری گروه از یک فرد مشخص بیشتر است. چرا که همه می دانند در صورتی که کارها خوب پیش نرود پیامدهای های آن گریبانگیر یک فرد نخواهد بود(Risky Shift). این موضوع می تواند بسیار خطرناک باشد به ویژه در مورد تصمیم های بسیار خاص، مانند هنگامی که قرار است راجع به شلیک اولین موشک اتمی تصمیم گیری شود.

 ✏ولی آیا رفتار تنبلی گروهی به مفهوم عدم کارایی تیمها است؟ پاسخ این سوال منفی است چرا که ما به جهت نیاز به تخصصهای متنوع در حوزه های مختلف و نیز آثار مثبت روانی همکاری بین افراد، الزام به تشکیل تیم داریم ولی جهت پرهیز از کاهش کارایی تیمی باید تا حد ممکن تیمهای کاری را در گروههای کوچکتر سازماندهی کنیم و به علاوه مکانیسم مشخصی برای اندازه گیری و ارزیابی عملکرد اعضاء تیم طراحی و اجراء کنیم.

 ✏شاید مثل "دیگی که برای من نجوشه، سر سگ توش بجوشه" نمایانگر شاخصه فرهنگی ما ایرانیان در فعالیتهای گروهی است. ما رفتارهای فردی و اجتماعی خود را متناسب با سودهای به شدت شخصی و کوتاه مدت تنظیم می کنیم و سوی چشمانمان در تشخیص منافع بلند اجتماعی به شدت ضعیف است. ما به طور آشکاری در فعالیتهای گروهی ضعیف ظاهر می شویم چون مسئولیت پذیری، تعهد، حس تعلق و همبستگی اجتماعی در جامعه اکنون ما در سطح مطلوبی نیست.

 *برگرفته از #کتاب The Art of Thinking Clearly

 به خانواده ام ال مارکتینگ بپیوندید

]]>
</content:encoded>
<category domain="http://forum.mlmarketing.ir/forumdisplay.php/128-روانشناسی">روانشناسی</category>
<dc:creator>Ali Mousavi</dc:creator>
<guid isPermaLink="true">
http://forum.mlmarketing.ir/showthread.php/241-◀تنبلی-گروهی-چیست؟
</guid>
</item>```
</div>
</div>
</p>

<p>I can read title, description, link and category tags data by the codes below, how can i read the dc:creator tag's data? i wrote some codes as dc:creator, and dc for element chooser, but it not works</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><?php
echo '<div id="MTForumBlock">
<table id="lastpost">
        <tr class="MTForumfirst">
            <td class="MTForumtitle">عنوان</td>
            <td class="MTForumview">موضوع</td>
            <td class="MTForumview">نویسنده</td>
</tr>';
$xml = simplexml_load_file('http://forum.mlmarketing.ir/external.php?type=RSS2', 'SimpleXMLElement',LIBXML_NOCDATA);
$p_cnt = count($xml->channel->item);
if($p_cnt == "0"){
echo'<div align="center"><font color="#008080" face="Tahoma">انجمن خالیست !</font></div>';
} else {
for($i = 0; $i < $p_cnt; $i++) {
$title = $xml->channel->item[$i]->title;
$description = $xml->channel->item[$i]->description;
$rssurl = $xml->channel->item[$i]->link;
$rsscat = $xml->channel->item[$i]->category;
$rsscreator = $xml->channel->item[$i]->dc;
if($title == ""){
$tle = 'بدون عنوان';
} else {
$tle = $xml->channel->item[$i]->title;
}
echo '<tr>
<td class="MTForumrowtitle">'.$tle.'</td>
<td class="MTForumrowtitle" style="width:186px">'.$rsscat.'</td>
<td class="MTForumrowtitle" style="width:186px">'.$rsscreator.'</td>
</tr>';
}

}

echo "        </tr>
    </table>
</div>";

?></code>```

答:
This is one worked for me:</p>

```<code>$credit = $item->children('dc', 'http://purl.org/dc/elements/1.1/');
echo("creator -".$credit."<br>");
</code>```

ContentLicense: CC BY-SA 3.0

Title: how to read Dc:creator tag in xml?

Body:
the rss feed export is:

<item>
<title>◀تنبلی گروهی چیست؟</title>
<link>
http://forum.mlmarketing.ir/showthread.php/241-◀تنبلی-گروهی-چیست؟?goto=newpost
</link>
<pubDate>Wed, 08 Feb 2017 07:37:19 GMT</pubDate>
<description>
*✏مهندس فرانسوی به نام رینگلمن که روی کارایی اسبها کار می کرد دریافت که قدرت حمل بار دو اسب با دو برابر قدرت حمل بار یک اسب برابر نیست. او این...
</description>
<content:encoded>
<![CDATA[

✏مهندس فرانسوی به نام رینگلمن که روی کارایی اسبها کار می کرد دریافت که قدرت حمل بار دو اسب با دو برابر قدرت حمل بار یک اسب برابر نیست. او این مطالعه را به رفتار گروهی انسانها نیز تعمیم داد. نتایج جالب توجه بود. اگر دو نفر در یک تیم طناب کشی حاضر شوند هر یک تا 93% توان خود را به کار خواهند گرفت. اگر طناب کشی بین گروههای سه نفره انجام شود هر یک از اعضاء تیم 85% توان خود را به کار خواهد گرفت، این عدد در مورد یک تیم هشت نفره برای هر فرد تنها 49% خواهد بود!

 ✏در روانشناسی اجتماعی ثابت شده است که کارایی گروهها و تیمهای کاری از جمع کارایی تک تک اعضاء گروه کمتر است. کاهش تلاش فرد در یک تیم ناشی از دیده نشدن است. در واقع افراد هنگامی حداکثر توان ذهنی و جسمی خود را به کار می گیرند که این تلاش به طور مشخص قابل سنجش و ارزیابی باشد. اگر صرف توان و تلاش یک فرد عضو یک تیم در عملکرد کلی گروه به طور مشخص قابل اندازه گیری نباشد، تنبلی کردن رفتار نرمال اعضاء گروه خواهد بود. به این پدیده تنبلی گروهی (Social Loafing) گفته می شود.

 ✏وقتی افراد با هم کار می کنند کارایی کاهش می یابد و این خیلی غیر عادی نیست. این کاهش کارایی تا حدی است که عملکرد کلی تیم به طور کامل مختل نشود چون در شرایطی که تیم ببازد هیچ یک از افراد از عواقب آن ایمن نخواهد بود. افراد در تیم سطح تنبلی خود را طوری تنظیم می کنند که به طور مشخص بازنده بودن تیم به چشم نیاید.

 ✏تنبلی گروهی پیامدهای جالب توجهی دارد. هیچ کس در یک گروه به تصور خود نمی خواهد پیامدهای منفی تصمیم گیریها و عملکرد گروهی را بپذیرد و مایل است(به ویژه زمانی که تیم باخته است) خود را پشت تصمیمات گروه پنهان کند(Diffusion of Responsibility).

 ✏از طرفی معمولا ریسک پذیری گروه از یک فرد مشخص بیشتر است. چرا که همه می دانند در صورتی که کارها خوب پیش نرود پیامدهای های آن گریبانگیر یک فرد نخواهد بود(Risky Shift). این موضوع می تواند بسیار خطرناک باشد به ویژه در مورد تصمیم های بسیار خاص، مانند هنگامی که قرار است راجع به شلیک اولین موشک اتمی تصمیم گیری شود.

 ✏ولی آیا رفتار تنبلی گروهی به مفهوم عدم کارایی تیمها است؟ پاسخ این سوال منفی است چرا که ما به جهت نیاز به تخصصهای متنوع در حوزه های مختلف و نیز آثار مثبت روانی همکاری بین افراد، الزام به تشکیل تیم داریم ولی جهت پرهیز از کاهش کارایی تیمی باید تا حد ممکن تیمهای کاری را در گروههای کوچکتر سازماندهی کنیم و به علاوه مکانیسم مشخصی برای اندازه گیری و ارزیابی عملکرد اعضاء تیم طراحی و اجراء کنیم.

 ✏شاید مثل "دیگی که برای من نجوشه، سر سگ توش بجوشه" نمایانگر شاخصه فرهنگی ما ایرانیان در فعالیتهای گروهی است. ما رفتارهای فردی و اجتماعی خود را متناسب با سودهای به شدت شخصی و کوتاه مدت تنظیم می کنیم و سوی چشمانمان در تشخیص منافع بلند اجتماعی به شدت ضعیف است. ما به طور آشکاری در فعالیتهای گروهی ضعیف ظاهر می شویم چون مسئولیت پذیری، تعهد، حس تعلق و همبستگی اجتماعی در جامعه اکنون ما در سطح مطلوبی نیست.

 *برگرفته از #کتاب The Art of Thinking Clearly

 به خانواده ام ال مارکتینگ بپیوندید

]]>
</content:encoded>
<category domain="http://forum.mlmarketing.ir/forumdisplay.php/128-روانشناسی">روانشناسی</category>
<dc:creator>Ali Mousavi</dc:creator>
<guid isPermaLink="true">
http://forum.mlmarketing.ir/showthread.php/241-◀تنبلی-گروهی-چیست؟
</guid>
</item>

I can read title, description, link and category tags data by the codes below, how can i read the dc:creator tag's data? i wrote some codes as dc:creator, and dc for element chooser, but it not works

<?php
echo '

            عنوان
            موضوع
            نویسنده

';
$xml = simplexml_load_file('http://forum.mlmarketing.ir/external.php?type=RSS2', 'SimpleXMLElement',LIBXML_NOCDATA);
$p_cnt = count($xml->channel->item);
if($p_cnt == "0"){
echo'
انجمن خالیست !
';
} else {
for($i = 0; $i < $p_cnt; $i++) {
$title = $xml->channel->item[$i]->title;
$description = $xml->channel->item[$i]->description;
$rssurl = $xml->channel->item[$i]->link;
$rsscat = $xml->channel->item[$i]->category;
$rsscreator = $xml->channel->item[$i]->dc;
if($title == ""){
$tle = 'بدون عنوان';
} else {
$tle = $xml->channel->item[$i]->title;
}
echo '

'.$tle.'
'.$rsscat.'
'.$rsscreator.'

';
}

}

echo "

";

?>

Body:
This is one worked for me:

$credit = $item->children('dc', 'http://purl.org/dc/elements/1.1/');
echo("creator -".$credit."<br>");


问:
pandas.concat forgets column names
I'm trying to create a new DataFrame from columns of two existing frames but after the concat(), the column names are lost and I can't assign new ones:

```<code>import pandas
import datetime

dt = datetime.datetime

df1 = pandas.DataFrame({'value': [1.1, 2.1], 'foo': ['a', 'b']}, index=[dt(2015, 11, 1), dt(2015, 11, 2)])
df2 = pandas.DataFrame({'value': [1.2, 2.2]}, index=[dt(2015, 11, 3), dt(2015, 11, 4)])

# Keeps 'foo'
df = pandas.concat([df1, df2])
print df
print

# Without foo but column names are also lost
# plus there is an additional odd line "Name: value, dtype: float64"
df = pandas.concat([df1['value'], df2['value']])
print df
print

# AttributeError: 'Series' object has no attribute 'columns'
print repr(df.columns)
# no effect (probably because this isn't a supported attribute)
df.columns = ['value']
print df

# Fails: rename() got an unexpected keyword argument "columns"
df.rename(columns={'': 'value'}, inplace=True)
print df
</code>```

Output that I get:

```<code>2015-11-01    1.1
2015-11-02    2.1
2015-11-03    1.2
2015-11-04    2.2
</code>```

Output that I want:

```<code>            value
2015-11-01    1.1
2015-11-02    2.1
2015-11-03    1.2
2015-11-04    2.2
</code>```

答:
I found it best to do this.</p>

```<code>new_df = pd.concat([my_df1, my_df2.rename('Name')], axis = 1)
</code>```

Title: pandas.concat forgets column names

Body:
I'm trying to create a new DataFrame from columns of two existing frames but after the concat(), the column names are lost and I can't assign new ones:

import pandas
import datetime

dt = datetime.datetime

df1 = pandas.DataFrame({'value': [1.1, 2.1], 'foo': ['a', 'b']}, index=[dt(2015, 11, 1), dt(2015, 11, 2)])
df2 = pandas.DataFrame({'value': [1.2, 2.2]}, index=[dt(2015, 11, 3), dt(2015, 11, 4)])

# Keeps 'foo'
df = pandas.concat([df1, df2])
print df
print

# Without foo but column names are also lost
# plus there is an additional odd line "Name: value, dtype: float64"
df = pandas.concat([df1['value'], df2['value']])
print df
print

# AttributeError: 'Series' object has no attribute 'columns'
print repr(df.columns)
# no effect (probably because this isn't a supported attribute)
df.columns = ['value']
print df

# Fails: rename() got an unexpected keyword argument "columns"
df.rename(columns={'': 'value'}, inplace=True)
print df

Output that I get:

2015-11-01    1.1
2015-11-02    2.1
2015-11-03    1.2
2015-11-04    2.2

Output that I want:

            value
2015-11-01    1.1
2015-11-02    2.1
2015-11-03    1.2
2015-11-04    2.2

Body:
I found it best to do this.

new_df = pd.concat([my_df1, my_df2.rename('Name')], axis = 1)


问:
Testing Facebook Messenger Opt-in callback
I am trying to test my webhook that subscribes to the messaging_optins event, but I am struggling to manually trigger the event.

The documentation seems to indicate that using the "Send to Messenger" plugin should fire this event, but after setting up the button no event is triggered. The user is redirected to messenger website and asked to login, and then directed to an empty conversation with my page. I have tried this as my admin user, a random real Facebook account and a test account for my app.

When should this event be fired? And how can i trigger the event manually?

Edit

I would like to note that my webhooks are working and I am able to receive events for messages being received. Just not the opt-ins event.

答:
You can use the curl request below, if you are checking sha1 signature then replace the SHA1OFTHEBODY with sha1 signature of the payload and replace the https://chabotproxy.com/messenger/webhooks with your webhook endpoint url:

```<code>curl -X POST -H "x-hub-signature: sha1=SHA1OFTHEBODY" -H "content-type: application/json" -d '{
  "object":"page",
  "entry":[
    {
      "id":"PAGE_ID",
      "time":1458692752478,
      "messaging":[
        {
          "sender":{
            "id":"USER_ID"
          },
          "recipient":{
            "id":"PAGE_ID"
          },
          "timestamp":1234567890,
          "optin":{
            "ref":"chatbotproxy.com"
          }
        }
      ]
    }
  ]
}' https://chabotproxy.com/messenger/webhooks
</code>```

Body:
You can use the curl request below, if you are checking sha1 signature then replace the SHA1OFTHEBODY with sha1 signature of the payload and replace the https://chabotproxy.com/messenger/webhooks with your webhook endpoint url:

curl -X POST -H "x-hub-signature: sha1=SHA1OFTHEBODY" -H "content-type: application/json" -d '{
  "object":"page",
  "entry":[
    {
      "id":"PAGE_ID",
      "time":1458692752478,
      "messaging":[
        {
          "sender":{
            "id":"USER_ID"
          },
          "recipient":{
            "id":"PAGE_ID"
          },
          "timestamp":1234567890,
          "optin":{
            "ref":"chatbotproxy.com"
          }
        }
      ]
    }
  ]
}' https://chabotproxy.com/messenger/webhooks


问:
Loop through files in directory, and compare latest 2 files for duplicates
I am writing a python 2.7 script to compare the latest (2) files in a list returned from all_current_files this lists all of the file names in a directory e.g. myimage.jpg, myimage1.jpg, etc.

For example, if my list looked like:

```<code>1  myfile1.jpg
2  myfile2.jpg
3  myfile3.jpg
4  myfile4.jpg
5  myfile5.jpg
6  myfile6.jpg
</code>```

defined as list = ['myfile1.jpg','myfile2'] etc..

if the differences between the hashes of file 6, and 5 was 10, then the script would do nothing, if it was less than 5, it'd delete it.

I'm having trouble formulating how to compare the last 2 elements in the list in a recursive fashion (starting from the end), until all list items are compared - can someone help?

I currently have:

```<code>def purgeDups():
    print "purging duplicate images every hour...\n\n"
    all_current_files = os.listdir('filllll...in...image...dir...here')
    for file in all_current_files:
        #check latest file... and compare to second latest file based on timestamp of file, recurse until no more files.

        #begin comparing files...if difference between latest all_current_files and second latest is less than 5, delete
        latest = imagehash.average_hash(Image.open(<<latestfilefrom2linesabove>>))
        secLatest = imagehash.average_hash(Image.open(<<secondlatestfrom2linesabove>>))
        compare = latest-secLatest
        if int(compare) < 5:
            os.remove(<<latestfilefrom2linesabove>>)
            os.remove(<<secondlatestfilefrom2linesabove>>)
</code>```

Thanks much.

答:
There's no need for recursion here. If you want to compare all possible pairs, I'd recommend you use a nested loop, like this:</p>

```<code>for f1 in os.listdir('.'):
    for f2 in os.listdir('.'):
        if f1 == f2 or not os.path.exists(f1) or not os.path.exists(f2):  # don't compare the same file, or files that have already been deleted
            continue
        ... # file comparison code here
</code>```

Body:
I am writing a python 2.7 script to compare the latest (2) files in a list returned from all_current_files this lists all of the file names in a directory e.g. myimage.jpg, myimage1.jpg, etc.

For example, if my list looked like:

1  myfile1.jpg
2  myfile2.jpg
3  myfile3.jpg
4  myfile4.jpg
5  myfile5.jpg
6  myfile6.jpg

defined as list = ['myfile1.jpg','myfile2'] etc..

if the differences between the hashes of file 6, and 5 was 10, then the script would do nothing, if it was less than 5, it'd delete it.

I'm having trouble formulating how to compare the last 2 elements in the list in a recursive fashion (starting from the end), until all list items are compared - can someone help?

I currently have:

def purgeDups():
    print "purging duplicate images every hour...\n\n"
    all_current_files = os.listdir('filllll...in...image...dir...here')
    for file in all_current_files:
        #check latest file... and compare to second latest file based on timestamp of file, recurse until no more files.

        #begin comparing files...if difference between latest all_current_files and second latest is less than 5, delete
        latest = imagehash.average_hash(Image.open(<<latestfilefrom2linesabove>>))
        secLatest = imagehash.average_hash(Image.open(<<secondlatestfrom2linesabove>>))
        compare = latest-secLatest
        if int(compare) < 5:
            os.remove(<<latestfilefrom2linesabove>>)
            os.remove(<<secondlatestfilefrom2linesabove>>)

Thanks much.

Body:
There's no need for recursion here. If you want to compare all possible pairs, I'd recommend you use a nested loop, like this:

for f1 in os.listdir('.'):
    for f2 in os.listdir('.'):
        if f1 == f2 or not os.path.exists(f1) or not os.path.exists(f2):  # don't compare the same file, or files that have already been deleted
            continue
        ... # file comparison code here


问:
How to add an on click event in server side for an Image control in C#/ASP.NET
I have added an image from toolbox in VS2008, and noticed that there isn't an onclick event in server side.

How do I add one on?

答:
Image control is just to display an image on the Web page. There is no onlick event in Image control.

asp:ImageButton Control  that handles mouse clicks on images .

ContentLicense: CC BY-SA 2.5


问:
How can I target a table cell in the same row with jQuery?
I have a table with a single input field and an AJAX script that runs when the input field value is modified. This is all working well. I now need to extend this to insert a date into another cell in the same row, but now sure how to target this as the ID will have to be dynamic. Here's the current table:

    Order Number
    Order Date
    Con Note

      123456

      <input type="text" class="form-control" placeholder="Con Note" name="conNote" value="">

      987654

      <input type="text" class="form-control" placeholder="Con Note" name="conNote" value="">

```
</div>
</div>
</p>

<p>I need to insert the current data into the Order Data cell when the AJAX script is run, something like this:</p>

```$("#85759.OrderDate").html('current date');
```

<p>but not sure how to dynamically target the Order Data cell? I'm setting the ID for the Order Data cell to be the same ID as the input field with ".OrderDate" appended. Current script is:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>$(document).ready(function() {
  $("input[type='text']").change(function() {
    var recid = $(this).closest('td').attr('id');
    var conNote = $(this).val();
    $this = $(this);
    $.post('updateOrder.php', {
      type: 'updateOrder',
      recid: recid,
      conNote: conNote
    }, function(data) {
      data = JSON.parse(data);
      if (data.error) {
        var ajaxError = (data.text);
        var errorAlert = 'There was an error updating the Con Note Number - ' + ajaxError;
        $this.closest('td').addClass("has-error");
        $("#serialNumberError").html(errorAlert);
        $("#serialNumberError").show();
        return; // stop executing this function any further
      } else {
        $this.closest('td').addClass("has-success")
        $this.closest('td').removeClass("has-error");
      }

    }).fail(function(xhr) {
      var httpStatus = (xhr.status);
      var ajaxError = 'There was an error updating the Con Note Number - AJAX request error. HTTP Status: ' + httpStatus;
      $this.closest('td').addClass("has-error");
      //display AJAX error details
      $("#serialNumberError").html(ajaxError);
      $("#serialNumberError").show();
    });
  });
});</code>```

答:
You can get the parent element 'tr' and then find the 'td.OrderDate', I suggest you to use a class to identify the td in the context of its parent.

$(function () {
 $("input[type='text']").change(function() {
  var parent = $(this).parents('tr');

  // Get any element inside the tr
  $('td.OrderDate', parent).text('[current date]')
 })
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
    <tr>
      <td>987654</td>
      <td id="85760.OrderDate" class="OrderDate"></td>
      <td id="85760"><input type="text" class="form-control" placeholder="Con Note" name="conNote" value=""></td>
    </tr>
</table></code>```

ContentLicense: CC BY-SA 4.0

Body:
I have a table with a single input field and an AJAX script that runs when the input field value is modified. This is all working well. I now need to extend this to insert a date into another cell in the same row, but now sure how to target this as the ID will have to be dynamic. Here's the current table:

    Order Number
    Order Date
    Con Note

      123456

      <input type="text" class="form-control" placeholder="Con Note" name="conNote" value="">

      987654

      <input type="text" class="form-control" placeholder="Con Note" name="conNote" value="">

I need to insert the current data into the Order Data cell when the AJAX script is run, something like this:

$("#85759.OrderDate").html('current date');

but not sure how to dynamically target the Order Data cell? I'm setting the ID for the Order Data cell to be the same ID as the input field with ".OrderDate" appended. Current script is:

$(document).ready(function() {
  $("input[type='text']").change(function() {
    var recid = $(this).closest('td').attr('id');
    var conNote = $(this).val();
    $this = $(this);
    $.post('updateOrder.php', {
      type: 'updateOrder',
      recid: recid,
      conNote: conNote
    }, function(data) {
      data = JSON.parse(data);
      if (data.error) {
        var ajaxError = (data.text);
        var errorAlert = 'There was an error updating the Con Note Number - ' + ajaxError;
        $this.closest('td').addClass("has-error");
        $("#serialNumberError").html(errorAlert);
        $("#serialNumberError").show();
        return; // stop executing this function any further
      } else {
        $this.closest('td').addClass("has-success")
        $this.closest('td').removeClass("has-error");
      }

    }).fail(function(xhr) {
      var httpStatus = (xhr.status);
      var ajaxError = 'There was an error updating the Con Note Number - AJAX request error. HTTP Status: ' + httpStatus;
      $this.closest('td').addClass("has-error");
      //display AJAX error details
      $("#serialNumberError").html(ajaxError);
      $("#serialNumberError").show();
    });
  });
});

Body:
You can get the parent element 'tr' and then find the 'td.OrderDate', I suggest you to use a class to identify the td in the context of its parent.

$(function () {
 $("input[type='text']").change(function() {
  var parent = $(this).parents('tr');

  // Get any element inside the tr
  $('td.OrderDate', parent).text('[current date]')
 })
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
    <tr>
      <td>987654</td>
      <td id="85760.OrderDate" class="OrderDate"></td>
      <td id="85760"><input type="text" class="form-control" placeholder="Con Note" name="conNote" value=""></td>
    </tr>
</table>


问:
HTML Forms Array Submission Simulation
I'm trying to mockup a simple HTML form that simulates an HTTP POST from an external party. When I look at the POST data coming in it looks like this:

```<code>array (
  'submission_id' => '1234567890',
  'name' =>
  array (
    0 => 'Bart',
    1 => 'Simpson',
  ),
  'address' =>
  array (
    0 => '1000 Springfield Road',
    1 => 'Level 2',
    2 => 'Los Angeles',
    3 => 'CA',
    4 => '90210',
    5 => '',
  ),
  'date' =>
  array (
    0 => '05',
    1 => '01',
    2 => '2017',
  ),
</code>```

I'm trying to simulate a simple HTML form with inputs but haven't worked with arrays before so not sure of the syntax. For example for the 'name' would it be:

<input type="text" name="name[]">
<input type="text" name="name[]">```

答:
I did need to use the [] syntax to get the numbered arrays:</p>

```<code><input type="text" name="name[]">
<input type="text" name="name[]">
</code>```

Title: HTML Forms Array Submission Simulation

Body:
I'm trying to mockup a simple HTML form that simulates an HTTP POST from an external party. When I look at the POST data coming in it looks like this:

array (
  'submission_id' => '1234567890',
  'name' =>
  array (
    0 => 'Bart',
    1 => 'Simpson',
  ),
  'address' =>
  array (
    0 => '1000 Springfield Road',
    1 => 'Level 2',
    2 => 'Los Angeles',
    3 => 'CA',
    4 => '90210',
    5 => '',
  ),
  'date' =>
  array (
    0 => '05',
    1 => '01',
    2 => '2017',
  ),

I'm trying to simulate a simple HTML form with inputs but haven't worked with arrays before so not sure of the syntax. For example for the 'name' would it be:

<input type="text" name="name[]">
<input type="text" name="name[]">

Body:
I did need to use the [] syntax to get the numbered arrays:

<input type="text" name="name[]">
<input type="text" name="name[]">


问:
How do I get this to refer to the React component?
I have a video component class that possesses a handleRecord method. Inside the handleRecord method, there's an object called recorder which returns a blob the object method call called stopRecording.

Whatever gets returned, I want the value to set state in the video component. But the this refers to recorder object in the callback, not the component itself. What's best practice to get the component within the callback and use the recorder object?

```<code>handleRecord() {

    ...

    } else {
        this.state.recordVideo
        recorder.stopRecording(function() {
            var blob = this.getBlob();
            console.log(this) // <= this refers to recorder object not the component
        });
    }
}
</code>```

答:
You could set a variable to refer to the component, then use it inside the function:

```<code>const component = this;
recorder.stopRecording(function() {
    var blob = this.getBlob();
    console.log(component);
});
</code>```

This will essentially capture the this value when it does refer to the component and cache it in component, so when you use it in the callback function this'll refer to the recorder object, but component will refer to your component.

Of course, you could just directly refer to the recorder object if you would like to use something like an arrow function, which takes the this value of its enclosing scope -- which is the component:

```<code>recorder.stopRecording(() => {
    var blob = recorder.getBlob();
    console.log(this) // <= this refers to component
});
</code>```

Body:
I have a video component class that possesses a handleRecord method. Inside the handleRecord method, there's an object called recorder which returns a blob the object method call called stopRecording.

Whatever gets returned, I want the value to set state in the video component. But the this refers to recorder object in the callback, not the component itself. What's best practice to get the component within the callback and use the recorder object?

handleRecord() {

    ...

    } else {
        this.state.recordVideo
        recorder.stopRecording(function() {
            var blob = this.getBlob();
            console.log(this) // <= this refers to recorder object not the component
        });
    }
}

Body:
You could set a variable to refer to the component, then use it inside the function:

const component = this;
recorder.stopRecording(function() {
    var blob = this.getBlob();
    console.log(component);
});

This will essentially capture the this value when it does refer to the component and cache it in component, so when you use it in the callback function this'll refer to the recorder object, but component will refer to your component.

Of course, you could just directly refer to the recorder object if you would like to use something like an arrow function, which takes the this value of its enclosing scope -- which is the component:

recorder.stopRecording(() => {
    var blob = recorder.getBlob();
    console.log(this) // <= this refers to component
});


问:
How to move (drag) a zoomed graph in overview pane?
When I'm in overview window and zoom in, some part of the graph is not visible. I want to drag the graph so that I can see it at the zoomed in size.

I tried the "Center on graph" button, but it zooms out the graph and centers it on the screen. I tried the direct and drag tool, which doesn't seem to do anything. What to do to accomplish this?

I want to drag the node in upper left corner so that I can see what it connects to:

答: Right-click and drag (Gephi 0.9.1 for Mac).</p>


问:
how to remove a portion of a table cell after form tag is closed
how can i remove everything after form and before the th is closed

```<code><th colspan="2">
  <form method="get" action="" name="ROSTER">
    Show Roster For:
    <select size="1" name="ROSTER_FRANCHISE" onchange="display_one_roster(this.value);">
      <option value="0005" class="fname0005">Franchise 5</option>
      <option value="0001" selected="selected" class="fname0001">Franchise 1 Long Team Name</option>
      <option value="0002" class="fname0002">Sticks</option>
      <option value="0003" class="fname0003">Tony's Testing Team</option>
      <option value="0004" class="fname0004">Mike's Testing Team</option>
      <option value="0006" class="fname0006">Franchise 6</option>
      <option value="0007" class="fname0007">Franchise 7</option>
      <option value="0008" class="fname0008">Franchise 8</option>
      <option value="0009" class="fname0009">Franchise 9</option>
      <option value="0010" class="fname0010">Franchise 10</option>
      <option value="0011" class="fname0011">Franchise 11</option>
      <option value="0012" class="fname0012">Franchise 12</option>
    </select>
  </form>
  - Rosters out of date?  <a href="javascript:window.location.reload();">Reload this page</a> to get them back in sync.
</th>
</code>```

so i'd like to remove this portion

```<code>- Rosters out of date?  <a href="javascript:window.location.reload();">Reload this page</a> to get them back in sync.
</code>```

答:
The easiest and cleanest way would be to put it in a

Then remove the div using jQuery as follows:

```<code>$("#roster_check").remove();
</code>```

The div would of course need to be closed after the last line you want removed.

Body:
how can i remove everything after form and before the th is closed

  <form method="get" action="" name="ROSTER">
    Show Roster For:
    <select size="1" name="ROSTER_FRANCHISE" onchange="display_one_roster(this.value);">
      <option value="0005" class="fname0005">Franchise 5</option>
      <option value="0001" selected="selected" class="fname0001">Franchise 1 Long Team Name</option>
      <option value="0002" class="fname0002">Sticks</option>
      <option value="0003" class="fname0003">Tony's Testing Team</option>
      <option value="0004" class="fname0004">Mike's Testing Team</option>
      <option value="0006" class="fname0006">Franchise 6</option>
      <option value="0007" class="fname0007">Franchise 7</option>
      <option value="0008" class="fname0008">Franchise 8</option>
      <option value="0009" class="fname0009">Franchise 9</option>
      <option value="0010" class="fname0010">Franchise 10</option>
      <option value="0011" class="fname0011">Franchise 11</option>
      <option value="0012" class="fname0012">Franchise 12</option>
    </select>
  </form>
  - Rosters out of date?  Reload this page to get them back in sync.

so i'd like to remove this portion

- Rosters out of date?  Reload this page to get them back in sync.

Body:
The easiest and cleanest way would be to put it in a <div id="roster_check">

Then remove the div using jQuery as follows:

$("#roster_check").remove();

The div would of course need to be closed after the last line you want removed.


问:
In the child page, I want to find master page's Content placeholder and add text to it. How do I make that possible?
I tried this much:-</p>

```<code>protected void Page_PreInit(object sender, EventArgs e)
  {
        class1 obj = new class1();
        DataTable dt = new DataTable();
        dt = obj.get_text();
        ContentPlaceHolder ContentPlaceHolder1 = (ContentPlaceHolder)this.Master.FindControl("ContentPlaceHolder1");
        ContentPlaceHolder1. ????

 }
</code>```

Body:
I tried this much:-

protected void Page_PreInit(object sender, EventArgs e)
  {
        class1 obj = new class1();
        DataTable dt = new DataTable();
        dt = obj.get_text();
        ContentPlaceHolder ContentPlaceHolder1 = (ContentPlaceHolder)this.Master.FindControl("ContentPlaceHolder1");
        ContentPlaceHolder1. ????

 }


问:
How do i hide a portion of a div in CSS/React?
I'm trying to do something like this where initially the entire div is shown (all the text is shown) and at the bottom you can click a button that says "show less" and only 300px of the content of the div will now be shown and the button changes to "show more".

    Lorem ipsum dolor sit amet, consectetur adipiscing elit. In sed nunc sit amet est sollicitudin tempus. Etiam ultricies velit dolor, et rutrum ante fermentum quis. In enim nibh, imperdiet id pulvinar at, euismod id justo. Sed nisl eros, viverra ut purus et, hendrerit dictum risus. Proin ut massa libero. Vestibulum eget nisi laoreet arcu vulputate mollis non eu ipsum. Praesent tempus ut felis id consequat. Duis tincidunt id nulla vitae suscipit. Sed nec erat varius turpis elementum mattis at eu dolor.

  Pellentesque ante orci, molestie ut tortor et, egestas varius felis. Morbi ultricies, nisl ac fringilla placerat, ante risus posuere lacus, vitae tempus lacus tellus a erat. Quisque lacinia laoreet purus sit amet facilisis. Praesent eu elementum leo. Phasellus consectetur, sapien non accumsan pulvinar, orci eros vehicula est, eget molestie diam dolor id massa. Proin ligula libero, tristique id finibus at, laoreet ac nisi. Morbi porttitor enim non turpis bibendum, id porta libero consectetur. In mattis lectus et urna luctus eleifend.

```

答:
Here is example how to do that.

    Lorem ipsum dolor sit amet, consectetur adipiscing elit. In sed nunc sit amet est sollicitudin tempus. Etiam ultricies velit dolor, et rutrum ante fermentum quis. In enim nibh, imperdiet id pulvinar at, euismod id justo. Sed nisl eros, viverra ut purus et, hendrerit dictum risus. Proin ut massa libero. Vestibulum eget nisi laoreet arcu vulputate mollis non eu ipsum. Praesent tempus ut felis id consequat. Duis tincidunt id nulla vitae suscipit. Sed nec erat varius turpis elementum mattis at eu dolor.

  Pellentesque ante orci, molestie ut tortor et, egestas varius felis. Morbi ultricies, nisl ac fringilla placerat, ante risus posuere lacus, vitae tempus lacus tellus a erat. Quisque lacinia laoreet purus sit amet facilisis. Praesent eu elementum leo. Phasellus consectetur, sapien non accumsan pulvinar, orci eros vehicula est, eget molestie diam dolor id massa. Proin ligula libero, tristique id finibus at, laoreet ac nisi. Morbi porttitor enim non turpis bibendum, id porta libero consectetur. In mattis lectus et urna luctus eleifend.

   Pellentesque ante orci, molestie ut tortor et, egestas varius felis. Morbi ultricies, nisl ac fringilla placerat, ante risus posuere lacus, vitae tempus lacus tellus a erat. Quisque lacinia laoreet purus sit amet facilisis. Praesent eu elementum leo. Phasellus consectetur, sapien non accumsan pulvinar, orci eros vehicula est, eget molestie diam dolor id massa. Proin ligula libero, tristique id finibus at, laoreet ac nisi. Morbi porttitor enim non turpis bibendum, id porta libero consectetur. In mattis lectus et urna luctus eleifend.

   Pellentesque ante orci, molestie ut tortor et, egestas varius felis. Morbi ultricies, nisl ac fringilla placerat, ante risus posuere lacus, vitae tempus lacus tellus a erat. Quisque lacinia laoreet purus sit amet facilisis. Praesent eu elementum leo. Phasellus consectetur, sapien non accumsan pulvinar, orci eros vehicula est, eget molestie diam dolor id massa. Proin ligula libero, tristique id finibus at, laoreet ac nisi. Morbi porttitor enim non turpis bibendum, id porta libero consectetur. In mattis lectus et urna luctus eleifend.

<input type="button" onclick="toggleBodyText()" value="Show Less" id="ButtonShow" />

```

Body:
Here is example how to do that.

<div class="bodyText">

    Lorem ipsum dolor sit amet, consectetur adipiscing elit. In sed nunc sit amet est sollicitudin tempus. Etiam ultricies velit dolor, et rutrum ante fermentum quis. In enim nibh, imperdiet id pulvinar at, euismod id justo. Sed nisl eros, viverra ut purus et, hendrerit dictum risus. Proin ut massa libero. Vestibulum eget nisi laoreet arcu vulputate mollis non eu ipsum. Praesent tempus ut felis id consequat. Duis tincidunt id nulla vitae suscipit. Sed nec erat varius turpis elementum mattis at eu dolor.

  Pellentesque ante orci, molestie ut tortor et, egestas varius felis. Morbi ultricies, nisl ac fringilla placerat, ante risus posuere lacus, vitae tempus lacus tellus a erat. Quisque lacinia laoreet purus sit amet facilisis. Praesent eu elementum leo. Phasellus consectetur, sapien non accumsan pulvinar, orci eros vehicula est, eget molestie diam dolor id massa. Proin ligula libero, tristique id finibus at, laoreet ac nisi. Morbi porttitor enim non turpis bibendum, id porta libero consectetur. In mattis lectus et urna luctus eleifend.

   Pellentesque ante orci, molestie ut tortor et, egestas varius felis. Morbi ultricies, nisl ac fringilla placerat, ante risus posuere lacus, vitae tempus lacus tellus a erat. Quisque lacinia laoreet purus sit amet facilisis. Praesent eu elementum leo. Phasellus consectetur, sapien non accumsan pulvinar, orci eros vehicula est, eget molestie diam dolor id massa. Proin ligula libero, tristique id finibus at, laoreet ac nisi. Morbi porttitor enim non turpis bibendum, id porta libero consectetur. In mattis lectus et urna luctus eleifend.

   Pellentesque ante orci, molestie ut tortor et, egestas varius felis. Morbi ultricies, nisl ac fringilla placerat, ante risus posuere lacus, vitae tempus lacus tellus a erat. Quisque lacinia laoreet purus sit amet facilisis. Praesent eu elementum leo. Phasellus consectetur, sapien non accumsan pulvinar, orci eros vehicula est, eget molestie diam dolor id massa. Proin ligula libero, tristique id finibus at, laoreet ac nisi. Morbi porttitor enim non turpis bibendum, id porta libero consectetur. In mattis lectus et urna luctus eleifend.

</div>
<div>
<input type="button" onclick="toggleBodyText()" value="Show Less" id="ButtonShow" />
</div>

<script>
function toggleBodyText() {
var btn=document.getElementById('ButtonShow');
var value=btn.value;
var div = document.querySelector('.bodyText');
if(value=='Show Less')
{
   div.style.height='300px';
   div.style.overflowX='scroll';
   div.style.overflowY='hidden';
   btn.value='Show More';
}
else
{
   div.style.height='auto';
   div.style.overflowX='inherit';
   div.style.overflowY='hidden';
   btn.value='Show Less';
}
}
</script>


问:
Ruby on Rails CanCan Gem
I am a bit confused regarding CanCan Gem. I basically understand how to set up abillity.rb. For example lest say we have the following code:

```<code>// in abillity.rb

user ||= User.new

can [:update, :destroy, :edit, :read], Book do |book|
  book.dashboard.user_id == user.id
end
</code>```

And then lets say we have the following books controller:

```<code>// books_controller.rb
load_and_authorize_resource

def destroy
  if can?(:destroy, @book)
    @book.destroy!
    redirect_to happy_world_path
  else
    redirect_to not_happy
  end
end
</code>```

My question is: Do we need to check 'can?(:destroy, @book)'?
From my understanding 'load_and_authorize_resource' will not even allow access to this method if we don't have abillity to destroy it.

答:
Yo do not need to add if can?(:destroy, @book) in your action if you use load_and_authorize_resource

Like the README say

Setting this for every action can be tedious, therefore the load_and_authorize_resource method is provided to automatically authorize all actions in a RESTful style resource controller.

If an user without authorization try to destroy, he get a unauthorized response ( not remember if is a 401 code)

Maybe you can use if can?(:destroy, @book) in your views, to do no show thte destroy button. Like also in Check Abilities & Authorization section

Title: Ruby on Rails CanCan Gem

Body:
I am a bit confused regarding CanCan Gem. I basically understand how to set up abillity.rb. For example lest say we have the following code:

// in abillity.rb

user ||= User.new

can [:update, :destroy, :edit, :read], Book do |book|
  book.dashboard.user_id == user.id
end

And then lets say we have the following books controller:

// books_controller.rb
load_and_authorize_resource

def destroy
  if can?(:destroy, @book)
    @book.destroy!
    redirect_to happy_world_path
  else
    redirect_to not_happy
  end
end

My question is: Do we need to check 'can?(:destroy, @book)'?
From my understanding 'load_and_authorize_resource' will not even allow access to this method if we don't have abillity to destroy it.


问:
Handling inconsistent test results when scraping a fluctuating website
Would appreciate advice from the community on how best to handle an aggravating situation.

I have a R package that scrapes the National Hurricane Center archives and returns tidy storm data. The website often does not respond.

An example of this would be this Appveyor failure and then the subsequent pass (same branch, same commit).

Right now it has failed on four consecutive tests:

Build 1.0.141

Build 1.0.142

Build 1.0.143

Build 1.0.144

Builds 1.0.141 and 1.0.143 pass the first 119 tests. Build 1.0.142 passes the first 142 tests. Build 1.0.144 fails only after 66 tests. The errors are consistent:

Error in curl::curl_fetch_memory(url, handle = handle) :

```<code>Timeout was reached
</code>```

Calls: test_check ... request_fetch -> request_fetch.write_memory ->  -> .Call

I have so many tests because there are minor discrepancies or typos in several of the products that are scraped. So, when I modify a regex pattern to accomodate these discrepancies I want to ensure I don't inadvertently break something else.

I have added options for multiple attempts, delays between requests and timeout options. Unfortunately they do not seem to have helped much, if at all.

My question to the community: can you offer advice or suggestions as a better way to handle this situation? I know it's bad form to keep tests isolated from your production environment. But I don't need all of these tests for the entire package.

How would you handle these issues?

答:
If you're OK with sporadically skipping the tests when you get a timeout then I'd capture the timeout like they did here and just skip the test if the response indicates there was a timeout. Something like:

safe_GET <- purrr::safely(httr::GET)

skip_if_cant_get <- function(url) {
  resp <- safe_GET(url)

  if (is.null(resp$result)) {
    testthat::skip(paste0("Couldn't get ", url, " for testing"))
  }

  resp
}

resp <- skip_if_cant_get("http://www.nhc.noaa.gov/archive/1998/1998archive.shtml")
httr::http_status(resp$result)
#> $category
#> [1] "Success"
#>
#> $reason
#> [1] "OK"
#>
#> $message
#> [1] "Success: (200) OK"

# The timeout on this one will trigger the skip()
# resp <- skip_if_cant_get("http://deadbeefdeadbeef.org/")
```

This approach will stop the builds from breaking.

Body:
Would appreciate advice from the community on how best to handle an aggravating situation.

I have a R package that scrapes the National Hurricane Center archives and returns tidy storm data. The website often does not respond.

An example of this would be this Appveyor failure and then the subsequent pass (same branch, same commit).

Right now it has failed on four consecutive tests:

Build 1.0.141

Build 1.0.142

Build 1.0.143

Build 1.0.144

Builds 1.0.141 and 1.0.143 pass the first 119 tests. Build 1.0.142 passes the first 142 tests. Build 1.0.144 fails only after 66 tests. The errors are consistent:

Error in curl::curl_fetch_memory(url, handle = handle) :

Timeout was reached

Calls: test_check ... request_fetch -> request_fetch.write_memory ->  -> .Call

I have so many tests because there are minor discrepancies or typos in several of the products that are scraped. So, when I modify a regex pattern to accomodate these discrepancies I want to ensure I don't inadvertently break something else.

I have added options for multiple attempts, delays between requests and timeout options. Unfortunately they do not seem to have helped much, if at all.

My question to the community: can you offer advice or suggestions as a better way to handle this situation? I know it's bad form to keep tests isolated from your production environment. But I don't need all of these tests for the entire package.

How would you handle these issues?

Body:
If you're OK with sporadically skipping the tests when you get a timeout then I'd capture the timeout like they did here and just skip the test if the response indicates there was a timeout. Something like:

safe_GET <- purrr::safely(httr::GET)

skip_if_cant_get <- function(url) {
  resp <- safe_GET(url)

  if (is.null(resp$result)) {
    testthat::skip(paste0("Couldn't get ", url, " for testing"))
  }

  resp
}

resp <- skip_if_cant_get("http://www.nhc.noaa.gov/archive/1998/1998archive.shtml")
httr::http_status(resp$result)
#> $category
#> [1] "Success"
#>
#> $reason
#> [1] "OK"
#>
#> $message
#> [1] "Success: (200) OK"

# The timeout on this one will trigger the skip()
# resp <- skip_if_cant_get("http://deadbeefdeadbeef.org/")

This approach will stop the builds from breaking.


问:
Accessing a tabbed fragment method from the parent activity?
Hi (I'm new to this so you'll have to forgive me)

I currently have a tabbed activity where MainActivity.java is the parent class and Absences.java and Notices.java are the fragments. I have a date picker fragment inside the MainActivity that is run when I tap on an options menu button.

When I've successfully selected my date I want to pass the information to a method in the Absences fragment. However, I'm really struggling with how to implement this part.

The research I've done seems to suggest this is the solution:

```<code>Absences fragment= (Absences) getSupportFragmentManager().findFragmentById(R.id.Absences);
        ((Absences)fragment).updateAbsences();
</code>```

However, getSupportFragmentManager() can't be referenced from a static context and I can't seem to find the id of my Fragment.

After doing a little more research it seemed to reveal this method doesn't work for a tabbed activity so I'm at a loss at this point.

Would someone be able to point me in the right direction? - I've been working on this for quite some time now!

SectionsPageAdapter class

```<code>Fragment one, two;

public class SectionsPagerAdapter extends FragmentPagerAdapter {

    public SectionsPagerAdapter(FragmentManager fm) {
        super(fm);
    }

    @Override
    public Fragment getItem(int position) {
        // getItem is called to instantiate the fragment for the given page.
        // Return a PlaceholderFragment (defined as a static inner class below).
        switch (position) {
            case 0:
                if(one==null){
                    one = new Absences();
                }
                return one;
            case 1:
                if(two==null){
                    two = new Notices();
                }
                return two;
        }
        return null;
    }

    @Override
    public int getCount() {
        // Show 3 total pages.
        return 2;
    }

    @Override
    public CharSequence getPageTitle(int position) {
        switch (position) {
            case 0:
                return "ABSENCES";
            case 1:
                return "NOTICES";
        }
        return null;
    }

}
</code>```

onOptionsItemSelected

```<code> public boolean onOptionsItemSelected(MenuItem item) {
    int id = item.getItemId();
    if (id == R.id.calendar) {
        DialogFragment newFragment = new DatePickerFragment();
        newFragment.show(getSupportFragmentManager(), "datePicker");
    }
    return super.onOptionsItemSelected(item);
}
</code>```

DatePickerFragment

```<code>public static class DatePickerFragment extends DialogFragment
        implements DatePickerDialog.OnDateSetListener {

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        final Calendar c = Calendar.getInstance();
        int year = c.get(Calendar.YEAR);
        int month = c.get(Calendar.MONTH);
        int day = c.get(Calendar.DAY_OF_MONTH);
        DatePickerDialog dialog = new DatePickerDialog(getActivity(), this, year, month, day);
        dialog.getDatePicker().setMaxDate(c.getTimeInMillis());
        dialog.setTitle("");
        return  dialog;
    }

    public void onDateSet(DatePicker view, int year, int month, int day) {
        Absences fragment= (Absences) getSupportFragmentManager().findFragmentById(R.id.Absences);
        ((Absences)fragment).updateAbsences();
    }
}
</code>```

--EDIT--

Updated code as per suggestion below

Method inside MainActivity

```<code>public void onDatePicked() {
    Absences fragment = (Absences) getSupportFragmentManager().findFragmentById(R.id.absences);
    fragment.updateAbsences();
}
</code>```

New DatePickerFragment Class

```<code>    package com.alexwoohouse.heartofengland;

import android.annotation.TargetApi;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.icu.util.Calendar;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.util.Log;
import android.widget.DatePicker;

import java.util.Date;

public class DatePickerFragment extends DialogFragment
        implements DatePickerDialog.OnDateSetListener {

    public interface OnDatePickedListener {
        void onDatePicked(); //This method seems to be greyed out!
    }

    @TargetApi(Build.VERSION_CODES.N)
    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        final Calendar c = Calendar.getInstance();
        int year = c.get(Calendar.YEAR);
        int month = c.get(Calendar.MONTH);
        int day = c.get(Calendar.DAY_OF_MONTH);
        DatePickerDialog dialog = new DatePickerDialog(getActivity(), this, year, month, day);
        dialog.getDatePicker().setMaxDate(c.getTimeInMillis());
        dialog.setTitle("");
        return  dialog;
    }

    @TargetApi(Build.VERSION_CODES.N)
    public void onDateSet(DatePicker view, int year, int month, int day) {
        Calendar cal = Calendar.getInstance();
        cal.set(Calendar.YEAR, year);
        cal.set(Calendar.MONTH, month);
        cal.set(Calendar.DAY_OF_MONTH, day);
    }
}
</code>```

答:
Here's my suggestion.

First, move DatePickerFragment out as its own top-level class. I don't know if you have a good reason for having it be a static inner class, but you likely don't need that.

Now then, generally the way you have fragments (dialog or otherwise) pass information is via interface callbacks. So instead of trying directly access the current activity's fragment manager as your are doing, you invoke a callback with the data you have to send. See the android documentation on this for details and sample code, but basically you'd define an interface in your DatePickerFragment that will be invoked when a date is picked:

```<code>public interface OnDatePickedListener {
    void onDatePicked(Date date);
}
</code>```

When your fragment is attached to the activity, you save that as the fragment's current listener instance.
When you pick a date in the dialog fragment, you invoke your listener's onDatePicked method.

Your activity then implements this interface to delegate down to the fragment you want to update:

```<code>public class MainActivity implements DatePickerFragment.OnDatePickedListner {
    @Override
    public void onDatePicked(Date date) {
        Absences fragment = (Absences) getSupportFragmentManager().findFragmentById(R.id.Absences);
        fragment.updateAbsences();
    }
}
</code>```

The main benefit to this being separation of concerns. Your dialog fragment does not know anything about the Activity that owns it. It just knows that it has to report the selected date to whomever implements the interface. Then you can show this dialog fragment in any other Activity you need to pick a date in as long as they also implement the correct interface.

Hope that helps!

Body:
Hi (I'm new to this so you'll have to forgive me)

I currently have a tabbed activity where MainActivity.java is the parent class and Absences.java and Notices.java are the fragments. I have a date picker fragment inside the MainActivity that is run when I tap on an options menu button.

When I've successfully selected my date I want to pass the information to a method in the Absences fragment. However, I'm really struggling with how to implement this part.

The research I've done seems to suggest this is the solution:

Absences fragment= (Absences) getSupportFragmentManager().findFragmentById(R.id.Absences);
        ((Absences)fragment).updateAbsences();

However, getSupportFragmentManager() can't be referenced from a static context and I can't seem to find the id of my Fragment.

After doing a little more research it seemed to reveal this method doesn't work for a tabbed activity so I'm at a loss at this point.

Would someone be able to point me in the right direction? - I've been working on this for quite some time now!

SectionsPageAdapter class

Fragment one, two;

public class SectionsPagerAdapter extends FragmentPagerAdapter {

    public SectionsPagerAdapter(FragmentManager fm) {
        super(fm);
    }

    @Override
    public Fragment getItem(int position) {
        // getItem is called to instantiate the fragment for the given page.
        // Return a PlaceholderFragment (defined as a static inner class below).
        switch (position) {
            case 0:
                if(one==null){
                    one = new Absences();
                }
                return one;
            case 1:
                if(two==null){
                    two = new Notices();
                }
                return two;
        }
        return null;
    }

    @Override
    public int getCount() {
        // Show 3 total pages.
        return 2;
    }

    @Override
    public CharSequence getPageTitle(int position) {
        switch (position) {
            case 0:
                return "ABSENCES";
            case 1:
                return "NOTICES";
        }
        return null;
    }

}

onOptionsItemSelected

 public boolean onOptionsItemSelected(MenuItem item) {
    int id = item.getItemId();
    if (id == R.id.calendar) {
        DialogFragment newFragment = new DatePickerFragment();
        newFragment.show(getSupportFragmentManager(), "datePicker");
    }
    return super.onOptionsItemSelected(item);
}

DatePickerFragment

public static class DatePickerFragment extends DialogFragment
        implements DatePickerDialog.OnDateSetListener {

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        final Calendar c = Calendar.getInstance();
        int year = c.get(Calendar.YEAR);
        int month = c.get(Calendar.MONTH);
        int day = c.get(Calendar.DAY_OF_MONTH);
        DatePickerDialog dialog = new DatePickerDialog(getActivity(), this, year, month, day);
        dialog.getDatePicker().setMaxDate(c.getTimeInMillis());
        dialog.setTitle("");
        return  dialog;
    }

    public void onDateSet(DatePicker view, int year, int month, int day) {
        Absences fragment= (Absences) getSupportFragmentManager().findFragmentById(R.id.Absences);
        ((Absences)fragment).updateAbsences();
    }
}

--EDIT--

Updated code as per suggestion below

Method inside MainActivity

public void onDatePicked() {
    Absences fragment = (Absences) getSupportFragmentManager().findFragmentById(R.id.absences);
    fragment.updateAbsences();
}

New DatePickerFragment Class

    package com.alexwoohouse.heartofengland;

import android.annotation.TargetApi;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.icu.util.Calendar;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.util.Log;
import android.widget.DatePicker;

import java.util.Date;

public class DatePickerFragment extends DialogFragment
        implements DatePickerDialog.OnDateSetListener {

    public interface OnDatePickedListener {
        void onDatePicked(); //This method seems to be greyed out!
    }

    @TargetApi(Build.VERSION_CODES.N)
    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        final Calendar c = Calendar.getInstance();
        int year = c.get(Calendar.YEAR);
        int month = c.get(Calendar.MONTH);
        int day = c.get(Calendar.DAY_OF_MONTH);
        DatePickerDialog dialog = new DatePickerDialog(getActivity(), this, year, month, day);
        dialog.getDatePicker().setMaxDate(c.getTimeInMillis());
        dialog.setTitle("");
        return  dialog;
    }

    @TargetApi(Build.VERSION_CODES.N)
    public void onDateSet(DatePicker view, int year, int month, int day) {
        Calendar cal = Calendar.getInstance();
        cal.set(Calendar.YEAR, year);
        cal.set(Calendar.MONTH, month);
        cal.set(Calendar.DAY_OF_MONTH, day);
    }
}

Body:
Here's my suggestion.

First, move DatePickerFragment out as its own top-level class. I don't know if you have a good reason for having it be a static inner class, but you likely don't need that.

Now then, generally the way you have fragments (dialog or otherwise) pass information is via interface callbacks. So instead of trying directly access the current activity's fragment manager as your are doing, you invoke a callback with the data you have to send. See the android documentation on this for details and sample code, but basically you'd define an interface in your DatePickerFragment that will be invoked when a date is picked:

public interface OnDatePickedListener {
    void onDatePicked(Date date);
}

When your fragment is attached to the activity, you save that as the fragment's current listener instance.
When you pick a date in the dialog fragment, you invoke your listener's onDatePicked method.

Your activity then implements this interface to delegate down to the fragment you want to update:

public class MainActivity implements DatePickerFragment.OnDatePickedListner {
    @Override
    public void onDatePicked(Date date) {
        Absences fragment = (Absences) getSupportFragmentManager().findFragmentById(R.id.Absences);
        fragment.updateAbsences();
    }
}

The main benefit to this being separation of concerns. Your dialog fragment does not know anything about the Activity that owns it. It just knows that it has to report the selected date to whomever implements the interface. Then you can show this dialog fragment in any other Activity you need to pick a date in as long as they also implement the correct interface.

Hope that helps!


问:
Equal height flex columns ruined by child element with display: flex
CSS:

```<code>* {
  padding: 0;
  margin: 0;
  box-sizing: border-box;
}
body {
  display: flex;
  background-color: #F5F5F5;
}
body > header {
  display: flex;
  position: fixed;
  width: 100%;
  height: 60px;
  align-items: center;
  background-color: #373737;
  -webkit-box-shadow: 0 3px 3px rgba(0, 0, 0, 0.19);
  box-shadow: 0 3px 3px rgba(0, 0, 0, 0.19);
}
aside {
  width: 250px;
  background-color: #484848;
  font-size: 18px "SL";
  margin-top: 60px;
}
aside > ul.side-menu {
  list-style-type: none;
  margin-top: 25px;
  width: 100%;
}
aside > ul > li > a {
  display: block;
  text-decoration: none;
  font-family: "SL";
  font-size: 18px;
  line-height: 40px;
  padding-left: 20px;
  color: #CCCCCC;
  border-bottom: 1px solid #8E8E8E;
  transition: 300ms;
}
aside > ul > li > a.active {
  color: white;
}
</code>```

HTML:

```<code><body>

  <header>

  </header>

  <aside>
    <ul class="side-menu">
      <li><a href="#" class="active">123</a></li>
      <li><a href="#">123</a></li>
      <li><a href="#">123</a></li>
      <li><a href="#">123</a></li>
    </ul>
  </aside>
</body>
</code>```

Codepan:

https://codepen.io/UADev/pen/zzmdPG

When you're opening fullscreen, this is what's happening:

Tried to use height: 100% on body and html elements, but it doesn't work correctly when you have another flex element with flex-wrap: wrap inside one of the flex-child elements like aside or section that follows immediately after body. I tried to remove display:flex from one of those elements and  it's broke the layout, but problem disappeared.

答:
Just add min-height: 100vh to the parent (body) and the default value align-items: stretch will cause the children to to fill the height of the parent.

* {
  padding: 0;
  margin: 0;
  box-sizing: border-box;
}
body {
  display: flex;
  background-color: #F5F5F5;
  min-height: 100vh;
}
body > header {
  display: flex;
  position: fixed;
  width: 100%;
  height: 60px;
  align-items: center;
  background-color: #373737;
  -webkit-box-shadow: 0 3px 3px rgba(0, 0, 0, 0.19);
  box-shadow: 0 3px 3px rgba(0, 0, 0, 0.19);
}
aside {
  width: 250px;
  background-color: #484848;
  font-size: 18px "SL";
  margin-top: 60px;
}
aside > ul.side-menu {
  list-style-type: none;
  margin-top: 25px;
  width: 100%;
}
aside > ul > li > a {
  display: block;
  text-decoration: none;
  font-family: "SL";
  font-size: 18px;
  line-height: 40px;
  padding-left: 20px;
  color: #CCCCCC;
  border-bottom: 1px solid #8E8E8E;
  transition: 300ms;
}
aside > ul > li > a.active {
  color: white;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><body>

  <header>

  </header>

  <aside>
    <ul class="side-menu">
      <li>123</li>
      <li>123</li>
      <li>123</li>
      <li>123</li>
    </ul>
  </aside>
</body></code>```

Body:
CSS:

* {
  padding: 0;
  margin: 0;
  box-sizing: border-box;
}
body {
  display: flex;
  background-color: #F5F5F5;
}
body > header {
  display: flex;
  position: fixed;
  width: 100%;
  height: 60px;
  align-items: center;
  background-color: #373737;
  -webkit-box-shadow: 0 3px 3px rgba(0, 0, 0, 0.19);
  box-shadow: 0 3px 3px rgba(0, 0, 0, 0.19);
}
aside {
  width: 250px;
  background-color: #484848;
  font-size: 18px "SL";
  margin-top: 60px;
}
aside > ul.side-menu {
  list-style-type: none;
  margin-top: 25px;
  width: 100%;
}
aside > ul > li > a {
  display: block;
  text-decoration: none;
  font-family: "SL";
  font-size: 18px;
  line-height: 40px;
  padding-left: 20px;
  color: #CCCCCC;
  border-bottom: 1px solid #8E8E8E;
  transition: 300ms;
}
aside > ul > li > a.active {
  color: white;
}

HTML:

123

123

123

123

Codepan:

https://codepen.io/UADev/pen/zzmdPG

When you're opening fullscreen, this is what's happening:

Tried to use height: 100% on body and html elements, but it doesn't work correctly when you have another flex element with flex-wrap: wrap inside one of the flex-child elements like aside or section that follows immediately after body. I tried to remove display:flex from one of those elements and  it's broke the layout, but problem disappeared.

Body:
Just add min-height: 100vh to the parent (body) and the default value align-items: stretch will cause the children to to fill the height of the parent.

* {
  padding: 0;
  margin: 0;
  box-sizing: border-box;
}
body {
  display: flex;
  background-color: #F5F5F5;
  min-height: 100vh;
}
body > header {
  display: flex;
  position: fixed;
  width: 100%;
  height: 60px;
  align-items: center;
  background-color: #373737;
  -webkit-box-shadow: 0 3px 3px rgba(0, 0, 0, 0.19);
  box-shadow: 0 3px 3px rgba(0, 0, 0, 0.19);
}
aside {
  width: 250px;
  background-color: #484848;
  font-size: 18px "SL";
  margin-top: 60px;
}
aside > ul.side-menu {
  list-style-type: none;
  margin-top: 25px;
  width: 100%;
}
aside > ul > li > a {
  display: block;
  text-decoration: none;
  font-family: "SL";
  font-size: 18px;
  line-height: 40px;
  padding-left: 20px;
  color: #CCCCCC;
  border-bottom: 1px solid #8E8E8E;
  transition: 300ms;
}
aside > ul > li > a.active {
  color: white;
}

<body>

  <header>

  </header>

  <aside>
    <ul class="side-menu">
      <li><a href="#" class="active">123</a></li>
      <li><a href="#">123</a></li>
      <li><a href="#">123</a></li>
      <li><a href="#">123</a></li>
    </ul>
  </aside>
</body>


问:
Get JSON data based on the item i clicked ionic 2
Hi I want to get the JSON data base only on the item I clicked, when I clicked on the item I dont get any JSON data instead it says its'undefined' in the console. Hope you can help me guys. Here is my code:</p>

```<code>Featured.ts

import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';

import { TestProviderPage } from '../testprovider/testprovider';
import { ProductPage } from '../product/product';

@Component({
  selector: 'page-featured',
  templateUrl: 'featured.html',
  providers: [TestProviderPage]
})
export class FeaturedPage {
  products: any;
  constructor(public navCtrl: NavController, public testProvider: TestProviderPage) {
    this.loadItems();
  }

  goToProductPage(item){
    this.navCtrl.push(ProductPage, { item: item });
  }

  loadItems(){
    this.testProvider.loadpatrick().then(data => {
    this.products = data;
    console.log(this.products);
    });
  }

}

product.ts

import { Component } from '@angular/core';
import { NavController, NavParams } from 'ionic-angular';

import { MorePage } from '../more/more';

@Component({
  selector: 'page-product',
  templateUrl: 'product.html'
})
export class ProductPage {
  item: any;
  tabBarElement: any;
  constructor(public navCtrl: NavController, public navParams: NavParams) {
    this.tabBarElement = document.querySelector('.tabbar.show-tabbar');
    this.item = this.navParams.get('product');
    console.log(this.item);
  }

}
</code>```

答:
In your FeaturePage, you pass parameter item to ProductPage. So you just need to retrieve the same parameter.

FeaturePage.ts

```<code> this.navCtrl.push(ProductPage, { item: item })
</code>```

Product Page.ts

```<code>this.navParams.get('item')
</code>```

Body:
Hi I want to get the JSON data base only on the item I clicked, when I clicked on the item I dont get any JSON data instead it says its'undefined' in the console. Hope you can help me guys. Here is my code:

Featured.ts

import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';

import { TestProviderPage } from '../testprovider/testprovider';
import { ProductPage } from '../product/product';

@Component({
  selector: 'page-featured',
  templateUrl: 'featured.html',
  providers: [TestProviderPage]
})
export class FeaturedPage {
  products: any;
  constructor(public navCtrl: NavController, public testProvider: TestProviderPage) {
    this.loadItems();
  }

  goToProductPage(item){
    this.navCtrl.push(ProductPage, { item: item });
  }

  loadItems(){
    this.testProvider.loadpatrick().then(data => {
    this.products = data;
    console.log(this.products);
    });
  }

}

product.ts

import { Component } from '@angular/core';
import { NavController, NavParams } from 'ionic-angular';

import { MorePage } from '../more/more';

@Component({
  selector: 'page-product',
  templateUrl: 'product.html'
})
export class ProductPage {
  item: any;
  tabBarElement: any;
  constructor(public navCtrl: NavController, public navParams: NavParams) {
    this.tabBarElement = document.querySelector('.tabbar.show-tabbar');
    this.item = this.navParams.get('product');
    console.log(this.item);
  }

}

Body:
In your FeaturePage, you pass parameter item to ProductPage. So you just need to retrieve the same parameter.

FeaturePage.ts

 this.navCtrl.push(ProductPage, { item: item })

Product Page.ts

this.navParams.get('item')


问:
Alphabetical scroll bar not showing up
I'm trying to make an alphabetical scroll bar like the scroll bar in Contacts and in Apple Music. However, when I call sectionIndexTitlesForTableView method, the alphabetical scroll bar does not show up. How do I fix this? I referenced this older tutorial and newer tutorial.

Code

```<code>class SongsViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
    private var sectionTitles = ["A", "B", "C"]

    func sectionIndexTitlesForTableView(tableView: UITableView) -> [AnyObject]! {
        return sectionTitles as [AnyObject]
    }

    func tableView(_ tableView: UITableView, sectionForSectionIndexTitle title: String, at index: Int) -> Int {
        return sectionTitles.index(of: title)!
    }
}
</code>```

答:
Your tutorials are for earlier versions of Swift.  The current function signatures are:</p>

```<code>func sectionIndexTitles(for tableView: UITableView) -> [String]? {
    return sectionTitles
}

func tableView(_ tableView: UITableView, sectionForSectionIndexTitle title: String, at index: Int) -> Int {
    return sectionTitles.index(of: title)!
}
</code>```

Title: Alphabetical scroll bar not showing up

Body:
I'm trying to make an alphabetical scroll bar like the scroll bar in Contacts and in Apple Music. However, when I call sectionIndexTitlesForTableView method, the alphabetical scroll bar does not show up. How do I fix this? I referenced this older tutorial and newer tutorial.

Code

class SongsViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
    private var sectionTitles = ["A", "B", "C"]

    func sectionIndexTitlesForTableView(tableView: UITableView) -> [AnyObject]! {
        return sectionTitles as [AnyObject]
    }

    func tableView(_ tableView: UITableView, sectionForSectionIndexTitle title: String, at index: Int) -> Int {
        return sectionTitles.index(of: title)!
    }
}

Body:
Your tutorials are for earlier versions of Swift.  The current function signatures are:

func sectionIndexTitles(for tableView: UITableView) -> [String]? {
    return sectionTitles
}

func tableView(_ tableView: UITableView, sectionForSectionIndexTitle title: String, at index: Int) -> Int {
    return sectionTitles.index(of: title)!
}


问:
Correctly migrate from Python 2 md5 library to Python 3 hashlib
I'm trying to integrate a 3rd party payment gateway (CCAvenue) in Django 1.11, Python 3.5.2

The reference code provided by the 3rd party uses the deprecated library md5 to encrypt texts.

```<code>from Crypto.Cipher import AES
import md5

def pad(data):
    length = 16 - (len(data) % 16)
    data += chr(length)*length
    return data

def encrypt(plainText,workingKey):
    iv = '\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f'
    plainText = pad(plainText)
    encDigest = md5.new ()
    encDigest.update(workingKey)
    enc_cipher = AES.new(encDigest.digest(), AES.MODE_CBC, iv)
    encryptedText = enc_cipher.encrypt(plainText).encode('hex')
    return encryptedText
</code>```

How do I make the above encrypt() method Python 3 compatible using the hashlib library of Python 3? Can you post the whole method?

答:
WARNING: Don't use crypto or pycrypto anymore! read more

Here's a Python 3 compatible way of doing the same:

```<code>from binascii import hexlify, unhexlify
from Crypto.Cipher import AES
from hashlib import md5

from django.utils.encoding import force_bytes

iv = '\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f'
# for python 3.9 & pycryptodome, this need to be byte
iv = b'\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f'

BS = 16

def _pad(data):
    return data + (BS - len(data) % BS) * chr(BS - len(data) % BS)

def _unpad(data):
    return data[0:-ord(data[-1])]

def encrypt(plain_text, working_key):
    plain_text = _pad(plain_text)
    enc_cipher = AES.new(md5(force_bytes(working_key)).digest(), AES.MODE_CBC, _iv)
    return hexlify(enc_cipher.encrypt(plain_text)).decode('utf-8')

def decrypt(cipher_text, working_key):
    encrypted_text = unhexlify(cipher_text)
    dec_cipher = AES.new(md5(force_bytes(working_key)).digest(), AES.MODE_CBC, _iv)
    return _unpad(dec_cipher.decrypt(encrypted_text).decode('utf-8'))
</code>```

Body:
I'm trying to integrate a 3rd party payment gateway (CCAvenue) in Django 1.11, Python 3.5.2

The reference code provided by the 3rd party uses the deprecated library md5 to encrypt texts.

from Crypto.Cipher import AES
import md5

def pad(data):
    length = 16 - (len(data) % 16)
    data += chr(length)*length
    return data

def encrypt(plainText,workingKey):
    iv = '\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f'
    plainText = pad(plainText)
    encDigest = md5.new ()
    encDigest.update(workingKey)
    enc_cipher = AES.new(encDigest.digest(), AES.MODE_CBC, iv)
    encryptedText = enc_cipher.encrypt(plainText).encode('hex')
    return encryptedText

How do I make the above encrypt() method Python 3 compatible using the hashlib library of Python 3? Can you post the whole method?

Body:
WARNING: Don't use crypto or pycrypto anymore! read more

Here's a Python 3 compatible way of doing the same:

from binascii import hexlify, unhexlify
from Crypto.Cipher import AES
from hashlib import md5

from django.utils.encoding import force_bytes

iv = '\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f'
# for python 3.9 & pycryptodome, this need to be byte
iv = b'\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f'

BS = 16

def _pad(data):
    return data + (BS - len(data) % BS) * chr(BS - len(data) % BS)

def _unpad(data):
    return data[0:-ord(data[-1])]

def encrypt(plain_text, working_key):
    plain_text = _pad(plain_text)
    enc_cipher = AES.new(md5(force_bytes(working_key)).digest(), AES.MODE_CBC, _iv)
    return hexlify(enc_cipher.encrypt(plain_text)).decode('utf-8')

def decrypt(cipher_text, working_key):
    encrypted_text = unhexlify(cipher_text)
    dec_cipher = AES.new(md5(force_bytes(working_key)).digest(), AES.MODE_CBC, _iv)
    return _unpad(dec_cipher.decrypt(encrypted_text).decode('utf-8'))


问:
Terraform s3 bucket notification having multiple topics
I am trying to write a flexible/dynamic resource for aws_s3_bucket_notification which may have variable topics for the specified s3 bucket. For one bucket, I may have just 2 prefixes and 2 topics and for others 4 or 5 and so on... I was thinking of using a map function which will store the "prefix" and "SNS ARN" for each prefix type as the events will be the same. I need to create a s3_bucket_notification which will have all the topics in it without having to manually write each of the topics. Any suggestions?

Example

```<code>resource "aws_s3_bucket_notification" "bucket_notification" {
  bucket = "${aws_s3_bucket.bucket.id}"

  topic {
    topic_arn     = "$map.value" ###prototype
    events        = ["s3:ObjectCreated:*"]
    filter_suffix = "$map.key" ###prototype
  }
}
</code>```

答:
If my understanding is correct, the codes should like this:

```<code>variable "sns_top" {
  type = "map"

  default = {
    dev  = "topic1"
    uat  = "topic2"
    prod = "topic3"
  }
}

variable "bucket_name" {
  default = "my-tf-test-bucket-dfsfddsf"
}

data "aws_caller_identity" "current" {}

resource "aws_sns_topic" "sns_topic" {
  count = "${length(keys(var.sns_top))}"
  name  = "sns-topic-${element(values(var.sns_top),count.index)}"
}

resource "aws_sns_topic_policy" "custom" {
  count = "${length(keys(var.sns_top))}"
  arn   = "${element(aws_sns_topic.sns_topic.*.arn, count.index)}"

  policy = <<POLICY
{
  "Version": "2012-10-17",
  "Id": "default",
  "Statement":[{
    "Sid": "default",
    "Effect": "Allow",
    "Principal": {"AWS":"*"},
    "Action": [
      "SNS:GetTopicAttributes",
      "SNS:SetTopicAttributes",
      "SNS:AddPermission",
      "SNS:RemovePermission",
      "SNS:DeleteTopic"
    ],
    "Resource": "${element(aws_sns_topic.sns_topic.*.arn, count.index)}"
  }]
}
POLICY

  depends_on = ["aws_sns_topic.sns_topic"]
}

resource "aws_s3_bucket" "bucket" {
  bucket = "${var.bucket_name}"
}

data "aws_iam_policy_document" "default" {
  statement {
    effect = "Allow"

    actions = [
      "s3:PutObject",
    ]

    resources = [
      "${aws_s3_bucket.bucket.arn}/*",
    ]

    principals {
      type        = "AWS"
      identifiers = ["arn:aws:iam::${data.aws_caller_identity.current.account_id}:root"]
    }
  }
}

resource "aws_s3_bucket_policy" "default" {
  bucket = "${aws_s3_bucket.bucket.id}"
  policy = "${data.aws_iam_policy_document.default.json}"
}

resource "aws_s3_bucket_notification" "bucket_notification" {
  count  = "${length(keys(var.sns_top))}"
  bucket = "${aws_s3_bucket.bucket.id}"

  topic {
    topic_arn     = "${element(aws_sns_topic.sns_topic.*.arn, count.index)}"
    events        = ["s3:ObjectCreated:*"]
    filter_suffix = "${element(keys(var.sns_top),count.index)}"
  }
}
</code>```

The codes hit an error explained in below link, but you should be fine to use it for further codings, such as how to use count.index with maps.

```<code>* aws_s3_bucket_notification.bucket_notification.0: Error putting S3 notification configuration: InvalidArgument: Unable to validate the following destination configurations
</code>```

Refer:

How do I avoid the error "Unable to validate the following destination configurations" when using S3 event notifications in CloudFormation?

Body:
I am trying to write a flexible/dynamic resource for aws_s3_bucket_notification which may have variable topics for the specified s3 bucket. For one bucket, I may have just 2 prefixes and 2 topics and for others 4 or 5 and so on... I was thinking of using a map function which will store the "prefix" and "SNS ARN" for each prefix type as the events will be the same. I need to create a s3_bucket_notification which will have all the topics in it without having to manually write each of the topics. Any suggestions?

Example

resource "aws_s3_bucket_notification" "bucket_notification" {
  bucket = "${aws_s3_bucket.bucket.id}"

  topic {
    topic_arn     = "$map.value" ###prototype
    events        = ["s3:ObjectCreated:*"]
    filter_suffix = "$map.key" ###prototype
  }
}

Body:
If my understanding is correct, the codes should like this:

variable "sns_top" {
  type = "map"

  default = {
    dev  = "topic1"
    uat  = "topic2"
    prod = "topic3"
  }
}

variable "bucket_name" {
  default = "my-tf-test-bucket-dfsfddsf"
}

data "aws_caller_identity" "current" {}

resource "aws_sns_topic" "sns_topic" {
  count = "${length(keys(var.sns_top))}"
  name  = "sns-topic-${element(values(var.sns_top),count.index)}"
}

resource "aws_sns_topic_policy" "custom" {
  count = "${length(keys(var.sns_top))}"
  arn   = "${element(aws_sns_topic.sns_topic.*.arn, count.index)}"

  policy = <<POLICY
{
  "Version": "2012-10-17",
  "Id": "default",
  "Statement":[{
    "Sid": "default",
    "Effect": "Allow",
    "Principal": {"AWS":"*"},
    "Action": [
      "SNS:GetTopicAttributes",
      "SNS:SetTopicAttributes",
      "SNS:AddPermission",
      "SNS:RemovePermission",
      "SNS:DeleteTopic"
    ],
    "Resource": "${element(aws_sns_topic.sns_topic.*.arn, count.index)}"
  }]
}
POLICY

  depends_on = ["aws_sns_topic.sns_topic"]
}

resource "aws_s3_bucket" "bucket" {
  bucket = "${var.bucket_name}"
}

data "aws_iam_policy_document" "default" {
  statement {
    effect = "Allow"

    actions = [
      "s3:PutObject",
    ]

    resources = [
      "${aws_s3_bucket.bucket.arn}/*",
    ]

    principals {
      type        = "AWS"
      identifiers = ["arn:aws:iam::${data.aws_caller_identity.current.account_id}:root"]
    }
  }
}

resource "aws_s3_bucket_policy" "default" {
  bucket = "${aws_s3_bucket.bucket.id}"
  policy = "${data.aws_iam_policy_document.default.json}"
}

resource "aws_s3_bucket_notification" "bucket_notification" {
  count  = "${length(keys(var.sns_top))}"
  bucket = "${aws_s3_bucket.bucket.id}"

  topic {
    topic_arn     = "${element(aws_sns_topic.sns_topic.*.arn, count.index)}"
    events        = ["s3:ObjectCreated:*"]
    filter_suffix = "${element(keys(var.sns_top),count.index)}"
  }
}

The codes hit an error explained in below link, but you should be fine to use it for further codings, such as how to use count.index with maps.

* aws_s3_bucket_notification.bucket_notification.0: Error putting S3 notification configuration: InvalidArgument: Unable to validate the following destination configurations

Refer:

How do I avoid the error "Unable to validate the following destination configurations" when using S3 event notifications in CloudFormation?


问:
Java, sum range of numbers in a for loop
Sorry I have been trying to figure this out and it's driving me crazy.

I need to write a java program that sums a range of numbers entered by the user and by the count of numbers entered by a user.  So if a user enters 5, 25 with count of 5.  It should sum 5+10+15+20+25=75  I have gotten it to work with a while loop, but not a for loop.  Sorry if I am asking for help for something that should be simple.  I left school almost 15 years ago involuntarily and struggling to get back into in.

Do I need to nest the loop?

```<code>import java.util.Scanner;
public class example1

{
  public static void main(String[] args) {
    int s, e, c = 0, sum = 0;
    Scanner sc = new Scanner(System.in);
    System.out.print("Enter a starting number:  ");
    s = sc.nextInt();
    System.out.print("Enter an end number:  ");
    e = sc.nextInt();
    System.out.print("Enter a count by number:  ");
    c = sc.nextInt();

    {

      for (; s <= e; s++)
        sum += c;
      System.out.println("Sum of your numbers  " + sum);
    }

  }
}
</code>```

答:
You are incrementing s by one with s++, sounds like you should be incrementing by the count:

```<code>for (; s <= e; s+=c)
    sum += s;
</code>```

Body:
Sorry I have been trying to figure this out and it's driving me crazy.

I need to write a java program that sums a range of numbers entered by the user and by the count of numbers entered by a user.  So if a user enters 5, 25 with count of 5.  It should sum 5+10+15+20+25=75  I have gotten it to work with a while loop, but not a for loop.  Sorry if I am asking for help for something that should be simple.  I left school almost 15 years ago involuntarily and struggling to get back into in.

Do I need to nest the loop?

import java.util.Scanner;
public class example1

{
  public static void main(String[] args) {
    int s, e, c = 0, sum = 0;
    Scanner sc = new Scanner(System.in);
    System.out.print("Enter a starting number:  ");
    s = sc.nextInt();
    System.out.print("Enter an end number:  ");
    e = sc.nextInt();
    System.out.print("Enter a count by number:  ");
    c = sc.nextInt();

    {

      for (; s <= e; s++)
        sum += c;
      System.out.println("Sum of your numbers  " + sum);
    }

  }
}

Body:
You are incrementing s by one with s++, sounds like you should be incrementing by the count:

for (; s <= e; s+=c)
    sum += s;


问:
Has Lua a future as a general-purpose scripting language?
As already discussed in "Lua as a general-purpose scripting language?" Lua currently probably isn't the best scripting language for the desktop environment.

But what do you think about the future? Will Lua get so popular that there will soon be enough libraries to be able to use it like Python, Ruby or something similar?

Or will it simply stay in it's WoW niche and that's it?

答: It's 2017, 9 years after this question was first asked, and lua is now being heavily used in the field of machine learning due to the Torch library.

LastEditorDisplayName: PhiLho


问:
Nesting PHP (to implement master & content pages)
Here I thought I was being smart.  Using PHP, I created a master page, master.php, that injects one of a selection of content pages: content1.php, content2.php, etc.  It didn't occur to me that I'd like to be able to use PHP in the content pages.

The master injects content like this:

```<code><?php
if($pageContentHtml != '') {
    echo $pageContentHtml;
}
?>
</code>```

Of course, when $pageContentHtml contains any <?php ?> blocks, the page does not render as desired.

I read about using PHP's ob_* functions to buffer the output but I couldn't quite figure out whether this will let me do what I want.  Will it?  Is this possible?

Sample content.php file:

```<code><div class="row">
<div class="row-centered">
    <div class="col-md-12">
        <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque...</p>
    </div>
</div>
</div>

<div class="row">
<div class="row-centered">
    <div class="col-md-12">

        <?php
            $bookFileNames = array(
                "book-cover1.jpg"
                ,"book-cover2.jpg"
                ,"book-cover3.jpg"
                ,"book-cover4.jpg"
                .
                .
                .
            );

            for($i=0; $i<count($bookFileNames); ++i) {
                echo '<a href="/images/books/' . $bookFileNames[$i] . '" class="book-title" data-toggle="lightbox" data-gallery="book-covers"><img src="/images/books/' . $bookFileNames[$i] . '" class="img-fluid"></a>';
            }
        ?>

    </div>
</div>
</div>
</code>```

答:
You can use include() or require() to include the content pages, rather than read in their contents. When included, PHP will be processed as normal:

```<code>include('content1.php');
</code>```

Body:
Here I thought I was being smart.  Using PHP, I created a master page, master.php, that injects one of a selection of content pages: content1.php, content2.php, etc.  It didn't occur to me that I'd like to be able to use PHP in the content pages.

The master injects content like this:

<?php
if($pageContentHtml != '') {
    echo $pageContentHtml;
}
?>

Of course, when $pageContentHtml contains any <?php ?> blocks, the page does not render as desired.

I read about using PHP's ob_* functions to buffer the output but I couldn't quite figure out whether this will let me do what I want.  Will it?  Is this possible?

Sample content.php file:

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque...

        <?php
            $bookFileNames = array(
                "book-cover1.jpg"
                ,"book-cover2.jpg"
                ,"book-cover3.jpg"
                ,"book-cover4.jpg"
                .
                .
                .
            );

            for($i=0; $i<count($bookFileNames); ++i) {
                echo '';
            }
        ?>

Body:
You can use include() or require() to include the content pages, rather than read in their contents. When included, PHP will be processed as normal:

include('content1.php');