问:
QtCharts auto range for y-axis
I would like to automatically change the y-axis by using a dynamic plot. I changed the dynamic plot example in the examples and have appended lots of points. After a new point is appended, the plot should adjust its y-axis to account for the new maximum value. Is it possible for the plot to do this automatically?

答:
We can use the signal pointAdded of the series to update the range, for this we will create 2 variables that store the maximum and minimum, respectively:

```<code>connect(m_series, &QSplineSeries::pointAdded, [=](int index){
    qreal y = m_series->at(index).y();

    if(y< yMin || y > yMax){
        if(y < yMin)
            yMin = y;
        if(y> yMax)
            yMax = y;
        axisY()->setRange(yMin-20, yMax+20);
    }

});
</code>```

Complete code:

chart.h

```<code>#ifndef CHART_H
#define CHART_H

#include <QtCharts/QChart>
#include <QTimer>

QT_CHARTS_BEGIN_NAMESPACE
class QSplineSeries;
class QValueAxis;
QT_CHARTS_END_NAMESPACE

QT_CHARTS_USE_NAMESPACE

//![1]
class Chart: public QChart
{
    Q_OBJECT
public:
    Chart(QGraphicsItem *parent = 0, Qt::WindowFlags wFlags = 0);
    virtual ~Chart();

public slots:
    void handleTimeout();

private:
    QTimer m_timer;
    QSplineSeries *m_series;
    QStringList m_titles;
    QValueAxis *m_axis;
    qreal m_step;
    qreal m_x;
    qreal m_y;
    //new variables
    qreal yMin;
    qreal yMax;
};
//![1]
</code>```

chart.cpp

```<code>#include "chart.h"
#include <QtCharts/QAbstractAxis>
#include <QtCharts/QSplineSeries>
#include <QtCharts/QValueAxis>
#include <QTime>
#include <QDebug>

Chart::Chart(QGraphicsItem *parent, Qt::WindowFlags wFlags):
    QChart(QChart::ChartTypeCartesian, parent, wFlags),
    m_series(0),
    m_axis(new QValueAxis),
    m_step(0),
    m_x(5),
    m_y(1)
{
    qsrand((uint) QTime::currentTime().msec());

    connect(&m_timer, &QTimer::timeout, this, &Chart::handleTimeout);
    m_timer.setInterval(1000);

    m_series = new QSplineSeries(this);

    QPen green(Qt::red);
    green.setWidth(3);
    m_series->setPen(green);
    m_series->append(m_x, m_y);

    addSeries(m_series);
    createDefaultAxes();
    setAxisX(m_axis, m_series);
    m_axis->setTickCount(5);

    yMax = 10;
    yMin = -5;

    axisX()->setRange(0, 10);
    axisY()->setRange(yMin, yMax);

    connect(m_series, &QSplineSeries::pointAdded, [=](int index){
        qreal y = m_series->at(index).y();

        if(y< yMin || y > yMax){
            if(y < yMin)
                yMin = y;
            if(y> yMax)
                yMax = y;
            axisY()->setRange(yMin-20, yMax+20);
        }

    });

    m_timer.start();
}

Chart::~Chart()
{

}

void Chart::handleTimeout()
{
    qreal x = plotArea().width() / m_axis->tickCount();
    qreal y = (m_axis->max() - m_axis->min()) / m_axis->tickCount();
    m_x += y;
    //m_y = qrand() % 5 - 2.5;
    m_y = 50*(qrand() % 5 - 2.5);
    m_series->append(m_x, m_y);
    scroll(x, 0);
    if (m_x == 100)
        m_timer.stop();
}
</code>```

Title: QtCharts auto range for y-axis

Body:
We can use the signal pointAdded of the series to update the range, for this we will create 2 variables that store the maximum and minimum, respectively:

connect(m_series, &QSplineSeries::pointAdded, [=](int index){
    qreal y = m_series->at(index).y();

    if(y< yMin || y > yMax){
        if(y < yMin)
            yMin = y;
        if(y> yMax)
            yMax = y;
        axisY()->setRange(yMin-20, yMax+20);
    }

});

Complete code:

chart.h

#ifndef CHART_H
#define CHART_H

#include <QtCharts/QChart>
#include <QTimer>

QT_CHARTS_BEGIN_NAMESPACE
class QSplineSeries;
class QValueAxis;
QT_CHARTS_END_NAMESPACE

QT_CHARTS_USE_NAMESPACE

//![1]
class Chart: public QChart
{
    Q_OBJECT
public:
    Chart(QGraphicsItem *parent = 0, Qt::WindowFlags wFlags = 0);
    virtual ~Chart();

public slots:
    void handleTimeout();

private:
    QTimer m_timer;
    QSplineSeries *m_series;
    QStringList m_titles;
    QValueAxis *m_axis;
    qreal m_step;
    qreal m_x;
    qreal m_y;
    //new variables
    qreal yMin;
    qreal yMax;
};
//![1]

chart.cpp

#include "chart.h"
#include <QtCharts/QAbstractAxis>
#include <QtCharts/QSplineSeries>
#include <QtCharts/QValueAxis>
#include <QTime>
#include <QDebug>

Chart::Chart(QGraphicsItem *parent, Qt::WindowFlags wFlags):
    QChart(QChart::ChartTypeCartesian, parent, wFlags),
    m_series(0),
    m_axis(new QValueAxis),
    m_step(0),
    m_x(5),
    m_y(1)
{
    qsrand((uint) QTime::currentTime().msec());

    connect(&m_timer, &QTimer::timeout, this, &Chart::handleTimeout);
    m_timer.setInterval(1000);

    m_series = new QSplineSeries(this);

    QPen green(Qt::red);
    green.setWidth(3);
    m_series->setPen(green);
    m_series->append(m_x, m_y);

    addSeries(m_series);
    createDefaultAxes();
    setAxisX(m_axis, m_series);
    m_axis->setTickCount(5);

    yMax = 10;
    yMin = -5;

    axisX()->setRange(0, 10);
    axisY()->setRange(yMin, yMax);

    connect(m_series, &QSplineSeries::pointAdded, [=](int index){
        qreal y = m_series->at(index).y();

        if(y< yMin || y > yMax){
            if(y < yMin)
                yMin = y;
            if(y> yMax)
                yMax = y;
            axisY()->setRange(yMin-20, yMax+20);
        }

    });

    m_timer.start();
}

Chart::~Chart()
{

}

void Chart::handleTimeout()
{
    qreal x = plotArea().width() / m_axis->tickCount();
    qreal y = (m_axis->max() - m_axis->min()) / m_axis->tickCount();
    m_x += y;
    //m_y = qrand() % 5 - 2.5;
    m_y = 50*(qrand() % 5 - 2.5);
    m_series->append(m_x, m_y);
    scroll(x, 0);
    if (m_x == 100)
        m_timer.stop();
}


来源: stackexchange

问:
Sql Server Pivot Rows Into Columns with NULL Values As Column wtih default name
I want to Pivot Rows into dynamic Columns which is working fine but the issue is NULL values in rows does not transformed into columns with any default name and instead of NULL I want ZERO(0) in value.

Please refer to this image for output :

Below is my sql query with table :

```<code>CREATE TABLE #CourseSales
 (Course VARCHAR(50) null,Year INT,Earning MONEY null)
 go
 --Populate Sample records
 INSERT INTO #CourseSales VALUES('.NET',2012,10000)
 INSERT INTO #CourseSales VALUES('.NET',2012,5000)
 INSERT INTO #CourseSales VALUES('Java',2012,20000)
 INSERT INTO #CourseSales VALUES('Java',2013,30000)
 INSERT INTO #CourseSales VALUES(null,2013,1200)
 INSERT INTO #CourseSales VALUES(null,2012,null)

 select * from #CourseSales

DECLARE @DynamicPivotQuery AS NVARCHAR(MAX),
        @PivotColumnNames AS NVARCHAR(MAX),
        @PivotSelectColumnNames AS NVARCHAR(MAX)

--Get distinct values of the PIVOT Column
SELECT @PivotColumnNames= ISNULL(@PivotColumnNames + ',','')+ QUOTENAME(Course)
FROM (SELECT DISTINCT Course FROM #CourseSales) AS Courses

--Get distinct values of the PIVOT Column with isnull
SELECT @PivotSelectColumnNames = ISNULL(@PivotSelectColumnNames + ',','') + 'ISNULL(' + QUOTENAME(Course) + ', 0) AS ' + QUOTENAME(Course)
FROM (SELECT DISTINCT Course FROM #CourseSales) AS Courses

--Prepare the PIVOT query using the dynamic
SET @DynamicPivotQuery =N'SELECT Year, ' + @PivotSelectColumnNames + ' FROM #CourseSales PIVOT(SUM(Earning) FOR Course IN (' + @PivotColumnNames + ')) AS PVTTable'

--Execute the Dynamic Pivot Query
EXEC sp_executesql @DynamicPivotQuery

drop table #CourseSales
</code>```

Any help would be appreciated. Thanks.

答:
You can try this</p>

