问:
How to convert a string UTC date to NSDate in Swift
I'm getting UTC string dates that look like this "2015-10-17T00:00:00.000Z" and want to convert them to an NSDate in this format "October 12th 2015 11:19:12 am"

This is the route that I'm trying but I can't seem to get the right dateFormat.

```<code>let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = //can't seem to get this right
dateFormatter.timeZone = NSTimeZone(name: "UTC")
let date = dateFormatter.dateFromString("2015-10-17T00:00:00.000Z")
</code>```

答:
This question is a few years old but let's answer it literally.

First of all DateFormatter doesn't provide a format specifier for an ordinal suffix so we have to write a function

```<code>func ordinalSuffix(for day : String) -> String {
    switch day {
        case "1", "11", "21", "31": return "st"
        case "2", "12", "22": return "nd"
        case "3", "13", "23": return "rd"
        default: return "th"
    }
}
</code>```

To convert the iso8601 string to date create a DateFormatter, set its calendar to an iso8601 calendar and convert the string to Date. As the time zone is specified in the string you don't need to set it explicitly

```<code>let dateString = "2015-10-17T00:00:00.000Z"
let formatter = DateFormatter()
formatter.calendar = Calendar(identifier: .iso8601)
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
guard let date = formatter.date(from: dateString) else {
    // replace that with a proper error handling
    fatalError("Could not convert date string")
}
</code>```

To convert the date back to string you have to set the Locale to a fixed value, set the am/pm symbols to the lowercase versions, extract the day component first for the ordinal suffix calculation and then take advantage of String(format to insert the ordinal suffix.

```<code>formatter.locale = Locale(identifier: "en_US_POSIX")
formatter.amSymbol = "am"
formatter.pmSymbol = "pm"
formatter.dateFormat = "dd"
let day = formatter.string(from: date)
formatter.dateFormat = "MMMM dd'%@' yyyy h:mm:ss a"
let output = String(format: formatter.string(from: date), ordinalSuffix(for: day))
print(output)
</code>```

Body:
I'm getting UTC string dates that look like this "2015-10-17T00:00:00.000Z" and want to convert them to an NSDate in this format "October 12th 2015 11:19:12 am"

This is the route that I'm trying but I can't seem to get the right dateFormat.

let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = //can't seem to get this right
dateFormatter.timeZone = NSTimeZone(name: "UTC")
let date = dateFormatter.dateFromString("2015-10-17T00:00:00.000Z")

Body:
This question is a few years old but let's answer it literally.

First of all DateFormatter doesn't provide a format specifier for an ordinal suffix so we have to write a function

func ordinalSuffix(for day : String) -> String {
    switch day {
        case "1", "11", "21", "31": return "st"
        case "2", "12", "22": return "nd"
        case "3", "13", "23": return "rd"
        default: return "th"
    }
}

To convert the iso8601 string to date create a DateFormatter, set its calendar to an iso8601 calendar and convert the string to Date. As the time zone is specified in the string you don't need to set it explicitly

let dateString = "2015-10-17T00:00:00.000Z"
let formatter = DateFormatter()
formatter.calendar = Calendar(identifier: .iso8601)
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
guard let date = formatter.date(from: dateString) else {
    // replace that with a proper error handling
    fatalError("Could not convert date string")
}

To convert the date back to string you have to set the Locale to a fixed value, set the am/pm symbols to the lowercase versions, extract the day component first for the ordinal suffix calculation and then take advantage of String(format to insert the ordinal suffix.

formatter.locale = Locale(identifier: "en_US_POSIX")
formatter.amSymbol = "am"
formatter.pmSymbol = "pm"
formatter.dateFormat = "dd"
let day = formatter.string(from: date)
formatter.dateFormat = "MMMM dd'%@' yyyy h:mm:ss a"
let output = String(format: formatter.string(from: date), ordinalSuffix(for: day))
print(output)


来源: stackexchange

问:
Entity Framework Code First contraint when one column value depends on another
I have the following model:

```<code>class RentOrder
{
    public DateTime StartDate { get; set; }
    public DateTime EndDate { get; set; }
}
</code>```

How can I add constraint in Entity Framework Code First that StartDate must be always less than EndDate? The only way I know is to add it by executing SQL-command in overridden Seed method. Is there more simple way, without SQL?

答:
The only way to solve this problem now, as I mentioned in question, is to write SQL-commands in Seed method:

```<code>public class MyDatabaseInitializer : DropCreateDatabaseAlways<MyDatabaseContext>
{
    protected override void Seed(MyDatabaseContext context)
    {
        context.Database.ExecuteSqlCommand(@"ALTER TABLE Orders
            ADD CONSTRAINT C_Dates CHECK(EndDate > StartDate)");
    }
}
</code>```

And call somewhere on the application start:

```<code>Database.SetInitializer(new MyDatabaseInitializer());
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have the following model:

class RentOrder
{
    public DateTime StartDate { get; set; }
    public DateTime EndDate { get; set; }
}

How can I add constraint in Entity Framework Code First that StartDate must be always less than EndDate? The only way I know is to add it by executing SQL-command in overridden Seed method. Is there more simple way, without SQL?

Body:
The only way to solve this problem now, as I mentioned in question, is to write SQL-commands in Seed method:

public class MyDatabaseInitializer : DropCreateDatabaseAlways<MyDatabaseContext>
{
    protected override void Seed(MyDatabaseContext context)
    {
        context.Database.ExecuteSqlCommand(@"ALTER TABLE Orders
            ADD CONSTRAINT C_Dates CHECK(EndDate > StartDate)");
    }
}

And call somewhere on the application start:

Database.SetInitializer(new MyDatabaseInitializer());


问:
cancel a web request and handle errors inside the ReverseProxy Director function
I am wondering if it would be possible to cancel a web request or send an internal response to the client inside the ReverseProxy.Director function.

Suppose we do something that throws an error, or we have other reason to not forward the request.

proxy := &httputil.ReverseProxy{
    Director: func(r *http.Request) {
        err := somethingThatThrows()
    },
}

http.Handle("/", proxy)
```
<p>A solution to this might be the below, but it's not as neat as the above way to use the proxy. I am also not sure to which degree the request should be modified that way. The director seems to be the place to do that.</p>
<pre class="lang-golang prettyprint-override"><code>http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
    err := somethingThatThrows()
    if err != nil {
        w.WriteHeader(http.StatusInternalServerError)
        return
    }
    proxy.ServeHTTP(w, r)
})
</code>```

答:
if it would be possible to cancel a web request [...]

You can cancel the request that is passed to the Director function, BUT there are some details to consider:

the correct way to cancel a request is to cancel its context

you can not cancel contexts where you didn't set a (deadline|timeout|cancelfunc) yourself → i.e. you must have access to the cancel function → i.e. you can't cancel parent contexts created by someone else.

the *http.Request passed to Director function is a clone of the original request

Based on the points above, you can replace the request in the Director with another one that has a cancellable context. It may look like the following:

```<code>proxy := &httputil.ReverseProxy{
    Director: func(req *http.Request) {

        // create a cancellable context, and re-set the request
        ctx, cancel := context.WithCancel(req.Context())
        *req = *req.WithContext(ctx)

        err := somethingThatThrows()
        if err != nil {
            cancel()
            return
        }
    },
}
</code>```

Then the code above doesn't do anything else by itself. What should happen is that the httputil.ReverseProxy.Transport function, which implements http.RoundTripper checks whether the request context is cancelled, before actually send anything to the upstream service.

The documentation of Director states:

Director must be a function which modifies the request into a new request to be sent using Transport.

When the Transport is not provided, it will fall back to http.DefaultTransport, which aborts the request when the context is cancelled. The current code (Go 1.17.5) looks like:

```<code>        select {
        case <-ctx.Done():
            req.closeBody()
            return nil, ctx.Err()
        default:
        }
</code>```

If you provide your own implementation of http.RoundTripper you may want to implement that behavior yourself. Remember also that the context done channel is nil if it's not cancellable, so you have to set a cancel func and call cancel() in order to have that select run the "done" case.

or send an internal response to the client inside the ReverseProxy.Director

Based on the same quote above docs, you should not write to the http.ResponseWriter from within the Director function — assuming you are even closing around it. As you can see the Director itself doesn't get the http.ResponseWriter as an argument, and this should already be a self-explanatory detail.

If you want to specify some other behavior in case the request can't be forwarded, and assuming that whatever implementation of http.RoundTripper is returning error when the req context is cancelled, you can provide your ReverseProxy.ErrorHandler function:

```<code>proxy.ErrorHandler = func(writer http.ResponseWriter, request *http.Request, err error) {
    // inspect err
    // write to writer
}
</code>```

The ErrorHandler will be invoked when Transport returns error, including when the error comes from a cancelled request, and it does have http.ResponseWriter as an argument.

ContentLicense: CC BY-SA 4.0

Body:
I am wondering if it would be possible to cancel a web request or send an internal response to the client inside the ReverseProxy.Director function.

Suppose we do something that throws an error, or we have other reason to not forward the request.

proxy := &httputil.ReverseProxy{
    Director: func(r *http.Request) {
        err := somethingThatThrows()
    },
}

http.Handle("/", proxy)

A solution to this might be the below, but it's not as neat as the above way to use the proxy. I am also not sure to which degree the request should be modified that way. The director seems to be the place to do that.

http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
    err := somethingThatThrows()
    if err != nil {
        w.WriteHeader(http.StatusInternalServerError)
        return
    }
    proxy.ServeHTTP(w, r)
})

Body:
if it would be possible to cancel a web request [...]

You can cancel the request that is passed to the Director function, BUT there are some details to consider:

the correct way to cancel a request is to cancel its context

you can not cancel contexts where you didn't set a (deadline|timeout|cancelfunc) yourself → i.e. you must have access to the cancel function → i.e. you can't cancel parent contexts created by someone else.

the *http.Request passed to Director function is a clone of the original request

Based on the points above, you can replace the request in the Director with another one that has a cancellable context. It may look like the following:

proxy := &httputil.ReverseProxy{
    Director: func(req *http.Request) {

        // create a cancellable context, and re-set the request
        ctx, cancel := context.WithCancel(req.Context())
        *req = *req.WithContext(ctx)

        err := somethingThatThrows()
        if err != nil {
            cancel()
            return
        }
    },
}

Then the code above doesn't do anything else by itself. What should happen is that the httputil.ReverseProxy.Transport function, which implements http.RoundTripper checks whether the request context is cancelled, before actually send anything to the upstream service.

The documentation of Director states:

Director must be a function which modifies the request into a new request to be sent using Transport.

When the Transport is not provided, it will fall back to http.DefaultTransport, which aborts the request when the context is cancelled. The current code (Go 1.17.5) looks like:

        select {
        case <-ctx.Done():
            req.closeBody()
            return nil, ctx.Err()
        default:
        }

If you provide your own implementation of http.RoundTripper you may want to implement that behavior yourself. Remember also that the context done channel is nil if it's not cancellable, so you have to set a cancel func and call cancel() in order to have that select run the "done" case.

or send an internal response to the client inside the ReverseProxy.Director

Based on the same quote above docs, you should not write to the http.ResponseWriter from within the Director function — assuming you are even closing around it. As you can see the Director itself doesn't get the http.ResponseWriter as an argument, and this should already be a self-explanatory detail.

If you want to specify some other behavior in case the request can't be forwarded, and assuming that whatever implementation of http.RoundTripper is returning error when the req context is cancelled, you can provide your ReverseProxy.ErrorHandler function:

proxy.ErrorHandler = func(writer http.ResponseWriter, request *http.Request, err error) {
    // inspect err
    // write to writer
}

The ErrorHandler will be invoked when Transport returns error, including when the error comes from a cancelled request, and it does have http.ResponseWriter as an argument.


问:
Covert SQL to Laravel Query Builder
I'm a beginner regarding Laravel Query Builder, can you guys help me convert this SQL to Query Builder

```<code>public function check_available_room(Request $request, $checkin_date)
{
    $available_rooms = DB::SELECT("SELECT * FROM rooms WHERE id NOT IN (SELECT room_id FROM bookings WHERE '$checkin_date' BETWEEN checkin_date AND checkout_date)");

}
</code>```

Book model

function rooms() {
   return $this->belongsTo(Room::class, 'room_id');
}
```
<p><strong>Room model</strong></p>
<pre class="lang-php prettyprint-override"><code>public function bookings() {
    return $this->hasMany(Booking::class);
}
</code>```

Thank you so much

答:
Here is a solution if you have your models and relations in place</p>
```<code>$availableRooms = Room::whereDoesntHave('bookings', function($bookingQuery) use ($checkin_date) {
    $bookingQuery->where('checkin_date', '<', $checkin_date)
    ->where('checkout_date', '>=', $checkin_date);
})->get();
</code>```

Title: Covert SQL to Laravel Query Builder

Body:
I'm a beginner regarding Laravel Query Builder, can you guys help me convert this SQL to Query Builder

public function check_available_room(Request $request, $checkin_date)
{
    $available_rooms = DB::SELECT("SELECT * FROM rooms WHERE id NOT IN (SELECT room_id FROM bookings WHERE '$checkin_date' BETWEEN checkin_date AND checkout_date)");

}

Book model

function rooms() {
   return $this->belongsTo(Room::class, 'room_id');
}

Room model

public function bookings() {
    return $this->hasMany(Booking::class);
}

Thank you so much

Body:
Here is a solution if you have your models and relations in place

$availableRooms = Room::whereDoesntHave('bookings', function($bookingQuery) use ($checkin_date) {
    $bookingQuery->where('checkin_date', '<', $checkin_date)
    ->where('checkout_date', '>=', $checkin_date);
})->get();


问:
SwiftUI: Custom view is un-hittable in XCTest
During Xcode UI test, I found my custom view's (MenuViewButton) is un-hittable in a test, I could found it but cannot touch it. In debug , when I po isHittable in console, it returns false. However I'm not sure if this is the correct behavior.

Per this thread XCUIElement exists, but is not hittable said, isHittable is default false for custom view element, and default true for UIKit standard view. But I don't know if it is the same behavior in SwiftUI.

Since the way someView.isAccessibilityElement = true  is not possible in SwiftUI. My question is how could I let my custom view became hittable? Then it could be tapped in a test.

```<code>    private var aView: some View {
        MenuViewButton(
            image: Image("an image name"),
            text: Text("a string")
        )
        .accessibility(identifier: "xxx name")
    }
