问:
Updating an existing Chrome tab instead of opening a new one
I have created a Chrome extension which upon selecting text, offers a context menu link to Salesforce using the selected text:

```<code>function doSearch (search_target, tab)
{
    chrome.tabs.create( {
        url : "https://my.salesforce.com/apex/BR_caseRedirectDependingLicense?number="+search_target.replace(/\D/g,''),
        selected : true,
        index : tab.index + 1
    } );
}

function selectionHandler (info, tab)
{
    doSearch( info.selectionText, tab );
}

function resetContextMenus ()
{
    chrome.contextMenus.removeAll(
    function()
    {
            var id = chrome.contextMenus.create( {
                title: "Open in Salesforce",
                contexts: [ "selection" ],
            onclick: selectionHandler
        } );
    }
    );
}
resetContextMenus();
</code>```

The intention here is to mark ticket numbers and open them in SF quickly, and it works perfectly.

However, I was wondering if it's possible to update an open salesforce tab instead of launching a new one every time.

I have tried looking around and encountered the following sample extension:
https://chromium.googlesource.com/chromium/src/+/master/chrome/common/extensions/docs/examples/api/tabs/inspector/

But it doesn't seem to work at all (perhaps because it's outdated).

I would much appreciate any help/guidance on how to approach this.

答:
Yes, you can do that, you can do it using the chrome.tabs.update(..) function, here is an example, this will update the tab in which your context menu item was clicked:

```<code>function selectionHandler (info, tab) {
    chrome.tabs.update(tab.id, {
        url : "https://my.salesforce.com/apex/BR_caseRedirectDependingLicense?number="+info.selectionText.replace(/\D/g,''),
        active : true
    });
}
</code>```

If you want to first create a new tab and then keep updating it, you can use something like this:

```<code>let tabId = -1;
function doSearch (search_target, tab)
{
    const tabDetails = {
        url : "https://my.salesforce.com/apex/BR_caseRedirectDependingLicense?number="+search_target.replace(/\D/g,''),
        active : true,
        index : tab.index + 1
    };

    if (tabId == -1) {
        chrome.tabs.create(tabDetails, tab => {
          tabId = tab.id;
        });
    } else {
        // check if tab is still around
        chrome.tabs.get(tabId, (tab) => {
          if (tab) {
            chrome.tabs.update(tab.id, tabDetails);
          } else {
            chrome.tabs.create(tabDetails, tab => {
              tabId = tab.id;
            });
          }
        });
    }
}
</code>```

Here is the chrome.tabs API documentation beside this two examples, you may also want to look into chrome.tabs.query(..), you can use that to find a specific tab.`

Also, in all these examples I've used active instead of selected because selected is deprecated.

Body:
I have created a Chrome extension which upon selecting text, offers a context menu link to Salesforce using the selected text:

function doSearch (search_target, tab)
{
    chrome.tabs.create( {
        url : "https://my.salesforce.com/apex/BR_caseRedirectDependingLicense?number="+search_target.replace(/\D/g,''),
        selected : true,
        index : tab.index + 1
    } );
}

function selectionHandler (info, tab)
{
    doSearch( info.selectionText, tab );
}

function resetContextMenus ()
{
    chrome.contextMenus.removeAll(
    function()
    {
            var id = chrome.contextMenus.create( {
                title: "Open in Salesforce",
                contexts: [ "selection" ],
            onclick: selectionHandler
        } );
    }
    );
}
resetContextMenus();

The intention here is to mark ticket numbers and open them in SF quickly, and it works perfectly.

However, I was wondering if it's possible to update an open salesforce tab instead of launching a new one every time.

I have tried looking around and encountered the following sample extension:
https://chromium.googlesource.com/chromium/src/+/master/chrome/common/extensions/docs/examples/api/tabs/inspector/

But it doesn't seem to work at all (perhaps because it's outdated).

I would much appreciate any help/guidance on how to approach this.

Body:
Yes, you can do that, you can do it using the chrome.tabs.update(..) function, here is an example, this will update the tab in which your context menu item was clicked:

function selectionHandler (info, tab) {
    chrome.tabs.update(tab.id, {
        url : "https://my.salesforce.com/apex/BR_caseRedirectDependingLicense?number="+info.selectionText.replace(/\D/g,''),
        active : true
    });
}

If you want to first create a new tab and then keep updating it, you can use something like this:

let tabId = -1;
function doSearch (search_target, tab)
{
    const tabDetails = {
        url : "https://my.salesforce.com/apex/BR_caseRedirectDependingLicense?number="+search_target.replace(/\D/g,''),
        active : true,
        index : tab.index + 1
    };

    if (tabId == -1) {
        chrome.tabs.create(tabDetails, tab => {
          tabId = tab.id;
        });
    } else {
        // check if tab is still around
        chrome.tabs.get(tabId, (tab) => {
          if (tab) {
            chrome.tabs.update(tab.id, tabDetails);
          } else {
            chrome.tabs.create(tabDetails, tab => {
              tabId = tab.id;
            });
          }
        });
    }
}

Here is the chrome.tabs API documentation beside this two examples, you may also want to look into chrome.tabs.query(..), you can use that to find a specific tab.`

Also, in all these examples I've used active instead of selected because selected is deprecated.


来源: stackexchange

问:
Custom creation of QFuture
I've faced quite an odd problem with QtConcurrent, mostly because of strange programming desires, maybe it's just an XY-problem, but...

So, there is my code, trying to communicate with the database, a backend code actually (on Qt, yes). It has to work quick and handle some requests, so I need a thread pool. As a well-known fact I suppose the connection establishing itself is a very time-consuming operation, so there is a need in persistent database connections resulting in persistent threads (QSqlDatabase cannot be moved around between the threads). Also it is quite natural to want asynchronous request handling, thus resulting in some need of a simple way to pass them to the persistent threads.

Nothing too complex, lets assume there already exists some boilerplate in a form like...

// That's what I want for now
QFuture<int> res = workers[i]->async(param1, param2);

// OR

// That's what I DO NOT want to get
workers[i]->async(param1, param2, [](QFuture<int> res) { // QFuture to pass exceptions
     // callback here
});

```

That can be done for sure. Why not std::future? Well, it is much easier to use QFutureWatcher and it's signals for notifications about result's readiness. Pure C++ notification solutions are muuuch more complex and callbacks are also someting that has to be dragged through the class hierarchy. Each worker interfaces a thread with DB connections, obviously.

Okay, all of that can be written, but... custom thread pool would mean no QtConcurrent convenience, there seem to be only risky ways to create that QFuture so that it could be returned by the custom worker. QThreadPool is of no use, because it would be a whole big story to create persistent runnables in it. More to say, the boilerplate I've briefly described is gonna be some kind of project's core, used in many places, not something to be easily replaced by a 100 hand-made thread managings.

In short: if I could construst a QFuture for my results, the problem would be solved.
Could anyone point me to a solution or a workaround? Would be grateful for any bright ideas.

UPD:

@VladimirBershov offered a good modern solution which implements observer pattern. After some googling I've found a QPromise library. Of course, constructing a custom QFuture is still hacky and can be only done via undocumented QFutureInterface class, but still some  "promise-like" solution makes asynchronous calls neater by far as I can judge.

答:
You can use AsyncFuture library as a custom QFuture creation tool or ideas source:

AsyncFuture - Use QFuture like a Promise object

QFuture is used together with QtConcurrent to represent the result of
  an asynchronous computation. It is a powerful component for
  multi-thread programming. But its usage is limited to the result of
  threads, it doesn't work with the asynchronous signal emitted by
  QObject. And it is a bit trouble to setup the listener function via
  QFutureWatcher.

AsyncFuture is designed to enhance the function to offer a better way
  to use it for asynchronous programming. It provides a Promise object
  like interface. This project is inspired by AsynQt and RxCpp.

Features:

Convert a signal from QObject into a QFuture object

Combine multiple futures with different type into a single future object

Use Future like a Promise object

Chainable Callback - Advanced multi-threading programming model

Convert a signal from QObject into a QFuture object:

```<code>#include "asyncfuture.h"
using namespace AsyncFuture;

// Convert a signal from QObject into a QFuture object

QFuture<void> future = observe(timer, &QTimer::timeout).future();

