问:
Reset Recycler view decoration with diff utils
I have a grid recycler view that I update using diff utils, but if something in the list data causes an item to go from any row below the first row, up to the first row then the decoration lacks padding top, this is kind of expected as I'm only adding padding to the top of an item in the list if it is in the first row. I then add bottom padding to every item,

Recycler View Decoration

```<code>    public class GridSpacing extends RecyclerView.ItemDecoration {
        private final int spacing;
        private final int numColumns;

        public  GridSpacing(int spacing, int numColumns) {
            this.spacing = spacing;
            this.numColumns = numColumns;
        }

        @Override
        public void getItemOffsets(@NonNull Rect outRect, @NonNull View view, @NonNull RecyclerView parent, @NonNull RecyclerView.State state) {

            int position = parent.getChildLayoutPosition(view);

            if (position < numColumns){
                outRect.top = spacing;
            }

            if (position % 2 != 0) {
                outRect.right = spacing;
            }

            outRect.left = spacing;
            outRect.bottom = spacing;

        }
    }
</code>```

If I call notifyDatasetChanged, this will recalculate my decoration and add the padding to the top row, but diff utils is not calling notifyDatasetChanged (think it calls a combination of item range changed, item inserted, item removed, to keep animations) so my decoration doesn't get reapplied, I could probably reapply it myself but that seems like a hack to have to remove and reapply the decoration every time an item changes, does anyone know of a better approach?

答:
so instead of trying to reapply the decorator I'm going to remove the padding top in the decorator and instead add padding to the top and clip to padding false on the recycler view</p>

```<code>  <androidx.recyclerview.widget.RecyclerView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:paddingTop="8dp"
        android:clipToPadding="false"
        android:id="@+id/recyclerView"/>
</code>```

Body:
I have a grid recycler view that I update using diff utils, but if something in the list data causes an item to go from any row below the first row, up to the first row then the decoration lacks padding top, this is kind of expected as I'm only adding padding to the top of an item in the list if it is in the first row. I then add bottom padding to every item,

Recycler View Decoration

    public class GridSpacing extends RecyclerView.ItemDecoration {
        private final int spacing;
        private final int numColumns;

        public  GridSpacing(int spacing, int numColumns) {
            this.spacing = spacing;
            this.numColumns = numColumns;
        }

        @Override
        public void getItemOffsets(@NonNull Rect outRect, @NonNull View view, @NonNull RecyclerView parent, @NonNull RecyclerView.State state) {

            int position = parent.getChildLayoutPosition(view);

            if (position < numColumns){
                outRect.top = spacing;
            }

            if (position % 2 != 0) {
                outRect.right = spacing;
            }

            outRect.left = spacing;
            outRect.bottom = spacing;

        }
    }

If I call notifyDatasetChanged, this will recalculate my decoration and add the padding to the top row, but diff utils is not calling notifyDatasetChanged (think it calls a combination of item range changed, item inserted, item removed, to keep animations) so my decoration doesn't get reapplied, I could probably reapply it myself but that seems like a hack to have to remove and reapply the decoration every time an item changes, does anyone know of a better approach?

Body:
so instead of trying to reapply the decorator I'm going to remove the padding top in the decorator and instead add padding to the top and clip to padding false on the recycler view

  <androidx.recyclerview.widget.RecyclerView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:paddingTop="8dp"
        android:clipToPadding="false"
        android:id="@+id/recyclerView"/>


来源: stackexchange

问:
Set-up PHP SOAP Extension in Windows
I'm having a lot of confusions on how to set up PHP SOAP extension in windows based on what's on the net.

Could you please help me, how would I be able to do it?

Any suggested references?

答:
open php.ini file in your text editor.

Find
;extension=soap

Remove ;

Save changes

Start the server again.

ContentLicense: CC BY-SA 3.0

Title: Set-up PHP SOAP Extension in Windows

ContentLicense: CC BY-SA 4.0


问:
How to use an instance method in a where clause
In my Category model I have an instance method that adds up all the price averages for all products within a category:

```<code>def price_average(store_id)
  products.pluck(:price_average).map { |h| h[store_id] }.sum
end
</code>```

In my Category controller I am trying to use a filter to only show categories where the price_average is above a specific amount. How can I do this?

My main challenge here is that price_average is not a column name so doing something like @categories.where("price_average('1') > 1000") just fails.

The structure of the models goes something like this:

```<code>class Category < ApplicationRecord
    # t.string "name"
    # t.datetime "created_at", precision: 6, null: false
    # t.datetime "updated_at", precision: 6, null: false

    has_and_belongs_to_many :products
    has_many :prices, through: :products

    def price_average(store_id)
      products.pluck(:price_average).map { |h| h[store_id] }.sum
    end
end

class Product < ApplicationRecord
    # t.string "name"
    # t.datetime "created_at", precision: 6, null: false
    # t.datetime "updated_at", precision: 6, null: false
    # t.jsonb "price_average", default: {}

    has_and_belongs_to_many :categories
    has_many :prices

end
</code>```

In the price_average column I'm storing json where store_id is the index used to retrieve the value.

答:
you can add a column in your categories table called price_average and update it every time you add a product in a category or remove a product from a category then you can depend on this field after that.

note that this will save the processing time whenever you need to show an average more than you calculate it on runtime

Body:
In my Category model I have an instance method that adds up all the price averages for all products within a category:

def price_average(store_id)
  products.pluck(:price_average).map { |h| h[store_id] }.sum
end

In my Category controller I am trying to use a filter to only show categories where the price_average is above a specific amount. How can I do this?

My main challenge here is that price_average is not a column name so doing something like @categories.where("price_average('1') > 1000") just fails.

The structure of the models goes something like this:

class Category < ApplicationRecord
    # t.string "name"
    # t.datetime "created_at", precision: 6, null: false
    # t.datetime "updated_at", precision: 6, null: false

    has_and_belongs_to_many :products
    has_many :prices, through: :products

    def price_average(store_id)
      products.pluck(:price_average).map { |h| h[store_id] }.sum
    end
end

class Product < ApplicationRecord
    # t.string "name"
    # t.datetime "created_at", precision: 6, null: false
    # t.datetime "updated_at", precision: 6, null: false
    # t.jsonb "price_average", default: {}

    has_and_belongs_to_many :categories
    has_many :prices

end

In the price_average column I'm storing json where store_id is the index used to retrieve the value.


问:
Manage window redimension
I'm currently developing a toolbar, but i'm having a problem with something.
Well the think is that if my window is on full screen everything is ok, but when the windows is redimensioned, then my buttons go on the bottom line of my toolbar...

Something important is that my toolbar have a height of 20px. So normally button can't go farther then 20px

Somebody know how i can fix this bug ?

yourToolbar Code:

CSS Code :

```<code>.yourToolbarBody
{
    height: 20px;
    -webkit-user-select: none;
}

body
{
    /* This step is to escape all the top css style from body webpage */
    position: fixed;
    width: 100%;
    height: 100%;

    /* Then reset it to relative to show the scrollbar */
    position:relative;
}

a
{
    margin-left: 4px;
    float: left;
}

.button
{
    position:relative;
    float: left;

    top: -3px;

    border-radius: 3px;
    font-family: Verdana, Geneva, Arial, Helvetica, sans-serif;
    border-width: thin;
    padding-bottom: 2px;
    padding-top: 2px;

    display: inline-block;
    outline: none;
    cursor: pointer;
    text-shadow: 0 1px 1px rgba(0,0,0,.5);

    -webkit-box-shadow: 0 1px 2px rgba(0,0,0,.2);
    -moz-box-shadow: 0 1px 2px rgba(0,0,0,.2);
    box-shadow: 0 1px 2px rgba(0,0,0,.2);
    color: #000;
    border: solid 1px #000;
}

button label
{
    vertical-align: super;
    cursor: pointer;
}

#clear
{
    clear: both;
    display: none;
}

#closeButton
{
    float: right;
}

#closeButton a
{
    padding-left: 30px;
    background-image: url(../images/close.png);
    background-repeat: no-repeat;
}

#dropMenu
{
    top: 39px;
    left: 0;
    overflow: hidden;
    /*background-color: #E5E5E5;*/
    margin: 0;
    padding: 0;
    position: fixed; !To do not move the toolbar when scrolling
    border: none;
    /*-webkit-box-sizing: content-box;*/
    z-index: 99999999;
    border-radius: 0 0 6px 6px;

    background: #ffffff;
    background: -webkit-gradient(linear, left top, left bottom, from(#ffffff), to(#E5E5E5));
    background: -moz-linear-gradient(top, #ffffff, #E5E5E5);
    filter: progid:DXImageTransform.Microsoft.gradient(startColorstr="#ffffff", endColorstr="#E5E5E5");
}

.dropMenuButton input
{
    vertical-align : super;
    padding-left : 2px;
    padding-right : 2px;
}

.dropMenuButton
{
    position:relative;
    float: left;

    top: -1px;

    height: 20px;

    border-radius: 3px;
    font-family: Verdana, Geneva, Arial, Helvetica, sans-serif;
    border-width: thin;
    padding-bottom: 2px;
    padding-top: 2px;

    display: inline-block;
    outline: none;
    cursor: pointer;
    text-shadow: 0 1px 1px rgba(0,0,0,.5);

    -webkit-box-shadow: 0 1px 2px rgba(0,0,0,.2);
    -moz-box-shadow: 0 1px 2px rgba(0,0,0,.2);
    box-shadow: 0 1px 2px rgba(0,0,0,.2);
    color: #000;
    border: solid 1px #000;

    text-decoration: none;
    display: inline-block;
    font-family: Verdana, Geneva, Arial, Helvetica, sans-serif;
    font-size: 80%;

    background: white;
    background: -webkit-gradient(linear, left top, left bottom, from(white), to(#D7D7D7));
    background: -moz-linear-gradient(top, white, #D7D7D7);
    filter: progid:DXImageTransform.Microsoft.gradient(startColorstr="white", endColorstr="#D7D7D7");
}

.dropMenuButton:hover
{
    background: #D7D7D7;
    background: -webkit-gradient(linear, left top, left bottom, from(#D7D7D7), to(white));
    background: -moz-linear-gradient(top, #D7D7D7, white);
    filter: progid:DXImageTransform.Microsoft.gradient(startColorstr="#D7D7D7", endColorstr="white");
}

/* To center the text with the image */
.dropMenuLabel
{
    /* Changer Later */
    color: white;

    text-shadow: 0 1px 1px rgba(0,0,0,.5);
    cursor: pointer;
    padding: 0 5px 0 5px;
    vertical-align:super ;
}

/* To hide the border */
iframe
{
    border: 0px solid #ffffff;
}

input
{
    font-family: Verdana, Geneva, Arial, Helvetica, sans-serif;
}

.go
{
    cursor: pointer;
    margin-left: -4px;
    height: 24px;
}

.imageButton
{
    float: left;
}

.inButtonImage
{
    height: 15px;
}

#searchForm
{
    float: left;
    vertical-align: middle;
    margin-left: -3px;
}

#searchForm img
{
    margin-left : 10px;
    vertical-align: middle;
    margin-bottom: 2px;
}

#searchForm input
{
    vertical-align: middle;
}

.separator
{
    width: 1px;
    height: 16px;
    margin: 5px 3px 0;
    border-left: 1px solid #ABC6D7;
    background:#fff;
    float: left;
}

.textButton
{
    position:relative;
    float: left;
    cursor: pointer;

    top: -2px;
    margin-left: 4px;

    font-family: Verdana, Geneva, Arial, Helvetica, sans-serif;
    border-width: thin;
    padding-bottom: 2px;
    padding-top: 2px;
    border-style: none;
}

#YourToolbarFrame
{
    top: 0;
    left: 0;
    width: 100%;
    height: 39px;
    overflow: hidden;
    background-color: #E5E5E5;
    margin: 0;
    padding: 0;
    position: fixed;
    /*border: 1px solid #BDC8D6;*/
    border: none;
    -webkit-box-sizing: content-box;
    z-index: 99999999;
}
</code>```