```<code>DECLARE @DynamicPivotQuery AS NVARCHAR(MAX),
        @PivotColumnNames AS NVARCHAR(MAX),
        @PivotSelectColumnNames AS NVARCHAR(MAX)

--Get distinct values of the PIVOT Column
SELECT @PivotColumnNames= ISNULL(@PivotColumnNames + ',','')+ QUOTENAME(Course)
FROM (SELECT DISTINCT ISNULL(Course,'ZAny') AS Course FROM #CourseSales) AS Courses

--Get distinct values of the PIVOT Column with isnull
SELECT @PivotSelectColumnNames = ISNULL(@PivotSelectColumnNames + ',','') + 'ISNULL(' + QUOTENAME(Course) + ', 0) AS ' + QUOTENAME(Course)
FROM (SELECT DISTINCT ISNULL(Course,'ZAny') AS Course FROM #CourseSales) AS Courses

--Prepare the PIVOT query using the dynamic
SET @DynamicPivotQuery =N'SELECT Year, ' + @PivotSelectColumnNames + ' FROM (SELECT ISNULL(Course,''ZAny'') AS Course,Year,Earning FROM #CourseSales) #CourseSales  PIVOT(SUM(Earning) FOR Course IN (' + @PivotColumnNames + ')) AS PVTTable'

--Execute the Dynamic Pivot Query
EXEC sp_executesql @DynamicPivotQuery
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I want to Pivot Rows into dynamic Columns which is working fine but the issue is NULL values in rows does not transformed into columns with any default name and instead of NULL I want ZERO(0) in value.

Please refer to this image for output :

Below is my sql query with table :

CREATE TABLE #CourseSales
 (Course VARCHAR(50) null,Year INT,Earning MONEY null)
 go
 --Populate Sample records
 INSERT INTO #CourseSales VALUES('.NET',2012,10000)
 INSERT INTO #CourseSales VALUES('.NET',2012,5000)
 INSERT INTO #CourseSales VALUES('Java',2012,20000)
 INSERT INTO #CourseSales VALUES('Java',2013,30000)
 INSERT INTO #CourseSales VALUES(null,2013,1200)
 INSERT INTO #CourseSales VALUES(null,2012,null)

 select * from #CourseSales

DECLARE @DynamicPivotQuery AS NVARCHAR(MAX),
        @PivotColumnNames AS NVARCHAR(MAX),
        @PivotSelectColumnNames AS NVARCHAR(MAX)

--Get distinct values of the PIVOT Column
SELECT @PivotColumnNames= ISNULL(@PivotColumnNames + ',','')+ QUOTENAME(Course)
FROM (SELECT DISTINCT Course FROM #CourseSales) AS Courses

--Get distinct values of the PIVOT Column with isnull
SELECT @PivotSelectColumnNames = ISNULL(@PivotSelectColumnNames + ',','') + 'ISNULL(' + QUOTENAME(Course) + ', 0) AS ' + QUOTENAME(Course)
FROM (SELECT DISTINCT Course FROM #CourseSales) AS Courses

--Prepare the PIVOT query using the dynamic
SET @DynamicPivotQuery =N'SELECT Year, ' + @PivotSelectColumnNames + ' FROM #CourseSales PIVOT(SUM(Earning) FOR Course IN (' + @PivotColumnNames + ')) AS PVTTable'

--Execute the Dynamic Pivot Query
EXEC sp_executesql @DynamicPivotQuery

drop table #CourseSales

Any help would be appreciated. Thanks.

Body:
You can try this

DECLARE @DynamicPivotQuery AS NVARCHAR(MAX),
        @PivotColumnNames AS NVARCHAR(MAX),
        @PivotSelectColumnNames AS NVARCHAR(MAX)

--Get distinct values of the PIVOT Column
SELECT @PivotColumnNames= ISNULL(@PivotColumnNames + ',','')+ QUOTENAME(Course)
FROM (SELECT DISTINCT ISNULL(Course,'ZAny') AS Course FROM #CourseSales) AS Courses

--Get distinct values of the PIVOT Column with isnull
SELECT @PivotSelectColumnNames = ISNULL(@PivotSelectColumnNames + ',','') + 'ISNULL(' + QUOTENAME(Course) + ', 0) AS ' + QUOTENAME(Course)
FROM (SELECT DISTINCT ISNULL(Course,'ZAny') AS Course FROM #CourseSales) AS Courses

--Prepare the PIVOT query using the dynamic
SET @DynamicPivotQuery =N'SELECT Year, ' + @PivotSelectColumnNames + ' FROM (SELECT ISNULL(Course,''ZAny'') AS Course,Year,Earning FROM #CourseSales) #CourseSales  PIVOT(SUM(Earning) FOR Course IN (' + @PivotColumnNames + ')) AS PVTTable'

--Execute the Dynamic Pivot Query
EXEC sp_executesql @DynamicPivotQuery


问:
How to have the data in the CSV file converted to JSON in the request body when using JMETER CSV Date set config
I have a CSV dataset config pointing to a CSV file with the following data:

```<code>Ids
87541
4551
15441
11117
.....
n
</code>```

Instead of looping through the file and do multiple POST requests for each value, I need to have a single POST request and pass ALL the IDs  the request body which should like this in the generated JSON:

```<code>{
  "ids": [
    84280,
    2334,
    235,
    32554,
    3663,
    346,
    344643,
    ....,
    n
  ]
}
</code>```

答:
Add JSR223 PreProcessor as a child of the request which needs to send this JSON.

Put the following code into "Script" area

```<code>def csvfile = new File('test.csv')
def jsonBuilder = new groovy.json.JsonBuilder()

jsonBuilder {
    ids csvfile.collect { it }
}

vars.put('requestBody', jsonBuilder.toPrettyString())
log.info(vars.get('requestBody'))
</code>```

The above code will read test.csv file in JMeter's "bin" folder and create an ids JSON Array where each element will be a line from the given file and put the result into ${requestBody} JMeter Variable

Demo:

References:

Parsing and producing JSON

Apache Groovy - Why and How You Should Use It

Body:
I have a CSV dataset config pointing to a CSV file with the following data:

Ids
87541
4551
15441
11117
.....
n

Instead of looping through the file and do multiple POST requests for each value, I need to have a single POST request and pass ALL the IDs  the request body which should like this in the generated JSON:

{
  "ids": [
    84280,
    2334,
    235,
    32554,
    3663,
    346,
    344643,
    ....,
    n
  ]
}

Body:
Add JSR223 PreProcessor as a child of the request which needs to send this JSON.

Put the following code into "Script" area

def csvfile = new File('test.csv')
def jsonBuilder = new groovy.json.JsonBuilder()

jsonBuilder {
    ids csvfile.collect { it }
}

vars.put('requestBody', jsonBuilder.toPrettyString())
log.info(vars.get('requestBody'))

The above code will read test.csv file in JMeter's "bin" folder and create an ids JSON Array where each element will be a line from the given file and put the result into ${requestBody} JMeter Variable

Demo:

References:

Parsing and producing JSON

Apache Groovy - Why and How You Should Use It


问:
How to change progress bar's progress color in Android
I'm using an horizontal progress bar in my Android application, and I want to change its progress color (which is Yellow by default). How can I do it using code (not XML)?

答:
This worked for me :</p>

```<code><ProgressBar
 android:indeterminateTint="#d60909"
 ... />
</code>```

Body:
This worked for me :

<ProgressBar
 android:indeterminateTint="#d60909"
 ... />


问:
Laravel 5.4 Paste JavaScript in blade template
I am adding AJAX script to my Laravel blade template file. But for some reason my JavaScript not working properly. It seats there on the page, and everything is good but when i try to trigger function by clicking on button it's just don't work.

This JavaScript code cannot be in the separate file, because I am crating a lot of different forms which should be processed with it own JavaScript function. So I need to have this functions on the loop with the form.

Here is my whole blade template file script:

```<code>@if($inventories)

<a href="{{ url('/inventory') }}" type="button" class="btn btn-sm btn-primary"> <<- Back To Inventory</a>
<div class="text-center"><b>Search Page</b></div>
<br>
<br>

<div class="search">
    <div class="col-md-12">
        @include(env('THEME').'.search_box')
    </div>
</div>

<table>

    @foreach($inventories as $inventory)
    <tr >
        <td class="part_img" rowspan="3"><a href="{{ route('inventory.show',['slug' => $inventory->slug]) }}"><img src="{{ asset(env('THEME')) }}/images/inventory/{{$inventory->main_img}}"></a></td>
    </tr>
    <tr>
        <td class="inventory_part_title" colspan="8">
            <div style="float: left; margin: 0 30px;">{{ $inventory->part_number }}</div>
            <div style="float: left;"><a href="{{ route('inventory.show',['slug' => $inventory->slug]) }}">{{ $inventory->title }}</a></div>
            <div style="float: right; margin-right: 50px;">{{ $inventory->upc_number }}</div>
        </td>
    </tr>
    <tr>
        <td><b>Location:</b> {{ $inventory->storage_location }}</td>
        <td><b>Brand:</b> {{ $inventory->brand }}</td>
        <td><b>Supplier:</b> {{ $inventory->supplier }}</td>
        <td><b>GBP:</b> £{{ $inventory->unit_price_gbp }}</td>
        <td><b>USD:</b> ${{ $inventory->unit_price_usd }}</td>
        <td><b>In Stock:</b> {{ $inventory->unit_in_stock }}</td>
        <td><b>Sold:</b> {{ $inventory->unit_sold }}</td>
        <td>
            <div class="onpage-sold-input">
                {!! Form::open(['url' => route('sold.sold'),'class'=>'contact-form', 'id'=>'search-sold-button-'.$inventory->id,'method'=>'POST']) !!}
                    {!! Form::text('sold', old('sold'), array('class'=>'form-control', 'placeholder'=>'Qty.')) !!}
                    <input type="hidden" name="part_id" value="{{ $inventory->id }}">
                    <input type="hidden" name="_token" value="{{ csrf_token() }}">
                    {!! Form::button('Sold', ['class' => 'btn btn-sm btn-success sold-button', 'id'=>'sold-button-'.$inventory->id,'type'=>'submit']) !!}
                {!! Form::close() !!}
            </div>

            <script type="text/javascript">
                $('#sold-button-{{ $inventory->id }}').on('click', function (e) {
                    e.preventDefault();

                    var form = $('#search-sold-button-{{ $inventory->id }}'),
                        data = form.serialize(),
                        ajax_url = form.attr('action'),
                        alert_section = $('.alert-section');

                        console.log(ajax_url);
                        console.log(data);

                    $.post(ajax_url, data, function (resp) {
                        alert_section.fadeIn().find('.alert').html(resp);
                        setTimeout(function () {
                            alert_section.fadeOut();
                        }, 3000)
                    })
                });
            </script>

        </td>
        <!--<td><button type="button" class="btn btn-sm btn-success">Edit</button></td>-->
    </tr>
    <tr>
        <td colspan="8"></td>
    </tr>
    @endforeach

</table>

@else
<p>Inventory is empty!</p>
@endif
</code>```

How can I fix this issue?

答:
Here is example with your given code. Hope this will help you.

Code might not work I haven't tested it. but this way you don't have to put JS code in Loop but with single function.

Here we are calling JS function "searchSold" on Submit click event.

```<code>    @if($inventories)

            <a href="{{ url('/inventory') }}" type="button" class="btn btn-sm btn-primary"> <<- Back To Inventory</a>
            <div class="text-center"><b>Search Page</b></div>
            <br>
            <br>

            <div class="search">
                <div class="col-md-12">
                    @include(env('THEME').'.search_box')
                </div>
            </div>

            <table>

                @foreach($inventories as $inventory)
                <tr >
                    <td class="part_img" rowspan="3"><a href="{{ route('inventory.show',['slug' => $inventory->slug]) }}"><img src="{{ asset(env('THEME')) }}/images/inventory/{{$inventory->main_img}}"></a></td>
                </tr>
                <tr>
                    <td class="inventory_part_title" colspan="8">
                        <div style="float: left; margin: 0 30px;">{{ $inventory->part_number }}</div>
                        <div style="float: left;"><a href="{{ route('inventory.show',['slug' => $inventory->slug]) }}">{{ $inventory->title }}</a></div>
                        <div style="float: right; margin-right: 50px;">{{ $inventory->upc_number }}</div>
                    </td>
                </tr>
                <tr>
                    <td><b>Location:</b> {{ $inventory->storage_location }}</td>
                    <td><b>Brand:</b> {{ $inventory->brand }}</td>
                    <td><b>Supplier:</b> {{ $inventory->supplier }}</td>
                    <td><b>GBP:</b> £{{ $inventory->unit_price_gbp }}</td>
                    <td><b>USD:</b> ${{ $inventory->unit_price_usd }}</td>
                    <td><b>In Stock:</b> {{ $inventory->unit_in_stock }}</td>
                    <td><b>Sold:</b> {{ $inventory->unit_sold }}</td>
                    <td>
                        <div class="onpage-sold-input">
                            {!! Form::open(['url' => route('sold.sold'),'class'=>'contact-form', 'id'=>'search-sold-button-'.$inventory->id,'method'=>'POST']) !!}
                                {!! Form::text('sold', old('sold'), array('class'=>'form-control', 'placeholder'=>'Qty.')) !!}
                                <input type="hidden" name="part_id" value="{{ $inventory->id }}">
                                <input type="hidden" name="_token" value="{{ csrf_token() }}">
                                {!! Form::button('Sold', ['class' => 'btn btn-sm btn-success sold-button', 'id'=>'sold-button-'.$inventory->id,'type'=>'submit','onclick' => 'searchSold(event,".$inventory->id.")' ]) !!}
                            {!! Form::close() !!}
                        </div>

                    </td>
                    <!--<td><button type="button" class="btn btn-sm btn-success">Edit</button></td>-->
                </tr>
                <tr>
                    <td colspan="8"></td>
                </tr>
                @endforeach

            </table>