</code>```

I also use force tap with coordinate in case tap() is not working, but to give a offset of normalizedOffset didn't fix the problem in all places, it means some un-hittable element could be tapped, that is great but some others still not.

So may I know where normalizedOffset is start, from the middle of frame to give the offset or the top left?

```<code>    func forceTapElement(timeout: TimeInterval) {
        if !self.waitForExistence(timeout: timeout) {
            return
        }

        if self.isHittable {
            self.tap()
        } else {
            let coordinate: XCUICoordinate = self.coordinate(withNormalizedOffset: CGVector(dx: 0.1, dy: 0.0))
            coordinate.tap()
        }
    }
</code>```

答:
Add https://github.com/devexperts/screenobject as a dependency

Use .tapUnhittable() instead of .tap() for this particular view. It gets the coordinates and taps using them

Body:
During Xcode UI test, I found my custom view's (MenuViewButton) is un-hittable in a test, I could found it but cannot touch it. In debug , when I po isHittable in console, it returns false. However I'm not sure if this is the correct behavior.

Per this thread XCUIElement exists, but is not hittable said, isHittable is default false for custom view element, and default true for UIKit standard view. But I don't know if it is the same behavior in SwiftUI.

Since the way someView.isAccessibilityElement = true  is not possible in SwiftUI. My question is how could I let my custom view became hittable? Then it could be tapped in a test.

    private var aView: some View {
        MenuViewButton(
            image: Image("an image name"),
            text: Text("a string")
        )
        .accessibility(identifier: "xxx name")
    }

I also use force tap with coordinate in case tap() is not working, but to give a offset of normalizedOffset didn't fix the problem in all places, it means some un-hittable element could be tapped, that is great but some others still not.

So may I know where normalizedOffset is start, from the middle of frame to give the offset or the top left?

    func forceTapElement(timeout: TimeInterval) {
        if !self.waitForExistence(timeout: timeout) {
            return
        }

        if self.isHittable {
            self.tap()
        } else {
            let coordinate: XCUICoordinate = self.coordinate(withNormalizedOffset: CGVector(dx: 0.1, dy: 0.0))
            coordinate.tap()
        }
    }


问:
Why Is My Inline Table UDF so much slower when I use variable parameters rather than constant parameters?
I have a table-valued, inline UDF.  I want to filter the results of that UDF to get one particular value.  When I specify the filter using a constant parameter, everything is great and performance is almost instantaneous.  When I specify the filter using a variable parameter, it takes a significantly larger chunk of time, on the order of 500x more logical reads and 20x greater duration.

The execution plan shows that in the variable parameter case the filter is not applied until very late in the process, causing multiple index scans rather than the seeks that are performed in the constant case.

I guess my questions are:  Why, since I'm specifying a single filter parameter that is going to be highly selective against an indexed field, does my performance go into the weeds when that parameter is in a variable?  Is there anything I can do about this?

Does it have something to do with the analytic function in the query?

Here are my queries:

```<code>CREATE FUNCTION fn_test()
RETURNS TABLE
WITH SCHEMABINDING
AS
    RETURN
    SELECT DISTINCT GCN_SEQNO, Drug_package_version_ID
    FROM
    (
        SELECT COALESCE(ndctbla.GCN_SEQNO, ndctblb.GCN_SEQNO) AS GCN_SEQNO,
            dpv.Drug_package_version_ID, ROW_NUMBER() OVER (PARTITION BY dpv.Drug_package_version_id ORDER BY
                ndctbla.GCN_SEQNO DESC) AS Predicate
        FROM dbo.Drug_Package_Version dpv
            LEFT JOIN dbo.NDC ndctbla ON ndctbla.NDC = dpv.Sp_package_code
            LEFT JOIN dbo.NDC ndctblb ON ndctblb.SPC_NDC = dpv.Sp_package_code
    ) iq
    WHERE Predicate = 1
GO

GRANT SELECT ON fn_test TO public
GO

-- very fast
SELECT GCN_SEQNO
FROM dbo.fn_test()
WHERE Drug_package_version_id = 10000

GO

-- comparatively slow
DECLARE @dpvid int
SET @dpvid = 10000
SELECT GCN_SEQNO
FROM dbo.fn_test()
WHERE Drug_package_version_id = @dpvid
</code>```

答:
Once you create a new projection through a UDF, it can't be expected that your indexes will still apply on the columns that are indexed on the original table and included in the projection.  When you filter on the projection (and not in the UDF against the original table with the indexes) the indexes no longer apply.

What you want to do is parameterize the function to take in the parameter.

If you find that you have too many fields that you want to set parameters on, then you might want to take a look at indexed views, as you can create your projection and index it as well and then run queries against that.

OwnerDisplayName: mwigdahl

ContentLicense: CC BY-SA 2.5

Body:
I have a table-valued, inline UDF.  I want to filter the results of that UDF to get one particular value.  When I specify the filter using a constant parameter, everything is great and performance is almost instantaneous.  When I specify the filter using a variable parameter, it takes a significantly larger chunk of time, on the order of 500x more logical reads and 20x greater duration.

The execution plan shows that in the variable parameter case the filter is not applied until very late in the process, causing multiple index scans rather than the seeks that are performed in the constant case.

I guess my questions are:  Why, since I'm specifying a single filter parameter that is going to be highly selective against an indexed field, does my performance go into the weeds when that parameter is in a variable?  Is there anything I can do about this?

Does it have something to do with the analytic function in the query?

Here are my queries:

CREATE FUNCTION fn_test()
RETURNS TABLE
WITH SCHEMABINDING
AS
    RETURN
    SELECT DISTINCT GCN_SEQNO, Drug_package_version_ID
    FROM
    (
        SELECT COALESCE(ndctbla.GCN_SEQNO, ndctblb.GCN_SEQNO) AS GCN_SEQNO,
            dpv.Drug_package_version_ID, ROW_NUMBER() OVER (PARTITION BY dpv.Drug_package_version_id ORDER BY
                ndctbla.GCN_SEQNO DESC) AS Predicate
        FROM dbo.Drug_Package_Version dpv
            LEFT JOIN dbo.NDC ndctbla ON ndctbla.NDC = dpv.Sp_package_code
            LEFT JOIN dbo.NDC ndctblb ON ndctblb.SPC_NDC = dpv.Sp_package_code
    ) iq
    WHERE Predicate = 1
GO

GRANT SELECT ON fn_test TO public
GO

-- very fast
SELECT GCN_SEQNO
FROM dbo.fn_test()
WHERE Drug_package_version_id = 10000

GO

-- comparatively slow
DECLARE @dpvid int
SET @dpvid = 10000
SELECT GCN_SEQNO
FROM dbo.fn_test()
WHERE Drug_package_version_id = @dpvid

OwnerDisplayName: casperOne

LastEditorDisplayName: casperOne


问:
Android Null Pointer Exception Madness?
So I have 3 Activities that need to all have access to the same custom class object (let's call it 'a') created by me when the very first Activity is created.

Because 'a' is made up of a whole bunch of non-primitives, I found it difficult to make Serializable or Parcelable. Instead I created a Service that binds to each Activity as they take the forefront, and gives the Activity 'a' in OnBind().

Now 'a' has a getter that gets another object of a different custom class stored with the same object (let's call it 'b'). In all three Activities, I also need to be able to access 'b'.

If I start the first Activity, use a button to navigate to the second Activity, press the "home" button on my phone, then go back into the application by pressing its icon, then navigate to the third activity by pressing a button, I get a null pointer exception on 'b' but not 'a'.

However if I add a line that prints 'a's getter for 'b' with sysout in the step where I press a button to get from the second Activity to the third, then there is no null pointer exception.

Does anybody know why this is and how I can resolve the issue?

答:
Seems you want this object a to always be there!

I suggest extending application

```<code>public class YourApplication extends Application {
    YourObject A;
    @Override
    public void onCreate(){
        A = new YourObject();
    }
    //add getters or setters //
}
</code>```

Now in your Activities:

```<code>YourApplication app;
app = app = ((YourApplication)getApplicationContext());
</code>```

Finally in your Mainfest: Add to <application>

```<code>android:name=".YourApplication"
</code>```

Title: Android Null Pointer Exception Madness?

Body:
Seems you want this object a to always be there!

I suggest extending application

public class YourApplication extends Application {
    YourObject A;
    @Override
    public void onCreate(){
        A = new YourObject();
    }
    //add getters or setters //
}

Now in your Activities:

YourApplication app;
app = app = ((YourApplication)getApplicationContext());

Finally in your Mainfest: Add to <application>

android:name=".YourApplication"


问:
How to solve Error inflating class in Android?
I have a custom view that extends the constraint layout as follows :

```<code><?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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="wrap_content">

    <TextView
        android:id="@+id/textViewMyTitle"
        style="@style/LabelLowLevel"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:text="My Title"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <Button
        android:id="@+id/buttonEditMy"
        style="@style/InlineButtonTransparent"
        android:layout_width="wrap_content"
        android:text="@string/edit"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/textViewMyTitle" />

    <Button
        android:id="@+id/buttonPlayMy"
        style="@style/InlineButtonHot"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/play"
        app:layout_constraintStart_toEndOf="@+id/buttonEditMy"
        app:layout_constraintTop_toBottomOf="@+id/textViewMyTitle" />

</androidx.constraintlayout.widget.ConstraintLayout>
</code>```

The view has some attributes :

```<code><?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="MyCard">
        <attr name="Mytitle" format="string"/>
        <attr name="Mydescription" format="string"/>
        <attr name="Myid" format="string"/>
    </declare-styleable>