/* Listen from the future without using QFutureWatcher<T>*/
observe(future).subscribe([]() {
    // onCompleted. It is invoked when the observed future is finished successfully
    qDebug() << "onCompleted";
},[]() {
    // onCanceled
    qDebug() << "onCancel";
});
</code>```

ContentLicense: CC BY-SA 4.0

Title: Custom creation of QFuture

Body:
I've faced quite an odd problem with QtConcurrent, mostly because of strange programming desires, maybe it's just an XY-problem, but...

So, there is my code, trying to communicate with the database, a backend code actually (on Qt, yes). It has to work quick and handle some requests, so I need a thread pool. As a well-known fact I suppose the connection establishing itself is a very time-consuming operation, so there is a need in persistent database connections resulting in persistent threads (QSqlDatabase cannot be moved around between the threads). Also it is quite natural to want asynchronous request handling, thus resulting in some need of a simple way to pass them to the persistent threads.

Nothing too complex, lets assume there already exists some boilerplate in a form like...

// That's what I want for now
QFuture<int> res = workers[i]->async(param1, param2);

// OR

// That's what I DO NOT want to get
workers[i]->async(param1, param2, [](QFuture<int> res) { // QFuture to pass exceptions
     // callback here
});

That can be done for sure. Why not std::future? Well, it is much easier to use QFutureWatcher and it's signals for notifications about result's readiness. Pure C++ notification solutions are muuuch more complex and callbacks are also someting that has to be dragged through the class hierarchy. Each worker interfaces a thread with DB connections, obviously.

Okay, all of that can be written, but... custom thread pool would mean no QtConcurrent convenience, there seem to be only risky ways to create that QFuture so that it could be returned by the custom worker. QThreadPool is of no use, because it would be a whole big story to create persistent runnables in it. More to say, the boilerplate I've briefly described is gonna be some kind of project's core, used in many places, not something to be easily replaced by a 100 hand-made thread managings.

In short: if I could construst a QFuture for my results, the problem would be solved.
Could anyone point me to a solution or a workaround? Would be grateful for any bright ideas.

UPD:

@VladimirBershov offered a good modern solution which implements observer pattern. After some googling I've found a QPromise library. Of course, constructing a custom QFuture is still hacky and can be only done via undocumented QFutureInterface class, but still some  "promise-like" solution makes asynchronous calls neater by far as I can judge.

Body:
You can use AsyncFuture library as a custom QFuture creation tool or ideas source:

AsyncFuture - Use QFuture like a Promise object

QFuture is used together with QtConcurrent to represent the result of
  an asynchronous computation. It is a powerful component for
  multi-thread programming. But its usage is limited to the result of
  threads, it doesn't work with the asynchronous signal emitted by
  QObject. And it is a bit trouble to setup the listener function via
  QFutureWatcher.

AsyncFuture is designed to enhance the function to offer a better way
  to use it for asynchronous programming. It provides a Promise object
  like interface. This project is inspired by AsynQt and RxCpp.

Features:

Convert a signal from QObject into a QFuture object

Combine multiple futures with different type into a single future object

Use Future like a Promise object

Chainable Callback - Advanced multi-threading programming model

Convert a signal from QObject into a QFuture object:

#include "asyncfuture.h"
using namespace AsyncFuture;

// Convert a signal from QObject into a QFuture object

QFuture<void> future = observe(timer, &QTimer::timeout).future();

/* Listen from the future without using QFutureWatcher<T>*/
observe(future).subscribe([]() {
    // onCompleted. It is invoked when the observed future is finished successfully
    qDebug() << "onCompleted";
},[]() {
    // onCanceled
    qDebug() << "onCancel";
});


问:
Remove empty paragraph elements from HTML via SQL
Post has been edited because the phrasing and structure of the original post was asking for the work to be done for me as opposed to the best method to complete the work.

Problem

Email template (shown below) contains tags (encapsulated in '$' characters), these tags are replaced with relevant data (if not null) via a SQL Server trigger. After processing, there may be instances where the tags are not replaced.

I could just replace the tags with empty varchars, but this will cause the email to contain large areas of whites space when rendered in an email client or the browser.

Embedding JavaScript into the email is a consideration for later development but that is outside the scope of what I am doing. This has to be achieved purely through SQL.

Question

What is a more intelligent way to achieve the same results?

Tags

```<code>$ChargeAmount_Changed$
$StartDate_Changed$
$EndDate_Changed$
$EscalationAmount_Changed$
$AccountCode_Changed$
$COSAccountCode_Changed$
$InvoiceDesc_Changed$
$BillingPeriod_Changed$
$BillingCycle_Changed$
$FinanceParty_Changed$
$FinanceAmount_Changed$
$BillingCustomerCode_Changed$
$ChargeAmount_Crtitical$
$StartDate_Critical$
$EndDate_Critical$
$EscalationAmount_Critical$
$AccountCode_Critical$
$COSAccountCode_Critical$
$InvoiceDescription_Critical$
$BillingPeriod_Critical$
$BillingCycle_Critical$
$FinanceParty_Critical$
$FinanceAmount_Critical$
$BillingCustomerCode_Critical$
</code>```

Code

```<code>CREATE FUNCTION fn_bpo_SALSEmail_RemoveTags(
        @Html       VARCHAR(MAX)
,       @EmailFlag  VARCHAR(50)
)
RETURNS VARCHAR(MAX)
WITH    ENCRYPTION
AS
BEGIN
    DECLARE @RowID INT
    ,   @Tag VARCHAR(50)
    ,   @StartIndex INT = 0
    ,   @EndIndex INT
    ,   @StartTag VARCHAR(50)
    ,   @EndTag VARCHAR(50)
    ,   @RowVar VARCHAR (MAX)
    ,   @DeterminedRow INT = 0

    DECLARE @Tags TABLE    (
        fldTagID    INT IDENTITY (1, 1) PRIMARY KEY
    ,   fldTag      VARCHAR(50) NOT NULL
    );

    INSERT INTO @Tags
    SELECT      fldTag
    FROM        tblSALSEmailLoopingFields WITH (NOLOCK)
    WHERE       fldEmailFlag = @EmailFlag

    SELECT @RowID = COUNT(fldTag) FROM @Tags

    WHILE @RowID <> 0
    BEGIN
        SET @DeterminedRow = 0
        SELECT  @Tag = fldTag
        FROM    @Tags
        WHERE   fldTagID = @RowID

        SET @StartIndex = PATINDEX('%' + @Tag +'%', @Html)
        SET @EndIndex = @StartIndex + LEN(@Tag)

        -- Expression found
        IF @StartIndex > 0
        BEGIN
        -- Have not found the whole row yet
        WHILE @DeterminedRow = 0
        BEGIN
            --See if the index is at the start of the opening paragraph element for the row
            SET @StartTag = SUBSTRING(@Html, @StartIndex, LEN('<p'))

            --See if the index is at the end of the closing paragraph element for the row
            SET @EndTag = SUBSTRING(@Html, @EndIndex,  LEN('</p>'))
            --March the start index back
            IF @StartTag <> '<p'
            BEGIN
                SET @StartIndex = @StartIndex - 1
            END

            --March the end index forward
            IF @EndTag <> '</p>'
            BEGIN
                SET @EndIndex = @EndIndex + 1
            END

            -- Found the whole row! replace with empty var
            IF @StartTag = '<p' AND @EndTag = '</p>'
            BEGIN
                SET @DeterminedRow = 1
                -- Get the whole row
                SET @RowVar = SUBSTRING(@Html, @StartIndex, @EndIndex - @StartIndex + LEN(@EndTag))
                SET @Html = REPLACE(@Html, @RowVar, '')
            END
        END
        END
        SET @Html = REPLACE(@Html, @Tag, '')
        SET @RowID = @RowID - 1
    END

    RETURN @Html
END
</code>```

HTML Template

```<code>
-- Start of template
<!DOCTYPE html
    PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">

<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title> </title>
    <style type="text/css">
        .cs2654AE3A {
            text-align: left;
            text-indent: 0pt;
            margin: 0pt 0pt 0pt 0pt
        }

        .cs37BA8FCA {
            color: #000000;
            background-color: transparent;
            font-family: Verdana;
            font-size: 9pt;
            font-weight: normal;
            font-style: normal;
        }
    </style>
</head>

<body>
    <p class="cs2654AE3A"><span class="cs37BA8FCA">A contract item fee has been ??fldAction?? on Contract No.
            ??fldContractNo?? , for customer ??fldCustomerCode?? .</span></p>
    <p class="cs2654AE3A"><span class="cs37BA8FCA">The fee ??fldAction?? is ??fldFeeType??</span></p>
    <p class="cs2654AE3A"><span class="cs37BA8FCA">Located on ??fldItemType?? : ??fldItemCode??</span></p>
    <p class="cs2654AE3A"><span class="cs37BA8FCA"> </span></p>
    <p class="cs2654AE3A"><span class="cs37BA8FCA">$ChargeAmount_Changed$</span></p>
    <p class="cs2654AE3A"><span class="cs37BA8FCA">$ChargeAmount_Crtitical$</span></p>
    <p class="cs2654AE3A"><span class="cs37BA8FCA"> </span></p>
    <p class="cs2654AE3A"><span class="cs37BA8FCA">$StartDate_Changed$</span></p>
    <p class="cs2654AE3A"><span class="cs37BA8FCA">$StartDate_Critical$</span></p>
    <p class="cs2654AE3A"><span class="cs37BA8FCA"> </span></p>
    <p class="cs2654AE3A"><span class="cs37BA8FCA">$EndDate_Changed$</span></p>
    <p class="cs2654AE3A"><span class="cs37BA8FCA">$EndDate_Critical$</span></p>
    <p class="cs2654AE3A"><span class="cs37BA8FCA"> </span></p>
    <p class="cs2654AE3A"><span class="cs37BA8FCA">$EscalationAmount_Changed$</span></p>
    <p class="cs2654AE3A"><span class="cs37BA8FCA">$EscalationAmount_Critical$</span></p>
    <p class="cs2654AE3A"><span class="cs37BA8FCA"> </span></p>
    <p class="cs2654AE3A"><span class="cs37BA8FCA">$AccountCode_Changed$</span></p>
    <p class="cs2654AE3A"><span class="cs37BA8FCA">$AccountCode_Critical$</span></p>
    <p class="cs2654AE3A"><span class="cs37BA8FCA"> </span></p>
    <p class="cs2654AE3A"><span class="cs37BA8FCA">$COSAccountCode_Changed$</span></p>
    <p class="cs2654AE3A"><span class="cs37BA8FCA">$COSAccountCode_Critical$</span></p>
    <p class="cs2654AE3A"><span class="cs37BA8FCA"> </span></p>
    <p class="cs2654AE3A"><span class="cs37BA8FCA">$InvoiceDesc_Changed$</span></p>
    <p class="cs2654AE3A"><span class="cs37BA8FCA">$InvoiceDescription_Critical$</span></p>
    <p class="cs2654AE3A"><span class="cs37BA8FCA"> </span></p>
    <p class="cs2654AE3A"><span class="cs37BA8FCA">$BillingPeriod_Changed$</span></p>
    <p class="cs2654AE3A"><span class="cs37BA8FCA">$BillingPeriod_Critical$</span></p>
    <p class="cs2654AE3A"><span class="cs37BA8FCA"> </span></p>
    <p class="cs2654AE3A"><span class="cs37BA8FCA">$BillingCycle_Changed$</span></p>
    <p class="cs2654AE3A"><span class="cs37BA8FCA">$BillingCycle_Critical$</span></p>
    <p class="cs2654AE3A"><span class="cs37BA8FCA"> </span></p>
    <p class="cs2654AE3A"><span class="cs37BA8FCA">$FinanceParty_Changed$</span></p>
    <p class="cs2654AE3A"><span class="cs37BA8FCA">$FinanceParty_Critical$</span></p>
    <p class="cs2654AE3A"><span class="cs37BA8FCA"> </span></p>
    <p class="cs2654AE3A"><span class="cs37BA8FCA">$FinanceAmount_Changed$</span></p>
    <p class="cs2654AE3A"><span class="cs37BA8FCA">$FinanceAmount_Critical$</span></p>
    <p class="cs2654AE3A"><span class="cs37BA8FCA"> </span></p>
    <p class="cs2654AE3A"><span class="cs37BA8FCA">$BillingCustomerCode_Changed$</span></p>
    <p class="cs2654AE3A"><span class="cs37BA8FCA">$BillingCustomerCode_Critical$</span></p>
    <p class="cs2654AE3A"><span class="cs37BA8FCA"> </span></p>
    <p class="cs2654AE3A"><span class="cs37BA8FCA">This change was made by : ??fldEmpFullName??</span></p>
    <p class="cs2654AE3A"><span class="cs37BA8FCA"> </span></p>
</body>

</html>
-- End of template
</code>```

答:
For my opinion, this is not for what a database is developed.

My guess here is, search for a tag which is not removed, then search backwards for

```<code><p
</code>```

save this patindex, search forward to

```<code></p>
</code>```

, now you can delete all between the patindex. (don`t forget to calculate the searchstrings here)

Another approach could be:
If you have to deal with such task, you can easy do this in frontend with JavaScript/jQuery.

```<code>$('p').each(function( index ) {if($(this).html() === '') { this.remove()}})
</code>```

This will stripe out all paragraph which are empty.

EDIT:

Loop thru the html and select every paragraph into a temp table.
Then you can handle it easy.

```<code>declare
    @tbl TABLE(
        [ID] [int] IDENTITY(1,1) NOT NULL,
        [paragraph] nvarchar(max) NOT NULL
    );

declare
    @HtmlLen INT = LEN(@Html)
    ,@StartIndex INT = 0
    ,@EndIndex INT

WHILE CHARINDEX('<p', @Html)>0
BEGIN
    SELECT
        @StartIndex = CHARINDEX('<p', @Html),
        @EndIndex = CHARINDEX('</p>', @Html)

    INSERT INTO @tbl([paragraph])
    select SUBSTRING ( @Html ,@StartIndex, @EndIndex -4 )
    select @Html = SUBSTRING(@Html, @EndIndex+3, @HtmlLen)

END

select * from @tbl
</code>```

the result

you can rebuild your html string with (for SQL2017+)

```<code> -- at least build up your string again
 SELECT STRING_AGG([paragraph], '')  FROM @tbl
</code>```

Body:
Post has been edited because the phrasing and structure of the original post was asking for the work to be done for me as opposed to the best method to complete the work.

Problem

Email template (shown below) contains tags (encapsulated in '$' characters), these tags are replaced with relevant data (if not null) via a SQL Server trigger. After processing, there may be instances where the tags are not replaced.

I could just replace the tags with empty varchars, but this will cause the email to contain large areas of whites space when rendered in an email client or the browser.

Embedding JavaScript into the email is a consideration for later development but that is outside the scope of what I am doing. This has to be achieved purely through SQL.