答:
If you are using DIV as your way of positioning then you can set them to

```<code>.yourDivClass {
 float:left;
}
</code>```

or you could go with position:absolut if you now where to place them.

If you do this and your wrapper allows it then it will continue to add the divs to the right but it is realy hard to help without any sample code.

Title: Manage window redimension

Body:
I'm currently developing a toolbar, but i'm having a problem with something.
Well the think is that if my window is on full screen everything is ok, but when the windows is redimensioned, then my buttons go on the bottom line of my toolbar...

Something important is that my toolbar have a height of 20px. So normally button can't go farther then 20px

Somebody know how i can fix this bug ?

yourToolbar Code:

CSS Code :

.yourToolbarBody
{
    height: 20px;
    -webkit-user-select: none;
}

body
{
    /* This step is to escape all the top css style from body webpage */
    position: fixed;
    width: 100%;
    height: 100%;

    /* Then reset it to relative to show the scrollbar */
    position:relative;
}

a
{
    margin-left: 4px;
    float: left;
}

.button
{
    position:relative;
    float: left;

    top: -3px;

    border-radius: 3px;
    font-family: Verdana, Geneva, Arial, Helvetica, sans-serif;
    border-width: thin;
    padding-bottom: 2px;
    padding-top: 2px;

    display: inline-block;
    outline: none;
    cursor: pointer;
    text-shadow: 0 1px 1px rgba(0,0,0,.5);

    -webkit-box-shadow: 0 1px 2px rgba(0,0,0,.2);
    -moz-box-shadow: 0 1px 2px rgba(0,0,0,.2);
    box-shadow: 0 1px 2px rgba(0,0,0,.2);
    color: #000;
    border: solid 1px #000;
}

button label
{
    vertical-align: super;
    cursor: pointer;
}

#clear
{
    clear: both;
    display: none;
}

#closeButton
{
    float: right;
}

#closeButton a
{
    padding-left: 30px;
    background-image: url(../images/close.png);
    background-repeat: no-repeat;
}