</resources>
</code>```

And then the corresponding Java class :

```<code>public class MyCard extends ConstraintLayout {
    public MyCard(@NonNull Context context) {
        super(context);
    }

    public MyCard(@NonNull Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        init(context, attrs);
    }

    public MyCard(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context, attrs);
    }

    public MyCard(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
        init(context, attrs);
    }

    public String Description;
    public String Topic;
    public String MyId;

    private void init(Context ctx, AttributeSet attrs) {
        TypedArray CustomAttr = ctx.obtainStyledAttributes(attrs, R.styleable.MyCard);

        Description = CustomAttr.getString(R.styleable.MyCard_Mydescription);
        Topic = CustomAttr.getString(R.styleable.MyCard_Mytitle);
        MyId = CustomAttr.getString(R.styleable.MyCard_Myid);

        LayoutInflater inflater = (LayoutInflater)ctx.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        inflater.inflate(R.layout.Mycard, this, true); // <<<<<< the error is raised here

        CustomAttr.recycle();

    }
}
</code>```

When running the code, I'm getting the error :

```<code>java.lang.RuntimeException:
Unable to start activity ComponentInfo{com.colman.myapp/com.colman.myapp.Activity20_PersonalSpace}:
android.view.InflateException: Binary XML file line #49 in com.colman.myapp:layout/activity_activity20_personal_space:
Binary XML file line #49 in com.colman.myapp:layout/activity_activity20_personal_space:
Error inflating class com.colman.myapp.Libraries.views.MyCard
</code>```

Does anyone know how to solve that please ?

Tthanks.
Cheers

答:
Try to change the way you inflate the layout:</p>
```<code>private void init(Context ctx, AttributeSet attrs) {
    inflate(ctx, R.layout.Mycard, this);

    TypedArray CustomAttr = ctx.obtainStyledAttributes(attrs, R.styleable.MyCard);

    Description = CustomAttr.getString(R.styleable.MyCard_Mydescription);
    Topic = CustomAttr.getString(R.styleable.MyCard_Mytitle);
    MyId = CustomAttr.getString(R.styleable.MyCard_Myid);

    CustomAttr.recycle();
}
</code>```

Body:
I have a custom view that extends the constraint layout as follows :

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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="wrap_content">

    <TextView
        android:id="@+id/textViewMyTitle"
        style="@style/LabelLowLevel"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:text="My Title"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <Button
        android:id="@+id/buttonEditMy"
        style="@style/InlineButtonTransparent"
        android:layout_width="wrap_content"
        android:text="@string/edit"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/textViewMyTitle" />

    <Button
        android:id="@+id/buttonPlayMy"
        style="@style/InlineButtonHot"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/play"
        app:layout_constraintStart_toEndOf="@+id/buttonEditMy"
        app:layout_constraintTop_toBottomOf="@+id/textViewMyTitle" />

</androidx.constraintlayout.widget.ConstraintLayout>

The view has some attributes :

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="MyCard">
        <attr name="Mytitle" format="string"/>
        <attr name="Mydescription" format="string"/>
        <attr name="Myid" format="string"/>
    </declare-styleable>
</resources>

And then the corresponding Java class :

public class MyCard extends ConstraintLayout {
    public MyCard(@NonNull Context context) {
        super(context);
    }

    public MyCard(@NonNull Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        init(context, attrs);
    }

    public MyCard(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context, attrs);
    }

    public MyCard(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
        init(context, attrs);
    }

    public String Description;
    public String Topic;
    public String MyId;

    private void init(Context ctx, AttributeSet attrs) {
        TypedArray CustomAttr = ctx.obtainStyledAttributes(attrs, R.styleable.MyCard);

        Description = CustomAttr.getString(R.styleable.MyCard_Mydescription);
        Topic = CustomAttr.getString(R.styleable.MyCard_Mytitle);
        MyId = CustomAttr.getString(R.styleable.MyCard_Myid);

        LayoutInflater inflater = (LayoutInflater)ctx.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        inflater.inflate(R.layout.Mycard, this, true); // <<<<<< the error is raised here

        CustomAttr.recycle();

    }
}

When running the code, I'm getting the error :

java.lang.RuntimeException:
Unable to start activity ComponentInfo{com.colman.myapp/com.colman.myapp.Activity20_PersonalSpace}:
android.view.InflateException: Binary XML file line #49 in com.colman.myapp:layout/activity_activity20_personal_space:
Binary XML file line #49 in com.colman.myapp:layout/activity_activity20_personal_space:
Error inflating class com.colman.myapp.Libraries.views.MyCard

Does anyone know how to solve that please ?

Tthanks.
Cheers

Body:
Try to change the way you inflate the layout:

private void init(Context ctx, AttributeSet attrs) {
    inflate(ctx, R.layout.Mycard, this);

    TypedArray CustomAttr = ctx.obtainStyledAttributes(attrs, R.styleable.MyCard);

    Description = CustomAttr.getString(R.styleable.MyCard_Mydescription);
    Topic = CustomAttr.getString(R.styleable.MyCard_Mytitle);
    MyId = CustomAttr.getString(R.styleable.MyCard_Myid);

    CustomAttr.recycle();
}


问:
ARCore – How to know if a device has a Time-of-Flight sensor?
I wonder what is the code to know if a device has a ToF sensor.

Thanks

答:
Since a depth data in ARCore can be calculated from motion and then might be merged with data from a hardware iToF sensor, devices running Android AR apps do not need a time-of-flight camera to support the Full Depth API or Raw Depth API. So at the moment there's no property in ARCore 1.29 to check if device has a hardware depth sensor. Nonetheless, @NivSaparov offered some solution.

However, to check whether a device supports Depth mode or not use the following code in Java:

Config config = session.getConfig();

if (session.isDepthModeSupported(Config.DepthMode.AUTOMATIC)) {
    config.setDepthMode(Config.DepthMode.AUTOMATIC);
}
session.configure(config);
```
<p>...or in Kotlin:</p>
<pre class="lang-kotlin prettyprint-override"><code>if (session.isDepthModeSupported(Config.DepthMode.AUTOMATIC)) {
    session.configure(session.config.apply {
        depthMode = Config.DepthMode.AUTOMATIC
    })
}
</code>```

By default, depth feature is disabled on ARCore, to save resources. Not every ARCore-compatible device supports the Depth API due to its high processing requirements.

But it's possible to indirectly determine whether a given device has an iToF sensor (but it's not 100% sure). For that, check if devices can support the Raw Depth API.

session = new Session(this);

if (!session.isDepthModeSupported(Config.DepthMode.RAW_DEPTH_ONLY)) {
    message = "Current device doesn't support Raw Depth API.";
}
```
<p>My logic is simple: if the device supports the Raw Depth API, then as a rule such a device has an iToF sensor.</p>
<p>If your AR app requires Depth API support, just add the following line to your AndroidManifest.xml:</p>
<pre class="lang-xml prettyprint-override"><code><uses-feature android:name="com.google.ar.core.depth" />
</code>```

Body:
Since a depth data in ARCore can be calculated from motion and then might be merged with data from a hardware iToF sensor, devices running Android AR apps do not need a time-of-flight camera to support the Full Depth API or Raw Depth API. So at the moment there's no property in ARCore 1.29 to check if device has a hardware depth sensor. Nonetheless, @NivSaparov offered some solution.

However, to check whether a device supports Depth mode or not use the following code in Java:

Config config = session.getConfig();

if (session.isDepthModeSupported(Config.DepthMode.AUTOMATIC)) {
    config.setDepthMode(Config.DepthMode.AUTOMATIC);
}
session.configure(config);

...or in Kotlin:

if (session.isDepthModeSupported(Config.DepthMode.AUTOMATIC)) {
    session.configure(session.config.apply {
        depthMode = Config.DepthMode.AUTOMATIC
    })
}

By default, depth feature is disabled on ARCore, to save resources. Not every ARCore-compatible device supports the Depth API due to its high processing requirements.

But it's possible to indirectly determine whether a given device has an iToF sensor (but it's not 100% sure). For that, check if devices can support the Raw Depth API.

session = new Session(this);

if (!session.isDepthModeSupported(Config.DepthMode.RAW_DEPTH_ONLY)) {
    message = "Current device doesn't support Raw Depth API.";
}

My logic is simple: if the device supports the Raw Depth API, then as a rule such a device has an iToF sensor.

If your AR app requires Depth API support, just add the following line to your AndroidManifest.xml:

<uses-feature android:name="com.google.ar.core.depth" />


问:
I cannot find my CREATE VIEW table after refreshing even after "Commands completed successfully." message. (SQL)
--Creating View to store data for later visualizations

```<code>CREATE VIEW PeopleVaccinatedpercent AS

SELECT dea.continent, dea.location, dea.date, dea.population, vac.new_vaccinations
,SUM(cast(new_vaccinations as bigint))
OVER (Partition by dea.location ORDER BY dea.location, dea.date) AS RollingPeopleVaccinated
    FROM PortofolioProject..CovidDeaths dea
    JOIN PortofolioProject..CovidVaccination vac
    ON dea.location = vac.location
    and dea.date = vac.date
    WHERE dea.continent is not null

</code>```

Commands completed successfully.

After Refreshing I still don't get any result under Views file on the left

答:
The simplest wat to test is :

```<code>select top 10 * from PeopleVaccinatedpercent
</code>```

Remember that you created a View, not a Table. In other words it will not be listed under "Tables" in SSMS, but rather "Views"

Body:
--Creating View to store data for later visualizations

CREATE VIEW PeopleVaccinatedpercent AS

SELECT dea.continent, dea.location, dea.date, dea.population, vac.new_vaccinations
,SUM(cast(new_vaccinations as bigint))
OVER (Partition by dea.location ORDER BY dea.location, dea.date) AS RollingPeopleVaccinated
    FROM PortofolioProject..CovidDeaths dea
    JOIN PortofolioProject..CovidVaccination vac
    ON dea.location = vac.location
    and dea.date = vac.date
    WHERE dea.continent is not null

Commands completed successfully.

After Refreshing I still don't get any result under Views file on the left

Body:
The simplest wat to test is :

select top 10 * from PeopleVaccinatedpercent

Remember that you created a View, not a Table. In other words it will not be listed under "Tables" in SSMS, but rather "Views"


答:
You may have created the view in a different schema accidentally , since you did not give a fully qualified name for the view like: "create view myschema.myview  ..."
If your session is using a different schema as default, this happens a lot ( to me :-))</p>

Title: I cannot find my CREATE VIEW table after refreshing even after "Commands completed successfully." message. (SQL)


问:
how to display data from productListComponentService in spartacus
i want to replace SearchResultsListComponent with my own to display more info than what spartacus provide OOTB when i search for something

i want to show product image, name, stock availability , price , rating

答:
You can replace a component providing ConfigModule in your B2cStorefrontModule(example):

```<code>ConfigModule.withConfig({
  cmsComponents: {
    BannerComponent: {
      component: CustomBannerComponent;
    }
  }
});
</code>```

There is a page specifically dedicated to component customization:
https://sap.github.io/spartacus-docs/customizing-cms-components

Body:
You can replace a component providing ConfigModule in your B2cStorefrontModule(example):

ConfigModule.withConfig({
  cmsComponents: {
    BannerComponent: {
      component: CustomBannerComponent;
    }
  }
});

There is a page specifically dedicated to component customization:
https://sap.github.io/spartacus-docs/customizing-cms-components


问:
Hover on anchor link and show icon
I'm trying to copy the CSS on those "documentation" pages of those projects such as bootstrap where when you hover on anchor link(s) it would show you a certain icon

a {
font-weight: bold;
font-size: 20px;
color: #000000;
text-decoration: none;
}

/* mouse hover link */
a:hover {
  background: url(https://icons.iconarchive.com/icons/custom-icon-design/mono-general-2/512/copy-icon.png);
  background-size: 15px 15px;
  background-repeat: no-repeat;
  background-position: 200px 50%;
  background-attachment: scroll;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code>Some Random Header Text<br>
Some Random Header Text but Longer</code>```

I want the icon to show at the right end of the text for the both instances of anchor link when hover unto them how can I achieve it?

Here's an expected result:

答:
Background images are a pain to position especially when dealing with text as well. Try Unicode chracters which are are just like text which means they sit perfectly with text.

Sorry, I forgot to mention, ::aftter and content makes this possible and the Unicode (from OS) is made easy by a simple copy and paste from here.

a {
  display: block;
  margin: 5px 0;
  font-weight: bold;
  font: 2ch/1.5 'Segoe UI';
  color: #000000;
  text-decoration: none;
}

.A:hover::after {
  content: '';
}

.B:hover::after {
  content: ''
}

.C:hover::after {
  content: '';
}