Question

What is a more intelligent way to achieve the same results?

Tags

$ChargeAmount_Changed$
$StartDate_Changed$
$EndDate_Changed$
$EscalationAmount_Changed$
$AccountCode_Changed$
$COSAccountCode_Changed$
$InvoiceDesc_Changed$
$BillingPeriod_Changed$
$BillingCycle_Changed$
$FinanceParty_Changed$
$FinanceAmount_Changed$
$BillingCustomerCode_Changed$
$ChargeAmount_Crtitical$
$StartDate_Critical$
$EndDate_Critical$
$EscalationAmount_Critical$
$AccountCode_Critical$
$COSAccountCode_Critical$
$InvoiceDescription_Critical$
$BillingPeriod_Critical$
$BillingCycle_Critical$
$FinanceParty_Critical$
$FinanceAmount_Critical$
$BillingCustomerCode_Critical$

Code

CREATE FUNCTION fn_bpo_SALSEmail_RemoveTags(
        @Html       VARCHAR(MAX)
,       @EmailFlag  VARCHAR(50)
)
RETURNS VARCHAR(MAX)
WITH    ENCRYPTION
AS
BEGIN
    DECLARE @RowID INT
    ,   @Tag VARCHAR(50)
    ,   @StartIndex INT = 0
    ,   @EndIndex INT
    ,   @StartTag VARCHAR(50)
    ,   @EndTag VARCHAR(50)
    ,   @RowVar VARCHAR (MAX)
    ,   @DeterminedRow INT = 0

    DECLARE @Tags TABLE    (
        fldTagID    INT IDENTITY (1, 1) PRIMARY KEY
    ,   fldTag      VARCHAR(50) NOT NULL
    );

    INSERT INTO @Tags
    SELECT      fldTag
    FROM        tblSALSEmailLoopingFields WITH (NOLOCK)
    WHERE       fldEmailFlag = @EmailFlag

    SELECT @RowID = COUNT(fldTag) FROM @Tags

    WHILE @RowID <> 0
    BEGIN
        SET @DeterminedRow = 0
        SELECT  @Tag = fldTag
        FROM    @Tags
        WHERE   fldTagID = @RowID

        SET @StartIndex = PATINDEX('%' + @Tag +'%', @Html)
        SET @EndIndex = @StartIndex + LEN(@Tag)

        -- Expression found
        IF @StartIndex > 0
        BEGIN
        -- Have not found the whole row yet
        WHILE @DeterminedRow = 0
        BEGIN
            --See if the index is at the start of the opening paragraph element for the row
            SET @StartTag = SUBSTRING(@Html, @StartIndex, LEN('<p'))

            --See if the index is at the end of the closing paragraph element for the row
            SET @EndTag = SUBSTRING(@Html, @EndIndex,  LEN('
'))
            --March the start index back
            IF @StartTag <> '<p'
            BEGIN
                SET @StartIndex = @StartIndex - 1
            END

            --March the end index forward
            IF @EndTag <> '
'
            BEGIN
                SET @EndIndex = @EndIndex + 1
            END

            -- Found the whole row! replace with empty var
            IF @StartTag = '<p' AND @EndTag = '
'
            BEGIN
                SET @DeterminedRow = 1
                -- Get the whole row
                SET @RowVar = SUBSTRING(@Html, @StartIndex, @EndIndex - @StartIndex + LEN(@EndTag))
                SET @Html = REPLACE(@Html, @RowVar, '')
            END
        END
        END
        SET @Html = REPLACE(@Html, @Tag, '')
        SET @RowID = @RowID - 1
    END

    RETURN @Html
END

HTML Template

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

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

A contract item fee has been ??fldAction?? on Contract No.
            ??fldContractNo?? , for customer ??fldCustomerCode?? .

The fee ??fldAction?? is ??fldFeeType??

Located on ??fldItemType?? : ??fldItemCode??

$ChargeAmount_Changed$

$ChargeAmount_Crtitical$

$StartDate_Changed$

$StartDate_Critical$

$EndDate_Changed$

$EndDate_Critical$

$EscalationAmount_Changed$

$EscalationAmount_Critical$

$AccountCode_Changed$

$AccountCode_Critical$

$COSAccountCode_Changed$

$COSAccountCode_Critical$

$InvoiceDesc_Changed$

$InvoiceDescription_Critical$

$BillingPeriod_Changed$

$BillingPeriod_Critical$

$BillingCycle_Changed$

$BillingCycle_Critical$

$FinanceParty_Changed$

$FinanceParty_Critical$

$FinanceAmount_Changed$

$FinanceAmount_Critical$

$BillingCustomerCode_Changed$

$BillingCustomerCode_Critical$

This change was made by : ??fldEmpFullName??

-- End of template

Body:
For my opinion, this is not for what a database is developed.

My guess here is, search for a tag which is not removed, then search backwards for

<p

save this patindex, search forward to

</p>

, now you can delete all between the patindex. (don`t forget to calculate the searchstrings here)

Another approach could be:
If you have to deal with such task, you can easy do this in frontend with JavaScript/jQuery.

$('p').each(function( index ) {if($(this).html() === '') { this.remove()}})

This will stripe out all paragraph which are empty.

EDIT:

Loop thru the html and select every paragraph into a temp table.
Then you can handle it easy.

declare
    @tbl TABLE(
        [ID] [int] IDENTITY(1,1) NOT NULL,
        [paragraph] nvarchar(max) NOT NULL
    );

declare
    @HtmlLen INT = LEN(@Html)
    ,@StartIndex INT = 0
    ,@EndIndex INT

WHILE CHARINDEX('<p', @Html)>0
BEGIN
    SELECT
        @StartIndex = CHARINDEX('<p', @Html),
        @EndIndex = CHARINDEX('</p>', @Html)

    INSERT INTO @tbl([paragraph])
    select SUBSTRING ( @Html ,@StartIndex, @EndIndex -4 )
    select @Html = SUBSTRING(@Html, @EndIndex+3, @HtmlLen)

END

select * from @tbl

the result

you can rebuild your html string with (for SQL2017+)

 -- at least build up your string again
 SELECT STRING_AGG([paragraph], '')  FROM @tbl


问:
AttributeError: 'DataFrame' object has no attribute 'set_value'
I'm using flask and getting error at set_values. I'm reading the input from html and passing it to the code </p>

```<code>@app.route('/home', methods=['POST'])
def first():
    source = request.files['first']
    destination = request.files['second']
    df = pd.read_csv(source)
    df1 = pd.read_csv(destination)
    val1 = int(request.form['val1'])
    val2 = int(request.form['val2'])
    val3 = int(request.form['val3'])
    target = request.form['str']
    df2 = df[df.columns[val2]]
    count = 0
    for j in df[df.columns[val1]]:
        x = df1.loc[df1[df1.columns[val3]] == j].index.values
        for i in x:
            df1.set_value(i, target, df2[count])
        count = count + 1
    df1.to_csv('result.csv', index=False)
</code>```

Body:
I'm using flask and getting error at set_values. I'm reading the input from html and passing it to the code

@app.route('/home', methods=['POST'])
def first():
    source = request.files['first']
    destination = request.files['second']
    df = pd.read_csv(source)
    df1 = pd.read_csv(destination)
    val1 = int(request.form['val1'])
    val2 = int(request.form['val2'])
    val3 = int(request.form['val3'])
    target = request.form['str']
    df2 = df[df.columns[val2]]
    count = 0
    for j in df[df.columns[val1]]:
        x = df1.loc[df1[df1.columns[val3]] == j].index.values
        for i in x:
            df1.set_value(i, target, df2[count])
        count = count + 1
    df1.to_csv('result.csv', index=False)

Body:
Check your pandas version.

df.set_value() is deprecated since pandas version 0.21.0

Instead use df.at

import pandas as pd

df = pd.DataFrame({"A":[1, 5, 3, 4, 2],
                   "B":[3, 2, 4, 3, 4],
                   "C":[2, 2, 7, 3, 4],
                   "D":[4, 3, 6, 12, 7]})

df.at[2,'B']=100

   A    B  C   D
0  1    3  2   4
1  5    2  2   3
2  3  100  7   6
3  4    3  3  12
4  2    4  4   7


答:
I think you need GroupBy.cumcount for counter Series, create MultiIndex by DataFrame.set_index and reshape by DataFrame.unstack, then flatten columns names by f-strings and last add pSpot values, seems first values per groups created by DataFrame.drop_duplicates and for first new column add DataFrame.insert:

```<code>g = df.groupby('optionType').cumcount()

df1 = (df.set_index(['optionType', g])[['expiration','iv']]
         .unstack()
         .sort_index(axis=1, level=1))
df1.columns = df1.columns.map(lambda x: f'{x[0]}{x[1]}')
df1 = df1.reset_index()
df1.insert(0,'pSpot', df.drop_duplicates('optionType')['pSpot'].to_numpy())
#oldier pandas versions
#df1.insert(0,'pSpot', df.drop_duplicates('optionType')['pSpot'].values)
print (df1)
   pSpot optionType          expiration0     iv0          expiration1     iv1  \
0   0.26          C  2017-01-20T00:00:00  157.79  2017-01-20T00:00:00  157.79
1   1.00          P  2017-01-20T00:00:00  178.34  2017-01-20T00:00:00  173.20

           expiration2     iv2          expiration3     iv3
0                  NaN     NaN                  NaN     NaN
1  2017-01-20T00:00:00  168.06  2017-01-20T00:00:00  162.92
</code>```

Title: How to reorganize dataframe for a different view of data

Body:
I have a dataframe that has columns like this:

   pSpot        quoteDatetime underlyingSymbol           expiration  strike optionType  bid  ask  underlyingBid  underlyingAsk     iv  id
0   0.26  2017-01-06T12:00:00              SPX  2017-01-20T00:00:00     600          P  NaN  NaN        2277.40        2278.08 178.34 nan
0   0.29  2017-01-06T12:00:00              SPX  2017-01-20T00:00:00     650          P  NaN  NaN        2277.40        2278.08 173.20 nan
0   0.31  2017-01-06T12:00:00              SPX  2017-01-20T00:00:00     700          P  NaN  NaN        2277.40        2278.08 168.06 nan
0   0.33  2017-01-06T12:00:00              SPX  2017-01-20T00:00:00     750          P  NaN  NaN        2277.40        2278.08 162.92 nan
0   1.00  2017-01-06T12:00:00              SPX  2017-01-20T00:00:00     2280         C  NaN  NaN        2277.40        2278.08 157.79 nan
0   1.01  2017-01-06T12:00:00              SPX  2017-01-20T00:00:00     2300         C  NaN  NaN        2277.40        2278.08 157.79 nan
.....
More data with different expiration dates

How do I reorganize the dataframe so that it displays pSpot and optionType columns along the left, and pivots all the expiry and iv from several rows into one row:

pSpot optionType   first expiry        iv      second expiry        iv      ... n-expiry              iv
.26       P        2017-01-20T00:00:00 178.34  2017-03-20T00:00:00  125.33      2017-09-20T00:00:00   101.23
...      ...          ...                ...                         ...                ...
1.01      C        2017-01-20T00:00:00 157.79  2017-03-20T00:00:00  145.45      2017-09-20T00:00:00   132.98

Go from stacked or record format, to a pivot of the expiry.

Body:
I think you need GroupBy.cumcount for counter Series, create MultiIndex by DataFrame.set_index and reshape by DataFrame.unstack, then flatten columns names by f-strings and last add pSpot values, seems first values per groups created by DataFrame.drop_duplicates and for first new column add DataFrame.insert:

g = df.groupby('optionType').cumcount()

df1 = (df.set_index(['optionType', g])[['expiration','iv']]
         .unstack()
         .sort_index(axis=1, level=1))
df1.columns = df1.columns.map(lambda x: f'{x[0]}{x[1]}')
df1 = df1.reset_index()
df1.insert(0,'pSpot', df.drop_duplicates('optionType')['pSpot'].to_numpy())
#oldier pandas versions
#df1.insert(0,'pSpot', df.drop_duplicates('optionType')['pSpot'].values)
print (df1)
   pSpot optionType          expiration0     iv0          expiration1     iv1  \
0   0.26          C  2017-01-20T00:00:00  157.79  2017-01-20T00:00:00  157.79
1   1.00          P  2017-01-20T00:00:00  178.34  2017-01-20T00:00:00  173.20

           expiration2     iv2          expiration3     iv3
0                  NaN     NaN                  NaN     NaN
1  2017-01-20T00:00:00  168.06  2017-01-20T00:00:00  162.92


问:
Hot reload using Electron and Angular
I'm using Angular and Electron for my app.
I'm looking for a way to enable hot reload...
When I run my yarn run electron (scripts : "electron": "ng build --base-href ./ && electron ."), if I save a change, my app isn't reloading.
Here is my main.js file :

```<code>const { app, BrowserWindow } = require("electron");
const path = require("path");
const url = require("url");

let win;

function createWindow() {
  win = new BrowserWindow({ width: 800, height: 600 });

  // load the dist folder from Angular
  win.loadURL(
    url.format({
      pathname: path.join(__dirname, `/dist/index.html`),
      protocol: "file:",
      slashes: true
    })
  );

  // The following is optional and will open the DevTools:
  // win.webContents.openDevTools()

  win.on("closed", () => {
    win = null;
  });
}

app.on("ready", createWindow);

// on macOS, closing the window doesn't quit the app
app.on("window-all-closed", () => {
  if (process.platform !== "darwin") {
    app.quit();
  }
});

// initialize the app's main window
app.on("activate", () => {
  if (win === null) {
    createWindow();
  }
});
</code>```

I tried to include require('electron-reload')(__dirname); in the main.js file but nothing changed

答:
These steps worked for me:

install electron-reload simply by npm install electron-reload

add these lines to your main.js

```<code>const electron = require('electron')

require('electron-reload')(__dirname, {
    electron: require("${__dirname}/node_modules/electron")
});
</code>```

Title: Hot reload using Electron and Angular

Body:
I'm using Angular and Electron for my app.
I'm looking for a way to enable hot reload...
When I run my yarn run electron (scripts : "electron": "ng build --base-href ./ && electron ."), if I save a change, my app isn't reloading.
Here is my main.js file :

const { app, BrowserWindow } = require("electron");
const path = require("path");
const url = require("url");

let win;

function createWindow() {
  win = new BrowserWindow({ width: 800, height: 600 });

  // load the dist folder from Angular
  win.loadURL(
    url.format({
      pathname: path.join(__dirname, `/dist/index.html`),
      protocol: "file:",
      slashes: true
    })
  );

  // The following is optional and will open the DevTools:
  // win.webContents.openDevTools()

  win.on("closed", () => {
    win = null;
  });
}

app.on("ready", createWindow);

// on macOS, closing the window doesn't quit the app
app.on("window-all-closed", () => {
  if (process.platform !== "darwin") {
    app.quit();
  }
});

// initialize the app's main window
app.on("activate", () => {
  if (win === null) {
    createWindow();
  }
});

I tried to include require('electron-reload')(__dirname); in the main.js file but nothing changed

Body:
These steps worked for me:

install electron-reload simply by npm install electron-reload

add these lines to your main.js

const electron = require('electron')

require('electron-reload')(__dirname, {
    electron: require("${__dirname}/node_modules/electron")
});


问:
My code doesn’t work when I put in in a function in python
I have a code that does a sliding window binning, it works when I use it outside the function, but when I put it in the function it only fills the first line and then it stops working. </p>

```<code>def slidefunc (data,window,step):
    minmz = data['mass'].min()
    maxmz = data['mass'].max()
    bins = []
    minbin = minmz+window
    maxbin = maxmz-window
    for i in np.arange(minbin,maxbin,step):
        bins.append(i)
    m = len(bins)-1
    i = 0
    j = 0
    first = 0
    n = 0
    accum = 0
    mzbins = pd.DataFrame(bins, columns= ['bins'])
    mzbins['intensity'] = np.nan
    mzbins['samples'] = np.nan

    while (j<=m):
        lower = bins[j]- window
        upper = bins[j]+ window
        while data.iat[i,0]<= lower:
            i = i + 1
        first = i
        while data.iat[i,0]< upper:
            accum = accum + data.iat[i,1]
            n = n + 1
            i = i + 1
        if (n>0):
            mzbins.iat[j,1] = accum/n
            mzbins.iat[j,2] = n
            #a = accum/n
            #b = n
            accum = 0
            n = 0
        j = j + 1
        i = first
            # Jump empty regions
        #empty =   mzbins.iat[j,0]+window
        #while j<m and data.iat[i,0] > empty :
         #   j = j + 1

        return mzbins
</code>```

答:
It looks like the last line

```<code>        return mzbins
</code>```

is indented too much and should be outside the while loop, i.e.

```<code>    return mzbins
</code>```

Body:
I have a code that does a sliding window binning, it works when I use it outside the function, but when I put it in the function it only fills the first line and then it stops working.

def slidefunc (data,window,step):
    minmz = data['mass'].min()
    maxmz = data['mass'].max()
    bins = []
    minbin = minmz+window
    maxbin = maxmz-window
    for i in np.arange(minbin,maxbin,step):
        bins.append(i)
    m = len(bins)-1
    i = 0
    j = 0
    first = 0
    n = 0
    accum = 0
    mzbins = pd.DataFrame(bins, columns= ['bins'])
    mzbins['intensity'] = np.nan
    mzbins['samples'] = np.nan

    while (j<=m):
        lower = bins[j]- window
        upper = bins[j]+ window
        while data.iat[i,0]<= lower:
            i = i + 1
        first = i
        while data.iat[i,0]< upper:
            accum = accum + data.iat[i,1]
            n = n + 1
            i = i + 1
        if (n>0):
            mzbins.iat[j,1] = accum/n
            mzbins.iat[j,2] = n
            #a = accum/n
            #b = n
            accum = 0
            n = 0
        j = j + 1
        i = first
            # Jump empty regions
        #empty =   mzbins.iat[j,0]+window
        #while j<m and data.iat[i,0] > empty :
         #   j = j + 1

        return mzbins

Body:
It looks like the last line

        return mzbins

is indented too much and should be outside the while loop, i.e.

    return mzbins


问:
Blue and Purple Default links, how to remove?
This is one of the links in my nav:

```<code><li><a href="#live-now" class="navBtn"><span id="navLiveNow" class="white innerShadow textShadow">Live Now</span></a></li>
</code>```

I also have the following in my css:

```<code>a { text-decoration: none; }
a:visited { text-decoration: none; }
a:hover { text-decoration: none; }
a:focus { text-decoration: none; }
a:hover, a:active { text-decoration: none; }
</code>```

But the links still display in the awful blue/purple visited /hover html default. What am i doing wrong?

答:
By default link color is blue and the visited color is purple. Also, the text-decoration is underlined and the color is blue.
If you want to keep the same color for visited, hover and focus then follow below code-

For example color is: #000

```<code>a:visited, a:hover, a:focus {
    text-decoration: none;
    color: #000;
}
</code>```

If you want to use a different color for hover, visited and focus. For example Hover color: red visited color: green and focus color: yellow  then follow below code

```<code>   a:hover {
        color: red;
    }
    a:visited {
        color: green;
    }
    a:focus {
        color: yellow;
    }
</code>```

NB: good practice is to use color code.

ContentLicense: CC BY-SA 3.0

Body:
This is one of the links in my nav:

Live Now

I also have the following in my css:

a { text-decoration: none; }
a:visited { text-decoration: none; }
a:hover { text-decoration: none; }
a:focus { text-decoration: none; }
a:hover, a:active { text-decoration: none; }

But the links still display in the awful blue/purple visited /hover html default. What am i doing wrong?

Body:
By default link color is blue and the visited color is purple. Also, the text-decoration is underlined and the color is blue.
If you want to keep the same color for visited, hover and focus then follow below code-

For example color is: #000

a:visited, a:hover, a:focus {
    text-decoration: none;
    color: #000;
}

If you want to use a different color for hover, visited and focus. For example Hover color: red visited color: green and focus color: yellow  then follow below code

   a:hover {
        color: red;
    }
    a:visited {
        color: green;
    }
    a:focus {
        color: yellow;
    }

NB: good practice is to use color code.


问:
CocoaLumberjack - Swift : Not getting Previous Days Log Files
I am using CocoaLumberjack/Swift Pod in my iOS project.

The problem is, I am getting always Current day(Today or Last day of last time app launched) log files. CocoaLumberjack doesn't keeping old log files of Previous days.

For me Today is 2020-02-19. And the files I get from CocoaLumberjack:

xyz 2020-02-19--05-55-39-774.log // file size -> 10 MB

xyz 2020-02-19--05-55-46-305.log // file size -> 1.7 MB

** There are no older files from previous days

I disabled Time Based Rolling.

logger.rollingFrequency = -1 // also tried with 0

And Use 10 MB memory limit for each file

logger.maximumFileSize = 10 * (1024 * 1024) //10MB

According the CocoaLumberjack document.

```<code>* You may optionally disable rolling due to filesize by setting `maximumFileSize` to zero.
* If you do so, rolling is based solely on `rollingFrequency`.
</code>```

Here is my source code from AppDelegate.

```<code>import CocoaLumberjack

......

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
    // Enable CocoaLumberjack logging
    self.setLoggingProperty()
}

private func setLoggingProperty() {
    if #available(iOS 10.0, *) {
        DDLog.add(DDOSLogger.sharedInstance)
    } else {
        // Fallback on earlier versions
        DDLog.add(DDASLLogger.sharedInstance)
        if let dDTTYLogger = DDTTYLogger.sharedInstance {
            DDLog.add(dDTTYLogger)
        }
    }

    let logger: DDFileLogger = DDFileLogger.init()

    logger.maximumFileSize = 10 * (1024*1024) //10MB
    logger.rollingFrequency = -1 // Disable time base rolling

    logger.logFileManager.maximumNumberOfLogFiles = 7
    DDLog.add(logger)
}
</code>```

Does anyone faces similar issue? Am I missing something?

答:
change the rolling frequency and size. Sets the bellow snippet</p>

```<code>let fileLogger = DDFileLogger(logFileManager: LogsManager.shared())
        DDLog.add(DDOSLogger.sharedInstance)
        // 24-hour rolling, maximum 14 files, max 50 MB per file.
        fileLogger.rollingFrequency = 60 * 60 * 24
        fileLogger.maximumFileSize = 50 * 1024 * 1024;
        fileLogger.logFileManager.maximumNumberOfLogFiles = 14;
        // The file logger
        DDLog.add(fileLogger)
        // TTY = The Xcode console logger
        DDLog.add(DDTTYLogger.sharedInstance)
        // ASL = The Apple System Logs
        DDLog.add(DDOSLogger.sharedInstance)
</code>```

Body:
I am using CocoaLumberjack/Swift Pod in my iOS project.

The problem is, I am getting always Current day(Today or Last day of last time app launched) log files. CocoaLumberjack doesn't keeping old log files of Previous days.

For me Today is 2020-02-19. And the files I get from CocoaLumberjack:

xyz 2020-02-19--05-55-39-774.log // file size -> 10 MB

xyz 2020-02-19--05-55-46-305.log // file size -> 1.7 MB

** There are no older files from previous days

I disabled Time Based Rolling.

logger.rollingFrequency = -1 // also tried with 0

And Use 10 MB memory limit for each file

logger.maximumFileSize = 10 * (1024 * 1024) //10MB

According the CocoaLumberjack document.

* You may optionally disable rolling due to filesize by setting `maximumFileSize` to zero.
* If you do so, rolling is based solely on `rollingFrequency`.

Here is my source code from AppDelegate.

import CocoaLumberjack

......

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
    // Enable CocoaLumberjack logging
    self.setLoggingProperty()
}

private func setLoggingProperty() {
    if #available(iOS 10.0, *) {
        DDLog.add(DDOSLogger.sharedInstance)
    } else {
        // Fallback on earlier versions
        DDLog.add(DDASLLogger.sharedInstance)
        if let dDTTYLogger = DDTTYLogger.sharedInstance {
            DDLog.add(dDTTYLogger)
        }
    }

    let logger: DDFileLogger = DDFileLogger.init()

    logger.maximumFileSize = 10 * (1024*1024) //10MB
    logger.rollingFrequency = -1 // Disable time base rolling

    logger.logFileManager.maximumNumberOfLogFiles = 7
    DDLog.add(logger)
}

Does anyone faces similar issue? Am I missing something?

Body:
change the rolling frequency and size. Sets the bellow snippet

let fileLogger = DDFileLogger(logFileManager: LogsManager.shared())
        DDLog.add(DDOSLogger.sharedInstance)
        // 24-hour rolling, maximum 14 files, max 50 MB per file.
        fileLogger.rollingFrequency = 60 * 60 * 24
        fileLogger.maximumFileSize = 50 * 1024 * 1024;
        fileLogger.logFileManager.maximumNumberOfLogFiles = 14;
        // The file logger
        DDLog.add(fileLogger)
        // TTY = The Xcode console logger
        DDLog.add(DDTTYLogger.sharedInstance)
        // ASL = The Apple System Logs
        DDLog.add(DDOSLogger.sharedInstance)


问:
How can we read JSON file
Utility to read JSON file from file server
2. Utility should run at scheduled time let’s say 6AM
3. Error message if JSON file is not properly formatted
4. Error message if Category is missing and ITEM need that Category to be saved.
5. Entity mapping as per the given relationship in data model
5. Documentation for the API, preferably using any tool
6. Junit Test cases using Mockito
7. Use either MySQL or Oracle for API development
8. add one point as JSON validation for not null and value range

Thanks

答:
i tried below to cover first question of this problem but not sure what to do to answer remaining 7 questions related with this probelm:-
Create a class named "JSONRead" in eclipse. In this we will using "JSONParser" to convert the JSON string in the file to JSONOBject.
 In order to use JSON Parser makes sure that your string is in JSON format.

```<code>enter code here`enter code here`
enter code here
{
package logicProgramming;

import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Iterator;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;

public class JsonRead {

    public static void main(String[] args) {

        JSONParser parser = new JSONParser();
        //JsonParser to convert JSON string into Json Object

        try {
            Object obj = parser.parse(new FileReader("g:\\newfile.json"));
            //parsing the JSON string inside the file that we created earlier.

            JSONObject jsonObject = (JSONObject) obj;
            System.out.println(jsonObject);
            //Json string has been converted into JSONObject

            String name = (String) jsonObject.get("name");
            System.out.println(name);

            String department = (String) jsonObject.get("department");
            System.out.println(department);

            String branch = (String) jsonObject.get("branch");
            System.out.println(branch);

            long year = (long) jsonObject.get("year");
            System.out.println(year);
            //Displaying values from JSON OBject by using Keys

            JSONArray remarks = (JSONArray) jsonObject.get("remarks");
            //converting the JSONObject into JSONArray as remark was an array.
            Iterator<String> iterator = remarks.iterator();
            //Iterator is used to access the each element in the list
            //loop will continue as long as there are elements in the array.
            while (iterator.hasNext()) {
                System.out.println(iterator.next());
                //accessing each elemnt by using next function.
            }

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ParseException e) {
            e.printStackTrace();
        }
    }

}

enter code here
enter code here
</code>```

Thanks

Title: How can we read JSON file

Body:
i tried below to cover first question of this problem but not sure what to do to answer remaining 7 questions related with this probelm:-
Create a class named "JSONRead" in eclipse. In this we will using "JSONParser" to convert the JSON string in the file to JSONOBject.
 In order to use JSON Parser makes sure that your string is in JSON format.

enter code here`enter code here`
enter code here
{
package logicProgramming;

import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Iterator;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;

public class JsonRead {

    public static void main(String[] args) {

        JSONParser parser = new JSONParser();
        //JsonParser to convert JSON string into Json Object

        try {
            Object obj = parser.parse(new FileReader("g:\\newfile.json"));
            //parsing the JSON string inside the file that we created earlier.

            JSONObject jsonObject = (JSONObject) obj;
            System.out.println(jsonObject);
            //Json string has been converted into JSONObject

            String name = (String) jsonObject.get("name");
            System.out.println(name);

            String department = (String) jsonObject.get("department");
            System.out.println(department);

            String branch = (String) jsonObject.get("branch");
            System.out.println(branch);

            long year = (long) jsonObject.get("year");
            System.out.println(year);
            //Displaying values from JSON OBject by using Keys

            JSONArray remarks = (JSONArray) jsonObject.get("remarks");
            //converting the JSONObject into JSONArray as remark was an array.
            Iterator<String> iterator = remarks.iterator();
            //Iterator is used to access the each element in the list
            //loop will continue as long as there are elements in the array.
            while (iterator.hasNext()) {
                System.out.println(iterator.next());
                //accessing each elemnt by using next function.
            }

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ParseException e) {
            e.printStackTrace();
        }
    }

}

enter code here
enter code here

Thanks


问:
Failed to generate application.xml
I'm trying to build ear with the command

mvn clean install

This is the error I got

Failed to execute goal org.apache.maven.plugins:maven-ear-plugin:2.10.1:generate-application-xml (default-generate-application-xml) on project my_project_name_ear: Failed to generate application.xml: Exception while opening file[D:\amt_bo\my_project_name_ear\target\applicati
  on.xml]: D:\amt_bo\my_project_name_ear\target\application.xml (Access is denied) -> [Help 1]

But if I run build again it successively builds.

答: Delete .m2\repository folder under C:\Users (or D:) and then retry clean install.</p>

Title: Failed to generate application.xml


问:
EditText: Disable Paste/Replace menu pop-up on Text Selection Handler click event
My goal is to have an EditText that has no fancy features, just the Text Selection Handler for moving the cursor more easily -- so no context menus or pop-ups.

I've disabled the appearance of the text editing function actionbar (copy/Paste etc.) by consuming the ActionMode Callback event, as per this solution.

The middle Middle Text Select Handle (see image below) still appears when text exists in the field and a click occurs within the text. Great! I want to keep this behaviour. What I DON'T want is the "PASTE" menu to appear when the Text Select Handle itself is clicked.

I have also disabled long-click input for the EditText by setting android:longClickable="false" in the styles XML. Disabling the long click prevents the "Paste/Replace" menu from appearing when the mouse is clicked and held (i.e. long touch), however when the mouse is clicked (single touch) within the text, the text selection handle appears, and when the text selection handle itself is clicked, then the "paste" menu option appears (when there's text in the clipboard). This is what I'm trying to prevent.

From what I can see from the source, the ActionPopupWindow is what pops up with the PASTE/REPLACE options. ActionPopupWindow is a protected variable (mActionPopupWindow) in the private abstract class HandleView within public class android.widget.Editor...

Short of disabling the clipboard service or editing the Android Source code, is there a way that I can prevent this from showing? I tried to define a new style for android:textSelectHandleWindowStyle, and set android:visibility to gone, but it didn't work (app froze for a while when it would otherwise have shown).

答:
I have found one easy solution.Hope it will help to someone, Extend Edittetxt class and ovverride below methods.
Same way if you want to disable other options by comparing menu.getItem(i).getTitle() you can do it.

```<code>private class ActionModeCallbackInterceptor implements ActionMode.Callback
    {
        public boolean onCreateActionMode(ActionMode mode, Menu menu) {
            return true;
        }

        public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
            for(int i =0;i<menu.size();i++){
                if(menu.getItem(i).getTitle().toString().equals("Clipboard")
               || menu.getItem(i).getTitle().toString().equals("Paste")) {
                    menu.getItem(i).setVisible(false);
                }
            }
              return false;
        }

        public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
            return false;
        }
        public void onDestroyActionMode(ActionMode mode) {}
    }