#dropMenu
{
    top: 39px;
    left: 0;
    overflow: hidden;
    /*background-color: #E5E5E5;*/
    margin: 0;
    padding: 0;
    position: fixed; !To do not move the toolbar when scrolling
    border: none;
    /*-webkit-box-sizing: content-box;*/
    z-index: 99999999;
    border-radius: 0 0 6px 6px;

    background: #ffffff;
    background: -webkit-gradient(linear, left top, left bottom, from(#ffffff), to(#E5E5E5));
    background: -moz-linear-gradient(top, #ffffff, #E5E5E5);
    filter: progid:DXImageTransform.Microsoft.gradient(startColorstr="#ffffff", endColorstr="#E5E5E5");
}

.dropMenuButton input
{
    vertical-align : super;
    padding-left : 2px;
    padding-right : 2px;
}

.dropMenuButton
{
    position:relative;
    float: left;

    top: -1px;

    height: 20px;

    border-radius: 3px;
    font-family: Verdana, Geneva, Arial, Helvetica, sans-serif;
    border-width: thin;
    padding-bottom: 2px;
    padding-top: 2px;

    display: inline-block;
    outline: none;
    cursor: pointer;
    text-shadow: 0 1px 1px rgba(0,0,0,.5);

    -webkit-box-shadow: 0 1px 2px rgba(0,0,0,.2);
    -moz-box-shadow: 0 1px 2px rgba(0,0,0,.2);
    box-shadow: 0 1px 2px rgba(0,0,0,.2);
    color: #000;
    border: solid 1px #000;

    text-decoration: none;
    display: inline-block;
    font-family: Verdana, Geneva, Arial, Helvetica, sans-serif;
    font-size: 80%;

    background: white;
    background: -webkit-gradient(linear, left top, left bottom, from(white), to(#D7D7D7));
    background: -moz-linear-gradient(top, white, #D7D7D7);
    filter: progid:DXImageTransform.Microsoft.gradient(startColorstr="white", endColorstr="#D7D7D7");
}

.dropMenuButton:hover
{
    background: #D7D7D7;
    background: -webkit-gradient(linear, left top, left bottom, from(#D7D7D7), to(white));
    background: -moz-linear-gradient(top, #D7D7D7, white);
    filter: progid:DXImageTransform.Microsoft.gradient(startColorstr="#D7D7D7", endColorstr="white");
}

/* To center the text with the image */
.dropMenuLabel
{
    /* Changer Later */
    color: white;

    text-shadow: 0 1px 1px rgba(0,0,0,.5);
    cursor: pointer;
    padding: 0 5px 0 5px;
    vertical-align:super ;
}

/* To hide the border */
iframe
{
    border: 0px solid #ffffff;
}

input
{
    font-family: Verdana, Geneva, Arial, Helvetica, sans-serif;
}

.go
{
    cursor: pointer;
    margin-left: -4px;
    height: 24px;
}

.imageButton
{
    float: left;
}

.inButtonImage
{
    height: 15px;
}

#searchForm
{
    float: left;
    vertical-align: middle;
    margin-left: -3px;
}

#searchForm img
{
    margin-left : 10px;
    vertical-align: middle;
    margin-bottom: 2px;
}

#searchForm input
{
    vertical-align: middle;
}

.separator
{
    width: 1px;
    height: 16px;
    margin: 5px 3px 0;
    border-left: 1px solid #ABC6D7;
    background:#fff;
    float: left;
}

.textButton
{
    position:relative;
    float: left;
    cursor: pointer;

    top: -2px;
    margin-left: 4px;

    font-family: Verdana, Geneva, Arial, Helvetica, sans-serif;
    border-width: thin;
    padding-bottom: 2px;
    padding-top: 2px;
    border-style: none;
}

#YourToolbarFrame
{
    top: 0;
    left: 0;
    width: 100%;
    height: 39px;
    overflow: hidden;
    background-color: #E5E5E5;
    margin: 0;
    padding: 0;
    position: fixed;
    /*border: 1px solid #BDC8D6;*/
    border: none;
    -webkit-box-sizing: content-box;
    z-index: 99999999;
}

Body:
If you are using DIV as your way of positioning then you can set them to

.yourDivClass {
 float:left;
}

or you could go with position:absolut if you now where to place them.

If you do this and your wrapper allows it then it will continue to add the divs to the right but it is realy hard to help without any sample code.


问:
The method given() is undefined for the type PendingTransactionsTest
I am conducting my first Acceptance Test case using Junit in Eclipse.  The code below is not complete because I'm still working on it.  I ran into this error, however, and I am not sure how to solve it.

Error Type: The method given() is undefined for the type

Code:

```<code>package bns.so.unitTest;
import java.util.HashMap;
import java.util.Map;
import org.junit.Test;
import com.jayway.restassured.RestAssured;
import bns.so.models.PendingTransactionsRequestModel;
public class PendingTransactionsTest extends BaseUnitTest{

    Map<String, Object> mapBody = new HashMap<String, Object>();
    private static PendingTransactionsRequestModel transModel = new PendingTransactionsRequestModel();
    private static final String countryID = "ZZ";
    private static final String accountID = "2";
    private static final String customerID = "3";
    private static final String startDate = "2016-10-31 00:00:00";
    private static final String endDate = "2016-12-07 00:00:00";
    private static final String startAmount = "123123";
    private static final String endAmount = "200000";
    private static final String sortOption = "asc";
    private static final String sortOrder = "desc";
    private static final String numRecords = "1";
    private static final String lastRecordKey = "0";
    private static final String transType = "FundsTransfer";

    @Test
    public void accountIdTest(){
        mapBody = new HashMap<String, Object>();
        mapBody.put("accountID", PendingTransactionsTest.accountID);
        RestAssured.
        given().
        header("accountID", 2).
        contentType("application/json").
        body(mapBody).

    when().
        post("path").

    then().
        statusCode(200).
        //body("status.status", equals (0)).- doesn't work how do I reword this?
        body("status.reason", null);

}}
</code>```

答:
I have used "import static io.restassured.RestAssured.given;" and declare the variable as
"io.restassured.response.Response res;"</p>

Body:
I am conducting my first Acceptance Test case using Junit in Eclipse.  The code below is not complete because I'm still working on it.  I ran into this error, however, and I am not sure how to solve it.

Error Type: The method given() is undefined for the type

Code:

package bns.so.unitTest;
import java.util.HashMap;
import java.util.Map;
import org.junit.Test;
import com.jayway.restassured.RestAssured;
import bns.so.models.PendingTransactionsRequestModel;
public class PendingTransactionsTest extends BaseUnitTest{

    Map<String, Object> mapBody = new HashMap<String, Object>();
    private static PendingTransactionsRequestModel transModel = new PendingTransactionsRequestModel();
    private static final String countryID = "ZZ";
    private static final String accountID = "2";
    private static final String customerID = "3";
    private static final String startDate = "2016-10-31 00:00:00";
    private static final String endDate = "2016-12-07 00:00:00";
    private static final String startAmount = "123123";
    private static final String endAmount = "200000";
    private static final String sortOption = "asc";
    private static final String sortOrder = "desc";
    private static final String numRecords = "1";
    private static final String lastRecordKey = "0";
    private static final String transType = "FundsTransfer";

    @Test
    public void accountIdTest(){
        mapBody = new HashMap<String, Object>();
        mapBody.put("accountID", PendingTransactionsTest.accountID);
        RestAssured.
        given().
        header("accountID", 2).
        contentType("application/json").
        body(mapBody).

    when().
        post("path").

    then().
        statusCode(200).
        //body("status.status", equals (0)).- doesn't work how do I reword this?
        body("status.reason", null);

}}


问:
Behaviors.same vs this
In akka typed, we have concept of Behavior.

If we want to retain same behaviour by an actor we return Behaviors.same when we are done processing a message. But then we can also return this. How are two different?

答:
They work the same. When using the FP:y-style of defining actors you will not have a this to return so you can only use Behaviors.same.

When defining actors in OO style (extending AbstractBehavior) you can use both, but we have tried to consistently use this in such samples in the docs and that's the recommendation.

Title: Behaviors.same vs this


问:
REST API DELETE LIST ITEM - USE THIS CODE
Delete Items:

This Code will help to delete the item in list using REST API for SharePoint.

var SiteUrl = _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getbytitle('ListName')/items('" + courtids + "')";

```<code>        $.ajax({
              url: SiteUrl
                         method: 'DELETE',
                         headers: {
                             'X-RequestDigest': $('#__REQUESTDIGEST').val()
                         },

            async: false,
            success: function (data) {
                alert("Delete success");

            },
            error: function (data) {

            }
        });
</code>```

答:
You dont need to reinvent the wheel. You should use the pnpjs: a microsoft library which uses the rest api to perform actions on sharepoint.

PNPJS

Body:
Delete Items:

This Code will help to delete the item in list using REST API for SharePoint.

var SiteUrl = _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getbytitle('ListName')/items('" + courtids + "')";

        $.ajax({
              url: SiteUrl
                         method: 'DELETE',
                         headers: {
                             'X-RequestDigest': $('#__REQUESTDIGEST').val()
                         },

            async: false,
            success: function (data) {
                alert("Delete success");

            },
            error: function (data) {

            }
        });


问:
How to parse specific field from GMAIL body to google SHEETS
I have a gmail body that starts with this:

```<code>Name: Full Report
Store: River North (Wells St)
Date Tripped: 18 Feb 2020 8:40 PM
Business Date: 18 Feb 2020 (Closed)
Message:
Information:
This alert was tripped based on a user defined trigger: Every 5 minutes.
</code>```

I'm trying to parse the Date Tripped: field and the Business Date: field but don't believe i'm getting the regex correct.

```<code>    // Implement Parsing rules using regular expressions
    if (content) {

      tmp = content.match(/Date Tripped: \s*([A-Za-z0-9.\s ]+)(\r?\n)/);
      var tripped = (tmp && tmp[1]) ? tmp[1].trim() : 'N/A';

      tmp = content.match(/Business Date: \[0-9][()]/);
      var businessdate = (tmp && tmp[1]) ? tmp[1].trim() : 'N/A';
</code>```

答:
You could also make the pattern a bit more specific and use a single pattern to match both options.

```<code>\b(?:Business Date|Date Tripped):\s*(?:3[01]|[12][0-9]|0?[1-9])\s+[A-Za-z]+\s+\d{4}\s+(?:\([^()]+\)|(?:1[0-2]|0?[1-9]):[0-5]?[0-9]\s*[AP]M)
</code>```

Explanation

\b(?:Business Date|Date Tripped):\s* Match one of the options

(?: Non capture group

3[01]|[12][0-9]|0?[1-9] Match a digit 1-31

) Close group

\s+[A-Za-z]+\s+\d{4}\s+ Match 1+ char A-Za-z followed by 4 digits

(?: Non capture group

\([^()]+\) Match from an openining parenthesis till closing parenthesis

| Or

(?:1[0-2]|0?[1-9]):[0-5]?[0-9]\s*[AP]M Match a time pattern

) Close group

Regex demo

Note that that pattern does not validate the date itself.

Body:
I have a gmail body that starts with this:

Name: Full Report
Store: River North (Wells St)
Date Tripped: 18 Feb 2020 8:40 PM
Business Date: 18 Feb 2020 (Closed)
Message:
Information:
This alert was tripped based on a user defined trigger: Every 5 minutes.

I'm trying to parse the Date Tripped: field and the Business Date: field but don't believe i'm getting the regex correct.

    // Implement Parsing rules using regular expressions
    if (content) {

      tmp = content.match(/Date Tripped: \s*([A-Za-z0-9.\s ]+)(\r?\n)/);
      var tripped = (tmp && tmp[1]) ? tmp[1].trim() : 'N/A';

      tmp = content.match(/Business Date: \[0-9][()]/);
      var businessdate = (tmp && tmp[1]) ? tmp[1].trim() : 'N/A';

Body:
You could also make the pattern a bit more specific and use a single pattern to match both options.

\b(?:Business Date|Date Tripped):\s*(?:3[01]|[12][0-9]|0?[1-9])\s+[A-Za-z]+\s+\d{4}\s+(?:\([^()]+\)|(?:1[0-2]|0?[1-9]):[0-5]?[0-9]\s*[AP]M)

Explanation

\b(?:Business Date|Date Tripped):\s* Match one of the options

(?: Non capture group

3[01]|[12][0-9]|0?[1-9] Match a digit 1-31

) Close group

\s+[A-Za-z]+\s+\d{4}\s+ Match 1+ char A-Za-z followed by 4 digits

(?: Non capture group

\([^()]+\) Match from an openining parenthesis till closing parenthesis

| Or

(?:1[0-2]|0?[1-9]):[0-5]?[0-9]\s*[AP]M Match a time pattern

) Close group

Regex demo

Note that that pattern does not validate the date itself.


问:
SQL Server turns off always after generate about 60 millions records
I write simple script in SQL to generate data. But always after generates 60
millions records SQL Server Management Studio turns of. My script use only 30% of my memory and 50% of CPU. I have SQL Server enterprise edition on my PC and I use SQL Server Management Studio 2017. Maybe there is some time limit that I have to change in server settings?  </p>

答:
See if the following solution work for you.

Right click on the database giving you the problem in the object explorer.

Click ‘Properties’

Click ‘Options’

Set ‘Auto Close’ to False


问:
How do I run Google Dataprep jobs automatically?
Is there a way to trigger Google Dataprep flow over API?

I need to run like 30 different flows every day. Every day the source dataset changes and the result has to be appended to Google BigQuery table. Is there a way to automate this process? Source files are .xls files. I can upload them to cloud storage and write a cloud function that will upload it wherever Dataprep needs. The problem is that it seems to be impossible to replace the source dataset in a Dataprep flow. If so, then what's the point of scheduled runs and the new Job Run API?

答:
There are several ways to do this. You will probably end up combining the parameterization and the scheduling features to run scheduled jobs that would pick new files every time.

Depending on your use case, you can for e.g. do:

Importing a directory

If you setup a directory that only contains one excel file (see picture below), you can use the + button to use the directory as input dataset.
Every time you will run a job the files present in that directory will be processed.

You can now schedule the job, create an output destination and you should be all set.

Using date time parameters

Let's assume you are in the situation where you add a new file every day with the date in the file name. For e.g. in Cloud storage, it would look like this:

You can use the Parameterize button in the Dataprep file browser and setup the following parameter:

This should select the file from the previous day:

You can them import the dataset and schedule the flow. If your schedule run every day, it will pick up the new file each time.

Using variables

Alternatively, you can define a variable in the file path of your dataset.

You can then use the JobGroup API to override that variable.

```<code>POST /v4/jobGroups

{
  "wrangledDataset": {
    "id": datasetId
  },
  "runParameters": {
    "overrides": {
      "data": [
        {
          "key": "folder-name",
          "value": "new folder name"
        }
      ]
    }
  }
}
</code>```

Note that for this to work, your file need to have the same structure. See https://cloud.google.com/dataprep/docs/html/Create-Dataset-with-Parameters_118228628#structuring-your-data for more details.

Using a wildcard parameter should also be possible as an alternative to the first method should also be possible.

Body:
There are several ways to do this. You will probably end up combining the parameterization and the scheduling features to run scheduled jobs that would pick new files every time.

Depending on your use case, you can for e.g. do:

Importing a directory

If you setup a directory that only contains one excel file (see picture below), you can use the + button to use the directory as input dataset.
Every time you will run a job the files present in that directory will be processed.

You can now schedule the job, create an output destination and you should be all set.

Using date time parameters

Let's assume you are in the situation where you add a new file every day with the date in the file name. For e.g. in Cloud storage, it would look like this:

You can use the Parameterize button in the Dataprep file browser and setup the following parameter:

This should select the file from the previous day:

You can them import the dataset and schedule the flow. If your schedule run every day, it will pick up the new file each time.

Using variables

Alternatively, you can define a variable in the file path of your dataset.

You can then use the JobGroup API to override that variable.

POST /v4/jobGroups

{
  "wrangledDataset": {
    "id": datasetId
  },
  "runParameters": {
    "overrides": {
      "data": [
        {
          "key": "folder-name",
          "value": "new folder name"
        }
      ]
    }
  }
}

Note that for this to work, your file need to have the same structure. See https://cloud.google.com/dataprep/docs/html/Create-Dataset-with-Parameters_118228628#structuring-your-data for more details.

Using a wildcard parameter should also be possible as an alternative to the first method should also be possible.


问:
Can't set hidden input field's value using jQuery
I have a simple input field inside a form tag:

```<code><body>
  <form action="#">
      <label>Input</label>
      <input type="hidden" id="foo" name="foo" />

  </form>
</body>
</code>```

I tried to set this value from a js file:

```<code>$(document).ready(function(){
    $('#foo').val('foo')
})
</code>```

but in the html source the attribute isn't set at all. If I try to set the input type to "button" or anything else, it works. I just can't do it with a hidden input field. What am I doing wrong?

答:
I've had this problem when POST-ing my form and my PHP script couldn't get POST-ed value. I used this:

```<code>$('#elemId').attr("name", theValue);
</code>```

Hope it helps.

Body:
I have a simple input field inside a form tag:

  <form action="#">
      Input
      <input type="hidden" id="foo" name="foo" />

  </form>

I tried to set this value from a js file:

$(document).ready(function(){
    $('#foo').val('foo')
})

but in the html source the attribute isn't set at all. If I try to set the input type to "button" or anything else, it works. I just can't do it with a hidden input field. What am I doing wrong?

Body:
I've had this problem when POST-ing my form and my PHP script couldn't get POST-ed value. I used this:

$('#elemId').attr("name", theValue);

Hope it helps.


问:
What is the difference between APIView class and generics.GenericAPIView
What is the difference between  APIView class and generics.GenericAPIView</p>

答:
APIView is the base class based view. Viewsets have APIView as a parent class.

With APIview you code methods etc for the different HTTP call methods such as post, get, put etc. These come with no standard configuration, so you can customise to your needs

With Viewsets, you code more specific methods . For example the ‘retrieve’ method, will expect arguments of the request and the pk of the object to be retrieved. Thus you write methods for create, retrieve, list, etc instead of post,get…

Moving on from that, you also have the routers. These work with viewsets and will create the urls for you based on how you coded the Viewset


问:
SwiftUI: Execute functions in Preview Provider
I think I'm going about this SwiftUI thing all wrong. It's clear that we're just defining the layout as a structs and there can be limited conventional programming embroiled in the layout. I'm having difficulties thinking like this. What is the best way of doing this?

Take the example below. Project is an NSManagedObject. All I want to do is pass in example record so the SwiftUI will render. Nothing I try works.

```<code>struct ProjectView: View
{
    @State var project: Project //NSManagedObject

     var body: some View
     {
         TextField("", text: Binding<String>($project.projectName)!)
     }
}

struct ProjectView_Previews: PreviewProvider
{
    static var previews: some View
    {
        var p:Project

        p = getFirstProject() //returns a Project

        return ProjectView(project: p)
    }
}
</code>```

If I try returning the struct it says it cannot preview in the file.

If I don't return the struct I get a Function declares an opaque return type, but has no return statements in its body from which to infer an underlying type error.

UPDATE:

```<code>var app = UIApplication.shared.delegate as! AppDelegate

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

lazy var persistentContainer: NSPersistentCloudKitContainer = {
                fatalError("Unresolved error \(error), \(error.userInfo)")
            }
        })
        return container
    }()

    lazy var managedObjectContext: NSManagedObjectContext =
    {
         return persistentContainer.viewContext
    }()
}
</code>```

And the rest of the code:

```<code>func allRecords<T: NSManagedObject>(_ type : T.Type, sort: NSSortDescriptor? = nil) -> [T]
{
    let context = app.managedObjectContext
    let request = T.fetchRequest()
    if let sortDescriptor = sort
    {
        request.sortDescriptors = [sortDescriptor]
    }

    do
    {
        let results = try context.fetch(request)
        return results as! [T]
    }
    catch
    {
        print("Error with request: \(error)")
        return []
    }
}

func getCount() -> String
{
    let r = allRecords(Project.self)

    return String(r.count)

}
struct ProjectView: View
{
//    @ObservedObject var project: Project

     var body: some View
     {
        Text(getCount())

//           TextField("", text: Binding<String>($project.projectName)!)
      }
}

struct ProjectView_Previews: PreviewProvider
{
    static var previews: some View
    {
        ProjectView()
    }
}
</code>```

r.count is returning 0, but in the main application thread it is returning 8. Has app.managedObjectContext not been defined properly? I think this has just got too complicated too quickly.

答:
Assuming getFirstProject works correctly the following should work

```<code>struct ProjectView_Previews: PreviewProvider
{
    static var previews: some View
    {
        ProjectView(project: getFirstProject())
    }
}
</code>```

However there are concerns about the following...

```<code>struct ProjectView: View
{
    @State var project: Project //NSManagedObject
</code>```

because @State is designed to be internal view state-only thing, but Project in your case is a model, so the recommended scenario for this is to use ObservableObject view model either by conforming Project or as standalone clue class holding Project instance(s).

Body:
I think I'm going about this SwiftUI thing all wrong. It's clear that we're just defining the layout as a structs and there can be limited conventional programming embroiled in the layout. I'm having difficulties thinking like this. What is the best way of doing this?

Take the example below. Project is an NSManagedObject. All I want to do is pass in example record so the SwiftUI will render. Nothing I try works.

struct ProjectView: View
{
    @State var project: Project //NSManagedObject

     var body: some View
     {
         TextField("", text: Binding<String>($project.projectName)!)
     }
}

struct ProjectView_Previews: PreviewProvider
{
    static var previews: some View
    {
        var p:Project

        p = getFirstProject() //returns a Project

        return ProjectView(project: p)
    }
}

If I try returning the struct it says it cannot preview in the file.

If I don't return the struct I get a Function declares an opaque return type, but has no return statements in its body from which to infer an underlying type error.

UPDATE:

var app = UIApplication.shared.delegate as! AppDelegate

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

lazy var persistentContainer: NSPersistentCloudKitContainer = {
                fatalError("Unresolved error \(error), \(error.userInfo)")
            }
        })
        return container
    }()

    lazy var managedObjectContext: NSManagedObjectContext =
    {
         return persistentContainer.viewContext
    }()
}

And the rest of the code:

func allRecords<T: NSManagedObject>(_ type : T.Type, sort: NSSortDescriptor? = nil) -> [T]
{
    let context = app.managedObjectContext
    let request = T.fetchRequest()
    if let sortDescriptor = sort
    {
        request.sortDescriptors = [sortDescriptor]
    }

    do
    {
        let results = try context.fetch(request)
        return results as! [T]
    }
    catch
    {
        print("Error with request: \(error)")
        return []
    }
}

func getCount() -> String
{
    let r = allRecords(Project.self)

    return String(r.count)

}
struct ProjectView: View
{
//    @ObservedObject var project: Project

     var body: some View
     {
        Text(getCount())

//           TextField("", text: Binding<String>($project.projectName)!)
      }
}

struct ProjectView_Previews: PreviewProvider
{
    static var previews: some View
    {
        ProjectView()
    }
}

r.count is returning 0, but in the main application thread it is returning 8. Has app.managedObjectContext not been defined properly? I think this has just got too complicated too quickly.

Body:
Assuming getFirstProject works correctly the following should work

struct ProjectView_Previews: PreviewProvider
{
    static var previews: some View
    {
        ProjectView(project: getFirstProject())
    }
}

However there are concerns about the following...

struct ProjectView: View
{
    @State var project: Project //NSManagedObject

because @State is designed to be internal view state-only thing, but Project in your case is a model, so the recommended scenario for this is to use ObservableObject view model either by conforming Project or as standalone clue class holding Project instance(s).


问:
pyspark: Converting string to struct
I have data as follows -

```<code>{
    "Id": "01d3050e",
    "Properties": "{\"choices\":null,\"object\":\"demo\",\"database\":\"pg\",\"timestamp\":\"1581534117303\"}",
    "LastUpdated": 1581530000000,
    "LastUpdatedBy": "System"
}
</code>```

Using aws glue, I want to relationalize the "Properties" column  but since the datatype is string it can't be done. Converting it to struct, might do it based on reading this blog -

https://aws.amazon.com/blogs/big-data/simplify-querying-nested-json-with-the-aws-glue-relationalize-transform/

```<code>>>> df.show
<bound method DataFrame.show of DataFrame[Id: string, LastUpdated: bigint, LastUpdatedBy: string, Properties: string]>
>>> df.show()
+--------+-------------+-------------+--------------------+
|      Id|  LastUpdated|LastUpdatedBy|          Properties|
+--------+-------------+-------------+--------------------+
|01d3050e|1581530000000|       System|{"choices":null,"...|
+--------+-------------+-------------+--------------------+

</code>```

How can I un-nested the "properties" column to break it into "choices", "object", "database" and "timestamp" columns, using relationalize transformer or any UDF in pyspark.

Title: pyspark: Converting string to struct

Body:
I have data as follows -

{
    "Id": "01d3050e",
    "Properties": "{\"choices\":null,\"object\":\"demo\",\"database\":\"pg\",\"timestamp\":\"1581534117303\"}",
    "LastUpdated": 1581530000000,
    "LastUpdatedBy": "System"
}

Using aws glue, I want to relationalize the "Properties" column  but since the datatype is string it can't be done. Converting it to struct, might do it based on reading this blog -

https://aws.amazon.com/blogs/big-data/simplify-querying-nested-json-with-the-aws-glue-relationalize-transform/

>>> df.show
<bound method DataFrame.show of DataFrame[Id: string, LastUpdated: bigint, LastUpdatedBy: string, Properties: string]>
>>> df.show()
+--------+-------------+-------------+--------------------+
|      Id|  LastUpdated|LastUpdatedBy|          Properties|
+--------+-------------+-------------+--------------------+
|01d3050e|1581530000000|       System|{"choices":null,"...|
+--------+-------------+-------------+--------------------+

How can I un-nested the "properties" column to break it into "choices", "object", "database" and "timestamp" columns, using relationalize transformer or any UDF in pyspark.

Body:
Use from_json since the column Properties is a JSON string.

If the schema is the same for all you records you can convert to a struct type by defining the schema like this:

schema = StructType([StructField("choices", StringType(), True),
                    StructField("object", StringType(), True),
                    StructField("database", StringType(), True),
                    StructField("timestamp", StringType(), True)],
                    )

df.withColumn("Properties", from_json(col("Properties"), schema)).show(truncate=False)

#+--------+-------------+-------------+---------------------------+
#|Id      |LastUpdated  |LastUpdatedBy|Properties                 |
#+--------+-------------+-------------+---------------------------+
#|01d3050e|1581530000000|System       |[, demo, pg, 1581534117303]|
#+--------+-------------+-------------+---------------------------+

However, if the schema can change from one row to another I'd suggest you to convert it to a Map type instead:

df.withColumn("Properties", from_json(col("Properties"), MapType(StringType(), StringType()))).show(truncate=False)

#+--------+-------------+-------------+------------------------------------------------------------------------+
#|Id      |LastUpdated  |LastUpdatedBy|Properties                                                              |
#+--------+-------------+-------------+------------------------------------------------------------------------+
#|01d3050e|1581530000000|System       |[choices ->, object -> demo, database -> pg, timestamp -> 1581534117303]|
#+--------+-------------+-------------+------------------------------------------------------------------------+

You can then access elements of the map using element_at (Spark 2.4+)


问:
Trying to remove a view index above child count error
What does this mean?
This happens when I update a list of iterated views something like

```<code><View style={{ flexDirection: 'row', padding: 20, backgroundColor: '#fff' }}>
  <Ionicons name={jobIcon} color={theme.iconColor} size={30} />
  <Text>{jobService}</Text>
  <Text>{jobDate}</Text>
</View>
</code>```

mapped inside a scrollview.

this error pops up when I modify the array from child scene.
scene1 - is where the ScrollView with job list array of views
sence2 - is where I delete a job and should update scene1 when I do remove a job

答:
I had the same issue, because I had an Array.map inside a condition which I was updating using LayoutAnimation.
I fixed it by moving the state variable inside the map function.</p>

Body:
What does this mean?
This happens when I update a list of iterated views something like

<View style={{ flexDirection: 'row', padding: 20, backgroundColor: '#fff' }}>
  <Ionicons name={jobIcon} color={theme.iconColor} size={30} />
  <Text>{jobService}</Text>
  <Text>{jobDate}</Text>
</View>

mapped inside a scrollview.

this error pops up when I modify the array from child scene.
scene1 - is where the ScrollView with job list array of views
sence2 - is where I delete a job and should update scene1 when I do remove a job


问:
Wordpress: srcset gets HTTP instead of HTTPS in all posts
In Wordpress 4.4 images get automatically a srcset attribute. My problem with this was the following (I solved it while I was writing this question, see my answer below):

in order to transit everything to https, I replaced all the src="http://... references in the posts table by src="https://... (I changed it later to src="//... for supporting both protocols);

the images on all the posts get the correct URL in the src attribute;

however in all the images that get the srcset attribute the URLs in it are always with http:// references.

Why does this happen? Why these URLs don't get my newly updated https:// beginnings?

答:
If you don't want to change your WordPress Address (URL) to https then just put this code inside your active themes functions.php file

```<code>function codextent_ssl_srcset( $sources ) {
    foreach ( $sources as &$source ) {
        $source['url'] = set_url_scheme( $source['url'], 'https' );
    }
    return $sources;
}
add_filter( 'wp_calculate_image_srcset', 'codextent_ssl_srcset' );
</code>```

** Also add this in top line of wp-config.php file.

```<code>$_SERVER['HTTPS'] = 'on';
</code>```

Body:
If you don't want to change your WordPress Address (URL) to https then just put this code inside your active themes functions.php file

function codextent_ssl_srcset( $sources ) {
    foreach ( $sources as &$source ) {
        $source['url'] = set_url_scheme( $source['url'], 'https' );
    }
    return $sources;
}
add_filter( 'wp_calculate_image_srcset', 'codextent_ssl_srcset' );

** Also add this in top line of wp-config.php file.

$_SERVER['HTTPS'] = 'on';


问:
Heavy CPU analysis while running foreground service
So, I've a Service that is important for applications logic and thus needs to be alive all the time.
First thing is first, I created it as a foreground service.

Whenever user starts to run, Service starts to do a lot of heavy things. It uses FusedLocationAPI different type of sensors and do a lot of different calculations. At this point phone starts to heat up (CPU usage is high). When running stops, heating stops and CPU drops lower.

This makes me think that the main problem is whenever these sensors are used and calculations are made, but there's a lot of possibilities that could cause this and I wanted to understand, how can I deeply analyze batter usage in this case? I read that Battery Historian should be way to go, but the information there is complicated and do not give me much information. How can I use this data to understand which class/runnable/code part is held responsible for the CPU usage? Maybe there's better ways to solve this? Thanks in advance.

Detailed analysis on what's happening using CPU profiler (after suggestion).

Image. Application is opened and few different screens are switch to and from. Nothing special. Phone does not heat up and from CPU analysis everything also looks pretty okay.

2.User starts to run and enter heavy state. The yellow (light green) rectangle shows previously mentioned "important service" that bring important role to application. Called functions does not use too much time of CPU considering the % of whole running trip - which makes me think, I've to look somewhere else..

What I saw is that CPU increases heavily whenever I lock the phone (while service is running. From CPU Bottom Up analysis I cannot understand what is causing the problem (orange rectangle) - looks like a bunch of Android stuff is happening, but it does not give me any clue.

From CPU profiler I do understand that I have a serious problem considering CPU usage, but right now I do not understand what is causing it (which piece of code/class/function). I know for the fact that whenever my important service is created (on app start) I use PARTIAL_WAKE_LOCK to not allow CPU go to sleep and also make service to be alive at all times. As I understand I need to find different solution for this, because CPU drains too much of battery.

How could I found this using only profiler? I now this fact only for code and profiler stack does not tell me much about this (maybe Im not looking at the right place?)

答:
I found out the root cause of high CPU usage.
I did detailed investigation on threads and found out that DefaultDispatcher threads are using A LOT of CPU.

Turns out the has been a bug in Kotlin-Coroutines library and latest version provides fixes. When I did tests I used version 1.3.1, but changing version number to 1.3.3 provided me with big improvements: from 40% usage to 10% CPU usage.


问:
androidx.spinner onItemSelectedListener not working
Am trying to use a spinner in a layout. I can add and select items to the spinner but I cannot retrieve the selected item. This is the main activity:

```<code>
class pageNewPurchaseOrder : AppCompatActivity() {
    lateinit var spinnerVendorX: androidx.appcompat.widget.AppCompatSpinner
    var spinnerArray: java.util.ArrayList<CharSequence> = ArrayList<CharSequence>()
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_page_new_purchase_order)
        setSupportActionBar(toolbar)
        supportActionBar?.setDisplayShowTitleEnabled(false)
     spinnerVendorX = findViewById(R.id.spinnerVendorX)
      spinnerVendorX.adapter = ArrayAdapter(this@pageNewPurchaseOrder, android.R.layout.simple_spinner_item, spinnerArray)
        spinnerVendorX.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
            override fun onNothingSelected(parent: AdapterView<*>?) {

            }
            override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) {
                Log.d("aaa", "This code is not running!")

            }

        }

    }
}

</code>```

This is the layout activity

```<code><?xml version="1.0" encoding="utf-8"?>
<androidx.core.widget.NestedScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="?attr/colorPrimary"
    android:fillViewport="true"
    android:focusable="true"
    android:focusableInTouchMode="true"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:context=".pageNewPurchaseOrder"
    tools:showIn="@layout/activity_page_new_purchase_order">

         <androidx.appcompat.widget.AppCompatSpinner
            android:padding="10dp"
            android:background="@drawable/bgselect"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="10dp"
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintRight_toRightOf="parent"
            app:layout_constraintTop_toBottomOf="@+id/lbl2"
            android:id="@+id/spinnerVendorX" />
</androidx.core.widget.NestedScrollView>
</code>```

Am getting result this on the logcat when I select an item: E/ViewRootImpl(31835): sendUserActionEvent() mView == null.I get tj=he same results even when I use <Spinner instead of <androidx.appcompat.widget.AppCompatSpinner

答: User must have to add data in the ArrayList. Here, you are initialising arrayList and set it but not adding data in ArrayList. Please add data in ArrayList then try it. Thank you.</p>

Body:
Am trying to use a spinner in a layout. I can add and select items to the spinner but I cannot retrieve the selected item. This is the main activity:

class pageNewPurchaseOrder : AppCompatActivity() {
    lateinit var spinnerVendorX: androidx.appcompat.widget.AppCompatSpinner
    var spinnerArray: java.util.ArrayList<CharSequence> = ArrayList<CharSequence>()
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_page_new_purchase_order)
        setSupportActionBar(toolbar)
        supportActionBar?.setDisplayShowTitleEnabled(false)
     spinnerVendorX = findViewById(R.id.spinnerVendorX)
      spinnerVendorX.adapter = ArrayAdapter(this@pageNewPurchaseOrder, android.R.layout.simple_spinner_item, spinnerArray)
        spinnerVendorX.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
            override fun onNothingSelected(parent: AdapterView<*>?) {

            }
            override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) {
                Log.d("aaa", "This code is not running!")

            }

        }

    }
}

This is the layout activity

<?xml version="1.0" encoding="utf-8"?>
<androidx.core.widget.NestedScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="?attr/colorPrimary"
    android:fillViewport="true"
    android:focusable="true"
    android:focusableInTouchMode="true"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:context=".pageNewPurchaseOrder"
    tools:showIn="@layout/activity_page_new_purchase_order">

         <androidx.appcompat.widget.AppCompatSpinner
            android:padding="10dp"
            android:background="@drawable/bgselect"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="10dp"
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintRight_toRightOf="parent"
            app:layout_constraintTop_toBottomOf="@+id/lbl2"
            android:id="@+id/spinnerVendorX" />
</androidx.core.widget.NestedScrollView>

Am getting result this on the logcat when I select an item: E/ViewRootImpl(31835): sendUserActionEvent() mView == null.I get tj=he same results even when I use <Spinner instead of <androidx.appcompat.widget.AppCompatSpinner


问:
Why doesn't boost::any have a "getter"?
Using boost::any is very useful but it's very depressing that it has no getter, and always we have to use any_cast for casting it to type we want. But why it has no such thing? In my opinion the one bellow can be useful member. Is there some bad things I can't see?

```<code>template <class T>
void get(T * handle)
{
    *handle = boost::any_cast<T>(*this);
}
</code>```

Edit:

The only bad thing I see, that this getter requires to have assignment operator.

答:
The point with any_cast is to force people not to use template argument deduction, since the failure or not of the cast is very sensitive to the exact type used for construction.

This usage is clear:

```<code>any x(2); // store an int
double f = any_cast<int>(x); // ok, request for an int, then cast to double
</code>```

This one is not:

```<code>int g;
...
x.get(&g); // Ok. For now.
</code>```

Indeed, imagine now you refactor your code, and you replace

```<code>int g;
</code>```

by

```<code>double g;
</code>```

Now, the new code looks like

```<code>double g;
... // There can be 100s of lines here
x.get(&g); // This line HAS changed semantics and cast will fail
</code>```

This will likely make you lose some half hours to debug.

Title: Why doesn't boost::any have a "getter"?

Body:
Using boost::any is very useful but it's very depressing that it has no getter, and always we have to use any_cast for casting it to type we want. But why it has no such thing? In my opinion the one bellow can be useful member. Is there some bad things I can't see?

template <class T>
void get(T * handle)
{
    *handle = boost::any_cast<T>(*this);
}

Edit:

The only bad thing I see, that this getter requires to have assignment operator.

Body:
The point with any_cast is to force people not to use template argument deduction, since the failure or not of the cast is very sensitive to the exact type used for construction.

This usage is clear:

any x(2); // store an int
double f = any_cast<int>(x); // ok, request for an int, then cast to double

This one is not:

int g;
...
x.get(&g); // Ok. For now.

Indeed, imagine now you refactor your code, and you replace

int g;

by

double g;

Now, the new code looks like

double g;
... // There can be 100s of lines here
x.get(&g); // This line HAS changed semantics and cast will fail

This will likely make you lose some half hours to debug.


问:
Update CurrentRecord column depending on EmployeeVersion column
I have the following table containing the versions for each employee:

```<code>EmployeeId Status Department CurrentRecord EmployeeVersion
45         1      33         0             1
45         1      45         0             2
45         2      45         0             3
</code>```

I want to update CurrentRecord and set it to 1 for the record having the maximum EmployeeVersion (as it is the latest version) like below:

```<code>EmployeeId Status Department CurrentRecord EmployeeVersion
45         1      33         0             1
45         1      45         0             2
45         2      45         1             3
</code>```

This is my query:

```<code>UPDATE DimEmployeeSharedV1
  SET CurrentRecord = 1
WHERE EmployeeVersion = (
  SELECT MAX(e.EmployeeVersion)
  FROM DimEmployeeSharedV1 e
  WHERE e.EmployeeId = EmployeeId
  GROUP BY e.EmployeeId
)
</code>```

I have the following error:

Subquery returned more than 1 value. This is not permitted when the
  subquery follows =, !=, <, <= , >, >= or when the subquery is used as
  an expression.

答:
Demo on db<>fiddle

```<code>; WITH cte as(
 select EmployeeId, max(EmployeeVersion) as EmployeeVersion
 from #A
 group by EmployeeId
)
update a
set CurrentRecord = 1
from #A a
inner join cte on a.EmployeeId = cte.EmployeeId and a.EmployeeVersion = cte.EmployeeVersion
</code>```

Output

Body:
I have the following table containing the versions for each employee:

EmployeeId Status Department CurrentRecord EmployeeVersion
45         1      33         0             1
45         1      45         0             2
45         2      45         0             3

I want to update CurrentRecord and set it to 1 for the record having the maximum EmployeeVersion (as it is the latest version) like below:

EmployeeId Status Department CurrentRecord EmployeeVersion
45         1      33         0             1
45         1      45         0             2
45         2      45         1             3

This is my query:

UPDATE DimEmployeeSharedV1
  SET CurrentRecord = 1
WHERE EmployeeVersion = (
  SELECT MAX(e.EmployeeVersion)
  FROM DimEmployeeSharedV1 e
  WHERE e.EmployeeId = EmployeeId
  GROUP BY e.EmployeeId
)

I have the following error:

Subquery returned more than 1 value. This is not permitted when the
  subquery follows =, !=, <, <= , >, >= or when the subquery is used as
  an expression.

Body:
Demo on db<>fiddle

; WITH cte as(
 select EmployeeId, max(EmployeeVersion) as EmployeeVersion
 from #A
 group by EmployeeId
)
update a
set CurrentRecord = 1
from #A a
inner join cte on a.EmployeeId = cte.EmployeeId and a.EmployeeVersion = cte.EmployeeVersion

Output


问:
Does MySQL database connections pool expire if it was not used within long amount of time or if application which used it collapsed?
I am connecting database MySQL (MariaDB) from Python script using MySQLConnectionPool. I use context manager to hadle connection in the pool. I wonder if pool can expire if it is not used for a long amount of time or if my program collapsed. I've found that connection to MySQL db expires, do it is released even if you've forgot or have not been able to close connection in your program, what's situation with connections pool?

```<code>from contextlib import contextmanager
import mysql.connector
from mysql.connector.errors import Error
from mysql.connector import pooling

SQL_CONN_POOL = pooling.MySQLConnectionPool(
    pool_name="mysqlpool",
    pool_size=1,
    user=DB_USER,
    password=DB_PASS,
    host=DB_HOST,
    database=DATABASE,
    auth_plugin=DB_PLUGIN
)

@contextmanager
def mysql_connection_from_pool() -> "conn":
    conn_pool = SQL_CONN_POOL  # get connection from the pool, all the rest is the same
    _conn = conn_pool.get_connection()
    try:
        yield _conn
    except (Exception, Error) as ex:
        # if error happened all made changes during the connection will be rolled back:
        _conn.rollback()
        # this statement re-raise error to let it be handled in outer scope:
        raise
    else:
        # if everything is fine commit all changes to save them in db:
        _conn.commit()
    finally:
        # actually it returns connection to the pool, rather than close it
        _conn.close()

@contextmanager
def mysql_curs_from_pool() -> "curs":
    with mysql_connection_from_pool() as _conn:
        _curs = _conn.cursor()
        try:
            yield _curs
        finally:
            _curs.close()
</code>```

答:
Yes it can be time outed. There are two timeout configuration.

See wait_timeout and interactive_timeout

Body:
I am connecting database MySQL (MariaDB) from Python script using MySQLConnectionPool. I use context manager to hadle connection in the pool. I wonder if pool can expire if it is not used for a long amount of time or if my program collapsed. I've found that connection to MySQL db expires, do it is released even if you've forgot or have not been able to close connection in your program, what's situation with connections pool?

from contextlib import contextmanager
import mysql.connector
from mysql.connector.errors import Error
from mysql.connector import pooling

SQL_CONN_POOL = pooling.MySQLConnectionPool(
    pool_name="mysqlpool",
    pool_size=1,
    user=DB_USER,
    password=DB_PASS,
    host=DB_HOST,
    database=DATABASE,
    auth_plugin=DB_PLUGIN
)

@contextmanager
def mysql_connection_from_pool() -> "conn":
    conn_pool = SQL_CONN_POOL  # get connection from the pool, all the rest is the same
    _conn = conn_pool.get_connection()
    try:
        yield _conn
    except (Exception, Error) as ex:
        # if error happened all made changes during the connection will be rolled back:
        _conn.rollback()
        # this statement re-raise error to let it be handled in outer scope:
        raise
    else:
        # if everything is fine commit all changes to save them in db:
        _conn.commit()
    finally:
        # actually it returns connection to the pool, rather than close it
        _conn.close()

@contextmanager
def mysql_curs_from_pool() -> "curs":
    with mysql_connection_from_pool() as _conn:
        _curs = _conn.cursor()
        try:
            yield _curs
        finally:
            _curs.close()


问:
Umbraco 8.0 Login Issues
am getting junk characters in the PostLogin API Response for Umbraco login. which is causing all other api's to show a 401 unauthorized error.

Even the isAuthenticated API is returning as false.

Umbraco is hosted version and we are running 8.2.0.

It is a standard installation. the LegacyEncoding is set to true.

This is the response i am getting. The leading characters are the junk characters.
Image here

```<code>)]}', ---Junk Values
{"email":"xxxxxxxxxxxxxxxxxx","locale":"en-US","emailHash":"ac88ae0de8ce43ba72dac1cd208d4e87","userGroups":[],"remainingAuthSeconds":1200.0,"startContentIds":[],"startMediaIds":[],"avatars":[],"allowedSections":[],"id":-1,"name":"xxxxxxxxxxxx"}
</code>```

答:
It's not junk, it's part of AngularJS JSON security:

"Protection from JSON Hijacking is provided if the server prefixes all
  JSON requests with following string ")]}',\n". AngularJS will
  automatically strip the prefix before processing it as JSON. For more
  information please visit JSON Hijacking Protection."

https://docs.angularjs.org/guide/security#json-hijacking-protection

You can also see the implementation in Umbraco source code:

Title: Umbraco 8.0 Login Issues

Body:
am getting junk characters in the PostLogin API Response for Umbraco login. which is causing all other api's to show a 401 unauthorized error.

Even the isAuthenticated API is returning as false.

Umbraco is hosted version and we are running 8.2.0.

It is a standard installation. the LegacyEncoding is set to true.

This is the response i am getting. The leading characters are the junk characters.
Image here

)]}', ---Junk Values
{"email":"xxxxxxxxxxxxxxxxxx","locale":"en-US","emailHash":"ac88ae0de8ce43ba72dac1cd208d4e87","userGroups":[],"remainingAuthSeconds":1200.0,"startContentIds":[],"startMediaIds":[],"avatars":[],"allowedSections":[],"id":-1,"name":"xxxxxxxxxxxx"}


问:
How to add and delete segments in a viewcontroller by clicking add button an delete button created in the same viewcontroller?
```<code>import UIKit

class ViewController: UIViewController {

// @IBAction func Btndel(_ sender: Any) {
//}

var Str:String?

override func viewDidLoad() {
    super.viewDidLoad()
    let items = [Str]
    let SegM = UISegmentedControl(items:items as Any as? [Any])
    SegM.selectedSegmentIndex = 0

    SegM.frame=CGRect(x: 70, y: 130, width: 100, height: 50)
    SegM.layer.cornerRadius = 8.0
    SegM.backgroundColor = .orange
    SegM.tintColor = .white

    self.view .addSubview(SegM)

    // Do any additional setup after loading the view, typically from a nib.
}

@IBAction func Btnadd(_ sender: Any)
{
var Str = 0;Str += 1

}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

}
</code>```

How to add and delete segments in a viewcontroller by clicking add button an delete button created in the same viewcontroller

答:
How to insert and remove(add or delete) segments in swift4

class ViewController: UIViewController {

```<code>@IBOutlet weak var segment1: UISegmentedControl!

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
}

@IBAction func insert(_ sender: Any) {

    segment1.insertSegment(withTitle: "\(segment1.numberOfSegments+1)", at: segment1.numberOfSegments, animated: true)

    }

    @IBAction func remove(_ sender: Any) {

    segment1.removeSegment(at: segment1.numberOfSegments-1, animated: true)
}
}
</code>```

Body:
import UIKit

class ViewController: UIViewController {

// @IBAction func Btndel(_ sender: Any) {
//}

var Str:String?

override func viewDidLoad() {
    super.viewDidLoad()
    let items = [Str]
    let SegM = UISegmentedControl(items:items as Any as? [Any])
    SegM.selectedSegmentIndex = 0

    SegM.frame=CGRect(x: 70, y: 130, width: 100, height: 50)
    SegM.layer.cornerRadius = 8.0
    SegM.backgroundColor = .orange
    SegM.tintColor = .white

    self.view .addSubview(SegM)

    // Do any additional setup after loading the view, typically from a nib.
}

@IBAction func Btnadd(_ sender: Any)
{
var Str = 0;Str += 1

}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

}

How to add and delete segments in a viewcontroller by clicking add button an delete button created in the same viewcontroller

Body:
How to insert and remove(add or delete) segments in swift4

class ViewController: UIViewController {

@IBOutlet weak var segment1: UISegmentedControl!

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
}

@IBAction func insert(_ sender: Any) {

    segment1.insertSegment(withTitle: "\(segment1.numberOfSegments+1)", at: segment1.numberOfSegments, animated: true)

    }

    @IBAction func remove(_ sender: Any) {

    segment1.removeSegment(at: segment1.numberOfSegments-1, animated: true)
}
}


问:
Extract value in Python
My Code:

```<code>import requests
import json

web_page = requests.get("http://api.bart.gov/api/etd.aspx?cmd=etd&orig=mont&key=MW9S-E7SL-26DU-VV8V&json=y")
response = web_page.text
parsed_json = json.loads(response)
#print(parsed_json)

print(parsed_json['root']['date'])
print(parsed_json['root']['time'])
print(parsed_json['root']['station']['name'])

</code>```

How to extract value of destination and minutes from below in Python.

```<code>[{'name': 'Montgomery St.', 'abbr': 'MONT', 'etd': [{'destination': 'Daly City', 'abbreviation': 'DALY', 'limited': '0', 'estimate': [{'minutes': '39', 'platform': '1', 'direction': 'South', 'length': '10', 'color': 'WHITE', 'hexcolor': '#ffffff', 'bikeflag': '1', 'delay': '220'}]}, {'destination': 'SF Airport', 'abbreviation': 'SFIA', 'limited': '0', 'estimate': [{'minutes': '16', 'platform': '1', 'direction': 'South', 'length': '10', 'color': 'YELLOW', 'hexcolor': '#ffff33', 'bikeflag': '1', 'delay': '132'}, {'minutes': '26', 'platform': '1', 'direction': 'South', 'length': '10', 'color': 'BLUE', 'hexcolor': '#0099cc', 'bikeflag': '1', 'delay': '69'}]}]}]

</code>```

答:
Assuming the data is in d_MONT:

```<code>d_MONT = {'name': 'Montgomery St.', 'abbr': 'MONT', 'etd': [{'destination': 'Antioch', 'abbreviation': 'ANTC', 'limited': '0', 'estimate': [{'minutes': '1', 'platform': '2', 'direction': 'North', 'length': '10', 'color': 'YELLOW', 'hexcolor': '#ffff33', 'bikeflag': '1', 'delay': '254'}]},

{'destination': 'Daly City', 'abbreviation': 'DALY', 'limited': '0', 'estimate': [{'minutes': '39', 'platform': '1', 'direction': 'South', 'length': '0', 'color': 'BLUE', 'hexcolor': '#0099cc', 'bikeflag': '1', 'delay': '0'}]},

{'destination': 'SF Airport', 'abbreviation': 'SFIA', 'limited': '0', 'estimate': [{'minutes': '38', 'platform': '1', 'direction': 'South', 'length': '10', 'color': 'YELLOW', 'hexcolor': '#ffff33', 'bikeflag': '1', 'delay': '0'}]}]}

</code>```

This will find the next train to destinationRequired:

```<code>destinationList = d_MONT['etd']

destinationRequired = 'Daly City'

for destinationDict in destinationList:
    if destinationDict['destination'] == destinationRequired:
        earliest = None
        for estimate in destinationDict['estimate']:
            if earliest is None or estimate['minutes'] < eariest:
                earliest = estimate['minutes']
        print("Next train to {0}: {1} minutes".format(destinationRequired, earliest))
        break

else:
    print("No trains to {0}".format(destinationRequired))
</code>```

Note there are more Pythonic ways to do this, and the code example above does not follow PEP8, but I think it is important you understand the basic logic of how to do what you want rather than a complex Python one-liner.

You do not document the JSON object format, so I don't think it is safe to assume the list of trains to destination will be in order, therefore the safest is to step through each one and find the earliest.  It isn't even clear if more than one train will ever be returned in the list, in which case a simple [0] would be sufficient rather than stepping through each one.

Title: Extract value in Python

Body:
My Code:

import requests
import json

web_page = requests.get("http://api.bart.gov/api/etd.aspx?cmd=etd&orig=mont&key=MW9S-E7SL-26DU-VV8V&json=y")
response = web_page.text
parsed_json = json.loads(response)
#print(parsed_json)

print(parsed_json['root']['date'])
print(parsed_json['root']['time'])
print(parsed_json['root']['station']['name'])

How to extract value of destination and minutes from below in Python.

[{'name': 'Montgomery St.', 'abbr': 'MONT', 'etd': [{'destination': 'Daly City', 'abbreviation': 'DALY', 'limited': '0', 'estimate': [{'minutes': '39', 'platform': '1', 'direction': 'South', 'length': '10', 'color': 'WHITE', 'hexcolor': '#ffffff', 'bikeflag': '1', 'delay': '220'}]}, {'destination': 'SF Airport', 'abbreviation': 'SFIA', 'limited': '0', 'estimate': [{'minutes': '16', 'platform': '1', 'direction': 'South', 'length': '10', 'color': 'YELLOW', 'hexcolor': '#ffff33', 'bikeflag': '1', 'delay': '132'}, {'minutes': '26', 'platform': '1', 'direction': 'South', 'length': '10', 'color': 'BLUE', 'hexcolor': '#0099cc', 'bikeflag': '1', 'delay': '69'}]}]}]

Body:
Assuming the data is in d_MONT:

d_MONT = {'name': 'Montgomery St.', 'abbr': 'MONT', 'etd': [{'destination': 'Antioch', 'abbreviation': 'ANTC', 'limited': '0', 'estimate': [{'minutes': '1', 'platform': '2', 'direction': 'North', 'length': '10', 'color': 'YELLOW', 'hexcolor': '#ffff33', 'bikeflag': '1', 'delay': '254'}]},

{'destination': 'Daly City', 'abbreviation': 'DALY', 'limited': '0', 'estimate': [{'minutes': '39', 'platform': '1', 'direction': 'South', 'length': '0', 'color': 'BLUE', 'hexcolor': '#0099cc', 'bikeflag': '1', 'delay': '0'}]},

{'destination': 'SF Airport', 'abbreviation': 'SFIA', 'limited': '0', 'estimate': [{'minutes': '38', 'platform': '1', 'direction': 'South', 'length': '10', 'color': 'YELLOW', 'hexcolor': '#ffff33', 'bikeflag': '1', 'delay': '0'}]}]}

This will find the next train to destinationRequired:

destinationList = d_MONT['etd']

destinationRequired = 'Daly City'

for destinationDict in destinationList:
    if destinationDict['destination'] == destinationRequired:
        earliest = None
        for estimate in destinationDict['estimate']:
            if earliest is None or estimate['minutes'] < eariest:
                earliest = estimate['minutes']
        print("Next train to {0}: {1} minutes".format(destinationRequired, earliest))
        break

else:
    print("No trains to {0}".format(destinationRequired))

Note there are more Pythonic ways to do this, and the code example above does not follow PEP8, but I think it is important you understand the basic logic of how to do what you want rather than a complex Python one-liner.

You do not document the JSON object format, so I don't think it is safe to assume the list of trains to destination will be in order, therefore the safest is to step through each one and find the earliest.  It isn't even clear if more than one train will ever be returned in the list, in which case a simple [0] would be sufficient rather than stepping through each one.


问:
Getting the error in react js that "this.props.sumOfPrices is not a function"?
I am new in react js and i am getting the following error "TypeError: this.props.sumOfPrices is not a function"
I am calling this function in the Course class clicker function using props.
My code is given below:

```<code>import React, { Component } from 'react';

class CourseSles extends Component {
    sumOfPrices(price){
        this.setState({total:this.state.total + price});
    }
    constructor(props) {
        super(props);
        this.state = { total:0 };
        this.sumOfPrices=this.sumOfPrices.bind(this);
    }

    render()
    {
        var courses=this.props.items.map(
        (item,i)=>{
         return <Course name={item.name} price={item.price} key={i} sumofPrices={this.sumOfPrices} active={item.active}/>
        });
        return(
        <div>
          <h1>You Can Buy Courses:</h1>
          <div id="courses">
              {courses}
        <p id="total">Toatal: <b>{this.state.total}</b></p>
          </div>
        </div>
        );
    }
}

class Course extends Component {
    clicker(){
      var active= !this.state.active;
      this.setState({active:active});
      this.props.sumOfPrices(active ? this.props.price : -this.props.price);
    }
    constructor(props) {
        super(props);
        this.state = { active:false };
        this.clicker=this.clicker.bind(this);
    }
    render() {
        return ( <div>
            <p onClick={this.clicker}>{this.props.name} <b>{this.props.price}</b></p>
        </div> );
    }
}

export default CourseSles;
</code>```

答:
You have typo error. Here is the running code</p>

```<code>import React, { Component } from 'react';
import Course from './Course';

class CourseSles extends Component {

    sumOfPrices(price){
        this.setState({total:this.state.total + price});
    }

    constructor(props) {
        super(props);
        this.state = { total:0 };
        this.sumOfPrices=this.sumOfPrices.bind(this);
    }

    render()
    {
        var courses=this.props.items.map(
        (item,i)=>{
         return <Course name={item.name} price={item.price} key={i} sumofPrices={this.sumOfPrices} active={item.active}/>
        });
        return(
        <div>
          <h1>You Can Buy Courses:</h1>
          <div id="courses">
              {courses}
        <p id="total">Toatal: <b>{this.state.total}</b></p>
          </div>
        </div>
        );
    }
}

class Course extends Component {

 clicker(){
   var active= !this.state.active;
   this.setState({active:active});
   this.props.sumofPrices(active ? this.props.price : -this.props.price);
 }
 constructor(props) {
     super(props);
     this.state = { active:false };
     this.clicker=this.clicker.bind(this);
 }
 render() {
     return ( <div>
         <p onClick={this.clicker}>{this.props.name} <b>{this.props.price}</b></p>
     </div> );
 }
}

export default CourseSles;
</code>```

Body:
I am new in react js and i am getting the following error "TypeError: this.props.sumOfPrices is not a function"
I am calling this function in the Course class clicker function using props.
My code is given below:

import React, { Component } from 'react';

class CourseSles extends Component {
    sumOfPrices(price){
        this.setState({total:this.state.total + price});
    }
    constructor(props) {
        super(props);
        this.state = { total:0 };
        this.sumOfPrices=this.sumOfPrices.bind(this);
    }

    render()
    {
        var courses=this.props.items.map(
        (item,i)=>{
         return <Course name={item.name} price={item.price} key={i} sumofPrices={this.sumOfPrices} active={item.active}/>
        });
        return(

You Can Buy Courses:

              {courses}

Toatal: {this.state.total}

        );
    }
}

class Course extends Component {
    clicker(){
      var active= !this.state.active;
      this.setState({active:active});
      this.props.sumOfPrices(active ? this.props.price : -this.props.price);
    }
    constructor(props) {
        super(props);
        this.state = { active:false };
        this.clicker=this.clicker.bind(this);
    }
    render() {
        return (

{this.props.name} {this.props.price}

 );
    }
}

export default CourseSles;

Body:
You have typo error. Here is the running code

import React, { Component } from 'react';
import Course from './Course';

class CourseSles extends Component {

    sumOfPrices(price){
        this.setState({total:this.state.total + price});
    }

    constructor(props) {
        super(props);
        this.state = { total:0 };
        this.sumOfPrices=this.sumOfPrices.bind(this);
    }

    render()
    {
        var courses=this.props.items.map(
        (item,i)=>{
         return <Course name={item.name} price={item.price} key={i} sumofPrices={this.sumOfPrices} active={item.active}/>
        });
        return(
        <div>
          <h1>You Can Buy Courses:</h1>
          <div id="courses">
              {courses}
        <p id="total">Toatal: <b>{this.state.total}</b></p>
          </div>
        </div>
        );
    }
}

class Course extends Component {

 clicker(){
   var active= !this.state.active;
   this.setState({active:active});
   this.props.sumofPrices(active ? this.props.price : -this.props.price);
 }
 constructor(props) {
     super(props);
     this.state = { active:false };
     this.clicker=this.clicker.bind(this);
 }
 render() {
     return ( <div>
         <p onClick={this.clicker}>{this.props.name} <b>{this.props.price}</b></p>
     </div> );
 }
}

export default CourseSles;


问:
Hold button howto
I need a hold button in android java. I tried with setOnTouchListener and it worked. But it is little too fast.
Is it possible to make the button slower, and to send value when the hold is let off for the same button?</p>

```<code>    buttonB.setOnTouchListener(new View.OnTouchListener() {
    @Override
    public boolean onTouch(View v, MotionEvent event) {
        yon=",B,";
        set++;

        if(set==360) set = 0;

        sensorView2.setText(set);
        packet+=set+yon;

        mConnectedThread.write(packet);
</code>```

答: for holding button, maybe you can use setOnLongClickListener instead of OnTouchListener</p>

Title: Hold button howto

Body:
I need a hold button in android java. I tried with setOnTouchListener and it worked. But it is little too fast.
Is it possible to make the button slower, and to send value when the hold is let off for the same button?

    buttonB.setOnTouchListener(new View.OnTouchListener() {
    @Override
    public boolean onTouch(View v, MotionEvent event) {
        yon=",B,";
        set++;

        if(set==360) set = 0;

        sensorView2.setText(set);
        packet+=set+yon;

        mConnectedThread.write(packet);


问:
Fill blank values with data from following columns
Having a dataframe like this:

```<code>data.frame(id = c(1,2,3,4), text1 = c("sth","","another",""), text2 = c("more","another","add",""), text3 = c("final","and","where","all"))
</code>```

How is it possible to detect if in the text1 column a row is blank and fill the blank with a value exist in text2, text3 or text4 column and leave from this NA after the process

Example of expected output

```<code>data.frame(id = c(1,2,3,4), text1 = c("sth","another","another","all"), text2 = c("more","","add",""), text3 = c("final","and","where",""))
</code>```

答:
You can use dplyr + purrr:

```<code>df %>%
 tidyr::nest(-id) %>%
 dplyr::mutate(
    new_text = purrr::map_chr(
    data, ~
       as.vector(t(.x[1,])) %>%
         .[. != ""] %>%
         dplyr::first())) %>%
  tidyr::unnest()

 A tibble: 4 x 5
     id text1   text2   text3 new_text
  <dbl> <fct>   <fct>   <fct> <chr>
1     1 sth     more    final sth
2     2 ""      another and   another
3     3 another add     where another
4     4 ""      ""      all   all
</code>```

Body:
Having a dataframe like this:

data.frame(id = c(1,2,3,4), text1 = c("sth","","another",""), text2 = c("more","another","add",""), text3 = c("final","and","where","all"))

How is it possible to detect if in the text1 column a row is blank and fill the blank with a value exist in text2, text3 or text4 column and leave from this NA after the process

Example of expected output

data.frame(id = c(1,2,3,4), text1 = c("sth","another","another","all"), text2 = c("more","","add",""), text3 = c("final","and","where",""))

Body:
You can use dplyr + purrr:

df %>%
 tidyr::nest(-id) %>%
 dplyr::mutate(
    new_text = purrr::map_chr(
    data, ~
       as.vector(t(.x[1,])) %>%
         .[. != ""] %>%
         dplyr::first())) %>%
  tidyr::unnest()

 A tibble: 4 x 5
     id text1   text2   text3 new_text
  <dbl> <fct>   <fct>   <fct> <chr>
1     1 sth     more    final sth
2     2 ""      another and   another
3     3 another add     where another
4     4 ""      ""      all   all


问:
How to map objects as fields with mapstruct?
I need to map multiples dto's to entities.
Almost all of them have a reference to another one and I don't know how to pass the reference while mapping the dto.

Here is one business implementation for the Address :

```<code>addressRepository.saveAll(dtos.stream()
                .map(addressMapper::asEntity)
                .collect(Collectors.toList())).stream()
                .map(addressMapper::asDto)
                .collect(Collectors.toList());
</code>```

Here is the mapper

```<code>    @Mappings({
            @Mapping(target="streetName", source="streetName"),
            @Mapping(target="streetNumber", source="streetNumber"),
            @Mapping(target="block", source="block"),
            @Mapping(target="floor", source="floor")

    })
    CsvBusinessData asDto(AddressEntity address);

    @InheritInverseConfiguration
    AddressEntity asAddressEntity(CsvBusinessData address);
</code>```

All the implementors reads from the same dto and then map them to dto and entites.

Here is for the customer implmentation :

```<code>customerRepository.saveAll(dtos.stream()
            .map( csvMapper::asCustomerEntity)

            .collect(Collectors.toList())).stream()
            .map(customerMapper::asDto)
            .collect(Collectors.toList());
</code>```

And the mapping where I want a reference to mapped address entity (my customer entity has an Address type field).

```<code> @Mappings({
            @Mapping(target = "nom", source = "lastName"),
            @Mapping(target = "nd", source = "accountNumber"),
            @Mapping(target = "logo", source = "logo"),
            @Mapping(target = "address", source = "address"
            )

    })
    CsvBusinessData asDto(CustomerEntity customer);

    @InheritInverseConfiguration
    CustomerEntity asCustomerEntity(CsvBusinessData customer);
</code>```

Thank You very much.

答:
First of all you don't have to make mapping for fields with the same name, MapStruct doing it for you.For example block-block.
1)Your objects are related:
You could use "uses" funcrionality for related objects.

```<code>@Mapper(uses = {AddressMapper.class}, unmappedTargetPolicy = ReportingPolicy.IGNORE)
public interface CustomerMapper {
    @Mapping(target = "nom", source = "lastName")
    @Mapping(target = "nd", source = "accountNumber")
    @Mapping(target = "logo", source = "logo") // not needed as same name, delete it
    @Mapping(target = "address", source = "address") // not needed as same name, delete it
    CsvBusinessData asDto(CustomerEntity customer);

    @InheritInverseConfiguration
    CustomerEntity asCustomerEntity(CsvBusinessData customer);
}

@Mapper( unmappedTargetPolicy = ReportingPolicy.IGNORE)
public interface CustomerMapper {
    @Mapping(target="streetName", source="streetName") // not needed as same name, delete it
    @Mapping(target="streetNumber", source="streetNumber") // not needed as same name, delete it
    @Mapping(target="block", source="block") // not needed as same name, delete it
    @Mapping(target="floor", source="floor") // not needed as same name, delete it
    CsvBusinessData asDto(AddressEntity address);
}
</code>```

2)Your objects don't related:
You could solve your case by passing few object as parameters. But then you must have your own methods for opposite direction. If you have same field name in AddressEntity and CustomerEntity then just specify it address.streetName or customer.lastName

```<code>@Mapping(target="streetName", source="streetName")// possibly not needed as same name
@Mapping(target="streetNumber", source="streetNumber")// possibly not needed as same name
@Mapping(target="block", source="block")// possibly not needed as same name
@Mapping(target="floor", source="floor")// possibly not needed as same name
@Mapping(target = "nom", source = "lastName")
@Mapping(target = "nd", source = "accountNumber")
@Mapping(target = "logo", source = "logo")// possibly not needed as same name
@Mapping(target = "address", source = "customer.address") // specified as you have parameter address
CsvBusinessData asDto(AddressEntity address, CustomerEntity customer);

@Mapping(target="streetName", source="streetName")// possibly not needed as same name
@Mapping(target="streetNumber", source="streetNumber")// possibly not needed as same name
@Mapping(target="block", source="block")// possibly not needed as same name
@Mapping(target="floor", source="floor")// possibly not needed as same name
AddressEntity asAddressEntity(CsvBusinessData businessData);

@Mapping(source = "nom", target = "lastName")
@Mapping(source = "nd", target = "accountNumber")
@Mapping(source = "logo", target = "logo")// possibly not needed as same name
@Mapping(source = "address", target = "address") // specified as you have parameter address
CustomerEntity asCustomerEntity(CsvBusinessData businessData);
</code>```

Body:
I need to map multiples dto's to entities.
Almost all of them have a reference to another one and I don't know how to pass the reference while mapping the dto.

Here is one business implementation for the Address :

addressRepository.saveAll(dtos.stream()
                .map(addressMapper::asEntity)
                .collect(Collectors.toList())).stream()
                .map(addressMapper::asDto)
                .collect(Collectors.toList());

Here is the mapper

    @Mappings({
            @Mapping(target="streetName", source="streetName"),
            @Mapping(target="streetNumber", source="streetNumber"),
            @Mapping(target="block", source="block"),
            @Mapping(target="floor", source="floor")

    })
    CsvBusinessData asDto(AddressEntity address);

    @InheritInverseConfiguration
    AddressEntity asAddressEntity(CsvBusinessData address);

All the implementors reads from the same dto and then map them to dto and entites.

Here is for the customer implmentation :

customerRepository.saveAll(dtos.stream()
            .map( csvMapper::asCustomerEntity)

            .collect(Collectors.toList())).stream()
            .map(customerMapper::asDto)
            .collect(Collectors.toList());

And the mapping where I want a reference to mapped address entity (my customer entity has an Address type field).

 @Mappings({
            @Mapping(target = "nom", source = "lastName"),
            @Mapping(target = "nd", source = "accountNumber"),
            @Mapping(target = "logo", source = "logo"),
            @Mapping(target = "address", source = "address"
            )

    })
    CsvBusinessData asDto(CustomerEntity customer);

    @InheritInverseConfiguration
    CustomerEntity asCustomerEntity(CsvBusinessData customer);

Thank You very much.

Body:
First of all you don't have to make mapping for fields with the same name, MapStruct doing it for you.For example block-block.
1)Your objects are related:
You could use "uses" funcrionality for related objects.

@Mapper(uses = {AddressMapper.class}, unmappedTargetPolicy = ReportingPolicy.IGNORE)
public interface CustomerMapper {
    @Mapping(target = "nom", source = "lastName")
    @Mapping(target = "nd", source = "accountNumber")
    @Mapping(target = "logo", source = "logo") // not needed as same name, delete it
    @Mapping(target = "address", source = "address") // not needed as same name, delete it
    CsvBusinessData asDto(CustomerEntity customer);

    @InheritInverseConfiguration
    CustomerEntity asCustomerEntity(CsvBusinessData customer);
}

@Mapper( unmappedTargetPolicy = ReportingPolicy.IGNORE)
public interface CustomerMapper {
    @Mapping(target="streetName", source="streetName") // not needed as same name, delete it
    @Mapping(target="streetNumber", source="streetNumber") // not needed as same name, delete it
    @Mapping(target="block", source="block") // not needed as same name, delete it
    @Mapping(target="floor", source="floor") // not needed as same name, delete it
    CsvBusinessData asDto(AddressEntity address);
}

2)Your objects don't related:
You could solve your case by passing few object as parameters. But then you must have your own methods for opposite direction. If you have same field name in AddressEntity and CustomerEntity then just specify it address.streetName or customer.lastName

@Mapping(target="streetName", source="streetName")// possibly not needed as same name
@Mapping(target="streetNumber", source="streetNumber")// possibly not needed as same name
@Mapping(target="block", source="block")// possibly not needed as same name
@Mapping(target="floor", source="floor")// possibly not needed as same name
@Mapping(target = "nom", source = "lastName")
@Mapping(target = "nd", source = "accountNumber")
@Mapping(target = "logo", source = "logo")// possibly not needed as same name
@Mapping(target = "address", source = "customer.address") // specified as you have parameter address
CsvBusinessData asDto(AddressEntity address, CustomerEntity customer);

@Mapping(target="streetName", source="streetName")// possibly not needed as same name
@Mapping(target="streetNumber", source="streetNumber")// possibly not needed as same name
@Mapping(target="block", source="block")// possibly not needed as same name
@Mapping(target="floor", source="floor")// possibly not needed as same name
AddressEntity asAddressEntity(CsvBusinessData businessData);

@Mapping(source = "nom", target = "lastName")
@Mapping(source = "nd", target = "accountNumber")
@Mapping(source = "logo", target = "logo")// possibly not needed as same name
@Mapping(source = "address", target = "address") // specified as you have parameter address
CustomerEntity asCustomerEntity(CsvBusinessData businessData);


答:
Try this to get json data:

```<code>import json

# some JSON:
json_data= {'destination': 'Daly City', 'abbreviation': 'DALY', 'limited': '0', 'estimate': [{'minutes': '39', 'platform': '1', 'direction': 'South', 'length': '0', 'color': 'BLUE', 'hexcolor': '#0099cc', 'bikeflag': '1', 'delay': '0'}]}

# parse json_data:
data = json.dumps(json_data)
extract_json = json.loads(data)

print("Destination: "+extract_json["destination"])
print("Minutes: "+extract_json["estimate"][0]["minutes"])
</code>```

Output:

```<code>Destination: Daly City
Minutes: 39
</code>```

Title: Extract value in Python

Body:
Try this to get json data:

import json

# some JSON:
json_data= {'destination': 'Daly City', 'abbreviation': 'DALY', 'limited': '0', 'estimate': [{'minutes': '39', 'platform': '1', 'direction': 'South', 'length': '0', 'color': 'BLUE', 'hexcolor': '#0099cc', 'bikeflag': '1', 'delay': '0'}]}

# parse json_data:
data = json.dumps(json_data)
extract_json = json.loads(data)

print("Destination: "+extract_json["destination"])
print("Minutes: "+extract_json["estimate"][0]["minutes"])

Output:

Destination: Daly City
Minutes: 39


问:
Laravel Deployment : PHP Error Unable to load dynamic library 'pdo_pgsql'
I want to deploy my laravel app in ubuntu server 18 LTS. So I have install nginx postgres php. But when i try to do php artisan migrate I have this returned error :

This is the errror (a picture beacose of comande line)
.

So I have verify different thing :
First I can access to my data base in localhost with the postgres user.
The laravel app work while database not be required.

In php.ini I have uncomment extention=pdo-pgsql; and extention=pgsql

I have install the php postgres sql extension with this command sudo apt-get install php7.2-pgsql

And this is my .env settings for database in laravel :

```<code>DB_CONNECTION=pgsql
DB_HOST=127.0.0.1
DB_PORT=5433
DB_DATABASE=THERY //I have already create the database
DB_USERNAME=postgres
DB_PASSWORD=postgres

</code>```

答:
There may be different issues for your problem. Any of the below may be occured:

php PGsql is not installed. install it by

```<code>apt-get install php-pgsql
</code>```

PGsql library is missing in the composer. install it by

```<code>composer require asmiarowski/laravel-postgres // There are multiple librariies available in packagist
</code>```

Your config in .env are not cached. you can cache them by running command

```<code>php artisan config:cache
</code>```

Your PGSql server is not reachable. you can take further action to resolve them.

Body:
I want to deploy my laravel app in ubuntu server 18 LTS. So I have install nginx postgres php. But when i try to do php artisan migrate I have this returned error :

This is the errror (a picture beacose of comande line)
.

So I have verify different thing :
First I can access to my data base in localhost with the postgres user.
The laravel app work while database not be required.

In php.ini I have uncomment extention=pdo-pgsql; and extention=pgsql

I have install the php postgres sql extension with this command sudo apt-get install php7.2-pgsql

And this is my .env settings for database in laravel :

DB_CONNECTION=pgsql
DB_HOST=127.0.0.1
DB_PORT=5433
DB_DATABASE=THERY //I have already create the database
DB_USERNAME=postgres
DB_PASSWORD=postgres

Body:
There may be different issues for your problem. Any of the below may be occured:

php PGsql is not installed. install it by

apt-get install php-pgsql

PGsql library is missing in the composer. install it by

composer require asmiarowski/laravel-postgres // There are multiple librariies available in packagist

Your config in .env are not cached. you can cache them by running command

php artisan config:cache

Your PGSql server is not reachable. you can take further action to resolve them.