@else
    <p>Inventory is empty!</p>
@endif

        <script type="text/javascript">

        function searchSold(event,inventory_id){

            event.preventDefault();

            var form = $('#search-sold-button-'+inventory_id);
            var data = form.serialize();
            var ajax_url = form.attr('action');
            var alert_section = $('.alert-section');

            $.post(ajax_url, data, function (resp) {
                alert_section.fadeIn().find('.alert').html(resp);
                setTimeout(function () {
                    alert_section.fadeOut();
                }, 3000)
            });
        }
        </script>
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am adding AJAX script to my Laravel blade template file. But for some reason my JavaScript not working properly. It seats there on the page, and everything is good but when i try to trigger function by clicking on button it's just don't work.

This JavaScript code cannot be in the separate file, because I am crating a lot of different forms which should be processed with it own JavaScript function. So I need to have this functions on the loop with the form.

Here is my whole blade template file script:

@if($inventories)

 <<- Back To Inventory

Search Page

        @include(env('THEME').'.search_box')

    @foreach($inventories as $inventory)

         $inventory->slug]) }}">main_img}}">

{{ $inventory->part_number }}

 $inventory->slug]) }}">{{ $inventory->title }}

{{ $inventory->upc_number }}

        Location: {{ $inventory->storage_location }}
        Brand: {{ $inventory->brand }}
        Supplier: {{ $inventory->supplier }}
        GBP: £{{ $inventory->unit_price_gbp }}
        USD: ${{ $inventory->unit_price_usd }}
        In Stock: {{ $inventory->unit_in_stock }}
        Sold: {{ $inventory->unit_sold }}

                {!! Form::open(['url' => route('sold.sold'),'class'=>'contact-form', 'id'=>'search-sold-button-'.$inventory->id,'method'=>'POST']) !!}
                    {!! Form::text('sold', old('sold'), array('class'=>'form-control', 'placeholder'=>'Qty.')) !!}
                    <input type="hidden" name="part_id" value="{{ $inventory->id }}">
                    <input type="hidden" name="_token" value="{{ csrf_token() }}">
                    {!! Form::button('Sold', ['class' => 'btn btn-sm btn-success sold-button', 'id'=>'sold-button-'.$inventory->id,'type'=>'submit']) !!}
                {!! Form::close() !!}

    @endforeach

@else

Inventory is empty!

@endif

How can I fix this issue?

Body:
Here is example with your given code. Hope this will help you.

Code might not work I haven't tested it. but this way you don't have to put JS code in Loop but with single function.

Here we are calling JS function "searchSold" on Submit click event.

    @if($inventories)

            <a href="{{ url('/inventory') }}" type="button" class="btn btn-sm btn-primary"> <<- Back To Inventory</a>
            <div class="text-center"><b>Search Page</b></div>
            <br>
            <br>

            <div class="search">
                <div class="col-md-12">
                    @include(env('THEME').'.search_box')
                </div>
            </div>

            <table>

                @foreach($inventories as $inventory)
                <tr >
                    <td class="part_img" rowspan="3"><a href="{{ route('inventory.show',['slug' => $inventory->slug]) }}"><img src="{{ asset(env('THEME')) }}/images/inventory/{{$inventory->main_img}}"></a></td>
                </tr>
                <tr>
                    <td class="inventory_part_title" colspan="8">
                        <div style="float: left; margin: 0 30px;">{{ $inventory->part_number }}</div>
                        <div style="float: left;"><a href="{{ route('inventory.show',['slug' => $inventory->slug]) }}">{{ $inventory->title }}</a></div>
                        <div style="float: right; margin-right: 50px;">{{ $inventory->upc_number }}</div>
                    </td>
                </tr>
                <tr>
                    <td><b>Location:</b> {{ $inventory->storage_location }}</td>
                    <td><b>Brand:</b> {{ $inventory->brand }}</td>
                    <td><b>Supplier:</b> {{ $inventory->supplier }}</td>
                    <td><b>GBP:</b> &#163;{{ $inventory->unit_price_gbp }}</td>
                    <td><b>USD:</b> ${{ $inventory->unit_price_usd }}</td>
                    <td><b>In Stock:</b> {{ $inventory->unit_in_stock }}</td>
                    <td><b>Sold:</b> {{ $inventory->unit_sold }}</td>
                    <td>
                        <div class="onpage-sold-input">
                            {!! Form::open(['url' => route('sold.sold'),'class'=>'contact-form', 'id'=>'search-sold-button-'.$inventory->id,'method'=>'POST']) !!}
                                {!! Form::text('sold', old('sold'), array('class'=>'form-control', 'placeholder'=>'Qty.')) !!}
                                <input type="hidden" name="part_id" value="{{ $inventory->id }}">
                                <input type="hidden" name="_token" value="{{ csrf_token() }}">
                                {!! Form::button('Sold', ['class' => 'btn btn-sm btn-success sold-button', 'id'=>'sold-button-'.$inventory->id,'type'=>'submit','onclick' => 'searchSold(event,".$inventory->id.")' ]) !!}
                            {!! Form::close() !!}
                        </div>

                    </td>
                    <!--<td><button type="button" class="btn btn-sm btn-success">Edit</button></td>-->
                </tr>
                <tr>
                    <td colspan="8"></td>
                </tr>
                @endforeach

            </table>

@else
    <p>Inventory is empty!</p>
@endif

        <script type="text/javascript">

        function searchSold(event,inventory_id){

            event.preventDefault();

            var form = $('#search-sold-button-'+inventory_id);
            var data = form.serialize();
            var ajax_url = form.attr('action');
            var alert_section = $('.alert-section');

            $.post(ajax_url, data, function (resp) {
                alert_section.fadeIn().find('.alert').html(resp);
                setTimeout(function () {
                    alert_section.fadeOut();
                }, 3000)
            });
        }
        </script>


问:
Resize code ruins quality?
So I'm trying to resize HUGE images, like 5500x3500 JPGs down to 1024x768 or less. The following function works, but it really runs the quality, makes the text all fuzzy.

```<code>static public Bitmap ScaleImage(Image image, int maxWidth, int maxHeight)
{
    var ratioX = (double)maxWidth / image.Width;
    var ratioY = (double)maxHeight / image.Height;
    var ratio = Math.Min(ratioX, ratioY);

    var newWidth = (int)(image.Width * ratio);
    var newHeight = (int)(image.Height * ratio);

    var newImage = new Bitmap(newWidth, newHeight);
    Graphics.FromImage(newImage).DrawImage(image, 0, 0, newWidth, newHeight);
    Bitmap bmp = new Bitmap(newImage);

    return bmp;
}
</code>```

Any idea of a better way to do this?

答:
You should set the quality-properties in Graphics-object to HighQuality:

```<code>static public Bitmap ScaleImage(Image image, int maxWidth, int maxHeight)
{
    var ratioX = (double)maxWidth / image.Width;
    var ratioY = (double)maxHeight / image.Height;
    var ratio = Math.Min(ratioX, ratioY);

    var newWidth = (int)(image.Width * ratio);
    var newHeight = (int)(image.Height * ratio);

    using (Bitmap newImage = new Bitmap(newWidth, newHeight))
    {
        using (Graphics g = Graphics.FromImage(newImage))
        {
            g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
            g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
            g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
            g.PixelOffsetMode = System.Drawing.Drawing2D.PixelOffsetMode.HighQuality;

            Bitmap bmp = new Bitmap(newImage);
            return bmp;
        }
    }
}
</code>```

Also be sure to use using-block with objects that implements iDisposable: Image, Bitmap and Graphichs all do.

Title: Resize code ruins quality?

Body:
So I'm trying to resize HUGE images, like 5500x3500 JPGs down to 1024x768 or less. The following function works, but it really runs the quality, makes the text all fuzzy.

static public Bitmap ScaleImage(Image image, int maxWidth, int maxHeight)
{
    var ratioX = (double)maxWidth / image.Width;
    var ratioY = (double)maxHeight / image.Height;
    var ratio = Math.Min(ratioX, ratioY);

    var newWidth = (int)(image.Width * ratio);
    var newHeight = (int)(image.Height * ratio);

    var newImage = new Bitmap(newWidth, newHeight);
    Graphics.FromImage(newImage).DrawImage(image, 0, 0, newWidth, newHeight);
    Bitmap bmp = new Bitmap(newImage);

    return bmp;
}

Any idea of a better way to do this?

Body:
You should set the quality-properties in Graphics-object to HighQuality:

static public Bitmap ScaleImage(Image image, int maxWidth, int maxHeight)
{
    var ratioX = (double)maxWidth / image.Width;
    var ratioY = (double)maxHeight / image.Height;
    var ratio = Math.Min(ratioX, ratioY);

    var newWidth = (int)(image.Width * ratio);
    var newHeight = (int)(image.Height * ratio);

    using (Bitmap newImage = new Bitmap(newWidth, newHeight))
    {
        using (Graphics g = Graphics.FromImage(newImage))
        {
            g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
            g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
            g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
            g.PixelOffsetMode = System.Drawing.Drawing2D.PixelOffsetMode.HighQuality;

            Bitmap bmp = new Bitmap(newImage);
            return bmp;
        }
    }
}

Also be sure to use using-block with objects that implements iDisposable: Image, Bitmap and Graphichs all do.


问:
Create parent child nested JSON from index
I am newb for D3. I am using d3.jd version 3.
I have following type of JSON:

```<code>[
  {
    "health": "OK",
    "name": "new A",
    "index": "A"
  },
  {
    "health": "SEVERE",
    "name": "new AB",
    "index": "A > B"
  },
  {
    "health": "OK",
    "name": "new ABC",
    "index": "A > B > C"
  },
  {
    "health": "OK",
    "name": "new ADE",
    "index": "A > D > E"
  },
  {
    "health": "SEVERE",
    "name": "new AD",
    "index": "A > D"
  }
]
</code>```

I want to create following parent child nested data from above JSON:

```<code>[
  {
    "health": "OK",
    "name": "new A",
    "index": "A",
    "children": [
      {
        "health": "SEVERE",
        "name": "new AB",
        "index": "A > B",
        "children": [
          {
            "health": "OK",
            "name": "new ABC",
            "index": "A > B > C"
          }
        ]
      },
      {
        "health": "SEVERE",
        "name": "new AD",
        "index": "A > D",
        "children": [
          {
            "health": "OK",
            "name": "new ADE",
            "index": "A > D > E"
          }
        ]
      }
    ]
  }
]
</code>```

I want create parent child data through index.
So, If index is "A > B" and "A" is parent and "B" is child.

this is just sample data I have no. of large data. So, want to increase performances.

it is possible with d3 or jquery to create nested parent child JSON form array of object?

答:
I have done it. for It I need to add parent id.