</code>```

Body:
I have found one easy solution.Hope it will help to someone, Extend Edittetxt class and ovverride below methods.
Same way if you want to disable other options by comparing menu.getItem(i).getTitle() you can do it.

private class ActionModeCallbackInterceptor implements ActionMode.Callback
    {
        public boolean onCreateActionMode(ActionMode mode, Menu menu) {
            return true;
        }

        public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
            for(int i =0;i<menu.size();i++){
                if(menu.getItem(i).getTitle().toString().equals("Clipboard")
               || menu.getItem(i).getTitle().toString().equals("Paste")) {
                    menu.getItem(i).setVisible(false);
                }
            }
              return false;
        }

        public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
            return false;
        }
        public void onDestroyActionMode(ActionMode mode) {}
    }


问:
Is there a way to query multiple tables at once based on common table name in Oracle through SQL or PL/SQL
I have a requirement to fetch data from all the tables based on common table name pattern every week.Basically my requirement is to merge all the data to form a single lookup table.

Example:

Table Names:

```<code>Department_20190101
Department_20190109
Department_20190122
Department_20190129
</code>```

I have to fetch data from all the tables and have to create a single lookup table. Is there a simple way to do this other than by going through iteration in PL/SQL by getting the table names with the help of ALL_TABLES

Note:The Date part is not consistent.If i can achieve this requirement once then i can easily start inserting the data from the new table to the existing lookup(n+1)

Please share your suggestions.

Regards,
Scott

答:
If you have a very long list of tables, or you requirement is to aggergate the results from all tables e.g. starting with Department_ followed by a certain date or range of dates, then you might need dynamic SQL for this.  For the exact example you did show in your question, a CTE with a union query might work:

```<code>WITH cte AS (
    SELECT * FROM Department_20190101 UNION ALL
    SELECT * FROM Department_20190109 UNION ALL
    SELECT * FROM Department_20190122 UNION ALL
    SELECT * FROM Department_20190129
)
</code>```

And then use the CTE as:

```<code>SELECT *
FROM cte;
</code>```

This assumes that all tables have identical structures.  Also, as a side note, if this be the case, you might want to consider just having a single table with a date column to differentiate between the otherwise common data.

Body:
I have a requirement to fetch data from all the tables based on common table name pattern every week.Basically my requirement is to merge all the data to form a single lookup table.

Example:

Table Names:

Department_20190101
Department_20190109
Department_20190122
Department_20190129

I have to fetch data from all the tables and have to create a single lookup table. Is there a simple way to do this other than by going through iteration in PL/SQL by getting the table names with the help of ALL_TABLES

Note:The Date part is not consistent.If i can achieve this requirement once then i can easily start inserting the data from the new table to the existing lookup(n+1)

Please share your suggestions.

Regards,
Scott

Body:
If you have a very long list of tables, or you requirement is to aggergate the results from all tables e.g. starting with Department_ followed by a certain date or range of dates, then you might need dynamic SQL for this.  For the exact example you did show in your question, a CTE with a union query might work:

WITH cte AS (
    SELECT * FROM Department_20190101 UNION ALL
    SELECT * FROM Department_20190109 UNION ALL
    SELECT * FROM Department_20190122 UNION ALL
    SELECT * FROM Department_20190129
)

And then use the CTE as:

SELECT *
FROM cte;

This assumes that all tables have identical structures.  Also, as a side note, if this be the case, you might want to consider just having a single table with a date column to differentiate between the otherwise common data.


问:
Select first row when there are multiple rows with repeated values in a column
I want to select the first row when there are multiple rows with repeated values in a column.

For example:

```<code>import pandas as pd
df = pd.DataFrame({'col1':['one', 'one', 'one', 'one', 'one', 'one', 'one', 'one'],
                   'col2':['ID=ABCD1234', 'ID=ABCD1234', 'ID=ABCD1234', 'ID=ABCD5678',
                           'ID=ABCD5678', 'ID=ABCD5678', 'ID=ABCD9102', 'ID=ABCD9102']})