.D:hover::after {
  content: '';
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code>Some Random Header Text
Some Random Header Text but Longer
Some Random Header Text
Some Random Header Text but Longer</code>```

Title: Hover on anchor link and show icon

Body:
I'm trying to copy the CSS on those "documentation" pages of those projects such as bootstrap where when you hover on anchor link(s) it would show you a certain icon

a {
font-weight: bold;
font-size: 20px;
color: #000000;
text-decoration: none;
}

/* mouse hover link */
a:hover {
  background: url(https://icons.iconarchive.com/icons/custom-icon-design/mono-general-2/512/copy-icon.png);
  background-size: 15px 15px;
  background-repeat: no-repeat;
  background-position: 200px 50%;
  background-attachment: scroll;
}

Some Random Header Text

Some Random Header Text but Longer

I want the icon to show at the right end of the text for the both instances of anchor link when hover unto them how can I achieve it?

Here's an expected result:

Body:
Background images are a pain to position especially when dealing with text as well. Try Unicode chracters which are are just like text which means they sit perfectly with text.

Sorry, I forgot to mention, ::aftter and content makes this possible and the Unicode (from OS) is made easy by a simple copy and paste from here.

a {
  display: block;
  margin: 5px 0;
  font-weight: bold;
  font: 2ch/1.5 'Segoe UI';
  color: #000000;
  text-decoration: none;
}

.A:hover::after {
  content: '';
}

.B:hover::after {
  content: ''
}

.C:hover::after {
  content: '';
}

.D:hover::after {
  content: '';
}

<a href="#" class='A'>Some Random Header Text</a>
<a href="#" class='B'>Some Random Header Text but Longer</a>
<a href="#" class='C'>Some Random Header Text</a>
<a href="#" class='D'>Some Random Header Text but Longer</a>


问:
R Tidyverse - Counting the number a word appears in a list by group
I am currently working on the following:

I have two dataframes. One dataframe contains a number of inventors per company and I would like to know how often their name appears in another dataframe in the same company.The company identifier (df_itemnumber_rounded) in both dataframes is called the same and present in both dataframes.

Example:

First dataframe includes:

```<code>df_itemnumber_rounded <- c(df_2002_77, df_2002_77, df_2002_77, df_2002_78
,df_2002_767)

assignees_split <- c("DSM IP ASSETS BV","DSM NV,GIST BROCADES NV","INRA INST NAT RECH AGRONOMIQUE","DE FORENEDE BRYGGERIER AS", "FORENEDE BRYGGERIER" )
</code>```

Second dataframe includes:

```<code>df_itemnumber_rounded <- c(df_2002_77,df_2002_77,df_2002_77,df_2002_77,df_2002_77)

citedp_assignee <- c("LANGEJAN AREND","PELLETIER RENE FRANCOIS ROGER ","LESAFFRE & CIE","GIST BROCADES NV ", "DISTILLERS CO YEAST LTD ")
</code>```

The aim is to have the first dataframe that includes a new variable ("counts") that shows how often a name appears within a company.

So like this:

df_itemnumber_rounded
assignees_split
count

df_2002_77
DSM IP ASSETS BV
0

df_2002_77
GIST BROCADES NV
1

I have tried to work on it using str_detect and sum but I don't kow how to do it by group instead of letting it run over the whole dataframe.

```<code>counts <- test_distinct_cleaned %>%
  group_by(df_itemnumber_rounded,assignees_split) %>%
mutate(counts=map_int(tolower(test_distinct_cleaned$assignees_split),~sum(str_detect(tolower(match_with_cleaned$citedp_assignee),.x))))
</code>```

However, it takes a long time and does not seem to come to an end. I have tried the solution above without the group_by function on a smaller df where it counts all the appearances of a name and not just the one of the same company. So I am not sure whether this works at all with the group_by and if there is a faster way to do it. The first df has 17000 lines and the second to match with has over 150000 lines...

Below there is a real example of the data:

Dataframe 1 are the assignees.

```<code>    structure(list(df_itemnumber_rounded = c("df_2012_2175", "df_2012_2175",
"df_2012_2175", "df_2012_2175", "df_2012_2175", "df_2012_2175",
"df_2012_2175", "df_2002_4897", "df_2002_4897", "df_2012_9460",
"df_2012_9460", "df_2012_9460", "df_2012_9460", "df_2016_6247",
"df_2016_6247", "df_2016_6247", "df_2016_6248", "df_2016_6248",
"df_2016_6248", "df_2016_6248", "df_2016_6248", "df_2016_6248",
"df_2012_9459", "df_2012_9459", "df_2016_14178", "df_2016_14178",
"df_2016_14689", "df_2016_14689", "df_2016_15814", "df_2016_15814",
"df_2012_2360", "df_2012_2360", "df_2012_2360", "df_2012_2360",
"df_2012_2360", "df_2012_2360", "df_2012_2360", "df_2012_8944",
"df_2012_8944", "df_2012_8944", "df_2012_3604", "df_2012_3604",
"df_2012_3604", "df_2012_3604", "df_2012_4967", "df_2012_4967",
"df_2012_4967", "df_2012_7883", "df_2012_7883", "df_2012_7883",
"df_2012_4836", "df_2012_4836", "df_2012_4836", "df_2002_18770",
"df_2012_1305", "df_2012_2576", "df_2012_10710", "df_2012_5541",
"df_2012_5578", "df_2012_5635", "df_2012_6044", "df_2012_6219",
"df_2012_6317", "df_2012_6488", "df_2012_6500", "df_2012_6613",
"df_2012_6615", "df_2012_6679", "df_2012_6928", "df_2012_6977",
"df_2012_7489", "df_2012_7552", "df_2012_7667", "df_2012_8017",
"df_2012_8302", "df_2012_8555", "df_2012_8809", "df_2012_9085",
"df_2012_9171", "df_2012_9298", "df_2012_9813", "df_2012_10236",
"df_2012_10437", "df_2012_10532", "df_2012_10602", "df_2012_11037",
"df_2012_11070", "df_2012_11183", "df_2012_11606", "df_2012_12362",
"df_2012_12618", "df_2016_678", "df_2016_790", "df_2016_1079",
"df_2016_1414", "df_2016_1539", "df_2016_2074", "df_2016_2167",
"df_2016_2314", "df_2016_2769"), `Publication Number` = c("WO2006046567A1",
"WO2006046567A1", "WO2006046567A1", "WO2006046567A1", "WO2006046567A1",
"WO2006046567A1", "WO2006046567A1", "DE3149931A1", "DE3149931A1",
"WO2013002007A1", "WO2013002007A1", "WO2013002007A1", "WO2013002007A1",
"WO2016114276A1", "WO2016114276A1", "WO2016114276A1", "WO2016114277A1",
"WO2016114277A1", "WO2016114277A1", "WO2016114277A1", "WO2016114277A1",
"WO2016114277A1", "JP2013005781A", "JP2013005781A", "WO2017094654A1",
"WO2017094654A1", "JP2017112924A", "JP2017112924A", "WO2017169107A1",
"WO2017169107A1", "WO2006070828A1", "WO2006070828A1", "WO2006070828A1",
"WO2006070828A1", "WO2006070828A1", "WO2006070828A1", "WO2006070828A1",
"JP2012183063A", "JP2012183063A", "JP2012183063A", "WO2007097088A1",
"WO2007097088A1", "WO2007097088A1", "WO2007097088A1", "WO2009017116A1",
"WO2009017116A1", "WO2009017116A1", "WO2011145670A1", "WO2011145670A1",
"WO2011145670A1", "WO2008153118A1", "WO2008153118A1", "WO2008153118A1",
"JP2013066497A", "JP2011030577A", "JP2011142922A", "JP2012105673A",
"JP2009213393A", "JP2009225740A", "JP2009254247A", "AU2008297027A1",
"JP2010130902A", "JP2010136658A", "JP2010207213A", "JP2010207217A",
"JP2010220529A", "JP2010220536A", "JP2010252640A", "JP2011036129A",
"JP2011030517A", "JP2011135841A", "JP2011142890A", "JP2011206047A",
"JP2012024081A", "JP2012055235A", "JP2012105572A", "JP2012147775A",
"JP2012213373A", "WO2012147465A1", "JP2012244965A", "JP2013042751A",
"WO2013073628A1", "JP2013143938A", "JP2013150602A", "JP2013165707A",
"JP2013255490A", "JP2013243970A", "JP2014000055A", "JP2014057537A",
"EP2737810A1", "JP2014128251A", "JP2014217315A", "WO2014192826A1",
"JP2015015926A", "WO2015029605A1", "JP2015053920A", "WO2015064748A1",
"JP2015116187A", "JP2015100294A", "WO2015098744A1"), assignees_split = structure(c(19L,
15L, 17L, 1L, 4L, 5L, 18L, 20L, 16L, 21L, 11L, 12L, 14L, 21L,
12L, 14L, 21L, 12L, 15L, 2L, 3L, 8L, 21L, 14L, 21L, 14L, 21L,
14L, 21L, 14L, 21L, 15L, 17L, 6L, 7L, 9L, 10L, 22L, 15L, 16L,
23L, 13L, 15L, 16L, 23L, 15L, 16L, 23L, 15L, 16L, 24L, 15L, 16L,
25L, 25L, 25L, 25L, 25L, 25L, 25L, 25L, 25L, 25L, 25L, 25L, 25L,
25L, 25L, 25L, 25L, 25L, 25L, 25L, 25L, 25L, 25L, 25L, 25L, 25L,
25L, 25L, 25L, 25L, 25L, 25L, 25L, 25L, 25L, 25L, 25L, 25L, 25L,
25L, 25L, 25L, 25L, 25L, 25L, 25L, 25L), .Label = c(" FURUKUBO S ",
" IBUSUKI D ", " ICHIMURA A ", " IZUMI T ", " KAKUDO Y ", " KIMURA M ",
" MAKI H ", " MIYAO Y", " NAGAO K ", " NAKAHARA K", " SUNTORY BEVERAGE&FOOD LTD ",
" SUNTORY FOOD & BEVERAGE CO LTD ", " SUNTORY HOLDINGS CO LTD ",
" SUNTORY HOLDINGS LTD", " SUNTORY HOLDINGS LTD ", " SUNTORY LTD",
" SUNTORY LTD ", " TAKAOKA S", "KOMATSU MFG CO LTD ", "SUN CHEM CORP ",
"SUNTORY BEVERAGE & FOOD LTD ", "SUNTORY FOOD & BEVERAGE CO LTD ",
"SUNTORY HOLDING LTD ", "SUNTORY HOLDINGS CO LTD ", "SUNTORY HOLDINGS LTD"
), class = "factor")), row.names = c(NA, -100L), class = c("tbl_df",
"tbl", "data.frame"))
</code>```

Dataframe are the assignees of the cited patents so cited_assignees.

```<code>structure(list(df_itemnumber_rounded = c("df_2012_2175", "df_2012_2175",
"df_2012_2175", "df_2012_2175", "df_2012_2175", "df_2012_2175",
"df_2002_4897", "df_2012_9460", "df_2012_9460", "df_2012_9460",
"df_2012_9460", "df_2012_9460", "df_2012_9460", "df_2012_9460",
"df_2016_6247", "df_2016_6247", "df_2016_6247", "df_2016_6247",
"df_2016_6247", "df_2016_6247", "df_2016_6248", "df_2016_6248",
"df_2016_6248", "df_2016_6248", "df_2016_6248", "df_2016_6248",
"df_2012_9459", "df_2012_9459", "df_2016_14178", "df_2016_14178",
"df_2016_14178", "df_2016_14178", "df_2016_14178", "df_2016_14178",
"df_2016_14178", "df_2016_14178", "df_2016_14178", "df_2016_14178",
"df_2016_14178", "df_2016_14178", "df_2016_14178", "df_2016_14689",
"df_2016_14689", "df_2016_14689", "df_2016_14689", "df_2016_14689",
"df_2016_14689", "df_2016_15814", "df_2016_15814", "df_2016_15814",
"df_2016_15814", "df_2016_15814", "df_2012_2360", "df_2012_2360",
"df_2012_2360", "df_2012_2360", "df_2012_2360", "df_2012_2360",
"df_2012_2360", "df_2012_2360", "df_2012_2360", "df_2012_2360",
"df_2012_2360", "df_2012_2360", "df_2012_8944", "df_2012_3604",
"df_2012_3604", "df_2012_3604", "df_2012_3604", "df_2012_3604",
"df_2012_3604", "df_2012_3604", "df_2012_3604", "df_2012_3604",
"df_2012_4967", "df_2012_4967", "df_2012_4967", "df_2012_4967",
"df_2012_4967", "df_2012_4967", "df_2012_4967", "df_2012_4967",
"df_2012_4967", "df_2012_4967", "df_2012_4967", "df_2012_4967",
"df_2012_4967", "df_2012_4967", "df_2012_4967", "df_2012_4967",
"df_2012_4967", "df_2012_4967", "df_2012_4967", "df_2012_4967",
"df_2012_7883", "df_2012_7883", "df_2012_7883", "df_2012_7883",
"df_2012_7883", "df_2012_4836"), citedp_assignee = structure(c(40L,
23L, 48L, 6L, 15L, 13L, 12L, 30L, 1L, 52L, 53L, 58L, 56L, 3L,
52L, 52L, 16L, 66L, 52L, 67L, 16L, 66L, 52L, 68L, 52L, 51L, 63L,
3L, 60L, 27L, 45L, 52L, 9L, 73L, 33L, 25L, 52L, 50L, 62L, 73L,
64L, 2L, 59L, 28L, 28L, 52L, 46L, 4L, 42L, 1L, 42L, 43L, 31L,
70L, 32L, 57L, 39L, 14L, 35L, 11L, 56L, 32L, 32L, 55L, 17L, 22L,
22L, 56L, 56L, 5L, 36L, 56L, 41L, 21L, 20L, 29L, 18L, 19L, 47L,
7L, 63L, 4L, 38L, 44L, 65L, 56L, 44L, 26L, 34L, 65L, 69L, 10L,
24L, 8L, 71L, 49L, 54L, 61L, 72L, 37L), .Label = c("  ", "ABURADA MASAKI,TOKIWA PHYTOCHEMICAL CO LTD ",
"ASAHI BREWERIES LTD", "ASAHI BREWERIES LTD ", "ASAHI BREWERIES LTD,JIBIKI MAKIKO ",
"CERESTAR HOLDING BV ", "CHOYA UMESHU CO LTD ", "CHUKO SHUZO KK",
"CREAGRI INC,CREA ROBERTO,MATTEUZZI FRANCESCO,ASTORE STEFANO,MILIONI IVANO ",
"DEZAINAA FOODS KYOKAI KK ", "FUKUI HISASHI ", "GULF OIL CORP",
"HOKKAIDO WAIN KK", "IKEDA SHOKKEN KK ", "INSUCHI PUROBUREMU NADEJINOSUT ",
"ITO EN LTD ", "ITOEN KK", "JAPAN MAIZE PROD ", "KANEBO LTD ",
"KANEBO LTD,HASEGAWA T CO LTD ", "KIRIN BREWERY", "KIRIN BREWERY ",
"KIRIN BREWERY,JAPAN MAIZE PROD ", "KOHJIN CO ", "LION CORP ",
"MANNS WINE CO LTD ", "MARUNAKA SHOKUHIN KK ", "MARUZEN PHARMA ",
"MATSUSHITA ELECTRIC IND CO LTD ", "MATSUTANI KAGAKU KOGYO KK ",
"MEIJI DAIRIES CORP ", "MEIJI MILK PROD CO LTD ", "MILLER BREWING INTERNATIONAL INC,LUSK LANCE T,RYDER DAVID S ",
"MITSUBISHI CHEM IND ", "MITSUBISHI HEAVY IND LTD,KADO TAKASHI,ISOZAKI TOSHIKAZU ",
"MIYAGI PREFECTURE,MIYAGIKEN SHUZO KYODO KUMIAI ", "NAT TAX ADMINISTRATION AGENCY ",
"NIPPON BEET SUGAR MFG ", "OGAWA & CO LTD ", "OKURA SYUZO KK ",
"OZEKI KK ", "PEPSICO INC ", "PEPSICO INC,LEE THOMAS,NATTRESS LAURA ANN,RIHA WILLIAM",
"POLA CHEM IND INC ", "RIVERSON KK ", "SAN EI GEN FFI INC", "SAN EI GEN FFI INC ",
"SAPPORO BREWERIES ", "SAPPORO BREWERIES,OONO MASAO,SANO TOMOHIRO ",
"SHOWA PHARM CHEM IND ", "SUNTORY HOLDINGS LTD", "SUNTORY HOLDINGS LTD ",
"SUNTORY HOLDINGS LTD,IDO YOSHIHIRO,KOMINE TETSUYA ", "SUNTORY HOLDINGS LTD,KAGEYAMA NORIHIKO,INUI TAKAKO,TAKAGI DAISUKE ",
"SUNTORY LTD", "SUNTORY LTD ", "SUNTORY LTD,KAGEYAMA NORIHIKO,NAKAHARA KOICHI,INUI TAKAKO,TAKAOKA SEISUKE,NAGAMI KENZO ",
"SUNTORY LTD,WATANABE TOKUTOMI,DAIDO HIROMI,YOSHIHIRO AKIRA ",
"SYMRISE GMBH & CO KG ", "TAISHO PHARMA CO LTD ", "TAKARA HOLDINGS INC ",
"TAKARA SHOKUHIN KK ", "TAKARA SHUZO CO ", "TAKASAGO PERFUMERY CO LTD",
"TOKYO SHIBAURA ELECTRIC CO ", "TOYO SEIKAN KAISHA LTD ", "TROPICANA PROD INC",
"TROPICANA PROD INC ", "TSUKISHIMA KIKAI CO ", "UNILEVER PLC,UNILEVER NV,LEVER HINDUSTAN LTD ",
"WOONGJIN FOODS CO LTD ", "YAKULT HONSHA KK,KUMAMOTOKEN KAJITSU NOGYO KYOD",
"YAMADA YASUYUKI "), class = "factor")), row.names = c(NA, -100L
), class = c("tbl_df", "tbl", "data.frame"))
</code>```

答:
Here's a potential solution. Note that your assignee and citetp variables are messy with whitespaces at the beginning/end taht you might not want to take into account for your string search:

library(tidyverse)

```<code>df1 <- data.frame(df_itemnumber_rounded = c("df_2002_77", "df_2002_77", "df_2002_77", "df_2002_78", "df_2002_767"),
                  assignees_split = c("DSM IP ASSETS BV","DSM NV,GIST BROCADES NV","INRA INST NAT RECH AGRONOMIQUE","DE FORENEDE BRYGGERIER AS", "FORENEDE BRYGGERIER" ))

df2 <- data.frame(citedp_assignee = c("LANGEJAN AREND","PELLETIER RENE FRANCOIS ROGER ","LESAFFRE & CIE","GIST BROCADES NV ", "DISTILLERS CO YEAST LTD "))
</code>```

The solution below gives ou the full information about which assignees appear in the citedp variable:

```<code>df1 |>
  mutate(is_match = str_detect(tolower(assignees_split),
                               paste0(tolower(trimws(df2$citedp_assignee, which = "both")),
                                      collapse = "|"))) |>
  group_by(df_itemnumber_rounded, assignees_split) |>
  summarize(counts = sum(is_match))
</code>```

which gives:

```<code># A tibble: 5 x 3
# Groups:   df_itemnumber_rounded [3]
  df_itemnumber_rounded assignees_split                counts
  <chr>                 <chr>                           <int>
1 df_2002_767           FORENEDE BRYGGERIER                 0
2 df_2002_77            DSM IP ASSETS BV                    0
3 df_2002_77            DSM NV,GIST BROCADES NV             1
4 df_2002_77            INRA INST NAT RECH AGRONOMIQUE      0
5 df_2002_78            DE FORENEDE BRYGGERIER AS           0
</code>```

If you only want to get the ids where there's at least one match, you can do:

```<code>df1 |>
  mutate(is_match = str_detect(tolower(assignees_split),
                               paste0(tolower(trimws(df2$citedp_assignee, which = "both")),
                                      collapse = "|"))) |>
  group_by(df_itemnumber_rounded, assignees_split) |>
  summarize(counts = sum(is_match)) |>
  filter(!all(counts == 0))
</code>```

which gives:

```<code># A tibble: 3 x 3
# Groups:   df_itemnumber_rounded [1]
  df_itemnumber_rounded assignees_split                counts
  <chr>                 <chr>                           <int>
1 df_2002_77            DSM IP ASSETS BV                    0
2 df_2002_77            DSM NV,GIST BROCADES NV             1
3 df_2002_77            INRA INST NAT RECH AGRONOMIQUE      0
</code>```

Another shot after TO provided some sample data.

So here's the idea:

Note: I named the two data frames df1 (assignees) and df2 (companies).

We first do some basic cleaning of the character columns, e.g. convert everything to lowercase characters and get rid of some whitespaces at the beginning/end.

We then go through each row/assignee in df1 (hence rowwise) and count how often this assigne name occurs in df2 for the same company identifier.

```<code>library(tidyverse)

df1 <- df1 |>
  mutate(assignee_new = tolower(trimws(assignees_split, "both")))

df2 <- df2 |>
  mutate(citedp_new = tolower(trimws(citedp_assignee, "both")))

df1 |>
  rowwise() |>
  mutate(assignee_count = length(str_which(df2$citedp_new[df2$df_itemnumber_rounded == df_itemnumber_rounded],
                                           assignee_new))) |>
  ungroup() |>
  print(n = 100)
</code>```

which gives (only printing the first 20 rows):

```<code># A tibble: 100 x 5
    df_itemnumber_rounded `Publication Number` assignees_split                    assignee_new                   assignee_count
    <chr>                 <chr>                <fct>                              <chr>                                   <int>
  1 df_2012_2175          WO2006046567A1       "KOMATSU MFG CO LTD "              komatsu mfg co ltd                          0
  2 df_2012_2175          WO2006046567A1       " SUNTORY HOLDINGS LTD "           suntory holdings ltd                        0
  3 df_2012_2175          WO2006046567A1       " SUNTORY LTD "                    suntory ltd                                 0
  4 df_2012_2175          WO2006046567A1       " FURUKUBO S "                     furukubo s                                  0
  5 df_2012_2175          WO2006046567A1       " IZUMI T "                        izumi t                                     0
  6 df_2012_2175          WO2006046567A1       " KAKUDO Y "                       kakudo y                                    0
  7 df_2012_2175          WO2006046567A1       " TAKAOKA S"                       takaoka s                                   0
  8 df_2002_4897          DE3149931A1          "SUN CHEM CORP "                   sun chem corp                               0
  9 df_2002_4897          DE3149931A1          " SUNTORY LTD"                     suntory ltd                                 0
 10 df_2012_9460          WO2013002007A1       "SUNTORY BEVERAGE & FOOD LTD "     suntory beverage & food ltd                 0
 11 df_2012_9460          WO2013002007A1       " SUNTORY BEVERAGE&FOOD LTD "      suntory beverage&food ltd                   0
 12 df_2012_9460          WO2013002007A1       " SUNTORY FOOD & BEVERAGE CO LTD " suntory food & beverage co ltd              0
 13 df_2012_9460          WO2013002007A1       " SUNTORY HOLDINGS LTD"            suntory holdings ltd                        2
 14 df_2016_6247          WO2016114276A1       "SUNTORY BEVERAGE & FOOD LTD "     suntory beverage & food ltd                 0
 15 df_2016_6247          WO2016114276A1       " SUNTORY FOOD & BEVERAGE CO LTD " suntory food & beverage co ltd              0
 16 df_2016_6247          WO2016114276A1       " SUNTORY HOLDINGS LTD"            suntory holdings ltd                        3
 17 df_2016_6248          WO2016114277A1       "SUNTORY BEVERAGE & FOOD LTD "     suntory beverage & food ltd                 0
 18 df_2016_6248          WO2016114277A1       " SUNTORY FOOD & BEVERAGE CO LTD " suntory food & beverage co ltd              0
 19 df_2016_6248          WO2016114277A1       " SUNTORY HOLDINGS LTD "           suntory holdings ltd                        3
 20 df_2016_6248          WO2016114277A1       " IBUSUKI D "                      ibusuki d                                   0
</code>```

I tested it by increasing the size of df1 to 10000 rows and df2 to 150000 rows (of course, you real-life pattern might be more complex) and it runs just fine in 20 seconds on my machine:

```<code>df1_new <- df1 |>
  slice(rep(1:n(), each = 100))

df2_new <- df2 |>
  slice(rep(1:n(), each = 1500))

t1 <- Sys.time()

df1_new |>
  rowwise() |>
  mutate(assignee_count = length(str_which(df2_new$citedp_new[df2_new$df_itemnumber_rounded == df_itemnumber_rounded],
                                           assignee_new))) |>
  ungroup()

Sys.time() - t1

Time difference of 20.36699 secs
</code>```

Body:
I am currently working on the following:

I have two dataframes. One dataframe contains a number of inventors per company and I would like to know how often their name appears in another dataframe in the same company.The company identifier (df_itemnumber_rounded) in both dataframes is called the same and present in both dataframes.

Example:

First dataframe includes:

df_itemnumber_rounded <- c(df_2002_77, df_2002_77, df_2002_77, df_2002_78
,df_2002_767)

assignees_split <- c("DSM IP ASSETS BV","DSM NV,GIST BROCADES NV","INRA INST NAT RECH AGRONOMIQUE","DE FORENEDE BRYGGERIER AS", "FORENEDE BRYGGERIER" )

Second dataframe includes:

df_itemnumber_rounded <- c(df_2002_77,df_2002_77,df_2002_77,df_2002_77,df_2002_77)

citedp_assignee <- c("LANGEJAN AREND","PELLETIER RENE FRANCOIS ROGER ","LESAFFRE & CIE","GIST BROCADES NV ", "DISTILLERS CO YEAST LTD ")

The aim is to have the first dataframe that includes a new variable ("counts") that shows how often a name appears within a company.

So like this:

df_itemnumber_rounded
assignees_split
count

df_2002_77
DSM IP ASSETS BV
0

df_2002_77
GIST BROCADES NV
1

I have tried to work on it using str_detect and sum but I don't kow how to do it by group instead of letting it run over the whole dataframe.

counts <- test_distinct_cleaned %>%
  group_by(df_itemnumber_rounded,assignees_split) %>%
mutate(counts=map_int(tolower(test_distinct_cleaned$assignees_split),~sum(str_detect(tolower(match_with_cleaned$citedp_assignee),.x))))

However, it takes a long time and does not seem to come to an end. I have tried the solution above without the group_by function on a smaller df where it counts all the appearances of a name and not just the one of the same company. So I am not sure whether this works at all with the group_by and if there is a faster way to do it. The first df has 17000 lines and the second to match with has over 150000 lines...

Below there is a real example of the data:

Dataframe 1 are the assignees.

    structure(list(df_itemnumber_rounded = c("df_2012_2175", "df_2012_2175",
"df_2012_2175", "df_2012_2175", "df_2012_2175", "df_2012_2175",
"df_2012_2175", "df_2002_4897", "df_2002_4897", "df_2012_9460",
"df_2012_9460", "df_2012_9460", "df_2012_9460", "df_2016_6247",
"df_2016_6247", "df_2016_6247", "df_2016_6248", "df_2016_6248",
"df_2016_6248", "df_2016_6248", "df_2016_6248", "df_2016_6248",
"df_2012_9459", "df_2012_9459", "df_2016_14178", "df_2016_14178",
"df_2016_14689", "df_2016_14689", "df_2016_15814", "df_2016_15814",
"df_2012_2360", "df_2012_2360", "df_2012_2360", "df_2012_2360",
"df_2012_2360", "df_2012_2360", "df_2012_2360", "df_2012_8944",
"df_2012_8944", "df_2012_8944", "df_2012_3604", "df_2012_3604",
"df_2012_3604", "df_2012_3604", "df_2012_4967", "df_2012_4967",
"df_2012_4967", "df_2012_7883", "df_2012_7883", "df_2012_7883",
"df_2012_4836", "df_2012_4836", "df_2012_4836", "df_2002_18770",
"df_2012_1305", "df_2012_2576", "df_2012_10710", "df_2012_5541",
"df_2012_5578", "df_2012_5635", "df_2012_6044", "df_2012_6219",
"df_2012_6317", "df_2012_6488", "df_2012_6500", "df_2012_6613",
"df_2012_6615", "df_2012_6679", "df_2012_6928", "df_2012_6977",
"df_2012_7489", "df_2012_7552", "df_2012_7667", "df_2012_8017",
"df_2012_8302", "df_2012_8555", "df_2012_8809", "df_2012_9085",
"df_2012_9171", "df_2012_9298", "df_2012_9813", "df_2012_10236",
"df_2012_10437", "df_2012_10532", "df_2012_10602", "df_2012_11037",
"df_2012_11070", "df_2012_11183", "df_2012_11606", "df_2012_12362",
"df_2012_12618", "df_2016_678", "df_2016_790", "df_2016_1079",
"df_2016_1414", "df_2016_1539", "df_2016_2074", "df_2016_2167",
"df_2016_2314", "df_2016_2769"), `Publication Number` = c("WO2006046567A1",
"WO2006046567A1", "WO2006046567A1", "WO2006046567A1", "WO2006046567A1",
"WO2006046567A1", "WO2006046567A1", "DE3149931A1", "DE3149931A1",
"WO2013002007A1", "WO2013002007A1", "WO2013002007A1", "WO2013002007A1",
"WO2016114276A1", "WO2016114276A1", "WO2016114276A1", "WO2016114277A1",
"WO2016114277A1", "WO2016114277A1", "WO2016114277A1", "WO2016114277A1",
"WO2016114277A1", "JP2013005781A", "JP2013005781A", "WO2017094654A1",
"WO2017094654A1", "JP2017112924A", "JP2017112924A", "WO2017169107A1",
"WO2017169107A1", "WO2006070828A1", "WO2006070828A1", "WO2006070828A1",
"WO2006070828A1", "WO2006070828A1", "WO2006070828A1", "WO2006070828A1",
"JP2012183063A", "JP2012183063A", "JP2012183063A", "WO2007097088A1",
"WO2007097088A1", "WO2007097088A1", "WO2007097088A1", "WO2009017116A1",
"WO2009017116A1", "WO2009017116A1", "WO2011145670A1", "WO2011145670A1",
"WO2011145670A1", "WO2008153118A1", "WO2008153118A1", "WO2008153118A1",
"JP2013066497A", "JP2011030577A", "JP2011142922A", "JP2012105673A",
"JP2009213393A", "JP2009225740A", "JP2009254247A", "AU2008297027A1",
"JP2010130902A", "JP2010136658A", "JP2010207213A", "JP2010207217A",
"JP2010220529A", "JP2010220536A", "JP2010252640A", "JP2011036129A",
"JP2011030517A", "JP2011135841A", "JP2011142890A", "JP2011206047A",
"JP2012024081A", "JP2012055235A", "JP2012105572A", "JP2012147775A",
"JP2012213373A", "WO2012147465A1", "JP2012244965A", "JP2013042751A",
"WO2013073628A1", "JP2013143938A", "JP2013150602A", "JP2013165707A",
"JP2013255490A", "JP2013243970A", "JP2014000055A", "JP2014057537A",
"EP2737810A1", "JP2014128251A", "JP2014217315A", "WO2014192826A1",
"JP2015015926A", "WO2015029605A1", "JP2015053920A", "WO2015064748A1",
"JP2015116187A", "JP2015100294A", "WO2015098744A1"), assignees_split = structure(c(19L,
15L, 17L, 1L, 4L, 5L, 18L, 20L, 16L, 21L, 11L, 12L, 14L, 21L,
12L, 14L, 21L, 12L, 15L, 2L, 3L, 8L, 21L, 14L, 21L, 14L, 21L,
14L, 21L, 14L, 21L, 15L, 17L, 6L, 7L, 9L, 10L, 22L, 15L, 16L,
23L, 13L, 15L, 16L, 23L, 15L, 16L, 23L, 15L, 16L, 24L, 15L, 16L,
25L, 25L, 25L, 25L, 25L, 25L, 25L, 25L, 25L, 25L, 25L, 25L, 25L,
25L, 25L, 25L, 25L, 25L, 25L, 25L, 25L, 25L, 25L, 25L, 25L, 25L,
25L, 25L, 25L, 25L, 25L, 25L, 25L, 25L, 25L, 25L, 25L, 25L, 25L,
25L, 25L, 25L, 25L, 25L, 25L, 25L, 25L), .Label = c(" FURUKUBO S ",
" IBUSUKI D ", " ICHIMURA A ", " IZUMI T ", " KAKUDO Y ", " KIMURA M ",
" MAKI H ", " MIYAO Y", " NAGAO K ", " NAKAHARA K", " SUNTORY BEVERAGE&FOOD LTD ",
" SUNTORY FOOD & BEVERAGE CO LTD ", " SUNTORY HOLDINGS CO LTD ",
" SUNTORY HOLDINGS LTD", " SUNTORY HOLDINGS LTD ", " SUNTORY LTD",
" SUNTORY LTD ", " TAKAOKA S", "KOMATSU MFG CO LTD ", "SUN CHEM CORP ",
"SUNTORY BEVERAGE & FOOD LTD ", "SUNTORY FOOD & BEVERAGE CO LTD ",
"SUNTORY HOLDING LTD ", "SUNTORY HOLDINGS CO LTD ", "SUNTORY HOLDINGS LTD"
), class = "factor")), row.names = c(NA, -100L), class = c("tbl_df",
"tbl", "data.frame"))

Dataframe are the assignees of the cited patents so cited_assignees.

structure(list(df_itemnumber_rounded = c("df_2012_2175", "df_2012_2175",
"df_2012_2175", "df_2012_2175", "df_2012_2175", "df_2012_2175",
"df_2002_4897", "df_2012_9460", "df_2012_9460", "df_2012_9460",
"df_2012_9460", "df_2012_9460", "df_2012_9460", "df_2012_9460",
"df_2016_6247", "df_2016_6247", "df_2016_6247", "df_2016_6247",
"df_2016_6247", "df_2016_6247", "df_2016_6248", "df_2016_6248",
"df_2016_6248", "df_2016_6248", "df_2016_6248", "df_2016_6248",
"df_2012_9459", "df_2012_9459", "df_2016_14178", "df_2016_14178",
"df_2016_14178", "df_2016_14178", "df_2016_14178", "df_2016_14178",
"df_2016_14178", "df_2016_14178", "df_2016_14178", "df_2016_14178",
"df_2016_14178", "df_2016_14178", "df_2016_14178", "df_2016_14689",
"df_2016_14689", "df_2016_14689", "df_2016_14689", "df_2016_14689",
"df_2016_14689", "df_2016_15814", "df_2016_15814", "df_2016_15814",
"df_2016_15814", "df_2016_15814", "df_2012_2360", "df_2012_2360",
"df_2012_2360", "df_2012_2360", "df_2012_2360", "df_2012_2360",
"df_2012_2360", "df_2012_2360", "df_2012_2360", "df_2012_2360",
"df_2012_2360", "df_2012_2360", "df_2012_8944", "df_2012_3604",
"df_2012_3604", "df_2012_3604", "df_2012_3604", "df_2012_3604",
"df_2012_3604", "df_2012_3604", "df_2012_3604", "df_2012_3604",
"df_2012_4967", "df_2012_4967", "df_2012_4967", "df_2012_4967",
"df_2012_4967", "df_2012_4967", "df_2012_4967", "df_2012_4967",
"df_2012_4967", "df_2012_4967", "df_2012_4967", "df_2012_4967",
"df_2012_4967", "df_2012_4967", "df_2012_4967", "df_2012_4967",
"df_2012_4967", "df_2012_4967", "df_2012_4967", "df_2012_4967",
"df_2012_7883", "df_2012_7883", "df_2012_7883", "df_2012_7883",
"df_2012_7883", "df_2012_4836"), citedp_assignee = structure(c(40L,
23L, 48L, 6L, 15L, 13L, 12L, 30L, 1L, 52L, 53L, 58L, 56L, 3L,
52L, 52L, 16L, 66L, 52L, 67L, 16L, 66L, 52L, 68L, 52L, 51L, 63L,
3L, 60L, 27L, 45L, 52L, 9L, 73L, 33L, 25L, 52L, 50L, 62L, 73L,
64L, 2L, 59L, 28L, 28L, 52L, 46L, 4L, 42L, 1L, 42L, 43L, 31L,
70L, 32L, 57L, 39L, 14L, 35L, 11L, 56L, 32L, 32L, 55L, 17L, 22L,
22L, 56L, 56L, 5L, 36L, 56L, 41L, 21L, 20L, 29L, 18L, 19L, 47L,
7L, 63L, 4L, 38L, 44L, 65L, 56L, 44L, 26L, 34L, 65L, 69L, 10L,
24L, 8L, 71L, 49L, 54L, 61L, 72L, 37L), .Label = c("  ", "ABURADA MASAKI,TOKIWA PHYTOCHEMICAL CO LTD ",
"ASAHI BREWERIES LTD", "ASAHI BREWERIES LTD ", "ASAHI BREWERIES LTD,JIBIKI MAKIKO ",
"CERESTAR HOLDING BV ", "CHOYA UMESHU CO LTD ", "CHUKO SHUZO KK",
"CREAGRI INC,CREA ROBERTO,MATTEUZZI FRANCESCO,ASTORE STEFANO,MILIONI IVANO ",
"DEZAINAA FOODS KYOKAI KK ", "FUKUI HISASHI ", "GULF OIL CORP",
"HOKKAIDO WAIN KK", "IKEDA SHOKKEN KK ", "INSUCHI PUROBUREMU NADEJINOSUT ",
"ITO EN LTD ", "ITOEN KK", "JAPAN MAIZE PROD ", "KANEBO LTD ",
"KANEBO LTD,HASEGAWA T CO LTD ", "KIRIN BREWERY", "KIRIN BREWERY ",
"KIRIN BREWERY,JAPAN MAIZE PROD ", "KOHJIN CO ", "LION CORP ",
"MANNS WINE CO LTD ", "MARUNAKA SHOKUHIN KK ", "MARUZEN PHARMA ",
"MATSUSHITA ELECTRIC IND CO LTD ", "MATSUTANI KAGAKU KOGYO KK ",
"MEIJI DAIRIES CORP ", "MEIJI MILK PROD CO LTD ", "MILLER BREWING INTERNATIONAL INC,LUSK LANCE T,RYDER DAVID S ",
"MITSUBISHI CHEM IND ", "MITSUBISHI HEAVY IND LTD,KADO TAKASHI,ISOZAKI TOSHIKAZU ",
"MIYAGI PREFECTURE,MIYAGIKEN SHUZO KYODO KUMIAI ", "NAT TAX ADMINISTRATION AGENCY ",
"NIPPON BEET SUGAR MFG ", "OGAWA & CO LTD ", "OKURA SYUZO KK ",
"OZEKI KK ", "PEPSICO INC ", "PEPSICO INC,LEE THOMAS,NATTRESS LAURA ANN,RIHA WILLIAM",
"POLA CHEM IND INC ", "RIVERSON KK ", "SAN EI GEN FFI INC", "SAN EI GEN FFI INC ",
"SAPPORO BREWERIES ", "SAPPORO BREWERIES,OONO MASAO,SANO TOMOHIRO ",
"SHOWA PHARM CHEM IND ", "SUNTORY HOLDINGS LTD", "SUNTORY HOLDINGS LTD ",
"SUNTORY HOLDINGS LTD,IDO YOSHIHIRO,KOMINE TETSUYA ", "SUNTORY HOLDINGS LTD,KAGEYAMA NORIHIKO,INUI TAKAKO,TAKAGI DAISUKE ",
"SUNTORY LTD", "SUNTORY LTD ", "SUNTORY LTD,KAGEYAMA NORIHIKO,NAKAHARA KOICHI,INUI TAKAKO,TAKAOKA SEISUKE,NAGAMI KENZO ",
"SUNTORY LTD,WATANABE TOKUTOMI,DAIDO HIROMI,YOSHIHIRO AKIRA ",
"SYMRISE GMBH & CO KG ", "TAISHO PHARMA CO LTD ", "TAKARA HOLDINGS INC ",
"TAKARA SHOKUHIN KK ", "TAKARA SHUZO CO ", "TAKASAGO PERFUMERY CO LTD",
"TOKYO SHIBAURA ELECTRIC CO ", "TOYO SEIKAN KAISHA LTD ", "TROPICANA PROD INC",
"TROPICANA PROD INC ", "TSUKISHIMA KIKAI CO ", "UNILEVER PLC,UNILEVER NV,LEVER HINDUSTAN LTD ",
"WOONGJIN FOODS CO LTD ", "YAKULT HONSHA KK,KUMAMOTOKEN KAJITSU NOGYO KYOD",
"YAMADA YASUYUKI "), class = "factor")), row.names = c(NA, -100L
), class = c("tbl_df", "tbl", "data.frame"))

Body:
Here's a potential solution. Note that your assignee and citetp variables are messy with whitespaces at the beginning/end taht you might not want to take into account for your string search:

library(tidyverse)

df1 <- data.frame(df_itemnumber_rounded = c("df_2002_77", "df_2002_77", "df_2002_77", "df_2002_78", "df_2002_767"),
                  assignees_split = c("DSM IP ASSETS BV","DSM NV,GIST BROCADES NV","INRA INST NAT RECH AGRONOMIQUE","DE FORENEDE BRYGGERIER AS", "FORENEDE BRYGGERIER" ))

df2 <- data.frame(citedp_assignee = c("LANGEJAN AREND","PELLETIER RENE FRANCOIS ROGER ","LESAFFRE &amp; CIE","GIST BROCADES NV ", "DISTILLERS CO YEAST LTD "))

The solution below gives ou the full information about which assignees appear in the citedp variable:

df1 |>
  mutate(is_match = str_detect(tolower(assignees_split),
                               paste0(tolower(trimws(df2$citedp_assignee, which = "both")),
                                      collapse = "|"))) |>
  group_by(df_itemnumber_rounded, assignees_split) |>
  summarize(counts = sum(is_match))

which gives:

# A tibble: 5 x 3
# Groups:   df_itemnumber_rounded [3]
  df_itemnumber_rounded assignees_split                counts
  <chr>                 <chr>                           <int>
1 df_2002_767           FORENEDE BRYGGERIER                 0
2 df_2002_77            DSM IP ASSETS BV                    0
3 df_2002_77            DSM NV,GIST BROCADES NV             1
4 df_2002_77            INRA INST NAT RECH AGRONOMIQUE      0
5 df_2002_78            DE FORENEDE BRYGGERIER AS           0

If you only want to get the ids where there's at least one match, you can do:

df1 |>
  mutate(is_match = str_detect(tolower(assignees_split),
                               paste0(tolower(trimws(df2$citedp_assignee, which = "both")),
                                      collapse = "|"))) |>
  group_by(df_itemnumber_rounded, assignees_split) |>
  summarize(counts = sum(is_match)) |>
  filter(!all(counts == 0))

which gives:

# A tibble: 3 x 3
# Groups:   df_itemnumber_rounded [1]
  df_itemnumber_rounded assignees_split                counts
  <chr>                 <chr>                           <int>
1 df_2002_77            DSM IP ASSETS BV                    0
2 df_2002_77            DSM NV,GIST BROCADES NV             1
3 df_2002_77            INRA INST NAT RECH AGRONOMIQUE      0

Another shot after TO provided some sample data.

So here's the idea:

Note: I named the two data frames df1 (assignees) and df2 (companies).

We first do some basic cleaning of the character columns, e.g. convert everything to lowercase characters and get rid of some whitespaces at the beginning/end.

We then go through each row/assignee in df1 (hence rowwise) and count how often this assigne name occurs in df2 for the same company identifier.

library(tidyverse)

df1 <- df1 |>
  mutate(assignee_new = tolower(trimws(assignees_split, "both")))

df2 <- df2 |>
  mutate(citedp_new = tolower(trimws(citedp_assignee, "both")))

df1 |>
  rowwise() |>
  mutate(assignee_count = length(str_which(df2$citedp_new[df2$df_itemnumber_rounded == df_itemnumber_rounded],
                                           assignee_new))) |>
  ungroup() |>
  print(n = 100)

which gives (only printing the first 20 rows):

# A tibble: 100 x 5
    df_itemnumber_rounded `Publication Number` assignees_split                    assignee_new                   assignee_count
    <chr>                 <chr>                <fct>                              <chr>                                   <int>
  1 df_2012_2175          WO2006046567A1       "KOMATSU MFG CO LTD "              komatsu mfg co ltd                          0
  2 df_2012_2175          WO2006046567A1       " SUNTORY HOLDINGS LTD "           suntory holdings ltd                        0
  3 df_2012_2175          WO2006046567A1       " SUNTORY LTD "                    suntory ltd                                 0
  4 df_2012_2175          WO2006046567A1       " FURUKUBO S "                     furukubo s                                  0
  5 df_2012_2175          WO2006046567A1       " IZUMI T "                        izumi t                                     0
  6 df_2012_2175          WO2006046567A1       " KAKUDO Y "                       kakudo y                                    0
  7 df_2012_2175          WO2006046567A1       " TAKAOKA S"                       takaoka s                                   0
  8 df_2002_4897          DE3149931A1          "SUN CHEM CORP "                   sun chem corp                               0
  9 df_2002_4897          DE3149931A1          " SUNTORY LTD"                     suntory ltd                                 0
 10 df_2012_9460          WO2013002007A1       "SUNTORY BEVERAGE & FOOD LTD "     suntory beverage & food ltd                 0
 11 df_2012_9460          WO2013002007A1       " SUNTORY BEVERAGE&FOOD LTD "      suntory beverage&food ltd                   0
 12 df_2012_9460          WO2013002007A1       " SUNTORY FOOD & BEVERAGE CO LTD " suntory food & beverage co ltd              0
 13 df_2012_9460          WO2013002007A1       " SUNTORY HOLDINGS LTD"            suntory holdings ltd                        2
 14 df_2016_6247          WO2016114276A1       "SUNTORY BEVERAGE & FOOD LTD "     suntory beverage & food ltd                 0
 15 df_2016_6247          WO2016114276A1       " SUNTORY FOOD & BEVERAGE CO LTD " suntory food & beverage co ltd              0
 16 df_2016_6247          WO2016114276A1       " SUNTORY HOLDINGS LTD"            suntory holdings ltd                        3
 17 df_2016_6248          WO2016114277A1       "SUNTORY BEVERAGE & FOOD LTD "     suntory beverage & food ltd                 0
 18 df_2016_6248          WO2016114277A1       " SUNTORY FOOD & BEVERAGE CO LTD " suntory food & beverage co ltd              0
 19 df_2016_6248          WO2016114277A1       " SUNTORY HOLDINGS LTD "           suntory holdings ltd                        3
 20 df_2016_6248          WO2016114277A1       " IBUSUKI D "                      ibusuki d                                   0

I tested it by increasing the size of df1 to 10000 rows and df2 to 150000 rows (of course, you real-life pattern might be more complex) and it runs just fine in 20 seconds on my machine:

df1_new <- df1 |>
  slice(rep(1:n(), each = 100))

df2_new <- df2 |>
  slice(rep(1:n(), each = 1500))

t1 <- Sys.time()

df1_new |>
  rowwise() |>
  mutate(assignee_count = length(str_which(df2_new$citedp_new[df2_new$df_itemnumber_rounded == df_itemnumber_rounded],
                                           assignee_new))) |>
  ungroup()

Sys.time() - t1

Time difference of 20.36699 secs


问:
Restoring nested recyclerview state
....
Hello, everyone.
I am developing an application where there is a nested recyclerviews like play store:

When you open one item a new fragment is opened. And when you press back button child recyclerview state (scroll positions, ...) is restored. How do they achieve that?

In my case ChildRecyclerviews are not restoring their state?

Thank you.

答:
I am using Shared Preferences for that. When an item is clicked I save its position, and when the list is restored, I go back to that position.

the code inside the main fragment:

```<code>    SharedPreferences XYsharedPreferences; // global variable

    ...

    final ListView listView = view.findViewById (R.id.list_view);
    listView.setAdapter (rowsAdapter); // created before...
    listView.setOnItemClickListener ((parent, view, position, id) -> {

        SharedPreferences.Editor editor = XYsharedPreferences.edit ();
        editor.putInt ("row", position);
        editor.apply ();

        ...

    });

    XYsharedPreferences = requireActivity().getSharedPreferences ("xyRows", Context.MODE_PRIVATE);
    if (XYsharedPreferences != null){
        final int position = XYsharedPreferences.getInt ("row", 0);
        listView.setSelection (position);
    }
</code>```

Title: Restoring nested recyclerview state

Body:
I am using Shared Preferences for that. When an item is clicked I save its position, and when the list is restored, I go back to that position.

the code inside the main fragment:

    SharedPreferences XYsharedPreferences; // global variable

    ...

    final ListView listView = view.findViewById (R.id.list_view);
    listView.setAdapter (rowsAdapter); // created before...
    listView.setOnItemClickListener ((parent, view, position, id) -> {

        SharedPreferences.Editor editor = XYsharedPreferences.edit ();
        editor.putInt ("row", position);
        editor.apply ();

        ...

    });

    XYsharedPreferences = requireActivity().getSharedPreferences ("xyRows", Context.MODE_PRIVATE);
    if (XYsharedPreferences != null){
        final int position = XYsharedPreferences.getInt ("row", 0);
        listView.setSelection (position);
    }


问:
How to ignore missing role error on Ansible
We have an ansible project using a lot of roles which are not included in the same git repository (I will refer to it as external roles). We use ansible-galaxy with a requirements.yml file to install these roles but we have to run it manually and frequently to get the last version of the roles.

I want to get rid of this manual task, so I created a playbook that will be called before the others via import_playbook in the site.yml. It's only purpose is running the ansible-galaxy command to ensure that the external roles are installed and in the last version available.

Projet Structure :

```<code>- project
  - roles
    - project_role1
    - project_role2
    - requirements.yml
  - playbook
    - 1_install_roles.yml
    - 2_mainplaybook.yml
  - site.yml

- external_roleA
  - tasks ...
</code>```

site.yml

```<code>  - import_playbook: ./playbooks/install_roles.yml
  - import_playbook: ./playbooks/playbook1.yml
</code>```

1_install_roles.yml

```<code>---
- hosts: localhost

  tasks:
    - name: Auto-Update ansible role
      command: ansible-galaxy install -r roles/requirements.yml -p roles --force
      delegate_to: localhost
      register: galaxy-output
      changed_when: '"was installed successfully" in galaxy-output.stdout'

    - name: Show ansible-galaxy output
      debug: msg="{{ galaxy-output.stdout }}"
</code>```

2_mainplaybook.yml

```<code>---
  - name: mainplaybook
    hosts: all

    roles:
    - role: project_role1
    - role: external_roleA
    - role: project_role2
</code>```

It works for updating the roles but fail when the roles are not installed yet on the local machine, I got the following error :

```<code>ERROR! the role 'external_roleA' was not found
</code>```

Because at this time ansible is right, the role cannot be found but will be installed before reaching this particular step. So my question is how to ignore this error ? or how do I tell ansible not to check for roles before using them.

答:
As mentionned by @Zeitounator a solution is to use include_role in tasks inside the playbook.

```<code>---
  - name: mainplaybook
    hosts: all

    tasks:
      - include_role:
        name: external_roleA
</code>```

When mixing Tasks and Roles in a playbook be aware that Ansible has a specific order of execution:

When you use the roles option at the play level, Ansible treats the
roles as static imports and processes them during playbook parsing.
Ansible executes your playbook in this order:

Any pre_tasks defined in the play.

Any handlers triggered by pre_tasks.

Each role listed in roles:, in the order listed. Any role dependencies defined in the role’s meta/main.yml run first, subject to tag filtering and conditionals. See Using role dependencies for more details.

Any tasks defined in the play.

Any handlers triggered by the roles or tasks.

Any post_tasks defined in the play.

Any handlers triggered by post_tasks.

Body:
We have an ansible project using a lot of roles which are not included in the same git repository (I will refer to it as external roles). We use ansible-galaxy with a requirements.yml file to install these roles but we have to run it manually and frequently to get the last version of the roles.

I want to get rid of this manual task, so I created a playbook that will be called before the others via import_playbook in the site.yml. It's only purpose is running the ansible-galaxy command to ensure that the external roles are installed and in the last version available.

Projet Structure :

- project
  - roles
    - project_role1
    - project_role2
    - requirements.yml
  - playbook
    - 1_install_roles.yml
    - 2_mainplaybook.yml
  - site.yml

- external_roleA
  - tasks ...

site.yml

  - import_playbook: ./playbooks/install_roles.yml
  - import_playbook: ./playbooks/playbook1.yml

1_install_roles.yml

---
- hosts: localhost

  tasks:
    - name: Auto-Update ansible role
      command: ansible-galaxy install -r roles/requirements.yml -p roles --force
      delegate_to: localhost
      register: galaxy-output
      changed_when: '"was installed successfully" in galaxy-output.stdout'

    - name: Show ansible-galaxy output
      debug: msg="{{ galaxy-output.stdout }}"

2_mainplaybook.yml

---
  - name: mainplaybook
    hosts: all

    roles:
    - role: project_role1
    - role: external_roleA
    - role: project_role2

It works for updating the roles but fail when the roles are not installed yet on the local machine, I got the following error :

ERROR! the role 'external_roleA' was not found

Because at this time ansible is right, the role cannot be found but will be installed before reaching this particular step. So my question is how to ignore this error ? or how do I tell ansible not to check for roles before using them.

Body:
As mentionned by @Zeitounator a solution is to use include_role in tasks inside the playbook.

---
  - name: mainplaybook
    hosts: all

    tasks:
      - include_role:
        name: external_roleA

When mixing Tasks and Roles in a playbook be aware that Ansible has a specific order of execution:

When you use the roles option at the play level, Ansible treats the
roles as static imports and processes them during playbook parsing.
Ansible executes your playbook in this order:

Any pre_tasks defined in the play.

Any handlers triggered by pre_tasks.

Each role listed in roles:, in the order listed. Any role dependencies defined in the role’s meta/main.yml run first, subject to tag filtering and conditionals. See Using role dependencies for more details.

Any tasks defined in the play.

Any handlers triggered by the roles or tasks.

Any post_tasks defined in the play.

Any handlers triggered by post_tasks.


问:
Rounding a double value to x number of decimal places in swift
Can anyone tell me how to round a double value to x number of decimal places in Swift?

I have:

```<code>var totalWorkTimeInHours = (totalWorkTime/60/60)
</code>```

With totalWorkTime being an NSTimeInterval (double) in second.

totalWorkTimeInHours will give me the hours, but it gives me the amount of time in such a long precise number e.g. 1.543240952039......

How do I round this down to, say, 1.543 when I print totalWorkTimeInHours?

答: Lots of example are using maths, the problem is floats are approximations of real number, there is no way to express 0.1 (1/10) exactly as a float just as there is no exact way to express ⅓ exactly using decimal points, so you need to ask your self exactly what your are trying to achieve, if you just want to display them leave them as they are in code, trying to round them is going to justify give you less accurate result as you are throwing away precious, round ⅓ in decimal notation to 1 decimal place is not going to give you a number closer to ⅓, us NumberFormate to round it, if you have something like a viewModel class it can be used to return a string representation to your models numbers. NumberFormaters give you lots of control on how numbers are formatted and the number of decimal places you want.</p>

Body:
Can anyone tell me how to round a double value to x number of decimal places in Swift?

I have:

var totalWorkTimeInHours = (totalWorkTime/60/60)

With totalWorkTime being an NSTimeInterval (double) in second.

totalWorkTimeInHours will give me the hours, but it gives me the amount of time in such a long precise number e.g. 1.543240952039......

How do I round this down to, say, 1.543 when I print totalWorkTimeInHours?


问:
How to split a patch into two parts (with pbranch)?
I am working on a mercurial repository and using pbrach for working on a set of patches.

Assume I have two files A and B, and two patches patchA (modifies A) and patchAB (modifies A and B).
The pgraph looks like this:

```<code>o  patchAB
|
@  patchA
|
o  default
</code>```

By mistake, I committed a change to file B into patchA.

How do I split the patch A into 2 parts, so that I end up with: patchA=patchA' + newPatch, where patchA=Original Patch, patchA'=changes of patchA in file A, P2=changes of patchA in file B.

```<code>o  patchAB
|
| o newPatch // rest of original patchA without changes already in patchA'
|/
@  patchA' // with only the changes to file A
|
o  default
</code>```

(I search something similar to splitting patches with mq but for pbranch).

答:
Finally, I found a relatively short solution myself.

First I get the revision number of the last 'good' commit (say 1), and the wrong commit (say 2).

1) I update to patchA, revert the change on fileB, and commit it, and pmerge the changes upwards:

```<code>hg up patchA
hg revert -r1 fileB  // get fileB before the wrong change
hg commit -m"revert fileB"
hg pmerge -a
</code>```

2) Update to patchA again, revert the wrong commit and create a new patch:

```<code>hg up patchA
hg revert -r2 fileB  // get fileB after the wrong change
hg pnew patchA2
</code>```

We now have the changes of fileA in patchA and the rest in patchA2.

Body:
I am working on a mercurial repository and using pbrach for working on a set of patches.

Assume I have two files A and B, and two patches patchA (modifies A) and patchAB (modifies A and B).
The pgraph looks like this:

o  patchAB
|
@  patchA
|
o  default

By mistake, I committed a change to file B into patchA.

How do I split the patch A into 2 parts, so that I end up with: patchA=patchA' + newPatch, where patchA=Original Patch, patchA'=changes of patchA in file A, P2=changes of patchA in file B.

o  patchAB
|
| o newPatch // rest of original patchA without changes already in patchA'
|/
@  patchA' // with only the changes to file A
|
o  default

(I search something similar to splitting patches with mq but for pbranch).

Body:
Finally, I found a relatively short solution myself.

First I get the revision number of the last 'good' commit (say 1), and the wrong commit (say 2).

1) I update to patchA, revert the change on fileB, and commit it, and pmerge the changes upwards:

hg up patchA
hg revert -r1 fileB  // get fileB before the wrong change
hg commit -m"revert fileB"
hg pmerge -a

2) Update to patchA again, revert the wrong commit and create a new patch:

hg up patchA
hg revert -r2 fileB  // get fileB after the wrong change
hg pnew patchA2

We now have the changes of fileA in patchA and the rest in patchA2.


问:
Stop process using a button
I created a "loading window", where during a process a progress bar appears, after the end of the process this window disappears.
The process in my Tool takes 2, 3 Minutes. I want to implement a button that when the Tool has started the process can be interrupted via this button.

```<code>    public partial class LoadingWindow : Form
    {
        public Action Worker { get; set; }
        public LoadingWindow(Action worker)
        {
            InitializeComponent();
            if (worker == null)
                throw new ArgumentNullException();
            Worker = worker;
        }

        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);
            Task.Factory.StartNew(Worker).ContinueWith(t => { this.Close(); }, TaskScheduler.FromCurrentSynchronizationContext());
        }

        private void btnStopProcess_Click(object sender, EventArgs e)
        {

        }
    }