var data = [
  {
    "health": "OK",
    "name": "new A",
    "index": "A"
  },
  {
    "health": "SEVERE",
    "name": "new AB",
    "index": "A > B"
  },
  {
    "health": "OK",
    "name": "new ABC",
    "index": "A > B > C"
  },
  {
    "health": "OK",
    "name": "new ADE",
    "index": "A > D > E"
  },
  {
    "health": "SEVERE",
    "name": "new AD",
    "index": "A > D"
  }
]

  function fnGetParentID(index) {
                     var indexArr = index.split(' > ');
                     var parentIndex = '';
                     if(indexArr.length !== 1){
                         parentIndex = index.replace(" > " + indexArr[indexArr.length - 1], '')
                     }
                     return parentIndex;
                 };

 function fnCreateStrunture(f) {
                    return f.sort(function (a, b) {
                        return a.index.length < b.index.length ? 1 : a.index.length == b.index.length ? a.index < b.index ? -1 : 1 : -1;
                    }).reduce(function (p, c, i, a) {
                        c.ParentID = fnGetParentID(c.index);
                        var parent = !!c.ParentID && a.find(function (e) {
                                return e.index === c.ParentID;
                            });
                        !!parent ? !!parent.children && parent.children.push(c) || (parent.children = [c]) : p.push(c);
                        return p;
                    }, []);
                };

var nestedJson = fnCreateStrunture(data);

document.getElementById("nested").innerHTML = JSON.stringify(nestedJson, undefined, 2);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><pre id="nested">``````

Body:
I am newb for D3. I am using d3.jd version 3.
I have following type of JSON:

[
  {
    "health": "OK",
    "name": "new A",
    "index": "A"
  },
  {
    "health": "SEVERE",
    "name": "new AB",
    "index": "A > B"
  },
  {
    "health": "OK",
    "name": "new ABC",
    "index": "A > B > C"
  },
  {
    "health": "OK",
    "name": "new ADE",
    "index": "A > D > E"
  },
  {
    "health": "SEVERE",
    "name": "new AD",
    "index": "A > D"
  }
]

I want to create following parent child nested data from above JSON:

[
  {
    "health": "OK",
    "name": "new A",
    "index": "A",
    "children": [
      {
        "health": "SEVERE",
        "name": "new AB",
        "index": "A > B",
        "children": [
          {
            "health": "OK",
            "name": "new ABC",
            "index": "A > B > C"
          }
        ]
      },
      {
        "health": "SEVERE",
        "name": "new AD",
        "index": "A > D",
        "children": [
          {
            "health": "OK",
            "name": "new ADE",
            "index": "A > D > E"
          }
        ]
      }
    ]
  }
]

I want create parent child data through index.
So, If index is "A > B" and "A" is parent and "B" is child.

this is just sample data I have no. of large data. So, want to increase performances.

it is possible with d3 or jquery to create nested parent child JSON form array of object?

Body:
I have done it. for It I need to add parent id.

var data = [
  {
    "health": "OK",
    "name": "new A",
    "index": "A"
  },
  {
    "health": "SEVERE",
    "name": "new AB",
    "index": "A > B"
  },
  {
    "health": "OK",
    "name": "new ABC",
    "index": "A > B > C"
  },
  {
    "health": "OK",
    "name": "new ADE",
    "index": "A > D > E"
  },
  {
    "health": "SEVERE",
    "name": "new AD",
    "index": "A > D"
  }
]

  function fnGetParentID(index) {
                     var indexArr = index.split(' > ');
                     var parentIndex = '';
                     if(indexArr.length !== 1){
                         parentIndex = index.replace(" > " + indexArr[indexArr.length - 1], '')
                     }
                     return parentIndex;
                 };

 function fnCreateStrunture(f) {
                    return f.sort(function (a, b) {
                        return a.index.length < b.index.length ? 1 : a.index.length == b.index.length ? a.index < b.index ? -1 : 1 : -1;
                    }).reduce(function (p, c, i, a) {
                        c.ParentID = fnGetParentID(c.index);
                        var parent = !!c.ParentID && a.find(function (e) {
                                return e.index === c.ParentID;
                            });
                        !!parent ? !!parent.children && parent.children.push(c) || (parent.children = [c]) : p.push(c);
                        return p;
                    }, []);
                };

var nestedJson = fnCreateStrunture(data);

document.getElementById("nested").innerHTML = JSON.stringify(nestedJson, undefined, 2);

<pre id="nested"></pre>


问:
Javascript - returning concatenates instead of sum of variables from input
I am trying to get values from input field using .each() and adding them to show the sum in another input value. But unfortunately in spite of using parseInt() I am unable to get sum.

HTML

```<code><input type=text name=value[] id=value class="value">
<input type=text name=value[] id=value class="value">
<input type=text name=totalvalue id=totalvalue>
</code>```

JavaScript

```<code>var totalvalue = parseInt(0);
$(document).on("focusout",".value",function() {
    $(".value").each(function() {
        totalvalue = parseInt(totalvalue + $(this).val());
    });
    $("#totalvalue").val(totalvalue);
});
</code>```

JSFiddle Demo

答: your appending String. $(this).val() is a string . just parse it to int or float.

Body:
I am trying to get values from input field using .each() and adding them to show the sum in another input value. But unfortunately in spite of using parseInt() I am unable to get sum.

HTML

<input type=text name=value[] id=value class="value">
<input type=text name=value[] id=value class="value">
<input type=text name=totalvalue id=totalvalue>

JavaScript

var totalvalue = parseInt(0);
$(document).on("focusout",".value",function() {
    $(".value").each(function() {
        totalvalue = parseInt(totalvalue + $(this).val());
    });
    $("#totalvalue").val(totalvalue);
});

JSFiddle Demo


问:
Newsletter slow sending - delay between 2 mails to the same server / max e-mails per hour?
I have to make a newsletter sending utility application which will collect the list of subscriber from our central database and send out the newsletter. I've considered the possibility to be blacklisted due to flooding if I just flush out all emails at once, so I decided to go on a desktop-based softwer which will email those slowly.

my question is

what is the max emails per hour that may be addressed to the same email domain (recipient/incoming server)?

or what should be delay between 2 e-mails to the same server for it doesn't consider it flooding?

whichever of the above applies more appropriate to the real-world of mail servers configuration...

thanks

答: I make Thread.Sleep(2000) after every 2 mail</p>

OwnerDisplayName: zappan

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Mitch Wheat

OwnerDisplayName: Barbaros


问:
How to find hash code of a Collection?
To my understanding, the following code should print HashCode of collection, as i am printing its HashCode directly.

However, when I run the following code  i am getting Stack overflow error:

```<code>    public class Test1  {

    public static void main(final String[] args) {
        m1(new LinkedHashSet<Collection<?>>());
    }

    private static void m1(final Collection<Collection<?>> cl) {
        cl.add(cl);
        try {
            System.out.println(cl.hashCode());
        } catch (Error err) {
            System.out.println(err);
        }
    }

}
</code>```

Can some one explain this behavior ?

答:
You have created a Collection that contains itself as an element.

A LinkedHashSet's hashCode() is a function of its elements' hashCodes (as you can see below), so computing the hashCode() leads to infinite recursion.

```<code>public int hashCode() {
    int h = 0;
    Iterator<E> i = iterator();
    while (i.hasNext()) {
        E obj = i.next();
        if (obj != null)
            h += obj.hashCode(); // when obj == this, as in your case, this
                                 // call leads to infinite recursion
    }
    return h;
}
</code>```

Title: How to find hash code of a Collection?

Body:
To my understanding, the following code should print HashCode of collection, as i am printing its HashCode directly.

However, when I run the following code  i am getting Stack overflow error:

    public class Test1  {

    public static void main(final String[] args) {
        m1(new LinkedHashSet<Collection<?>>());
    }

    private static void m1(final Collection<Collection<?>> cl) {
        cl.add(cl);
        try {
            System.out.println(cl.hashCode());
        } catch (Error err) {
            System.out.println(err);
        }
    }

}

Can some one explain this behavior ?

Body:
You have created a Collection that contains itself as an element.

A LinkedHashSet's hashCode() is a function of its elements' hashCodes (as you can see below), so computing the hashCode() leads to infinite recursion.

public int hashCode() {
    int h = 0;
    Iterator<E> i = iterator();
    while (i.hasNext()) {
        E obj = i.next();
        if (obj != null)
            h += obj.hashCode(); // when obj == this, as in your case, this
                                 // call leads to infinite recursion
    }
    return h;
}


问:
How to use OR operator in Linq
I want to use OR function in my linq query.
Ex:
Sql:

```<code>select * from tblusers where userid=1 and status='a' or status='b';
</code>```

Linq:

```<code>var result= _Repository.selectAll().where(x=>x.UserID==1 && x.status=="a" OR x.status=="B");
</code>```

It's does work for linq query. so does anyone have any idea?

答:
Try code:

```<code>var result =( from  x in _Repository.selectAll()
           where x.UserID==1 && (x.status=="a" || x.status=="B") select x);
</code>```

another Solution

```<code> var result =( from  x in _Repository.selectAll().where(c=>c.status=="a" || x.status=="B")
               where x.UserID==1  select x);
</code>```

Title: How to use OR operator in Linq

Body:
I want to use OR function in my linq query.
Ex:
Sql:

select * from tblusers where userid=1 and status='a' or status='b';

Linq:

var result= _Repository.selectAll().where(x=>x.UserID==1 && x.status=="a" OR x.status=="B");

It's does work for linq query. so does anyone have any idea?

Body:
Try code:

var result =( from  x in _Repository.selectAll()
           where x.UserID==1 && (x.status=="a" || x.status=="B") select x);

another Solution

 var result =( from  x in _Repository.selectAll().where(c=>c.status=="a" || x.status=="B")
               where x.UserID==1  select x);


问:
How to combine multiple SQL files with different separators in one EmbeddedDatabaseBuilder?
I need to setup an embedded database in order to run my test cases in a spring boot project.

I have separated my SQL scripts into two files in order to set different separators for them :

One contains my basic create table scripts (NAME = create-table.sql, SEPARATOR = ;) and the other contains the Stored procedures (NAME = stored-procedures.sql, , SEPARATOR = /;).

As per comments on this post, I can configure different separators for the two sql files by doing this in applicationContext.xml:

```<code><jdbc:initialize-database data-source="mctDBDataSource" ignore-failures="DROPS" >
  <jdbc:script location="classpath:databaseTesting/inMemory/createInMemoryDatabase.sql" separator=";"/>
  <jdbc:script location="classpath:databaseTesting/inMemory/createInMemoryDatabaseProcedures.sql" separator="/;"/>
</jdbc:initialize-database>
</code>```

But in my case I am trying to use the non-XML approach as below.

```<code>public DataSource myDataSource(){
   return new EmbeddedDatabaseBuilder().generateUniqueName(true)
   .setType(EmbeddedDatabaseType.HSQL).addScript("create-table").setSeparator(";").setEncryptEncoding("UTF-8")
   .ignoreFiledDrops(true).build();
}
</code>```

The above code works fine if I were to use only one SQL file.

How can I combine two SQL files with different separators so as to create one DataSource.

Doing this doesn't work :

```<code>public DataSource myDataSource(){
  return new EmbeddedDatabaseBuilder().generateUniqueName(true)
  .setType(EmbeddedDatabaseType.HSQL).addScript("create-table")
  .setSeparator(";").addScript("stored-procedures").setSeparator("/;")setEncryptEncoding("UTF-8")
  .ignoreFiledDrops(true).build();
}
</code>```

答: You can't do it with an EmbeddedDatabaseFactor directly, but you can use one script in the EmbeddedDatabaseFactor and then use a fresh ResourceDatabasePopulator to execute the second script on the database.

Body:
I need to setup an embedded database in order to run my test cases in a spring boot project.

I have separated my SQL scripts into two files in order to set different separators for them :