</code>```

The pandas dataframe looks like this:

```<code>print(df)
  col1         col2
0  one  ID=ABCD1234
1  one  ID=ABCD1234
2  one  ID=ABCD1234
3  one  ID=ABCD5678
4  one  ID=ABCD5678
5  one  ID=ABCD5678
6  one  ID=ABCD9102
7  one  ID=ABCD9102
</code>```

I want the row 0, row 3, and row 6 to be selected and output as a new dataframe.

Expected output:

```<code>      col1         col2
    0  one  ID=ABCD1234
    3  one  ID=ABCD5678
    6  one  ID=ABCD9102
</code>```

答:
Simply group by the values of the row and use first() to pick the first row:

```<code>df.groupby('col2').first()
</code>```

You might decide to group by multiple columns too:

```<code>df.groupby(['col1', 'col2']).first()
</code>```

Body:
I want to select the first row when there are multiple rows with repeated values in a column.

For example:

import pandas as pd
df = pd.DataFrame({'col1':['one', 'one', 'one', 'one', 'one', 'one', 'one', 'one'],
                   'col2':['ID=ABCD1234', 'ID=ABCD1234', 'ID=ABCD1234', 'ID=ABCD5678',
                           'ID=ABCD5678', 'ID=ABCD5678', 'ID=ABCD9102', 'ID=ABCD9102']})

The pandas dataframe looks like this:

print(df)
  col1         col2
0  one  ID=ABCD1234
1  one  ID=ABCD1234
2  one  ID=ABCD1234
3  one  ID=ABCD5678
4  one  ID=ABCD5678
5  one  ID=ABCD5678
6  one  ID=ABCD9102
7  one  ID=ABCD9102

I want the row 0, row 3, and row 6 to be selected and output as a new dataframe.

Expected output:

      col1         col2
    0  one  ID=ABCD1234
    3  one  ID=ABCD5678
    6  one  ID=ABCD9102

Body:
Simply group by the values of the row and use first() to pick the first row:

df.groupby('col2').first()

You might decide to group by multiple columns too:

df.groupby(['col1', 'col2']).first()


问:
To add Life to date measures with a date slicer on the report
I am facing this issue in understanding how to add a measure Amount LTD which looks back to all the data for projects since its start.
I am able to give total amounts per project between the dates on the data slicer but unable to get Amount which looks back beyond the data filters applied and get the LTD sum value till the to date selected on the date slicer.
Can someone please help.
TIA.</p>

答:
See this Cumulative Total pattern. </p>

<blockquote>
```<code>Cumulative Quantity :=
CALCULATE (
    SUM ( Transactions[Quantity] ),
    FILTER (
        ALL ( 'Date'[Date] ),
        'Date'[Date] <= MAX ( 'Date'[Date] )
    )
)
</code>```
</blockquote>

Body:
See this Cumulative Total pattern.

Cumulative Quantity :=
CALCULATE (
    SUM ( Transactions[Quantity] ),
    FILTER (
        ALL ( 'Date'[Date] ),
        'Date'[Date] <= MAX ( 'Date'[Date] )
    )
)


问:
sending email using codeigniter email class
i have an error by trying to send an email using codeigniter email Class.

I have an error of :
Failed to connect to mailserver at "localhost" port 25, verify your "SMTP" and "smtp_port" setting in php.ini or use ini_set()

How can i test to send email in codeigniter?. I am also using localhost. Is this problem only occurs when i use localhost?

Here is my code:

```<code>public function emailme() {
        $this->load->library('email');
        $message = $this->input->post('email_msg');
        $this->email->from('iamjohnx3303@yahoo.com', 'John');
        $this->email->to('iamjohnx3302@gmail.com');
        $this->email->subject('Email Test');
        $this->email->message($message);
        $this->email->send();
    }