</code>```

Does anyone have any idea, what to implement in btnStopProcess_Click function (...) ?

答:
Yes, but you need to adapt your worker accordingly, because the task must be able to "assist" that it can be terminated.

    public partial class LoadingWindow : Form
    {
        private CancellationTokenSource _cancel;
        public Action<CancellationToken> Worker { get; set; }
        public LoadingWindow(Action<CancellationToken> worker)
        {
            _cancel = new CancellationTokenSource();
            InitializeComponent();
            if (worker == null)
                throw new ArgumentNullException();
            Worker = worker;
        }

        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);
            Task.Factory.StartNew(() => Worker(_cancel.Token)).ContinueWith(t => { this.Close(); }, TaskScheduler.FromCurrentSynchronizationContext());
        }

        private void btnStopProcess_Click(object sender, EventArgs e)
        {
            _cancel.Cancel(); // Inform worker that abort was pressed.
        }
    }
```

And then, in your worker, regularly test whether the token is cancelled and abort if so. You may need to forward it to the methods that get called from there.

[You might also want to remove the setter from the Worker property. Changing the worker while the window is already visible will result in weird behavior]

Title: Stop process using a button

Body:
I created a "loading window", where during a process a progress bar appears, after the end of the process this window disappears.
The process in my Tool takes 2, 3 Minutes. I want to implement a button that when the Tool has started the process can be interrupted via this button.

    public partial class LoadingWindow : Form
    {
        public Action Worker { get; set; }
        public LoadingWindow(Action worker)
        {
            InitializeComponent();
            if (worker == null)
                throw new ArgumentNullException();
            Worker = worker;
        }

        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);
            Task.Factory.StartNew(Worker).ContinueWith(t => { this.Close(); }, TaskScheduler.FromCurrentSynchronizationContext());
        }

        private void btnStopProcess_Click(object sender, EventArgs e)
        {

        }
    }

Does anyone have any idea, what to implement in btnStopProcess_Click function (...) ?

Body:
Yes, but you need to adapt your worker accordingly, because the task must be able to "assist" that it can be terminated.

    public partial class LoadingWindow : Form
    {
        private CancellationTokenSource _cancel;
        public Action<CancellationToken> Worker { get; set; }
        public LoadingWindow(Action<CancellationToken> worker)
        {
            _cancel = new CancellationTokenSource();
            InitializeComponent();
            if (worker == null)
                throw new ArgumentNullException();
            Worker = worker;
        }

        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);
            Task.Factory.StartNew(() => Worker(_cancel.Token)).ContinueWith(t => { this.Close(); }, TaskScheduler.FromCurrentSynchronizationContext());
        }

        private void btnStopProcess_Click(object sender, EventArgs e)
        {
            _cancel.Cancel(); // Inform worker that abort was pressed.
        }
    }

And then, in your worker, regularly test whether the token is cancelled and abort if so. You may need to forward it to the methods that get called from there.

[You might also want to remove the setter from the Worker property. Changing the worker while the window is already visible will result in weird behavior]