One contains my basic create table scripts (NAME = create-table.sql, SEPARATOR = ;) and the other contains the Stored procedures (NAME = stored-procedures.sql, , SEPARATOR = /;).

As per comments on this post, I can configure different separators for the two sql files by doing this in applicationContext.xml:

<jdbc:initialize-database data-source="mctDBDataSource" ignore-failures="DROPS" >
  <jdbc:script location="classpath:databaseTesting/inMemory/createInMemoryDatabase.sql" separator=";"/>
  <jdbc:script location="classpath:databaseTesting/inMemory/createInMemoryDatabaseProcedures.sql" separator="/;"/>
</jdbc:initialize-database>

But in my case I am trying to use the non-XML approach as below.

public DataSource myDataSource(){
   return new EmbeddedDatabaseBuilder().generateUniqueName(true)
   .setType(EmbeddedDatabaseType.HSQL).addScript("create-table").setSeparator(";").setEncryptEncoding("UTF-8")
   .ignoreFiledDrops(true).build();
}

The above code works fine if I were to use only one SQL file.

How can I combine two SQL files with different separators so as to create one DataSource.

Doing this doesn't work :

public DataSource myDataSource(){
  return new EmbeddedDatabaseBuilder().generateUniqueName(true)
  .setType(EmbeddedDatabaseType.HSQL).addScript("create-table")
  .setSeparator(";").addScript("stored-procedures").setSeparator("/;")setEncryptEncoding("UTF-8")
  .ignoreFiledDrops(true).build();
}


问:
Manipulate elements inside html string
I have the following template.

```<code><script id="signoff-form" type="text/plain">
    <form method="POST" action="" accept-charset="UTF-8" role="form">
        <input name="_token" type="hidden" value="{{ csrf_token() }}">
        <input name="task_id" value="" id="task_id">
    </form>
</script>
</code>```

Now I want to set the URL for the action and set the value for the task_id input.

```<code>var href = $(this).attr('href');
var task = $(this).data('task-id');

var form = $("#signoff-form").html();
</code>```

This handles the URL part ok however I cant work out how to set both.

```<code>$(form).attr('action', href).appendTo('body');
</code>```

Your expertise would be much appreciated.

Thanks.

答:
Get the element by id or gen by the name attribute and update the value of the input element.

```<code>$(form).attr('action', href).appendTo('body').find('[name="task_id"]').val(task);

// or by id

$(form).attr('action', href).appendTo('body').find('#task_id').val(task);
</code>```

var href = '/abc';
var task = 'POST';
var form = $("#signoff-form").html();

$(form).attr('action', href).appendTo('body').find('[name="task_id"]').val(task);```
<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>
<script id="signoff-form" type="text/plain">
  <form method="POST" action="" accept-charset="UTF-8" role="form">
    <input name="_token" type="hidden" value="{{ csrf_token() }}">
    <input name="task_id" value="" id="task_id">
  </form>
</script></code>```

Title: Manipulate elements inside html string

Body:
I have the following template.

Now I want to set the URL for the action and set the value for the task_id input.

var href = $(this).attr('href');
var task = $(this).data('task-id');

var form = $("#signoff-form").html();

This handles the URL part ok however I cant work out how to set both.

$(form).attr('action', href).appendTo('body');

Your expertise would be much appreciated.

Thanks.

Body:
Get the element by id or gen by the name attribute and update the value of the input element.

$(form).attr('action', href).appendTo('body').find('[name="task_id"]').val(task);

// or by id

$(form).attr('action', href).appendTo('body').find('#task_id').val(task);

var href = '/abc';
var task = 'POST';
var form = $("#signoff-form").html();

$(form).attr('action', href).appendTo('body').find('[name="task_id"]').val(task);

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script id="signoff-form" type="text/plain">
  <form method="POST" action="" accept-charset="UTF-8" role="form">
    <input name="_token" type="hidden" value="{{ csrf_token() }}">
    <input name="task_id" value="" id="task_id">
  </form>
</script>


问:
ElementRef is undefined in TemplateRef
Experimenting with ElementRef, TemplateRef, ViewRef and ViewContainerRef in Angular. I have created an HTML template, from there I want to create a View and pass that view to ViewContainerRef but it isn't working

Code for template

```<code>template: `
  <ng-container #vc></ng-container>
  <ng-template #mytmpl>
    <div>Name: <input type="text" name="name" /> </div>
    <div>Gender:
      <select  name="gender" >
        <option>Male(1)</option>
        <option>Female(2)</option>
      </select>
    </div>
    <div>About you: <textarea ></textarea></div>
    <div>Married: <input type="checkbox" /></div>
    <div>Children:
      <ng-container *ngFor = "let option of this.selectOptions">
        <input  type="radio" [id]="option" name="children" [value]=option [(ngModel)]="this.children"/> {{option}}
      </ng-container>
   </div>
   <p>Some para</p>
   <p>Para with span <span>Inside span</span></p>
  </ng-template>
`
</code>```

In the class, I access the template and view container

```<code>@ViewChild('vc',{read:ViewContainerRef}) v:ViewContainerRef;
@ViewChildren("mytmpl") myTemplateList:TemplateRef<any>;
</code>```

I use the following code to create the view

```<code>ngAfterViewInit(){
  let elementRef = this.myTemplateList.elementRef
  let view = this.myTemplateList.createEmbeddedView(null)
  this.v.insert(view)
  console.log(elementRef);
}
</code>```

Problems

1) elementRef is undefined!- I want to print on the console, all the elements inside the template. but elementRef is undefined!

2) I get the error that createEmbeddedView is not a function.

答:
I get the error that createEmbeddedView is not a function.

There are few problems:

1) Use {read: TemplateRef} here:

```<code>@ViewChildren("mytmpl", {read: TemplateRef}) myTemplateList:TemplateRef<any>;
</code>```

2) If you use ViewChildren, not ViewChild, it returns a collection so you need to access the member by the index:

```<code>myTemplateList.first
</code>```

So it becomes:

```<code>@ViewChildren("mytmpl", {read: TemplateRef}) myTemplateList:TemplateRef<any>;
...
let view = this.myTemplateList.first.createEmbeddedView(null)
</code>```

Or simply use ViewChild:

```<code>@ViewChild("mytmpl", {read: TemplateRef}) myTemplateList:TemplateRef<any>;
...
let view = this.myTemplateList.createEmbeddedView(null)
</code>```

1) elementRef is undefined!- I want to print on the console, all the
  elements inside the template. but elementRef is undefined!

You can't directly access the elements from the templateRef. You need to follow the same process using @ViewChildren. The elementRef that is available on the templateRef as shown here just points to the DOM host element that Angular created for the template element - it's a comment node. It's not what you think it is, not the contents of the template. To get it just use:

```<code>this.myTemplateList.first.elementRef
</code>```

Read Exploring Angular DOM manipulation techniques using ViewContainerRef for more details.

Title: ElementRef is undefined in TemplateRef

Body:
Experimenting with ElementRef, TemplateRef, ViewRef and ViewContainerRef in Angular. I have created an HTML template, from there I want to create a View and pass that view to ViewContainerRef but it isn't working

Code for template

template: `
  <ng-container #vc></ng-container>
  <ng-template #mytmpl>

Name: <input type="text" name="name" />

Gender:
      <select  name="gender" >
        <option>Male(1)</option>
        <option>Female(2)</option>
      </select>

About you: <textarea ></textarea>

Married: <input type="checkbox" />

Children:
      <ng-container *ngFor = "let option of this.selectOptions">
        <input  type="radio" [id]="option" name="children" [value]=option [(ngModel)]="this.children"/> {{option}}
      </ng-container>

Some para

Para with span Inside span

  </ng-template>
`

In the class, I access the template and view container

@ViewChild('vc',{read:ViewContainerRef}) v:ViewContainerRef;
@ViewChildren("mytmpl") myTemplateList:TemplateRef<any>;

I use the following code to create the view

ngAfterViewInit(){
  let elementRef = this.myTemplateList.elementRef
  let view = this.myTemplateList.createEmbeddedView(null)
  this.v.insert(view)
  console.log(elementRef);
}

Problems

1) elementRef is undefined!- I want to print on the console, all the elements inside the template. but elementRef is undefined!

2) I get the error that createEmbeddedView is not a function.

Body:
I get the error that createEmbeddedView is not a function.

There are few problems:

1) Use {read: TemplateRef} here:

@ViewChildren("mytmpl", {read: TemplateRef}) myTemplateList:TemplateRef<any>;

2) If you use ViewChildren, not ViewChild, it returns a collection so you need to access the member by the index:

myTemplateList.first

So it becomes:

@ViewChildren("mytmpl", {read: TemplateRef}) myTemplateList:TemplateRef<any>;
...
let view = this.myTemplateList.first.createEmbeddedView(null)

Or simply use ViewChild:

@ViewChild("mytmpl", {read: TemplateRef}) myTemplateList:TemplateRef<any>;
...
let view = this.myTemplateList.createEmbeddedView(null)

1) elementRef is undefined!- I want to print on the console, all the
  elements inside the template. but elementRef is undefined!

You can't directly access the elements from the templateRef. You need to follow the same process using @ViewChildren. The elementRef that is available on the templateRef as shown here just points to the DOM host element that Angular created for the template element - it's a comment node. It's not what you think it is, not the contents of the template. To get it just use:

this.myTemplateList.first.elementRef

Read Exploring Angular DOM manipulation techniques using ViewContainerRef for more details.


问:
Why google firebase not clarifying that firebase no more supporting cordova?
Why Google firebase not clarifying that firebase no more supporting Cordova?

Officially they have said OAuth will not be supported from inAppBrowser but they are still maintaining the article- https://firebase.google.com/docs/auth/web/cordova

When I spoke to one of the support members they also said it's working my project has some issues.
But the truth is when I am running with Old API Level like 19 /platform 4.4.2 its working -not able to show the working image as more than 2 links not supported.

but when running with new API level 24/platform 7.0 it's not working and showing "disallowed user agent"

API24-firebase-not-working

Can anyone clarify why it's not working with newer versions?

答:
Firebase Auth supports OAuth sign-in for Cordova apps. As you mentioned, the link https://firebase.google.com/docs/auth/web/cordova supports that. It should work for all modern Android and iOS versions.
However, it doesn't actually work with inAppBrowser plugin the way the legacy Firebase Auth SDK did. inAppBrowser is used only as a fallback for certain cases (old iOS versions). It will use browsertab plugin to open the app in a Chrome custom tab (system browser when chrome not installed) or SFSafariViewController. The instructions explain that.
What you are experiencing "disallowed user agent" is only specific to Google sign-in using an embedded webview. That is now blocked due to the insecurity of embedded webviews. Firebase Auth uses the recommendeded Chrome custom tab (system browser when chrome not installed) or SFSafariViewController instead. Check this post for more details on this specific issue (Google sign-in being blocked in embedded webviews): https://developers.googleblog.com/2016/08/modernizing-oauth-interactions-in-native-apps.html</p>


问:
RegEx to match Json format
I have regEx \{\s*"lat"\s*:\s*(.+?)\s*,\s*"lng":\s*(.+?)\s*} to match following JSON value {"lat": 0.788,"lng":0.878798}, but i want in such a way that it will only match if the "lat" and "lng" values are either integer or decimal

Title: RegEx to match Json format