</code>```

答:
Use this before your send mail script</p>

```<code>// Please specify your Mail Server - Example: mail.yourdomain.com.
ini_set("SMTP","mail.YourDomain.com");

// Please specify an SMTP Number 25 and 8889 are valid SMTP Ports.
ini_set("smtp_port","25");

// Please specify the return address to use
ini_set('sendmail_from', 'ValidEmailAccount@YourDomain.com');
</code>```

Body:
i have an error by trying to send an email using codeigniter email Class.

I have an error of :
Failed to connect to mailserver at "localhost" port 25, verify your "SMTP" and "smtp_port" setting in php.ini or use ini_set()

How can i test to send email in codeigniter?. I am also using localhost. Is this problem only occurs when i use localhost?

Here is my code:

public function emailme() {
        $this->load->library('email');
        $message = $this->input->post('email_msg');
        $this->email->from('iamjohnx3303@yahoo.com', 'John');
        $this->email->to('iamjohnx3302@gmail.com');
        $this->email->subject('Email Test');
        $this->email->message($message);
        $this->email->send();
    }

Body:
Use this before your send mail script

// Please specify your Mail Server - Example: mail.yourdomain.com.
ini_set("SMTP","mail.YourDomain.com");

// Please specify an SMTP Number 25 and 8889 are valid SMTP Ports.
ini_set("smtp_port","25");

// Please specify the return address to use
ini_set('sendmail_from', 'ValidEmailAccount@YourDomain.com');


问:
Range function is not working properly in jupyter notebook

for i in range():
    for j in range(i):
        print("*",end = " ")
    print()
```
<p>Error:</p>
<pre class="lang-none prettyprint-override"><code>TypeError
Traceback (most recent call last) <ipython-input-81-6bc40b03c32e> in <module>
----> 1 for i in range():
      2     for j in range(i):
      3         print("*",end = " ")
      4     print()
      5

TypeError: 'int' object is not callable
</code>```

答:
You have to pass an int  parameter in range() just the way you did in the second for loop. like, range(10).

```<code>for i in range(10):
    for j in range(i):
        print("*",end = " ")
    print()
</code>```

Body:
for i in range():
    for j in range(i):
        print("*",end = " ")
    print()

Error:

TypeError
Traceback (most recent call last) <ipython-input-81-6bc40b03c32e> in <module>
----> 1 for i in range():
      2     for j in range(i):
      3         print("*",end = " ")
      4     print()
      5

TypeError: 'int' object is not callable

Body:
You have to pass an int  parameter in range() just the way you did in the second for loop. like, range(10).

for i in range(10):
    for j in range(i):
        print("*",end = " ")
    print()


问:
How to disable button and change color if the time is expire
PHP Code:

```<code><?php
include 'security.php';

$mysqli = new mysqli('localhost', 'root', '', 'halcondentalclinic');
if (isset($_GET['date'])) {
    $date = $_GET['date'];
    $stmt = $mysqli->prepare("select * from bookings where dates = ?");
    $stmt->bind_param('s', $date);
    $bookings = array();
    if ($stmt->execute()) {
        $result = $stmt->get_result();
        if ($result->num_rows > 0) {
            while ($row = $result->fetch_assoc()) {
                $bookings[] = $row['timeslot'];
            }

            $stmt->close();
        }
    }
}

$duration = 30;
$cleanup = 00;
$start = "9:00";
$end = "16:00";
function timeslots($duration, $cleanup, $start, $end)
{
    $start = new DateTime($start);
    $end = new DateTime($end);
    $interval = new DateInterval("PT" . $duration . "M");
    $cleanupinterval = new DateInterval("PT" . $cleanup . "M");
    $slots = array();
    for ($intStart = $start; $intStart < $end; $intStart->add($interval)->add($cleanupinterval)) {
        $endPeriod = clone $intStart;
        $endPeriod->add($interval);
        if ($endPeriod > $end) {
            break;
        }
        $slots[] = $intStart->format("H:iA") . "-" . $endPeriod->format("H:iA");
    }

    return $slots;
}

?>
</code>```

html and php

```<code><div class="container">
    <h1 class="text-center">Book for Date: <?php echo date('m/d/Y', strtotime($date)); ?></h1>
    <hr>
    <div class="row">
        <div class="col-md-12">
            <?php echo isset($msg) ? $msg : ""; ?>

        </div>
        <?php $timeslots = timeslots($duration, $cleanup, $start, $end);
        foreach ($timeslots as $ts) {

            ?>
            <div class="col-md-2">

                <div class="form-group">
                    <?php if (in_array($ts, $bookings)) { ?>
                        <button class="btn btn-danger"><?php echo $ts; ?></button>
                    <?php } else { ?>
                        <button class="btn btn-success book"
                                data-timeslot="<?php echo $ts; ?>"><?php echo $ts; ?></button>
                    <?php } ?>

                </div>

            </div>
            <?php

        } ?>
    </div>