问:
Graph API Office 365 usage report - Forbidden
I try to use Office 365 usage reports in Graph API. I would like for example export the EmailActivity report with the request GET /reports/EmailActivity(view=view-value, period=period-value, date=date-value)/content

When I try the example https://graph.microsoft.com/beta/reports/EmailActivity(view='Detail',period='D7')/content in Graph Explorer I have the following error

Failure - Status Code 403705msLooks like you may not have the permissions for this call. Please modify your permissions.

```<code>{
    "error": {
        "code": "Forbidden",
        "message": "Invalid scope claims/roles.",
        "innerError": {
            "request-id": "f1f89dcf-b2df-4537-a4ad-f07ccfff2899",
            "date": "2017-07-05T17:01:23"
        }
    }
}
</code>```

I don't uderstand because I looging like an admin of Office 365 I have add almost all the permision. What I had miss ?

Edit : More details,
I use Graph Explorer, when I click to grant access

I have th confirmation

I've the admin right

I try my request in graph explorer

And I have my error

I don't know what I could do be better.

答:
According to Get EmailActivity report document , read that report needs Reports.Read.All permission . And according to Reports permissions of microsoft graph api, Reports.Read.All is application permissionwhich allows an app to read all service usage reports without a signed-in user. To call that api , you need to use client credential flow to acquire token with app identity :

Add Read all usage reports application permission of microsoft graph in your azure ad application :

Grant that application permission by clicking Grant Permissions button in above screenshot with admin account of your AAD .

Using client credential flow to acquire access token for microsoft graph :

```<code>POST https://login.microsoftonline.com/chencl.onmicrosoft.com/oauth2/token

grant_type=client_credentials&client_id=<client_id>&client_secret=<client_secret>&resource=https%3A%2F%2Fgraph.microsoft.com%2F
</code>```

After you get the access token , you could decode the token using online tool, you should find Reports.Read.All in roles claim .

Then you could call the EmailActivity api , it returns 302 Found response redirecting to a pre-authenticated download URL for the report:

Please let me know if it helps.

Body:
I try to use Office 365 usage reports in Graph API. I would like for example export the EmailActivity report with the request GET /reports/EmailActivity(view=view-value, period=period-value, date=date-value)/content

When I try the example https://graph.microsoft.com/beta/reports/EmailActivity(view='Detail',period='D7')/content in Graph Explorer I have the following error

Failure - Status Code 403705msLooks like you may not have the permissions for this call. Please modify your permissions.

{
    "error": {
        "code": "Forbidden",
        "message": "Invalid scope claims/roles.",
        "innerError": {
            "request-id": "f1f89dcf-b2df-4537-a4ad-f07ccfff2899",
            "date": "2017-07-05T17:01:23"
        }
    }
}

I don't uderstand because I looging like an admin of Office 365 I have add almost all the permision. What I had miss ?

Edit : More details,
I use Graph Explorer, when I click to grant access

I have th confirmation

I've the admin right

I try my request in graph explorer

And I have my error

I don't know what I could do be better.

Body:
According to Get EmailActivity report document , read that report needs Reports.Read.All permission . And according to Reports permissions of microsoft graph api, Reports.Read.All is application permissionwhich allows an app to read all service usage reports without a signed-in user. To call that api , you need to use client credential flow to acquire token with app identity :

Add Read all usage reports application permission of microsoft graph in your azure ad application :

Grant that application permission by clicking Grant Permissions button in above screenshot with admin account of your AAD .

Using client credential flow to acquire access token for microsoft graph :

POST https://login.microsoftonline.com/chencl.onmicrosoft.com/oauth2/token

grant_type=client_credentials&client_id=<client_id>&client_secret=<client_secret>&resource=https%3A%2F%2Fgraph.microsoft.com%2F

After you get the access token , you could decode the token using online tool, you should find Reports.Read.All in roles claim .

Then you could call the EmailActivity api , it returns 302 Found response redirecting to a pre-authenticated download URL for the report:

Please let me know if it helps.


问:
PHP & MySQL - not inserting into database
I've got an problem in my code. The insert is not working. The code is below.

HTML:

```<code><form action="staff.php" method="post" class="center" enctype="multipart/form-data" autocomplete="off">
    <input type="hidden" name="size" value="1000000">
    <input type="text" placeholder="headline of the news" name="title">
    <input type="file" accept="image/*" name="image">
    <select name="side" value="side">
        <option>Left</option>
        <option>Header</option>
        <option>Main</option>
        <option>Ending</option>
    </select>
    <textarea name="desc" id="description" cols="30" rows="10" placeholder="full news" name="desc"></textarea>
    <input type="submit" name="go" value="Post">
</form>
</code>```

PHP:

```<code><?php
$db = mysqli_connect("DB SERVER", "DB USER", "DB PASS", "DataBase");
$charset = mysqli_set_charset($db,"utf8");
$msg = "";
if (isset($_POST['go'])) {
    $target = "images/".basename($_FILES['image']['name']);
    $title = $_POST['title'];
    $image = $_FILES['image']['name'];
    $side = $_POST['side'];
    $desc = $_POST['desc'];
    $sql = "INSERT INTO contents (title, image, side, description)
    VALUES ('$title', '$image', '$side', '$desc')";
    $result = mysqli_query($db, $sql);
    if (move_uploaded_file($_FILES['image']['tmp_name'], $target)) {
        $msg = "<p class='success'>Image uploaded successfully</p>";
    } else {
        $msg = "<p class='error'>There was a problem uploading the image</p>";
    }
}
?>
</code>```

Everything is fine except the inserting into database.

答:
$sql = "INSERT INTO contents VALUES ('".$title."', '".$image."', '".$side."', '".$desc."')";

This could be a shorter way.

Body:
I've got an problem in my code. The insert is not working. The code is below.

HTML:

<form action="staff.php" method="post" class="center" enctype="multipart/form-data" autocomplete="off">
    <input type="hidden" name="size" value="1000000">
    <input type="text" placeholder="headline of the news" name="title">
    <input type="file" accept="image/*" name="image">
    <select name="side" value="side">
        <option>Left</option>
        <option>Header</option>
        <option>Main</option>
        <option>Ending</option>
    </select>
    <textarea name="desc" id="description" cols="30" rows="10" placeholder="full news" name="desc"></textarea>
    <input type="submit" name="go" value="Post">
</form>

PHP:

<?php
$db = mysqli_connect("DB SERVER", "DB USER", "DB PASS", "DataBase");
$charset = mysqli_set_charset($db,"utf8");
$msg = "";
if (isset($_POST['go'])) {
    $target = "images/".basename($_FILES['image']['name']);
    $title = $_POST['title'];
    $image = $_FILES['image']['name'];
    $side = $_POST['side'];
    $desc = $_POST['desc'];
    $sql = "INSERT INTO contents (title, image, side, description)
    VALUES ('$title', '$image', '$side', '$desc')";
    $result = mysqli_query($db, $sql);
    if (move_uploaded_file($_FILES['image']['tmp_name'], $target)) {
        $msg = "
Image uploaded successfully
";
    } else {
        $msg = "
There was a problem uploading the image
";
    }
}
?>

Everything is fine except the inserting into database.


答:
It's caused by this line:

```<code>cl.add(cl);
</code>```

You're adding the collection to itself. Since the hash code of the set is based on the elements contained in the set, the hashCode() method of cl will be called recursively.

From the AbstractSet.hashCode() javadoc (emphasis mine):

Returns the hash code value for this set. The hash code of a set is
  defined to be the sum of the hash codes of the elements in the set,
  where the hash code of a null element is defined to be zero. This
  ensures that s1.equals(s2) implies that s1.hashCode()==s2.hashCode()
  for any two sets s1 and s2, as required by the general contract of
  Object.hashCode().

Title: How to find hash code of a Collection?

Body:
It's caused by this line:

cl.add(cl);

You're adding the collection to itself. Since the hash code of the set is based on the elements contained in the set, the hashCode() method of cl will be called recursively.

From the AbstractSet.hashCode() javadoc (emphasis mine):

Returns the hash code value for this set. The hash code of a set is
  defined to be the sum of the hash codes of the elements in the set,
  where the hash code of a null element is defined to be zero. This
  ensures that s1.equals(s2) implies that s1.hashCode()==s2.hashCode()
  for any two sets s1 and s2, as required by the general contract of
  Object.hashCode().


问:
Blocking comment spam without using captcha
What are some non-captcha methods for blocking spam on my comments?</p>

答:
This is simple trick to block spam bot or brute force attack without using captcha.

Put this in your form:

```<code><input type="hidden" name="hash" value="<?php echo md5($secret_key.time()).','.time(); ?>" />
</code>```

Put this in your php code

```<code>$human_typing_time = 5;/** page load (1s) + submit (1s) + typing time (3s) */
$vars = explode(',', $_POST['hash']);
if(md5($secret_key.$vars[1]) != $vars[0] || time() < $var[1] + $human_typing_time){
    //bot?
    exit();
}
</code>```

Depend on weight of form you can increase or decrease $human_typing_time.

Body:
This is simple trick to block spam bot or brute force attack without using captcha.

Put this in your form:

<input type="hidden" name="hash" value="<?php echo md5($secret_key.time()).','.time(); ?>" />

Put this in your php code

$human_typing_time = 5;/** page load (1s) + submit (1s) + typing time (3s) */
$vars = explode(',', $_POST['hash']);
if(md5($secret_key.$vars[1]) != $vars[0] || time() < $var[1] + $human_typing_time){
    //bot?
    exit();
}

Depend on weight of form you can increase or decrease $human_typing_time.


问:
Tiki: Unexpected return from trackerlib -> get_item_creators
I upgraded my tiki from 15.4 to 16.2. Everything runs fine. The problem is the site registration does not work. I have a tracker to extend my user information. In the tracker, I created a field called "Network" that allows the users to choose a group that them want to be in. Hence, they won't see each other content due to different group permission. This registration broke. The error message showed:

Cannot add nonexistent user xxx to group students

I found out the problem was that there is a change in trackerlib.php line 3671. Instead of returning "null", it now returns an empty array().

```<code>else {
    return array();
}
</code>```

In GroupSelector.php, line 124, the condition check

```<code>if (empty ($creators))) $creators=array($user);
</code>```

This if will never be executed since the function now return an array not null. Hence causing the problem that no one can be registered if they choose a group in the registration form.

Propose solution, change the if condition in line 124 to:

```<code>if (empty($creators[0]))
</code>```

答:
Did you check the actual 16.x version (dev branch) of this file (lib/core/Tracker/Field/GroupSelector.php) ?

https://sourceforge.net/p/tikiwiki/code/HEAD/tree/branches/16.x/lib/core/Tracker/Field/GroupSelector.php

Chances are, this is fixed already. :)

Bernard

Body:
I upgraded my tiki from 15.4 to 16.2. Everything runs fine. The problem is the site registration does not work. I have a tracker to extend my user information. In the tracker, I created a field called "Network" that allows the users to choose a group that them want to be in. Hence, they won't see each other content due to different group permission. This registration broke. The error message showed:

Cannot add nonexistent user xxx to group students

I found out the problem was that there is a change in trackerlib.php line 3671. Instead of returning "null", it now returns an empty array().

else {
    return array();
}

In GroupSelector.php, line 124, the condition check

if (empty ($creators))) $creators=array($user);

This if will never be executed since the function now return an array not null. Hence causing the problem that no one can be registered if they choose a group in the registration form.

Propose solution, change the if condition in line 124 to:

if (empty($creators[0]))


问:
How to Find All TRUE Conditions and Concatenate Corresponding Variables into New Variable?
```<code>a = 4
b = 5
c = 7

if (a >= 4){
    text1 = “a is high”;
}
if (b >= 8){
    text2 = “b is high”;
}
if (c >= 6){
    text3 = “c is high”;
}
</code>```

In C or C++, how would I find which of these statements are true (a & c) and create a new variable that concatenates their accompanying variables containing text to produce a result like “a is high and c is high”? The next time the code executes it may find that only a is high, or whatever the case may be.  How would I go about doing this?

答:
The answer of Gaurav Sehgal is elegant. Here is another way of writing it-

C++

```<code>string text = "";
if (a >= 4)
   text += "a is high";
if (b >= 8)
{
    if(text.size() > 0)
         text += " and ";
    text += "b is high";
}
if (c <= 6)
{
   if(text.size() > 0)
        text += " and ";
   text += "c is high";
}
</code>```

C

```<code>char text[buf_size] = {'\0'};
if (a >= 4)
   strcat(text, "a is high");
if (b >= 8)
{
    if(strlen(text) > 0)
         strcat(text, " and ");
    strcat(text, "b is high");
}
if (c <= 6)
{
   if(strlen(text) > 0)
         strcat(text, " and ");
    strcat(text, "c is high");
}
</code>```

Body:
a = 4
b = 5
c = 7

if (a >= 4){
    text1 = “a is high”;
}
if (b >= 8){
    text2 = “b is high”;
}
if (c >= 6){
    text3 = “c is high”;
}

In C or C++, how would I find which of these statements are true (a & c) and create a new variable that concatenates their accompanying variables containing text to produce a result like “a is high and c is high”? The next time the code executes it may find that only a is high, or whatever the case may be.  How would I go about doing this?

Body:
The answer of Gaurav Sehgal is elegant. Here is another way of writing it-

C++

string text = "";
if (a >= 4)
   text += "a is high";
if (b >= 8)
{
    if(text.size() > 0)
         text += " and ";
    text += "b is high";
}
if (c <= 6)
{
   if(text.size() > 0)
        text += " and ";
   text += "c is high";
}

C

char text[buf_size] = {'\0'};
if (a >= 4)
   strcat(text, "a is high");
if (b >= 8)
{
    if(strlen(text) > 0)
         strcat(text, " and ");
    strcat(text, "b is high");
}
if (c <= 6)
{
   if(strlen(text) > 0)
         strcat(text, " and ");
    strcat(text, "c is high");
}


问:
Locating Backup folder used by Vestacp
From the command line, I am trying to locate the backup directory VestaCP are using to save the backup and I failed to find out.

https://snag.gy/I8Tt4z.jpg

Please help me.

I have checked the following locations

/usr/local/vesta

but no luck.

I will highly appreciate your help.

Regards

答: According to the screenshot, VestaCP is storing the backups in the /backup directory on your server. Did you check this directory?

Title: Locating Backup folder used by Vestacp


问:
How to $apply and $digest in Angular 4 and IONIC 3?
I am trying to create an application in IONIC 3, but it does not seem to refresh the view properly.

I remember $apply and $digest would solve such kind of issues in Angular 1X.

How is that done in Angular 4?

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

@Component({
  selector: 'page-led',
  templateUrl: 'led.html'
})
export class LEDPage {

  constructor(public navCtrl: NavController, private ble: BLE) {
    this['myCount'] = 0;
    this['valor'] = 0;
    this['messages'] = [];
    this['service_id'] = "19B10010-E8F2-537E-4F6C-D104768A1214";
    this.setMessage("Constructor: Begin!");
    this['ble'] = ble;
    this['ComandoTXT'] = "FIND BLYNK";
    this['targetDevice'] = {};
  }

  public Command(){
    if(this['ComandoTXT']==="FIND BLYNK") {
      this.findBlynk();
    }

    if(this['ComandoTXT']=== "CAMBIAR LED"){
      //this.txData();
      this.setMessage("CAMBIAR LED txData DISABLEd");
    }
  }

  public findBlynk(){
      this.setMessage("SCAN: Begin!");
      this['ComandoTXT'] = "Scanning...";

      let  ble = this['ble'];

      this.setMessage("SCAN: BLE ENABLE!");
      ble.enable();

      this.setMessage("SCAN: Setting Interval...");
      this['intervalHandle'] = setInterval(() => { // SET AN INTERVAL THAT RUNS EVERY 3 Seconds
        this.setMessage("INTERVAL: BLE SCAN...");
        //https://ionicframework.com/docs/native/ble/
        ble.scan([], 2 /*seconds (0) */).subscribe( data => { //DO SCAN DURING 1 SECOND
          this.setMessage("SCAN SUBSCRIBER: " + data['id'] + ' | ' + data['name'] + ' | ' + data['rssi']);
          if(data['name']=="Blynk"){
            this.setMessage("SCAN SUBSCRIBER: BLYNK FOUND! STOPPED SCANNING!");
            clearInterval(this["intervalHandle"]);
            this["targetDevice"] = data;
            this["ComandoTXT"] = "CAMBIAR LED";

            let idx = 0;
            while(idx<10000){
              this["test"] = idx;
              idx ++;
            }
          }
        });
      },2100);//END OF INTERVAL DEFINITION
    }

  /*
  public findBlynk(){
    this.setMessage("findBlynk: BEGIN...");
    this['ComandoTXT'] = "Buscando...";
    this.setMessage("findBlynk: BLE ENABLE...");
    this['ble'].enable();
    this.setMessage("findBlynk: encontrar()...");

    this.ble.scan([],500).subscribe(deviceData=>{
      this.setMessage("SUBSCRIBER: Found Device...");
      let deviceMessage = deviceData.id + ":" + deviceData.name + "(" + deviceData.rssi + ")";
      this.setMessage(deviceMessage);

      if(deviceData.name == "Blynk"){
        this.setMessage("BLYNK FOUND!");
        this["ComandoTXT"] = "CAMBIAR LED";
        this['dispositivo'] = deviceData;

        this.ble.stopScan().then(() => {
          this.setMessage('SCANNING STOPPED!');
        });

      } else {
        //setTimeout(()=>{this.findBlynk();},500);
      }

    }, error=>{
      this.setMessage("BLE SCAN ERROR");
      this.setMessage(error.message);
      setTimeout(()=>{this.findBlynk();},1000);
    });
  }

  public txData(){
    this.setMessage("txData: BEGIN! Doing ble connect...");
    let id = this['deviceData'].id;
    this.ble.connect(id).subscribe(datos=>{
      this.setMessage("BLE CONNECT SUBSCRIBE: BEGIN. Doing ble write...");
      this.ble.write(id,this['service_id'],this['service_id'],this['valor'].buffer).then(()=>{
        this.setMessage("BLE WRITE THEN!");
        this['valor'] = (this['valor'] + 1) % 2;
        this.ble.disconnect(id);
      },(error)=>{
        this.setMessage("BLE Write ERROR!");
      });
    },error=>{
      this.setMessage("BLE Connect ERROR!");
    });
  }
  */
/*

  public conectar(id){
    this.ble.connect(id).subscribe(datos=>{
      this.escribir(id);
    },error=>{
      this.encontrar();
    });
  }

  public escribir(id){

  }

*/
  public setMessage(message){
    this['myCount'] ++;
    message = this['myCount'] + ':' + message;
    this['messages'].unshift(message);
  }

}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><ion-header>
  <ion-navbar>
    <ion-title>LED </ion-title>
    <button ion-button (click)="Command()">{{ComandoTXT}}</button>
  </ion-navbar>
</ion-header>
<ion-content padding>
  <p>LED  Messages: ({{myCount}} | {{test}})</p>
  <hr />
  <p *ngFor="let message of messages">{{message}}</p>
</ion-content></code>```

答:
you can use LifeCycle::tick() method to do it. See below code</p>

```<code>import {Component, LifeCycle, NgZone} from 'angular2/angular2'

@Component({
  selector: 'my-app',
  template: `
    <div>
      Hello world!!! Time: {{ time }}.
    </div>
  `
})
export class App {
  time: number = 0;

  constructor(lc: LifeCycle, zone: NgZone) {
    zone.runOutsideAngular(() => {
      setInterval(() => {
        this.time = Date.now();

        lc.tick(); // comment this line and "time" will stop updating
      }, 1000);
    })
  }
  doCheck() {
    console.log('check', Date.now());
  }
}
</code>```

Body:
I am trying to create an application in IONIC 3, but it does not seem to refresh the view properly.

I remember $apply and $digest would solve such kind of issues in Angular 1X.

How is that done in Angular 4?

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

@Component({
  selector: 'page-led',
  templateUrl: 'led.html'
})
export class LEDPage {

  constructor(public navCtrl: NavController, private ble: BLE) {
    this['myCount'] = 0;
    this['valor'] = 0;
    this['messages'] = [];
    this['service_id'] = "19B10010-E8F2-537E-4F6C-D104768A1214";
    this.setMessage("Constructor: Begin!");
    this['ble'] = ble;
    this['ComandoTXT'] = "FIND BLYNK";
    this['targetDevice'] = {};
  }

  public Command(){
    if(this['ComandoTXT']==="FIND BLYNK") {
      this.findBlynk();
    }

    if(this['ComandoTXT']=== "CAMBIAR LED"){
      //this.txData();
      this.setMessage("CAMBIAR LED txData DISABLEd");
    }
  }

  public findBlynk(){
      this.setMessage("SCAN: Begin!");
      this['ComandoTXT'] = "Scanning...";

      let  ble = this['ble'];

      this.setMessage("SCAN: BLE ENABLE!");
      ble.enable();

      this.setMessage("SCAN: Setting Interval...");
      this['intervalHandle'] = setInterval(() => { // SET AN INTERVAL THAT RUNS EVERY 3 Seconds
        this.setMessage("INTERVAL: BLE SCAN...");
        //https://ionicframework.com/docs/native/ble/
        ble.scan([], 2 /*seconds (0) */).subscribe( data => { //DO SCAN DURING 1 SECOND
          this.setMessage("SCAN SUBSCRIBER: " + data['id'] + ' | ' + data['name'] + ' | ' + data['rssi']);
          if(data['name']=="Blynk"){
            this.setMessage("SCAN SUBSCRIBER: BLYNK FOUND! STOPPED SCANNING!");
            clearInterval(this["intervalHandle"]);
            this["targetDevice"] = data;
            this["ComandoTXT"] = "CAMBIAR LED";

            let idx = 0;
            while(idx<10000){
              this["test"] = idx;
              idx ++;
            }
          }
        });
      },2100);//END OF INTERVAL DEFINITION
    }

  /*
  public findBlynk(){
    this.setMessage("findBlynk: BEGIN...");
    this['ComandoTXT'] = "Buscando...";
    this.setMessage("findBlynk: BLE ENABLE...");
    this['ble'].enable();
    this.setMessage("findBlynk: encontrar()...");

    this.ble.scan([],500).subscribe(deviceData=>{
      this.setMessage("SUBSCRIBER: Found Device...");
      let deviceMessage = deviceData.id + ":" + deviceData.name + "(" + deviceData.rssi + ")";
      this.setMessage(deviceMessage);

      if(deviceData.name == "Blynk"){
        this.setMessage("BLYNK FOUND!");
        this["ComandoTXT"] = "CAMBIAR LED";
        this['dispositivo'] = deviceData;

        this.ble.stopScan().then(() => {
          this.setMessage('SCANNING STOPPED!');
        });

      } else {
        //setTimeout(()=>{this.findBlynk();},500);
      }

    }, error=>{
      this.setMessage("BLE SCAN ERROR");
      this.setMessage(error.message);
      setTimeout(()=>{this.findBlynk();},1000);
    });
  }

  public txData(){
    this.setMessage("txData: BEGIN! Doing ble connect...");
    let id = this['deviceData'].id;
    this.ble.connect(id).subscribe(datos=>{
      this.setMessage("BLE CONNECT SUBSCRIBE: BEGIN. Doing ble write...");
      this.ble.write(id,this['service_id'],this['service_id'],this['valor'].buffer).then(()=>{
        this.setMessage("BLE WRITE THEN!");
        this['valor'] = (this['valor'] + 1) % 2;
        this.ble.disconnect(id);
      },(error)=>{
        this.setMessage("BLE Write ERROR!");
      });
    },error=>{
      this.setMessage("BLE Connect ERROR!");
    });
  }
  */
/*

  public conectar(id){
    this.ble.connect(id).subscribe(datos=>{
      this.escribir(id);
    },error=>{
      this.encontrar();
    });
  }

  public escribir(id){

  }

*/
  public setMessage(message){
    this['myCount'] ++;
    message = this['myCount'] + ':' + message;
    this['messages'].unshift(message);
  }

}

<ion-header>
  <ion-navbar>
    <ion-title>LED </ion-title>
    <button ion-button (click)="Command()">{{ComandoTXT}}</button>
  </ion-navbar>
</ion-header>
<ion-content padding>

LED  Messages: ({{myCount}} | {{test}})

{{message}}

</ion-content>

Body:
you can use LifeCycle::tick() method to do it. See below code

import {Component, LifeCycle, NgZone} from 'angular2/angular2'

@Component({
  selector: 'my-app',
  template: `
    <div>
      Hello world!!! Time: {{ time }}.
    </div>
  `
})
export class App {
  time: number = 0;

  constructor(lc: LifeCycle, zone: NgZone) {
    zone.runOutsideAngular(() => {
      setInterval(() => {
        this.time = Date.now();

        lc.tick(); // comment this line and "time" will stop updating
      }, 1000);
    })
  }
  doCheck() {
    console.log('check', Date.now());
  }
}


问:
C# HTTP Web Service Method with Optional Parameters
This project is a HTTP WEB API. I want to build an interface which users can post some information to the server.

The finger_print_base64 is a integrant parameter, and threshold or mini_matches is selectable parameter.

I knew the way to set MessageName .

```<code>[WebMethod(MessageName = "Default")]
public void SearchPerson(String finger_print_base64)
{

}

[WebMethod(MessageName = "AddThreshold")]
public void SearchPerson(String finger_print_base64,int threshold)
{

}

[WebMethod(MessageName = "AddMinMatches")]
public void SearchPerson(String finger_print_base64,int mini_matches)
{

}
</code>```

But It doesn't work. And I know why it is wrong.

Please tell me how to achieve this interface with optional parameters

Thanks in advance.

答:
Rename your Methods to :</p>

```<code>[WebMethod(MessageName = "AddThreshold")]
public void SearchPersonTreshold(String finger_print_base64,int threshold)
{

}

[WebMethod(MessageName = "AddMinMatches")]
public void SearchPersonMiniMatches(String finger_print_base64,int mini_matches)
{

}
</code>```

Body:
This project is a HTTP WEB API. I want to build an interface which users can post some information to the server.

The finger_print_base64 is a integrant parameter, and threshold or mini_matches is selectable parameter.

I knew the way to set MessageName .

[WebMethod(MessageName = "Default")]
public void SearchPerson(String finger_print_base64)
{

}

[WebMethod(MessageName = "AddThreshold")]
public void SearchPerson(String finger_print_base64,int threshold)
{

}

[WebMethod(MessageName = "AddMinMatches")]
public void SearchPerson(String finger_print_base64,int mini_matches)
{

}

But It doesn't work. And I know why it is wrong.

Please tell me how to achieve this interface with optional parameters

Thanks in advance.

Body:
Rename your Methods to :

[WebMethod(MessageName = "AddThreshold")]
public void SearchPersonTreshold(String finger_print_base64,int threshold)
{

}

[WebMethod(MessageName = "AddMinMatches")]
public void SearchPersonMiniMatches(String finger_print_base64,int mini_matches)
{

}


问:
How to display messages in invalidHandler in JQuery validator
I'm trying to use the JQuery validator on a form and am trying to figure out to get the messages of the errors in the invalidHandler option (or if there's somewhere else, do tell).

When a user clicks the submit button, whatever the first error is, I want to display an alert box with the message of the error. I don't want the error to be written on the document. I can't seem to figure out how to get the error messages to use in an alert after validation. I only found how to get the elements, and that doesn't really help me.

Pulling out from the example, here's some code I'm testing with

```<code>$(document).ready(function() {
    $('#commentForm').validate({
        invalidHandler: function(f, v) {
            var errors = v.numberOfInvalids();
            if (errors) {
                var invalidElements = v.invalidElements();
                alert(invalidElements[0]);
            }
        }
    });
});
</code>```

and

```<code> <form class="cmxform" id="commentForm" method="get" action="">
 <fieldset>
   <legend>A simple comment form with submit validation and default messages</legend>
   <p>
     <label for="cname">Name</label>
     <em>*</em><input id="cname" name="name" size="25" class="required" minlength="2" />
   </p>
   <p>
     <input class="submit" type="submit" value="Submit"/>
   </p>
 </fieldset>
 </form>
</code>```

答:
I know the question is quite old, but to help other people to get a better answer I would advise you guys not using invalidHandler, but showErrors.

Thats because invalidHandler will be called only when you submit your form while
showErrors is called every time a field is updated.

So, do this:

Script in the end of the page

```<code> $("form").validate({
    rules: {
        name: {
            required: true
        }
    },
    messages: {
        name: {
            required: "required"
        }
    },
    highlight: function (element) {
        $(element).closest('.form-group').removeClass('has-success').addClass('has-error')
        $(element).parent().find('.form-control-feedback').removeClass('glyphicon-ok').addClass('glyphicon-remove');
    },
    unhighlight: function (element) {
        $(element).closest('.form-group').removeClass('has-error').addClass('has-success');
        $(element).parent().find('.form-control-feedback').removeClass('glyphicon-remove').addClass('glyphicon-ok');
    },
    errorElement: 'span',
    errorClass: 'help-block',
    errorPlacement: function (error, element) {
        if (element.parent('.input-group').length) {
            error.insertAfter(element.parent());
        } else {
            error.insertAfter(element);
        }
    },
    showErrors: function (errorMap, errorList) {
        var errors = this.numberOfInvalids();
        if (errors) {
            var message = errors == 1
              ? 'Your form has 1 error'
              : 'Your form has ' + errors + ' errors.';
            message = message + ' Please, fix then.'
            $("#error span").empty().html(message);
            $("#error").show();
        } else {
            $("#error").hide();
        }
        this.defaultShowErrors();
    },
});
</code>```

Don't forget your html tag

```<code><div id="error"><span></span></div>
</code>```

Body:
I'm trying to use the JQuery validator on a form and am trying to figure out to get the messages of the errors in the invalidHandler option (or if there's somewhere else, do tell).

When a user clicks the submit button, whatever the first error is, I want to display an alert box with the message of the error. I don't want the error to be written on the document. I can't seem to figure out how to get the error messages to use in an alert after validation. I only found how to get the elements, and that doesn't really help me.

Pulling out from the example, here's some code I'm testing with

$(document).ready(function() {
    $('#commentForm').validate({
        invalidHandler: function(f, v) {
            var errors = v.numberOfInvalids();
            if (errors) {
                var invalidElements = v.invalidElements();
                alert(invalidElements[0]);
            }
        }
    });
});

and

 <form class="cmxform" id="commentForm" method="get" action="">
 <fieldset>
   <legend>A simple comment form with submit validation and default messages</legend>

     Name
     *<input id="cname" name="name" size="25" class="required" minlength="2" />

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

 </fieldset>
 </form>

Body:
I know the question is quite old, but to help other people to get a better answer I would advise you guys not using invalidHandler, but showErrors.

Thats because invalidHandler will be called only when you submit your form while
showErrors is called every time a field is updated.

So, do this:

Script in the end of the page

 $("form").validate({
    rules: {
        name: {
            required: true
        }
    },
    messages: {
        name: {
            required: "required"
        }
    },
    highlight: function (element) {
        $(element).closest('.form-group').removeClass('has-success').addClass('has-error')
        $(element).parent().find('.form-control-feedback').removeClass('glyphicon-ok').addClass('glyphicon-remove');
    },
    unhighlight: function (element) {
        $(element).closest('.form-group').removeClass('has-error').addClass('has-success');
        $(element).parent().find('.form-control-feedback').removeClass('glyphicon-remove').addClass('glyphicon-ok');
    },
    errorElement: 'span',
    errorClass: 'help-block',
    errorPlacement: function (error, element) {
        if (element.parent('.input-group').length) {
            error.insertAfter(element.parent());
        } else {
            error.insertAfter(element);
        }
    },
    showErrors: function (errorMap, errorList) {
        var errors = this.numberOfInvalids();
        if (errors) {
            var message = errors == 1
              ? 'Your form has 1 error'
              : 'Your form has ' + errors + ' errors.';
            message = message + ' Please, fix then.'
            $("#error span").empty().html(message);
            $("#error").show();
        } else {
            $("#error").hide();
        }
        this.defaultShowErrors();
    },
});

Don't forget your html tag

<div id="error"><span></span></div>


问:
WEB APPLICATION OR PAGE SPEED TESTER [OR TEST TOOL]
Is there a browser add-on or application that can use to test the speed of web applications?

If there is an existing tools like this.
What do you use to check the speed ?

Thank you.

答:
If you are referring to checking page load times, you can simply use google chrome developer tools and check how much time being taken to load each resource and whole document and also you can below mentioned chrome extensions/add-ons to have better view of those statistics:
https://chrome.google.com/webstore/detail/page-load-time/fploionmjgeclbkemipmkogoaohcdbig?hl=en

https://chrome.google.com/webstore/detail/performance-analyser/djgfmlohefpomchfabngccpbaflcahjf?hl=en

As you might know already, developer tools are available in all the major browsers through which you can check the page load times (Network tab)

Edit:
Some tools which you can use:

https://speedcurve.com/

https://github.com/SOASTA/boomerang

https://tools.pingdom.com/

if you are using google analytics: http://www.dummies.com/web-design-development/web-analytics/social-media-metrics/how-to-track-page-load-times-with-a-metrics-tool/


问:
what is the simplest way to check for occurrence of character/substring in dataframe values?
consider a pandas dataframe that has values such as 'a - b'. I would like to check for the occurrence of '-' anywhere across all values of the dataframe without looping through individual columns. Clearly a check such as the following won't work:

if '-' in df.values

Any suggestions on how to check for this? Thanks.

答:
You can use replace to to swap a regex match with something else then check for equality

```<code>df.replace('.*-.*', True, regex=True).eq(True)
</code>```

Body:
You can use replace to to swap a regex match with something else then check for equality

df.replace('.*-.*', True, regex=True).eq(True)