</div>
</code>```

This is the appointment system I want if the date is already past the button for the calendar time change to red and become disabled. For example, 9:00 am - 9:30 am so if the date is already 12:00 pm the 9:00 am - 9:30 become disabled

It is possible to do it? Sorry I am a beginner in PHP and MySQL.

答:
I am not Php developer but as I see you can define a php function to check time is past

```<code>function isPastTime($time){
 // check $time is past
}
</code>```

And when you render view, you can add class to remark past booking

```<code><?php if(isPastTime){ ?>

<button class="btn btn-past"><?php echo $ts;?></button>
.btn-past {
  color: red;
  pointer-events: none;
}
</code>```

It is my advise. Hope you can resolve it.

Body:
PHP Code:

<?php
include 'security.php';

$mysqli = new mysqli('localhost', 'root', '', 'halcondentalclinic');
if (isset($_GET['date'])) {
    $date = $_GET['date'];
    $stmt = $mysqli->prepare("select * from bookings where dates = ?");
    $stmt->bind_param('s', $date);
    $bookings = array();
    if ($stmt->execute()) {
        $result = $stmt->get_result();
        if ($result->num_rows > 0) {
            while ($row = $result->fetch_assoc()) {
                $bookings[] = $row['timeslot'];
            }

            $stmt->close();
        }
    }
}

$duration = 30;
$cleanup = 00;
$start = "9:00";
$end = "16:00";
function timeslots($duration, $cleanup, $start, $end)
{
    $start = new DateTime($start);
    $end = new DateTime($end);
    $interval = new DateInterval("PT" . $duration . "M");
    $cleanupinterval = new DateInterval("PT" . $cleanup . "M");
    $slots = array();
    for ($intStart = $start; $intStart < $end; $intStart->add($interval)->add($cleanupinterval)) {
        $endPeriod = clone $intStart;
        $endPeriod->add($interval);
        if ($endPeriod > $end) {
            break;
        }
        $slots[] = $intStart->format("H:iA") . "-" . $endPeriod->format("H:iA");
    }

    return $slots;
}

?>

html and php

Book for Date: <?php echo date('m/d/Y', strtotime($date)); ?>

            <?php echo isset($msg) ? $msg : ""; ?>

        <?php $timeslots = timeslots($duration, $cleanup, $start, $end);
        foreach ($timeslots as $ts) {

            ?>

                    <?php if (in_array($ts, $bookings)) { ?>
                        <button class="btn btn-danger"><?php echo $ts; ?></button>
                    <?php } else { ?>
                        <button class="btn btn-success book"
                                data-timeslot="<?php echo $ts; ?>"><?php echo $ts; ?></button>
                    <?php } ?>

            <?php

        } ?>

This is the appointment system I want if the date is already past the button for the calendar time change to red and become disabled. For example, 9:00 am - 9:30 am so if the date is already 12:00 pm the 9:00 am - 9:30 become disabled

It is possible to do it? Sorry I am a beginner in PHP and MySQL.

Body:
I am not Php developer but as I see you can define a php function to check time is past

function isPastTime($time){
 // check $time is past
}

And when you render view, you can add class to remark past booking

<?php if(isPastTime){ ?>

<button class="btn btn-past"><?php echo $ts;?></button>
.btn-past {
  color: red;
  pointer-events: none;
}

It is my advise. Hope you can resolve it.


答:
You can use:</p>

```<code>df.drop_duplicates(subset = ['col2'], keep = 'first', inplace = True)
</code>```

Title: Select first row when there are multiple rows with repeated values in a column

Body:
You can use:

df.drop_duplicates(subset = ['col2'], keep = 'first', inplace = True)


问:
How to solve duplicate data in recyclerview
I get duplicate data items in the RecyclerView when data is retrieved.

I have tried some such like way NotifyDataSetChanged() and setHasStableIds (true). But still has not succeeded and I tried this way (How to solve duplicate data items in recyclerview) but still has not succeededed too.

```<code>private void loadFirstPage() {
    Log.d(TAG, "loadFirstPage: ");

    callTopRatedMoviesApi().enqueue(new Callback<JsonObject>() {
        @Override
        public void onResponse(Call<JsonObject> call, Response<JsonObject> response) {
            if (!response.isSuccessful()) {
                Log.e(TAG, "Response Error : " + response.code());
            } else {
                try {
                    JSONObject jsonObject = new JSONObject(response.body().toString());
                    JSONObject dataObject = jsonObject.getJSONObject("data");
                    JSONArray itemsObject = dataObject.getJSONArray("items");
                    modelGetProductSearchList = new ArrayList<>();
                    progressBar.setVisibility(View.GONE);

                    if (itemsObject.length() == 0) {
                        // Set GONE Visibility of TextView
                    } else {
                        for (int a = 0; a <= itemsObject.length(); a++) {
                            JSONObject object = itemsObject.getJSONObject(a);
                            ModelGetProductSearch modelGetProductSearch = new ModelGetProductSearch();
                            modelGetProductSearch.setId(object.getInt("id"));
                            modelGetProductSearch.setName(object.getString("name"));

                            JSONObject sourceObject = object.getJSONObject("source");
                            modelGetProductSearch.setSourceNames(sourceObject.getString("name"));

                            modelGetProductSearchList.add(modelGetProductSearch);
                            adapter.addAll(modelGetProductSearchList);
                            progressBar.setVisibility(View.GONE);
                            tvTidakAdaHasil.setVisibility(View.GONE);
                        }
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }

                if (currentPage <= TOTAL_PAGES && currentPage <= adapter.getItemCount()) adapter.addLoadingFooter();
                else isLastPage = true;
            }
        }

        @Override
        public void onFailure(Call<JsonObject> call, Throwable t) {
            Log.e(TAG, "onFailure: " + t.getMessage());
            tvTidakAdaHasil.setText("Maaf, cek koneksi internet anda dan coba kembali");
            progressBar.setVisibility(View.GONE);
        }
    });
}

private void loadNextPage() {
    Log.d(TAG, "loadNextPage: " + currentPage);

    callTopRatedMoviesApi().enqueue(new Callback<JsonObject>() {
        @Override
        public void onResponse(Call<JsonObject> call, Response<JsonObject> response) {
            adapter.removeLoadingFooter();
            isLoading = false;

            if (!response.isSuccessful()) {
                Log.e(TAG, "Response Error : " + response.code());
            } else {
                try {
                    JSONObject jsonObject = new JSONObject(response.body().toString());
                    JSONObject dataObject = jsonObject.getJSONObject("data");
                    JSONArray itemsObject = dataObject.getJSONArray("items");
                    modelGetProductSearchList = new ArrayList<>();
                    progressBar.setVisibility(View.GONE);

                    for (int a = 0; a <= itemsObject.length(); a++) {
                        JSONObject object = itemsObject.getJSONObject(a);
                        ModelGetProductSearch modelGetProductSearch = new ModelGetProductSearch();
                        modelGetProductSearch.setId(object.getInt("id"));
                        modelGetProductSearch.setName(object.getString("name"));

                        JSONObject sourceObject = object.getJSONObject("source");
                        modelGetProductSearch.setSourceNames(sourceObject.getString("name"));

                        modelGetProductSearchList.add(modelGetProductSearch);
                        adapter.addAll(modelGetProductSearchList);
                        progressBar.setVisibility(View.GONE);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }

                if (currentPage != TOTAL_PAGES && currentPage <= adapter.getItemCount()) adapter.addLoadingFooter();
                else isLastPage = true;
            }
        }

        @Override
        public void onFailure(Call<JsonObject> call, Throwable t) {
            Log.e(TAG, "onFailure: " + t.getMessage());
            tvTidakAdaHasil.setText("Maaf, cek koneksi internet anda dan coba kembali");
            progressBar.setVisibility(View.GONE);
        }
    });
}
</code>```

and this is my adapter

```<code>public class AdapterDetailSearch extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
    private static final int ITEM = 0;
    private static final int LOADING = 1;

    private List<ModelGetProductSearch> modelGetProductSearchList;
    private Context context;

    private boolean isLoadingAdded = false;

    public AdapterDetailSearch(Context context) {
        this.context = context;
        modelGetProductSearchList = new ArrayList<>();
    }

    public List<ModelGetProductSearch> getMovies() {
        return modelGetProductSearchList;
    }

    public void setMovies(List<ModelGetProductSearch> movieResults) {
        this.modelGetProductSearchList = movieResults;
    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        RecyclerView.ViewHolder viewHolder = null;
        LayoutInflater inflater = LayoutInflater.from(parent.getContext());

        switch (viewType) {
            case ITEM:
                viewHolder = getViewHolder(parent, inflater);
                break;
            case LOADING:
                View v2 = inflater.inflate(R.layout.row_item_progress, parent, false);
                viewHolder = new LoadingVH(v2);
                break;
        }
        return viewHolder;
    }

    @NonNull
    private RecyclerView.ViewHolder getViewHolder(ViewGroup parent, LayoutInflater inflater) {
        RecyclerView.ViewHolder viewHolder;
        View viewHolder = inflater.inflate(R.layout.row_item_detail_list, parent, false);
        return new MovieVH(viewHolder);
    }

    @Override
    public void onBindViewHolder(final RecyclerView.ViewHolder holder, final int position) {

        final ModelGetProductSearch result = modelGetProductSearchList.get(position);

        switch (getItemViewType(position)) {
            case ITEM:
                final MovieVH itemsListVH = (MovieVH) holder;

                // Visible and Invisible set TextView
        }
    }

    @Override
    public int getItemCount() {
        return modelGetProductSearchList == null ? 0 : modelGetProductSearchList.size();
    }

    @Override
    public int getItemViewType(int position) {
        return (position == modelGetProductSearchList.size() - 1 && isLoadingAdded) ? LOADING : ITEM;
    }

   /*
   Helpers
   _________________________________________________________________________________________________
   */

    public void add(ModelGetProductSearch r) {
        modelGetProductSearchList.add(r);
        notifyItemInserted(modelGetProductSearchList.size() - 1);
    }

    public void addAll(List<ModelGetProductSearch> moveResults) {
        for (ModelGetProductSearch result : moveResults) {
            add(result);
        }
    }

    public void remove(ModelGetProductSearch r) {
        int position = modelGetProductSearchList.indexOf(r);
        if (position > -1) {
            modelGetProductSearchList.remove(position);
            notifyItemRemoved(position);
        }
    }

    public void clear() {
        isLoadingAdded = false;
        while (getItemCount() > 0) {
            remove(getItem(0));
        }
    }

    public boolean isEmpty() {
        return getItemCount() == 0;
    }

    public void addLoadingFooter() {
        isLoadingAdded = true;
        add(new ModelGetProductSearch());
    }

    public void removeLoadingFooter() {
        isLoadingAdded = false;

        int position = modelGetProductSearchList.size() - 1;
        ModelGetProductSearch result = getItem(position);

        if (result != null) {
            modelGetProductSearchList.remove(position);
            notifyItemRemoved(position);
        }
    }

    public ModelGetProductSearch getItem(int position) {
        return modelGetProductSearchList.get(position);
    }

   /*
   View Holders
   _________________________________________________________________________________________________
   */

    /**
     * Main list's content ViewHolder
     */
    protected class MovieVH extends RecyclerView.ViewHolder {
        private LinearLayout llContainer;
        private ImageView ivItem;
        private TextView tvItemTitle, tvPriceRegular, tvPriceAfterDiscount, textFrom;

        public MovieVH(View itemView) {
            super(itemView);

            llContainer = itemView.findViewById(R.id.container);
            ivItem = itemView.findViewById(R.id.iv_item);
            textFrom = itemView.findViewById(R.id.tv_from);
        }
    }

    protected class LoadingVH extends RecyclerView.ViewHolder {
        public LoadingVH(View itemView) {
            super(itemView);
        }
    }
}
</code>```

答:
You add the same list multiple times in your adapter inside for-loop that's why it creates duplication. Move adapter.addAll outside for loop like below:

```<code>if (itemsObject.length() == 0) {
    // Set GONE Visibility of TextView
} else {
    for (int a = 0; a < itemsObject.length(); a++) {
        ...

        //Remove from here
        /*adapter.addAll(modelGetProductSearchList);
        progressBar.setVisibility(View.GONE);
        tvTidakAdaHasil.setVisibility(View.GONE);*/
    }

    //Add list here
    adapter.addAll(modelGetProductSearchList);
    progressBar.setVisibility(View.GONE);
    tvTidakAdaHasil.setVisibility(View.GONE);
}
</code>```

Body:
I get duplicate data items in the RecyclerView when data is retrieved.

I have tried some such like way NotifyDataSetChanged() and setHasStableIds (true). But still has not succeeded and I tried this way (How to solve duplicate data items in recyclerview) but still has not succeededed too.

private void loadFirstPage() {
    Log.d(TAG, "loadFirstPage: ");

    callTopRatedMoviesApi().enqueue(new Callback<JsonObject>() {
        @Override
        public void onResponse(Call<JsonObject> call, Response<JsonObject> response) {
            if (!response.isSuccessful()) {
                Log.e(TAG, "Response Error : " + response.code());
            } else {
                try {
                    JSONObject jsonObject = new JSONObject(response.body().toString());
                    JSONObject dataObject = jsonObject.getJSONObject("data");
                    JSONArray itemsObject = dataObject.getJSONArray("items");
                    modelGetProductSearchList = new ArrayList<>();
                    progressBar.setVisibility(View.GONE);

                    if (itemsObject.length() == 0) {
                        // Set GONE Visibility of TextView
                    } else {
                        for (int a = 0; a <= itemsObject.length(); a++) {
                            JSONObject object = itemsObject.getJSONObject(a);
                            ModelGetProductSearch modelGetProductSearch = new ModelGetProductSearch();
                            modelGetProductSearch.setId(object.getInt("id"));
                            modelGetProductSearch.setName(object.getString("name"));

                            JSONObject sourceObject = object.getJSONObject("source");
                            modelGetProductSearch.setSourceNames(sourceObject.getString("name"));

                            modelGetProductSearchList.add(modelGetProductSearch);
                            adapter.addAll(modelGetProductSearchList);
                            progressBar.setVisibility(View.GONE);
                            tvTidakAdaHasil.setVisibility(View.GONE);
                        }
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }

                if (currentPage <= TOTAL_PAGES && currentPage <= adapter.getItemCount()) adapter.addLoadingFooter();
                else isLastPage = true;
            }
        }

        @Override
        public void onFailure(Call<JsonObject> call, Throwable t) {
            Log.e(TAG, "onFailure: " + t.getMessage());
            tvTidakAdaHasil.setText("Maaf, cek koneksi internet anda dan coba kembali");
            progressBar.setVisibility(View.GONE);
        }
    });
}

private void loadNextPage() {
    Log.d(TAG, "loadNextPage: " + currentPage);

    callTopRatedMoviesApi().enqueue(new Callback<JsonObject>() {
        @Override
        public void onResponse(Call<JsonObject> call, Response<JsonObject> response) {
            adapter.removeLoadingFooter();
            isLoading = false;

            if (!response.isSuccessful()) {
                Log.e(TAG, "Response Error : " + response.code());
            } else {
                try {
                    JSONObject jsonObject = new JSONObject(response.body().toString());
                    JSONObject dataObject = jsonObject.getJSONObject("data");
                    JSONArray itemsObject = dataObject.getJSONArray("items");
                    modelGetProductSearchList = new ArrayList<>();
                    progressBar.setVisibility(View.GONE);

                    for (int a = 0; a <= itemsObject.length(); a++) {
                        JSONObject object = itemsObject.getJSONObject(a);
                        ModelGetProductSearch modelGetProductSearch = new ModelGetProductSearch();
                        modelGetProductSearch.setId(object.getInt("id"));
                        modelGetProductSearch.setName(object.getString("name"));

                        JSONObject sourceObject = object.getJSONObject("source");
                        modelGetProductSearch.setSourceNames(sourceObject.getString("name"));

                        modelGetProductSearchList.add(modelGetProductSearch);
                        adapter.addAll(modelGetProductSearchList);
                        progressBar.setVisibility(View.GONE);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }

                if (currentPage != TOTAL_PAGES && currentPage <= adapter.getItemCount()) adapter.addLoadingFooter();
                else isLastPage = true;
            }
        }

        @Override
        public void onFailure(Call<JsonObject> call, Throwable t) {
            Log.e(TAG, "onFailure: " + t.getMessage());
            tvTidakAdaHasil.setText("Maaf, cek koneksi internet anda dan coba kembali");
            progressBar.setVisibility(View.GONE);
        }
    });
}

and this is my adapter

public class AdapterDetailSearch extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
    private static final int ITEM = 0;
    private static final int LOADING = 1;

    private List<ModelGetProductSearch> modelGetProductSearchList;
    private Context context;

    private boolean isLoadingAdded = false;

    public AdapterDetailSearch(Context context) {
        this.context = context;
        modelGetProductSearchList = new ArrayList<>();
    }

    public List<ModelGetProductSearch> getMovies() {
        return modelGetProductSearchList;
    }

    public void setMovies(List<ModelGetProductSearch> movieResults) {
        this.modelGetProductSearchList = movieResults;
    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        RecyclerView.ViewHolder viewHolder = null;
        LayoutInflater inflater = LayoutInflater.from(parent.getContext());

        switch (viewType) {
            case ITEM:
                viewHolder = getViewHolder(parent, inflater);
                break;
            case LOADING:
                View v2 = inflater.inflate(R.layout.row_item_progress, parent, false);
                viewHolder = new LoadingVH(v2);
                break;
        }
        return viewHolder;
    }

    @NonNull
    private RecyclerView.ViewHolder getViewHolder(ViewGroup parent, LayoutInflater inflater) {
        RecyclerView.ViewHolder viewHolder;
        View viewHolder = inflater.inflate(R.layout.row_item_detail_list, parent, false);
        return new MovieVH(viewHolder);
    }

    @Override
    public void onBindViewHolder(final RecyclerView.ViewHolder holder, final int position) {

        final ModelGetProductSearch result = modelGetProductSearchList.get(position);

        switch (getItemViewType(position)) {
            case ITEM:
                final MovieVH itemsListVH = (MovieVH) holder;

                // Visible and Invisible set TextView
        }
    }

    @Override
    public int getItemCount() {
        return modelGetProductSearchList == null ? 0 : modelGetProductSearchList.size();
    }

    @Override
    public int getItemViewType(int position) {
        return (position == modelGetProductSearchList.size() - 1 && isLoadingAdded) ? LOADING : ITEM;
    }

   /*
   Helpers
   _________________________________________________________________________________________________
   */

    public void add(ModelGetProductSearch r) {
        modelGetProductSearchList.add(r);
        notifyItemInserted(modelGetProductSearchList.size() - 1);
    }

    public void addAll(List<ModelGetProductSearch> moveResults) {
        for (ModelGetProductSearch result : moveResults) {
            add(result);
        }
    }

    public void remove(ModelGetProductSearch r) {
        int position = modelGetProductSearchList.indexOf(r);
        if (position > -1) {
            modelGetProductSearchList.remove(position);
            notifyItemRemoved(position);
        }
    }

    public void clear() {
        isLoadingAdded = false;
        while (getItemCount() > 0) {
            remove(getItem(0));
        }
    }

    public boolean isEmpty() {
        return getItemCount() == 0;
    }

    public void addLoadingFooter() {
        isLoadingAdded = true;
        add(new ModelGetProductSearch());
    }

    public void removeLoadingFooter() {
        isLoadingAdded = false;

        int position = modelGetProductSearchList.size() - 1;
        ModelGetProductSearch result = getItem(position);

        if (result != null) {
            modelGetProductSearchList.remove(position);
            notifyItemRemoved(position);
        }
    }

    public ModelGetProductSearch getItem(int position) {
        return modelGetProductSearchList.get(position);
    }

   /*
   View Holders
   _________________________________________________________________________________________________
   */

    /**
     * Main list's content ViewHolder
     */
    protected class MovieVH extends RecyclerView.ViewHolder {
        private LinearLayout llContainer;
        private ImageView ivItem;
        private TextView tvItemTitle, tvPriceRegular, tvPriceAfterDiscount, textFrom;

        public MovieVH(View itemView) {
            super(itemView);

            llContainer = itemView.findViewById(R.id.container);
            ivItem = itemView.findViewById(R.id.iv_item);
            textFrom = itemView.findViewById(R.id.tv_from);
        }
    }

    protected class LoadingVH extends RecyclerView.ViewHolder {
        public LoadingVH(View itemView) {
            super(itemView);
        }
    }
}

Body:
You add the same list multiple times in your adapter inside for-loop that's why it creates duplication. Move adapter.addAll outside for loop like below:

if (itemsObject.length() == 0) {
    // Set GONE Visibility of TextView
} else {
    for (int a = 0; a < itemsObject.length(); a++) {
        ...

        //Remove from here
        /*adapter.addAll(modelGetProductSearchList);
        progressBar.setVisibility(View.GONE);
        tvTidakAdaHasil.setVisibility(View.GONE);*/
    }

    //Add list here
    adapter.addAll(modelGetProductSearchList);
    progressBar.setVisibility(View.GONE);
    tvTidakAdaHasil.setVisibility(View.GONE);
}


问:
Is it possible to train data on 4 features and test on only using features?
I have done training on four features including Month, day, Hour and Temperature which is predicting some value , what i wan to do is to predict value on basis of month ,hour and day of next day only because i don't know the temp of next day(which is going to be unseen data not used in training) so this makes the testing of data using only 3 features.
Classifier used is SVR.
I am a beginner in machine learning.

Your response will be appreciated

答:
This is pretty obvious, you will not be having the dependent variable in your test set/real production set(after deployment in generic case).
Hence, while training you can divide your dataset into train and test, example:
df_x = df[:-1] (Independent variables)
df_y = df[-1] (Dependent variable, temperature in your case)
Now you can divide this in train and test (for basic use ratios in train_test_split), and train on train set and predict on test set.
Reference: https://medium.com/@contactsunny/how-to-split-your-dataset-to-train-and-test-datasets-using-scikit-learn-e7cf6eb5e0d
Hope this helps!</p>


问:
setNeedsDisplay not working?
I have a problem redrawing a custom view in simple cocoa application. Drawing is based on one parameter that is being changed by a simple NSSlider. However, although i implement -setParameter: and -parameter methods and bind slider's value to that parameter in interface builder i cannot seem to make a custom view to redraw itself.

The code that does redrawing is like this:

```<code>- (void)setParameter:(int)newParameter {
  parameter = newParamter;
  NSLog(@"Updated parameter: %d", parameter);
  [self setNeedsDisplay:YES];
}
</code>```

I DO get the message about setting the new parameter although the view doesn't redraw itself. Any ideas are welcome!

答:
Sometimes reason can be very simple: File's owner has no connection to UIView object. i.e. it's Outlet is not setup properly.
Use IB, ctrl button and drag method :) </p>

OwnerDisplayName: Eimantas

Title: setNeedsDisplay not working?

Body:
I have a problem redrawing a custom view in simple cocoa application. Drawing is based on one parameter that is being changed by a simple NSSlider. However, although i implement -setParameter: and -parameter methods and bind slider's value to that parameter in interface builder i cannot seem to make a custom view to redraw itself.

The code that does redrawing is like this:

- (void)setParameter:(int)newParameter {
  parameter = newParamter;
  NSLog(@"Updated parameter: %d", parameter);
  [self setNeedsDisplay:YES];
}

I DO get the message about setting the new parameter although the view doesn't redraw itself. Any ideas are welcome!

LastEditorDisplayName: Eimantas


问:
missing } after property list error in javascript
I am encountering the above mentioned error, I wonder why it is popping up. All my curly brackets are correct as far as I see. Given below is the code segment:

```<code>var mapped = data.map(d => {

    return {
        date: d.date;
        value: d.count;
    }
});
</code>```

The console is pointing to this line:

```<code>date: d.date;
</code>```

I wonder why this is popping up. Any help is appreciated. thanks!

答:
You have incorrectly used semicolon within objects.

The properties within an object should be separated using commas.

var data = [];

var mapped = data.map(d => {

    return {
        date: d.date, // here you used `;` instead of comma
        value: d.count
    }
});```

Body:
I am encountering the above mentioned error, I wonder why it is popping up. All my curly brackets are correct as far as I see. Given below is the code segment:

var mapped = data.map(d => {

    return {
        date: d.date;
        value: d.count;
    }
});

The console is pointing to this line:

date: d.date;

I wonder why this is popping up. Any help is appreciated. thanks!