问:
Can someone explain this regular expression?
```<code>(.*)([0-9]{6})|(.*)([0-9]{4})
</code>```

<p>Does it mean pick up a number that is either 6 digits or 4 digits ? Is there a concise way to write it ? </p>

答:
The only way that regex makes sense to me is if you're trying to extract a certain number of contiguous digits from a string.  If there's more than one potential match in the string, you want the last one.

The (.*) in the first alternative initially gobbles up the whole string, but then it backs off far enough to enable ([0-9]{6}) to capture the last six of them.  If it backs off all the way to the beginning without finding a match, the first alternative reports failure.  Control then passes to second alternative, which uses the same technique to try and the last match four digits.  If that fails, the overall match attempt fails.

I started to say the regex was trying to match six or four digits at the end of the string, because that's the usual reason why people use that technique.  But that would require it to be anchored at the end like @Cybernate's regex is.  In your case it would look like this:

```<code>^(?:(.*)([0-9]{6})|(.*)([0-9]{4}))$
</code>```

The start anchor - ^ - isn't required for matching purposes, but it improves efficiency by allowing only one match attempt per alternative.  Some regex flavors are smart enough to realize that if (.*) doesn't match at the beginning of the string there's no point trying it at the second position, the third position, etc., but you can't count on that.

EDIT: I just noticed the java tag.  If you're using this regex with Java's matches() method, you don't need to add anchors; that method automatically anchors every match at both ends.  If you don't want your matches anchored at the end, you'll have to "pad" the regex with more dot-stars:

```<code>(.*)([0-9]{6}).*|(.*)([0-9]{4}).*
</code>```

Body:
(.*)([0-9]{6})|(.*)([0-9]{4})

Does it mean pick up a number that is either 6 digits or 4 digits ? Is there a concise way to write it ?

Body:
The only way that regex makes sense to me is if you're trying to extract a certain number of contiguous digits from a string.  If there's more than one potential match in the string, you want the last one.

The (.*) in the first alternative initially gobbles up the whole string, but then it backs off far enough to enable ([0-9]{6}) to capture the last six of them.  If it backs off all the way to the beginning without finding a match, the first alternative reports failure.  Control then passes to second alternative, which uses the same technique to try and the last match four digits.  If that fails, the overall match attempt fails.

I started to say the regex was trying to match six or four digits at the end of the string, because that's the usual reason why people use that technique.  But that would require it to be anchored at the end like @Cybernate's regex is.  In your case it would look like this:

^(?:(.*)([0-9]{6})|(.*)([0-9]{4}))$

The start anchor - ^ - isn't required for matching purposes, but it improves efficiency by allowing only one match attempt per alternative.  Some regex flavors are smart enough to realize that if (.*) doesn't match at the beginning of the string there's no point trying it at the second position, the third position, etc., but you can't count on that.

EDIT: I just noticed the java tag.  If you're using this regex with Java's matches() method, you don't need to add anchors; that method automatically anchors every match at both ends.  If you don't want your matches anchored at the end, you'll have to "pad" the regex with more dot-stars:

(.*)([0-9]{6}).*|(.*)([0-9]{4}).*


来源: stackexchange

问:
Lodash: filter when I have nested array property?
Consider below example. I am using Lodash

```<code>"home":[
   {
      "data":{
         "interests":["sports", "travel", "boxing"],
         "city":["x", "y", "z"],
         "name":"test1"
      },
      "count":["1", "2"],
      "country":"CA"
   },
   {
      "data":{
         "interests":["painting", "travel", "dancing"],
         "city":["a", "y", "b"],
         "name":"test2"
      },
      "count":["1","3"],
      "country":"US"
   }
]
</code>```

If I'll try the function on key value pair example :

```<code>_.find(home, ['data.country', 'US']);  // It is returning me the 2nd object
</code>```

requirement :

I want all the objects where data.interests is 'dancing'.

Tried :

```<code>_.find(home, ['data.interests', 'dancing'])  // It is returning []
</code>```

I have also tried filter(), where() and map but unable to get the complete object.

Thanks in advance.

答:
You can use vanilla JS or lodash funcntions -  Filter the array, and for each item check if the data.interests array includes the requested word.

Vanilla:

const home = [{"data":{"interests":["sports","travel","boxing"],"city":["x","y","z"],"name":"test1"},"count":["1","2"],"country":"CA"},{"data":{"interests":["painting","travel","dancing"],"city":["a","y","b"],"name":"test2"},"count":["1","3"],"country":"US"}]

const result = home.filter(o => o.data.interests.includes('dancing'))

console.log(result)```
</div>
</div>
</p>

<p>Lodash:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const home = [{"data":{"interests":["sports","travel","boxing"],"city":["x","y","z"],"name":"test1"},"count":["1","2"],"country":"CA"},{"data":{"interests":["painting","travel","dancing"],"city":["a","y","b"],"name":"test2"},"count":["1","3"],"country":"US"}]

const result = _.filter(home, o => _.includes(o.data.interests, 'dancing'))

console.log(result)</code>```

```

ContentLicense: CC BY-SA 4.0

Body:
Consider below example. I am using Lodash

"home":[
   {
      "data":{
         "interests":["sports", "travel", "boxing"],
         "city":["x", "y", "z"],
         "name":"test1"
      },
      "count":["1", "2"],
      "country":"CA"
   },
   {
      "data":{
         "interests":["painting", "travel", "dancing"],
         "city":["a", "y", "b"],
         "name":"test2"
      },
      "count":["1","3"],
      "country":"US"
   }
]

If I'll try the function on key value pair example :

_.find(home, ['data.country', 'US']);  // It is returning me the 2nd object

requirement :

I want all the objects where data.interests is 'dancing'.

Tried :

_.find(home, ['data.interests', 'dancing'])  // It is returning []

I have also tried filter(), where() and map but unable to get the complete object.

Thanks in advance.

Body:
You can use vanilla JS or lodash funcntions -  Filter the array, and for each item check if the data.interests array includes the requested word.

Vanilla:

const home = [{"data":{"interests":["sports","travel","boxing"],"city":["x","y","z"],"name":"test1"},"count":["1","2"],"country":"CA"},{"data":{"interests":["painting","travel","dancing"],"city":["a","y","b"],"name":"test2"},"count":["1","3"],"country":"US"}]

const result = home.filter(o => o.data.interests.includes('dancing'))

console.log(result)

Lodash:

const home = [{"data":{"interests":["sports","travel","boxing"],"city":["x","y","z"],"name":"test1"},"count":["1","2"],"country":"CA"},{"data":{"interests":["painting","travel","dancing"],"city":["a","y","b"],"name":"test2"},"count":["1","3"],"country":"US"}]

const result = _.filter(home, o => _.includes(o.data.interests, 'dancing'))

console.log(result)

<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.js"></script>


问:
How to stub ES6 class constructors with Sinon
I'm trying stub class constructors with Sinon.

The stub of the regular method 'omg' works fine, but the stub of the constructor fails the test, and the 'real' constructor is called instead of the stub.

Any ideas on what syntax I need to stub this correctly?

class Foo {
    constructor() {
        this.bar = new Bar();
    }

    omg() {
        this.bar.omg();
    }
}

class Bar {
    constructor() {
        console.log('In bar constructor');
    }

    omg() {
        console.log('In bar omg');
    }
}

const sandbox = sinon.createSandbox();
sandbox.stub(Bar.prototype, 'constructor');
sandbox.stub(Bar.prototype, 'omg');

describe('Foo', () => {
    describe('Constructor', () => {
        it('Should instantiate bar', () => {
            const foo = new Foo();
            expect(Bar.prototype.constructor.called).to.be.true;
        });
    });

    describe('Omg', () => {
        it("Should call Bar's omg method', () => {
            const foo = new Foo();
            foo.omg();
            expect(Bar.prototype.omg.called).to.be.true;
        });
    });
});```

答:
Its been more than 2 years, means this is hard. :)

When it is hard to do, then the code need refactoring.

Below example works but may not usable at real world (need to define Bar as stub before define Foo).

Highlight:

usage of stub calledWithNew() to check whether Bar called with new.

not use arrow functions.

Usage of chai's expect instanceof, because of Foo constructor will add property bar, then, additional expectation can be added to check property bar, which means check whether Foo's construction function run.

// @file stackoverflow.js
const sinon = require('sinon');
const { expect } = require('chai');

const sandbox = sinon.createSandbox();

// Define Bar as a stub.
const Bar = sandbox.stub();
const BarOmgFn = sinon.fake();
Bar.prototype.omg = BarOmgFn;

// class Bar {
//   constructor() {
//     console.log('In bar constructor');
//   }
//   omg() {
//     console.log('In bar omg');
//   }
// }

class Foo {
  constructor() {
    this.bar = new Bar();
  }

  omg() {
    this.bar.omg();
  }
}

describe('Foo', function () {
  after(function () {
    sandbox.restore();
  });
  describe('Constructor', function () {
    it('Should instantiate bar', function () {
      const foo = new Foo();

      // Check whether Bar called with new.
      expect(Bar.calledWithNew()).to.equal(true);
      // Check bar property.
      expect(foo.bar).to.be.instanceOf(Bar);
    });
  });

  describe('Omg', () => {
    it("Should call Bar's omg method", function () {
      const foo = new Foo();
      foo.omg();

      expect(BarOmgFn.calledOnce).to.equal(true);
    });
  });
});
```

<p>Run the example using mocha:</p>

```$ npx mocha stackoverflow.js

  Foo
    Constructor
      ✓ Should instantiate bar
    Omg
      ✓ Should call Bar's omg method

  2 passing (14ms)

$
```

<p>From design pattern point of view, class Foo is highly dependent to class Bar. Refactoring can use dependency injection pattern. For example: simple change to class Foo, by require 1 argument, which is Bar itself or instance of Bar. This change make the code easier to test.</p>

<pre class="lang-js prettyprint-override"><code>class Foo {
  // Now constructor need 1 argument
  constructor(Bar) {
    this.bar = new Bar();
  }

  omg() {
    this.bar.omg();
  }
}

</code>```

Hope this helps.

ContentLicense: CC BY-SA 3.0

Body:
Its been more than 2 years, means this is hard. :)

When it is hard to do, then the code need refactoring.

Below example works but may not usable at real world (need to define Bar as stub before define Foo).

Highlight:

usage of stub calledWithNew() to check whether Bar called with new.

not use arrow functions.

Usage of chai's expect instanceof, because of Foo constructor will add property bar, then, additional expectation can be added to check property bar, which means check whether Foo's construction function run.

// @file stackoverflow.js
const sinon = require('sinon');
const { expect } = require('chai');

const sandbox = sinon.createSandbox();

// Define Bar as a stub.
const Bar = sandbox.stub();
const BarOmgFn = sinon.fake();
Bar.prototype.omg = BarOmgFn;

// class Bar {
//   constructor() {
//     console.log('In bar constructor');
//   }
//   omg() {
//     console.log('In bar omg');
//   }
// }

class Foo {
  constructor() {
    this.bar = new Bar();
  }

  omg() {
    this.bar.omg();
  }
}

describe('Foo', function () {
  after(function () {
    sandbox.restore();
  });
  describe('Constructor', function () {
    it('Should instantiate bar', function () {
      const foo = new Foo();

      // Check whether Bar called with new.
      expect(Bar.calledWithNew()).to.equal(true);
      // Check bar property.
      expect(foo.bar).to.be.instanceOf(Bar);
    });
  });

  describe('Omg', () => {
    it("Should call Bar's omg method", function () {
      const foo = new Foo();
      foo.omg();

      expect(BarOmgFn.calledOnce).to.equal(true);
    });
  });
});

Run the example using mocha:

$ npx mocha stackoverflow.js

  Foo
    Constructor
      ✓ Should instantiate bar
    Omg
      ✓ Should call Bar's omg method

  2 passing (14ms)

$

From design pattern point of view, class Foo is highly dependent to class Bar. Refactoring can use dependency injection pattern. For example: simple change to class Foo, by require 1 argument, which is Bar itself or instance of Bar. This change make the code easier to test.

class Foo {
  // Now constructor need 1 argument
  constructor(Bar) {
    this.bar = new Bar();
  }

  omg() {
    this.bar.omg();
  }
}

Hope this helps.


问:
How inflate a Linear layout with custom view by databinding
I just want to make a map with some Vertical LinearLayout that in each of that have a Horizontal LinearLayout and in each of this layout wanna inflate a view that is like below code :

each_cell.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<layout xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:android="http://schemas.android.com/apk/res/android">
<data>
    <variable name="live" type="Integer" />
    <variable name="i" type="Integer" />
    <variable name="j" type="Integer" />
</data>

<ImageView
    android:id="@+id/itemView"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textSize="30sp"
    app:setI="@{i}"
    app:setJ="@{j}"/>
</code>```

each_row.xml :

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/row_instance"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginBottom="2dp"
    android:orientation="horizontal">

</LinearLayout>
</code>```

that I will add this Horizontal LL view to my main Vertical LL and the map will created

and kotlin code :

```<code>            val cell = DataBindingUtil.inflate<EachCellBinding>(inflater , R.layout.each_cell , HorizontalLinearLayout.row_instance , true   )
</code>```

but the error is :

```<code>Required DataBindingComponent is null in class EachCellBindingImpl. A BindingAdapter in com.example.gameoflife.SartFragment.StartFragment is not static and requires an object to use, retrieved from the DataBindingComponent. If you don't use an inflation method taking a DataBindingComponent, use DataBindingUtil.setDefaultComponent or make all BindingAdapter methods static.
</code>```

答: As shown in the error you have declared the binding adapter methods in com.example.gameoflife.SartFragment.StartFragment. Declaring it inside a class makes it non-static. But the binding adapter methods should be always static. So take the methods from inside the class and put it outside the class and it will become static and your error will be resolved.

Body:
I just want to make a map with some Vertical LinearLayout that in each of that have a Horizontal LinearLayout and in each of this layout wanna inflate a view that is like below code :

each_cell.xml

<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:android="http://schemas.android.com/apk/res/android">
<data>
    <variable name="live" type="Integer" />
    <variable name="i" type="Integer" />
    <variable name="j" type="Integer" />
</data>

<ImageView
    android:id="@+id/itemView"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textSize="30sp"
    app:setI="@{i}"
    app:setJ="@{j}"/>

each_row.xml :

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/row_instance"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginBottom="2dp"
    android:orientation="horizontal">

</LinearLayout>

that I will add this Horizontal LL view to my main Vertical LL and the map will created

and kotlin code :

            val cell = DataBindingUtil.inflate<EachCellBinding>(inflater , R.layout.each_cell , HorizontalLinearLayout.row_instance , true   )

but the error is :

Required DataBindingComponent is null in class EachCellBindingImpl. A BindingAdapter in com.example.gameoflife.SartFragment.StartFragment is not static and requires an object to use, retrieved from the DataBindingComponent. If you don't use an inflation method taking a DataBindingComponent, use DataBindingUtil.setDefaultComponent or make all BindingAdapter methods static.


问:
Finding matching keys in two large dictionaries and doing it fast
I am trying to find corresponding keys in two different dictionaries.  Each has about 600k entries.

Say for example:

```<code>    myRDP = { 'Actinobacter': 'GATCGA...TCA', 'subtilus sp.': 'ATCGATT...ACT' }
    myNames = { 'Actinobacter': '8924342' }
</code>```

I want to print out the value for Actinobacter (8924342) since it matches a value in myRDP.

The following code works, but is very slow:

```<code>    for key in myRDP:
        for jey in myNames:
            if key == jey:
                print key, myNames[key]
</code>```

I've tried the following but it always results in a KeyError:

```<code>    for key in myRDP:
        print myNames[key]
</code>```

Is there perhaps a function implemented in C for doing this?  I've googled around but nothing seems to work.

答:
You can simply write this code and it will save the common key in a list.
common = [i for i in myRDP.keys() if i in myNames.keys()]

Body:
I am trying to find corresponding keys in two different dictionaries.  Each has about 600k entries.

Say for example:

    myRDP = { 'Actinobacter': 'GATCGA...TCA', 'subtilus sp.': 'ATCGATT...ACT' }
    myNames = { 'Actinobacter': '8924342' }

I want to print out the value for Actinobacter (8924342) since it matches a value in myRDP.

The following code works, but is very slow:

    for key in myRDP:
        for jey in myNames:
            if key == jey:
                print key, myNames[key]

I've tried the following but it always results in a KeyError:

    for key in myRDP:
        print myNames[key]

Is there perhaps a function implemented in C for doing this?  I've googled around but nothing seems to work.


问:
Violation of PRIMARY KEY constraint PK_Casting
I'm trying to add a new data base through a script, but getting some errors, already tried to let out the double fields, but that didn't work for me.

```<code>USE master
GO

IF EXISTS (SELECT * FROM sysdatabases WHERE NAME = 'MijnFilms')
BEGIN
    ALTER DATABASE MijnFilms SET SINGLE_USER WITH ROLLBACK IMMEDIATE
    DROP DATABASE MijnFilms
END
GO

-- Creatie databank Bibliotheek
CREATE DATABASE MijnFilms
GO

USE MijnFilms
GO

--Creatie tabel AUTEUR
CREATE TABLE ACTEUR
(
    Acteur_id int NOT NULL,
    ActeurNaam nvarchar(40),
    CONSTRAINT PK_Acteur PRIMARY KEY(acteur_id)
)
GO

--Creatie tabel CATEGORIE
CREATE TABLE CASTING
(
    Film_id int NOT NULL,
    Acteur_id int NOT NULL,
    CONSTRAINT PK_Casting PRIMARY KEY(Film_id),
    CONSTRAINT FK1_Casting FOREIGN KEY(Acteur_id) REFERENCES Acteur(acteur_id)
)
GO

--Creatie tabel BOEKEN
CREATE TABLE FILM
(
    Film_id int NOT NULL,
    Titel nvarchar(40),
    Jaar smallint,
    Score int,
    Stemmen int,
    CONSTRAINT FK1_Film FOREIGN KEY(Film_id) REFERENCES Casting(film_id),
)
GO

--Opvullen van de tabellen met testdata
INSERT INTO ACTEUR(Acteur_id, ActeurNaam) VALUES (1, 'Tom Hanks')
INSERT INTO ACTEUR(Acteur_id, ActeurNaam) VALUES (2, 'Helen Hunt')
INSERT INTO ACTEUR(Acteur_id, ActeurNaam) VALUES (3, 'Catherine Zeta Jones')
GO

INSERT INTO CASTING (Film_id, Acteur_id) VALUES (1, 1)
INSERT INTO CASTING (Film_id, Acteur_id) VALUES (1, 2)
INSERT INTO CASTING (Film_id, Acteur_id) VALUES (2, 1)
INSERT INTO CASTING (Film_id, Acteur_id) VALUES (2, 3)
GO

INSERT INTO FILM(Film_id, Titel, jaar, Score, Stemmen) VALUES (1, 'Cast Away', 2000, 75,1)
INSERT INTO FILM(Film_id, Titel, jaar, Score, Stemmen) VALUES (2, 'The Terminal', 2004, 62,1)
GO
</code>```

Right now, I get an error:

Msg 2627, Level 14, State 1, Line 60

  Violation of PRIMARY KEY constraint 'PK_Casting'. Cannot insert duplicate key in object 'dbo.CASTING'. The duplicate key value is (2).

答:
You are creating the table with constraints

```<code>CREATE TABLE CASTING
(
    Film_id int NOT NULL,
    Acteur_id int NOT NULL,
    CONSTRAINT PK_Casting PRIMARY KEY(Film_id),
    CONSTRAINT FK1_Casting FOREIGN KEY(Acteur_id) REFERENCES Acteur(acteur_id)
)
GO
</code>```

and then you are inserting duplicated records in the table

```<code>INSERT INTO CASTING (Film_id, Acteur_id) VALUES (1, 1)
INSERT INTO CASTING (Film_id, Acteur_id) VALUES (1, 2)
INSERT INTO CASTING (Film_id, Acteur_id) VALUES (2, 1)
INSERT INTO CASTING (Film_id, Acteur_id) VALUES (2, 3)
</code>```

You need to remove the constraint or you need to make COMPOSITE KEY by creating the key on FILM_ID and ACTEUR_ID

Body:
I'm trying to add a new data base through a script, but getting some errors, already tried to let out the double fields, but that didn't work for me.

USE master
GO

IF EXISTS (SELECT * FROM sysdatabases WHERE NAME = 'MijnFilms')
BEGIN
    ALTER DATABASE MijnFilms SET SINGLE_USER WITH ROLLBACK IMMEDIATE
    DROP DATABASE MijnFilms
END
GO

-- Creatie databank Bibliotheek
CREATE DATABASE MijnFilms
GO

USE MijnFilms
GO

--Creatie tabel AUTEUR
CREATE TABLE ACTEUR
(
    Acteur_id int NOT NULL,
    ActeurNaam nvarchar(40),
    CONSTRAINT PK_Acteur PRIMARY KEY(acteur_id)
)
GO

--Creatie tabel CATEGORIE
CREATE TABLE CASTING
(
    Film_id int NOT NULL,
    Acteur_id int NOT NULL,
    CONSTRAINT PK_Casting PRIMARY KEY(Film_id),
    CONSTRAINT FK1_Casting FOREIGN KEY(Acteur_id) REFERENCES Acteur(acteur_id)
)
GO

--Creatie tabel BOEKEN
CREATE TABLE FILM
(
    Film_id int NOT NULL,
    Titel nvarchar(40),
    Jaar smallint,
    Score int,
    Stemmen int,
    CONSTRAINT FK1_Film FOREIGN KEY(Film_id) REFERENCES Casting(film_id),
)
GO

--Opvullen van de tabellen met testdata
INSERT INTO ACTEUR(Acteur_id, ActeurNaam) VALUES (1, 'Tom Hanks')
INSERT INTO ACTEUR(Acteur_id, ActeurNaam) VALUES (2, 'Helen Hunt')
INSERT INTO ACTEUR(Acteur_id, ActeurNaam) VALUES (3, 'Catherine Zeta Jones')
GO

INSERT INTO CASTING (Film_id, Acteur_id) VALUES (1, 1)
INSERT INTO CASTING (Film_id, Acteur_id) VALUES (1, 2)
INSERT INTO CASTING (Film_id, Acteur_id) VALUES (2, 1)
INSERT INTO CASTING (Film_id, Acteur_id) VALUES (2, 3)
GO

INSERT INTO FILM(Film_id, Titel, jaar, Score, Stemmen) VALUES (1, 'Cast Away', 2000, 75,1)
INSERT INTO FILM(Film_id, Titel, jaar, Score, Stemmen) VALUES (2, 'The Terminal', 2004, 62,1)
GO

Right now, I get an error:

Msg 2627, Level 14, State 1, Line 60

  Violation of PRIMARY KEY constraint 'PK_Casting'. Cannot insert duplicate key in object 'dbo.CASTING'. The duplicate key value is (2).

Body:
You are creating the table with constraints

CREATE TABLE CASTING
(
    Film_id int NOT NULL,
    Acteur_id int NOT NULL,
    CONSTRAINT PK_Casting PRIMARY KEY(Film_id),
    CONSTRAINT FK1_Casting FOREIGN KEY(Acteur_id) REFERENCES Acteur(acteur_id)
)
GO

and then you are inserting duplicated records in the table

INSERT INTO CASTING (Film_id, Acteur_id) VALUES (1, 1)
INSERT INTO CASTING (Film_id, Acteur_id) VALUES (1, 2)
INSERT INTO CASTING (Film_id, Acteur_id) VALUES (2, 1)
INSERT INTO CASTING (Film_id, Acteur_id) VALUES (2, 3)

You need to remove the constraint or you need to make COMPOSITE KEY by creating the key on FILM_ID and ACTEUR_ID


问:
How to cache API calls on dev in Angular?
Angular uses webpack dev server as a proxy to an actual API. API is sometimes slow. It makes debugging integration and user tests slow. How to introduce a cache for API calls that works only while development and stores cache so that it is used also after application reload?</p>

答:
There are several ways to do it. It is possible to use a proxy with caching functionality like for example Squid.

Another solution is to use webpack-dev-server that is part of Angular to add cache functionality. Unfortunately, the webpack-dev-server is poorly documented and it's almost impossible to add such functionality.

But there is a way to accomplish it. In your application code you need to modify your get handler:

```<code>devCacheGet = true && !environment.production;
get(url: string, ...) { //generic get handler in your service handling all get calls
  if (devCacheGet) {
     if (localStorage.getItem("devCache" + url)) {
         return localStorage.getItem(JSON.parse("devCache" + url));
     }
  }

  result = callAPI(...);
  if (devCacheGet) {
      localStorage.setItem("devCache" + url, JSON.stringify(result));
  }
  return result;
}
</code>```

The code has to be modified to handle Observables if you use if and adjusted to your code base. But more or less it is the idea.

You can enable cache with true/false in devCacheGet. Second part of the condition blocks the devCache to be enabled in production stage.

The cons of this solution is that you need to remember is on (i put a warning in console to remember).

Pros is that when working on near integration parts you work on real data from API. So it makes debugging faster. If you make 5 calls each for 2 seconds = 10 seconds. With this solution the time for load data drops to 5x20ms = 100ms. You save 9,9 second on each page load.

It won't replace unit tests and integration tests, but it is very helpful in specific set of situations.

Body:
There are several ways to do it. It is possible to use a proxy with caching functionality like for example Squid.

Another solution is to use webpack-dev-server that is part of Angular to add cache functionality. Unfortunately, the webpack-dev-server is poorly documented and it's almost impossible to add such functionality.

But there is a way to accomplish it. In your application code you need to modify your get handler:

devCacheGet = true && !environment.production;
get(url: string, ...) { //generic get handler in your service handling all get calls
  if (devCacheGet) {
     if (localStorage.getItem("devCache" + url)) {
         return localStorage.getItem(JSON.parse("devCache" + url));
     }
  }

  result = callAPI(...);
  if (devCacheGet) {
      localStorage.setItem("devCache" + url, JSON.stringify(result));
  }
  return result;
}

The code has to be modified to handle Observables if you use if and adjusted to your code base. But more or less it is the idea.

You can enable cache with true/false in devCacheGet. Second part of the condition blocks the devCache to be enabled in production stage.

The cons of this solution is that you need to remember is on (i put a warning in console to remember).

Pros is that when working on near integration parts you work on real data from API. So it makes debugging faster. If you make 5 calls each for 2 seconds = 10 seconds. With this solution the time for load data drops to 5x20ms = 100ms. You save 9,9 second on each page load.

It won't replace unit tests and integration tests, but it is very helpful in specific set of situations.


问:
How to integrate recoil library with react-native?
I'm trying the new state management library from facebook recoil, I tried the Getting started example on a reactjs project and it worked perfectly. After that I tried recoil on a react-native project but I got an error:

Here's the code I've tried:

App.js

```<code>import React from 'react';
import {RecoilRoot} from 'recoil';
import RecoilTest from './RecoilTest';

const App = () => {
  return (
    <RecoilRoot>
      <RecoilTest />
    </RecoilRoot>
  );
};

export default App;
</code>```

RecoilTest.js

```<code>import React from 'react';
import {useRecoilState} from 'recoil';
import {View, Text} from 'react-native';
import {textState} from './Atoms';

const RecoilTest = () => {
  const [text, setText] = useRecoilState(textState);
  return (
    <View>
      <Text>{text}</Text>
    </View>
  );
};

export default RecoilTest;
</code>```

Atoms.js

```<code>import {atom} from 'recoil';

export const textState = atom({
  key: 'textState',
  default: 'initial value',
});
</code>```

答: Recoil don't has a fully support to react native yet</p>

Body:
I'm trying the new state management library from facebook recoil, I tried the Getting started example on a reactjs project and it worked perfectly. After that I tried recoil on a react-native project but I got an error:

Here's the code I've tried:

App.js

import React from 'react';
import {RecoilRoot} from 'recoil';
import RecoilTest from './RecoilTest';

const App = () => {
  return (
    <RecoilRoot>
      <RecoilTest />
    </RecoilRoot>
  );
};

export default App;

RecoilTest.js

import React from 'react';
import {useRecoilState} from 'recoil';
import {View, Text} from 'react-native';
import {textState} from './Atoms';

const RecoilTest = () => {
  const [text, setText] = useRecoilState(textState);
  return (
    <View>
      <Text>{text}</Text>
    </View>
  );
};

export default RecoilTest;

Atoms.js

import {atom} from 'recoil';

export const textState = atom({
  key: 'textState',
  default: 'initial value',
});


问:
What's the best way to find the closest matching type to an existing type?
I've got a registry of classes and types in Python 2.5, like so:

```<code>class ClassA(object):
    pass

class ClassB(ClassA):
    pass

MY_TYPES = {
    basestring : 'A string',
    int : 'An integer',
    ClassA : 'This is ClassA or a subclass',
}
</code>```

I'd like to be able to pass types to a function, and have it look up the closest matching type in the hierarchy.  So, looking up str would return "A string" and looking up ClassB would return "This is ClassA or a subclass" The problem is, I don't know how to find the superclass (or, rather, trace the MRO chain) of a type object.

What's the best way of handling this?

答:
(st for cls, st in MY_TYPES.iteritems() if cls in getmro(ClassB))

The simpler way to write that would be:

```<code>(st for cls, st in MY_TYPES.iteritems() if issubclass(ClassB, cls))
</code>```

However this does not find the “nearest” match; if ‘object’ were in the lookup, it could match everything! If you had things that were subclasses of other things in the lookup, or you wanted to support multiple inheritance, you'd have to pick out the one that was the first in MRO:

```<code>for cls in inspect.getmro(ClassB):
    if cls in MY_TYPES:
        print MY_TYPES[cls]
        break
else:
    print 'Dunno what it is'
</code>```

Anyway... I would generally regard type lookups as a little bit of a code smell, is there no nicer way to do what you want?

OwnerDisplayName: Chris B.

ContentLicense: CC BY-SA 2.5

Body:
I've got a registry of classes and types in Python 2.5, like so:

class ClassA(object):
    pass

class ClassB(ClassA):
    pass

MY_TYPES = {
    basestring : 'A string',
    int : 'An integer',
    ClassA : 'This is ClassA or a subclass',
}

I'd like to be able to pass types to a function, and have it look up the closest matching type in the hierarchy.  So, looking up str would return "A string" and looking up ClassB would return "This is ClassA or a subclass" The problem is, I don't know how to find the superclass (or, rather, trace the MRO chain) of a type object.

What's the best way of handling this?

Body:
(st for cls, st in MY_TYPES.iteritems() if cls in getmro(ClassB))

The simpler way to write that would be:

(st for cls, st in MY_TYPES.iteritems() if issubclass(ClassB, cls))

However this does not find the “nearest” match; if ‘object’ were in the lookup, it could match everything! If you had things that were subclasses of other things in the lookup, or you wanted to support multiple inheritance, you'd have to pick out the one that was the first in MRO:

for cls in inspect.getmro(ClassB):
    if cls in MY_TYPES:
        print MY_TYPES[cls]
        break
else:
    print 'Dunno what it is'

Anyway... I would generally regard type lookups as a little bit of a code smell, is there no nicer way to do what you want?

OwnerDisplayName: bobince


问:
Why doesn't this work (wxpython/color dialog)
```<code>class iFrame(wx.Frame):
    def __init__(blah blah blah):
        wx.Frame.__init.__(blah blah blah)

        self.panel = wx.Panel(self, -1)
        self.panel.SetBackgroundColour((I put a random RGB here for test purposes))

        c_color = wx.Button(self.panel, -1, 'Press To Change Color')
        c_color.Bind(wx.EVT_BUTTON, self.OnCC)

    def OnCC(self, evt):
        dlg = wx.ColourDialog().SetChooseFull(1)
        if dlg.ShowModal() == wx.ID_OK:
            data = dlg.GetColourData()
            color = data.Colour
            print (color) # I did this just to test it was returning a RGB
            self.panel.SetBackgroundColour(color)
        dlg.Destroy()
</code>```

What I've tried to do was link a button to a color dialog, store the RGB in a variable and use it to set the panel's background color...I've tested almost all of this, I've inserted the returned RGB directly into the self.panel itself and it works, so why doesn't it work when I use it within this method

答:
The line dlg = wx.ColourDialog().SetChooseFull(1) seems like a bug -- isn't SetChooseFull a method on wx.ColourData?

I made a few changes to get it working and commented the code to illustrate:

```<code>def OnCC(self, evt):
    data = wx.ColourData()
    data.SetChooseFull(True)

    # set the first custom color (index 0)
    data.SetCustomColour(0, (255, 170, 128))
    # set indexes 1-N here if you like.

    # set the default color in the chooser
    data.SetColour(wx.Colour(128, 255, 170))

    # construct the chooser
    dlg = wx.ColourDialog(self, data)

    if dlg.ShowModal() == wx.ID_OK:
        # set the panel background color
        color = dlg.GetColourData().Colour
        self.panel.SetBackgroundColour(color)
    dlg.Destroy()
</code>```

The data.SetCustomColor(index, color) populates the N custom colors in the dialog. I've circled the one at index 0 below:

Body:
class iFrame(wx.Frame):
    def __init__(blah blah blah):
        wx.Frame.__init.__(blah blah blah)

        self.panel = wx.Panel(self, -1)
        self.panel.SetBackgroundColour((I put a random RGB here for test purposes))

        c_color = wx.Button(self.panel, -1, 'Press To Change Color')
        c_color.Bind(wx.EVT_BUTTON, self.OnCC)

    def OnCC(self, evt):
        dlg = wx.ColourDialog().SetChooseFull(1)
        if dlg.ShowModal() == wx.ID_OK:
            data = dlg.GetColourData()
            color = data.Colour
            print (color) # I did this just to test it was returning a RGB
            self.panel.SetBackgroundColour(color)
        dlg.Destroy()

What I've tried to do was link a button to a color dialog, store the RGB in a variable and use it to set the panel's background color...I've tested almost all of this, I've inserted the returned RGB directly into the self.panel itself and it works, so why doesn't it work when I use it within this method

Body:
The line dlg = wx.ColourDialog().SetChooseFull(1) seems like a bug -- isn't SetChooseFull a method on wx.ColourData?

I made a few changes to get it working and commented the code to illustrate:

def OnCC(self, evt):
    data = wx.ColourData()
    data.SetChooseFull(True)

    # set the first custom color (index 0)
    data.SetCustomColour(0, (255, 170, 128))
    # set indexes 1-N here if you like.

    # set the default color in the chooser
    data.SetColour(wx.Colour(128, 255, 170))

    # construct the chooser
    dlg = wx.ColourDialog(self, data)

    if dlg.ShowModal() == wx.ID_OK:
        # set the panel background color
        color = dlg.GetColourData().Colour
        self.panel.SetBackgroundColour(color)
    dlg.Destroy()

The data.SetCustomColor(index, color) populates the N custom colors in the dialog. I've circled the one at index 0 below:


问:
How to add the ImageMagick install to my path on Ubuntu
I have had been on a roller coaster trying to get ImageMagick to work on my Ubuntu slice. I Whenever I try to upload an image I get the following error: /tmp/stream.1170.0 is not recognized by the 'identify' command.

If I type 'which identify' I get: /usr/local/bin/identify

If I run '/usr/local/bin/identify' or just 'identify', I get the following error: /usr/local/bin/identify: error while loading shared libraries: libMagickCore.so.3: cannot open shared object file: No such file or directory

If I run '/usr/bin/identify', ImageMagick is run just fine. How can I set my path to where when Paperclip runs the identify command, it points to /usr/bin/identify? Thanks.

p.s. I have tried adding this to paperclip.rb: Paperclip.options[:command_path] = '/usr/bin' and Paperclip.options[:command_path] = '/usr/local/bin'

答: You can also install it using Software Manager


问:
Input is available in VS Code?
I heard that it is not possible to give input to the python program In VS Code and for this issue We should open the python file on Command Prompt.

I wonder is it really true? Because Sometimes I write code on VS Code it asks for Input but sometimes It doesn't show anything. So what is going on?

答:
The official python extension of VSCode provides Run and Debugging, almost like a IDE. It's impossible not to support input.

As for the source of your misunderstanding, it may be an extension like Code Runner, which does not support input, just quickly help you run the code and display the output.

Title: Input is available in VS Code?


问:
How to pass data/Images from one page to another in Bottom Navigation Bar
I wanted to send Data/images from one page to another. In the Homepage when I tap on the add Icon button image should be passed to the Cart page and if the icon is tapped again image is removed from the Cart page. But, the cart page should be accessed from bottom navigation bar.
but it is showing an error called 1 positional argument(s) expected, but 0 found.
Try adding the missing arguments.. when it calls the cart page.

HomePage.dart file

```<code>void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blueGrey,
      ),
      home: NavBar(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);
  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  List<Dish> _dishes = List<Dish>();

  List<Dish> _cartList = List<Dish>();

  @override
  void initState() {
    super.initState();
    _populateDishes();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
        actions: <Widget>[
          Padding(
            padding: const EdgeInsets.only(right: 16.0, top: 8.0),
            child: GestureDetector(
              child: Stack(
                alignment: Alignment.topCenter,
                children: <Widget>[
                  Icon(
                    Icons.shopping_cart,
                    size: 36.0,
                  ),
                  if (_cartList.length > 0)
                    Padding(
                      padding: const EdgeInsets.only(left: 2.0),
                      child: CircleAvatar(
                        radius: 8.0,
                        backgroundColor: Colors.red,
                        foregroundColor: Colors.white,
                        child: Text(
                          _cartList.length.toString(),
                          style: TextStyle(
                            fontWeight: FontWeight.bold,
                            fontSize: 12.0,
                          ),
                        ),
                      ),
                    ),
                ],
              ),
              onTap: () {
                if (_cartList.isNotEmpty)
                  Navigator.of(context).push(
                    MaterialPageRoute(
                      builder: (context) => Cart(_cartList),
                    ),
                  );
              },
            ),
          )
        ],
      ),
      body: _buildGridView(),
    );
  }

  ListView _buildListView() {
    return ListView.builder(
      itemCount: _dishes.length,
      itemBuilder: (context, index) {
        var item = _dishes[index];
        return Padding(
          padding: const EdgeInsets.symmetric(
            horizontal: 8.0,
            vertical: 2.0,
          ),
          child: Card(
            elevation: 4.0,
            child: ListTile(
              leading: Icon(
                item.icon,
                color: item.color,
              ),
              title: Text(item.name),
              trailing: GestureDetector(
                child: (!_cartList.contains(item))
                    ? Icon(
                        Icons.add_circle,
                        color: Colors.green,
                      )
                    : Icon(
                        Icons.remove_circle,
                        color: Colors.red,
                      ),
                onTap: () {
                  setState(() {
                    if (!_cartList.contains(item))
                      _cartList.add(item);
                    else
                      _cartList.remove(item);
                  });
                },
              ),
            ),
          ),
        );
      },
    );
  }

  GridView _buildGridView() {
    return GridView.builder(
        padding: const EdgeInsets.all(4.0),
        gridDelegate:
            SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: 2),
        itemCount: _dishes.length,
        itemBuilder: (context, index) {
          var item = _dishes[index];
          return Card(
              elevation: 4.0,
              child: Stack(
                fit: StackFit.loose,
                alignment: Alignment.center,
                children: <Widget>[
                  Column(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: <Widget>[
                      Icon(
                        item.icon,
                        color: (_cartList.contains(item))
                            ? Colors.grey
                            : item.color,
                        size: 100.0,
                      ),
                      Text(
                        item.name,
                        textAlign: TextAlign.center,
                        style: Theme.of(context).textTheme.subhead,
                      )
                    ],
                  ),
                  Padding(
                    padding: const EdgeInsets.only(
                      right: 8.0,
                      bottom: 8.0,
                    ),
                    child: Align(
                      alignment: Alignment.bottomRight,
                      child: GestureDetector(
                        child: (!_cartList.contains(item))
                            ? Icon(
                                Icons.add_circle,
                                color: Colors.green,
                              )
                            : Icon(
                                Icons.remove_circle,
                                color: Colors.red,
                              ),
                        onTap: () {
                          setState(() {
                            if (!_cartList.contains(item))
                              _cartList.add(item);
                            else
                              _cartList.remove(item);
                          });
                        },
                      ),
                    ),
                  ),
                ],
              ));
        });
  }

  void _populateDishes() {
    var list = <Dish>[
      Dish(
        name: 'Chicken Zinger',
        icon: Icons.fastfood,
        color: Colors.amber,
      ),
      Dish(
        name: 'Chicken Zinger without chicken',
        icon: Icons.print,
        color: Colors.deepOrange,
      ),
      Dish(
        name: 'Rice',
        icon: Icons.child_care,
        color: Colors.brown,
      ),
      Dish(
        name: 'Beef burger without beef',
        icon: Icons.whatshot,
        color: Colors.green,
      ),
      Dish(
        name: 'Laptop without OS',
        icon: Icons.laptop,
        color: Colors.purple,
      ),
      Dish(
        name: 'Mac wihout macOS',
        icon: Icons.laptop_mac,
        color: Colors.blueGrey,
      ),
    ];

    setState(() {
      _dishes = list;
    });
  }
}

</code>```

Cart.dart file

```<code>import 'package:flutter/material.dart';
import 'dish_object.dart';

class Cart extends StatefulWidget {
  final List<Dish> _cart;

  Cart(this._cart);

  @override
  _CartState createState() => _CartState(this._cart);
}

class _CartState extends State<Cart> {
  _CartState(this._cart);

  List<Dish> _cart;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Cart'),
      ),
      body: ListView.builder(
        itemCount: _cart.length,
        itemBuilder: (context, index) {
          var item = _cart[index];
          return Padding(
            padding: const EdgeInsets.symmetric(horizontal: 8.0, vertical: 2.0),
            child: Card(
              elevation: 4.0,
              child: ListTile(
                leading: Icon(
                  item.icon,
                  color: item.color,
                ),
                title: Text(item.name),
                trailing: GestureDetector(
                  child: Icon(
                    Icons.remove_circle,
                    color: Colors.red,
                  ),
                  onTap: () {
                    setState(() {
                      _cart.remove(item);
                    });
                  },
                ),
              ),
            ),
          );
        },
      ),
    );
  }
}
</code>```

NavBar.dart file

```<code>import 'package:flutter/material.dart';
import 'package:sharewallpaper/cart.dart';
import 'package:sharewallpaper/main.dart';

class NavBar extends StatefulWidget {
  @override
  _NavBarState createState() => _NavBarState();
}

class _NavBarState extends State<NavBar> {

  int _currentIndex = 0;
  final List<Widget> _children = [
    MyHomePage(),
    Cart(), ** This line is throwing an error **
  ];

  void onTappedBar(int index) {
    setState(() {
      _currentIndex = index;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: _children[_currentIndex],
      bottomNavigationBar: BottomNavigationBar(
        onTap: onTappedBar,
        currentIndex: _currentIndex,
        items: [
          BottomNavigationBarItem(icon: Icon(Icons.home), title: Text('Home')),
          BottomNavigationBarItem(
              icon: Icon(Icons.bookmark), title: Text('BookMark')),
        ],
      ),
    );
  }
}
</code>```

答:
Yep, it will throw an error because the constructor of the Cart class is expecting one parameter to be passed in. You could use a named constructor instead like this:

```<code>class Cart extends StatefulWidget {
  final List<Dish> _cart;

  Cart(this._cart);
</code>```

That way, you can call it like so:

```<code>Cart(cart: _cartList),
</code>```

But if you actually need the cart list, I would recommend that you write a provider to keep track of the cart data across screens.

Body:
I wanted to send Data/images from one page to another. In the Homepage when I tap on the add Icon button image should be passed to the Cart page and if the icon is tapped again image is removed from the Cart page. But, the cart page should be accessed from bottom navigation bar.
but it is showing an error called 1 positional argument(s) expected, but 0 found.
Try adding the missing arguments.. when it calls the cart page.

HomePage.dart file

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blueGrey,
      ),
      home: NavBar(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);
  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  List<Dish> _dishes = List<Dish>();

  List<Dish> _cartList = List<Dish>();

  @override
  void initState() {
    super.initState();
    _populateDishes();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
        actions: <Widget>[
          Padding(
            padding: const EdgeInsets.only(right: 16.0, top: 8.0),
            child: GestureDetector(
              child: Stack(
                alignment: Alignment.topCenter,
                children: <Widget>[
                  Icon(
                    Icons.shopping_cart,
                    size: 36.0,
                  ),
                  if (_cartList.length > 0)
                    Padding(
                      padding: const EdgeInsets.only(left: 2.0),
                      child: CircleAvatar(
                        radius: 8.0,
                        backgroundColor: Colors.red,
                        foregroundColor: Colors.white,
                        child: Text(
                          _cartList.length.toString(),
                          style: TextStyle(
                            fontWeight: FontWeight.bold,
                            fontSize: 12.0,
                          ),
                        ),
                      ),
                    ),
                ],
              ),
              onTap: () {
                if (_cartList.isNotEmpty)
                  Navigator.of(context).push(
                    MaterialPageRoute(
                      builder: (context) => Cart(_cartList),
                    ),
                  );
              },
            ),
          )
        ],
      ),
      body: _buildGridView(),
    );
  }

  ListView _buildListView() {
    return ListView.builder(
      itemCount: _dishes.length,
      itemBuilder: (context, index) {
        var item = _dishes[index];
        return Padding(
          padding: const EdgeInsets.symmetric(
            horizontal: 8.0,
            vertical: 2.0,
          ),
          child: Card(
            elevation: 4.0,
            child: ListTile(
              leading: Icon(
                item.icon,
                color: item.color,
              ),
              title: Text(item.name),
              trailing: GestureDetector(
                child: (!_cartList.contains(item))
                    ? Icon(
                        Icons.add_circle,
                        color: Colors.green,
                      )
                    : Icon(
                        Icons.remove_circle,
                        color: Colors.red,
                      ),
                onTap: () {
                  setState(() {
                    if (!_cartList.contains(item))
                      _cartList.add(item);
                    else
                      _cartList.remove(item);
                  });
                },
              ),
            ),
          ),
        );
      },
    );
  }

  GridView _buildGridView() {
    return GridView.builder(
        padding: const EdgeInsets.all(4.0),
        gridDelegate:
            SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: 2),
        itemCount: _dishes.length,
        itemBuilder: (context, index) {
          var item = _dishes[index];
          return Card(
              elevation: 4.0,
              child: Stack(
                fit: StackFit.loose,
                alignment: Alignment.center,
                children: <Widget>[
                  Column(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: <Widget>[
                      Icon(
                        item.icon,
                        color: (_cartList.contains(item))
                            ? Colors.grey
                            : item.color,
                        size: 100.0,
                      ),
                      Text(
                        item.name,
                        textAlign: TextAlign.center,
                        style: Theme.of(context).textTheme.subhead,
                      )
                    ],
                  ),
                  Padding(
                    padding: const EdgeInsets.only(
                      right: 8.0,
                      bottom: 8.0,
                    ),
                    child: Align(
                      alignment: Alignment.bottomRight,
                      child: GestureDetector(
                        child: (!_cartList.contains(item))
                            ? Icon(
                                Icons.add_circle,
                                color: Colors.green,
                              )
                            : Icon(
                                Icons.remove_circle,
                                color: Colors.red,
                              ),
                        onTap: () {
                          setState(() {
                            if (!_cartList.contains(item))
                              _cartList.add(item);
                            else
                              _cartList.remove(item);
                          });
                        },
                      ),
                    ),
                  ),
                ],
              ));
        });
  }

  void _populateDishes() {
    var list = <Dish>[
      Dish(
        name: 'Chicken Zinger',
        icon: Icons.fastfood,
        color: Colors.amber,
      ),
      Dish(
        name: 'Chicken Zinger without chicken',
        icon: Icons.print,
        color: Colors.deepOrange,
      ),
      Dish(
        name: 'Rice',
        icon: Icons.child_care,
        color: Colors.brown,
      ),
      Dish(
        name: 'Beef burger without beef',
        icon: Icons.whatshot,
        color: Colors.green,
      ),
      Dish(
        name: 'Laptop without OS',
        icon: Icons.laptop,
        color: Colors.purple,
      ),
      Dish(
        name: 'Mac wihout macOS',
        icon: Icons.laptop_mac,
        color: Colors.blueGrey,
      ),
    ];

    setState(() {
      _dishes = list;
    });
  }
}

Cart.dart file

import 'package:flutter/material.dart';
import 'dish_object.dart';

class Cart extends StatefulWidget {
  final List<Dish> _cart;

  Cart(this._cart);

  @override
  _CartState createState() => _CartState(this._cart);
}

class _CartState extends State<Cart> {
  _CartState(this._cart);

  List<Dish> _cart;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Cart'),
      ),
      body: ListView.builder(
        itemCount: _cart.length,
        itemBuilder: (context, index) {
          var item = _cart[index];
          return Padding(
            padding: const EdgeInsets.symmetric(horizontal: 8.0, vertical: 2.0),
            child: Card(
              elevation: 4.0,
              child: ListTile(
                leading: Icon(
                  item.icon,
                  color: item.color,
                ),
                title: Text(item.name),
                trailing: GestureDetector(
                  child: Icon(
                    Icons.remove_circle,
                    color: Colors.red,
                  ),
                  onTap: () {
                    setState(() {
                      _cart.remove(item);
                    });
                  },
                ),
              ),
            ),
          );
        },
      ),
    );
  }
}

NavBar.dart file

import 'package:flutter/material.dart';
import 'package:sharewallpaper/cart.dart';
import 'package:sharewallpaper/main.dart';

class NavBar extends StatefulWidget {
  @override
  _NavBarState createState() => _NavBarState();
}

class _NavBarState extends State<NavBar> {

  int _currentIndex = 0;
  final List<Widget> _children = [
    MyHomePage(),
    Cart(), ** This line is throwing an error **
  ];

  void onTappedBar(int index) {
    setState(() {
      _currentIndex = index;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: _children[_currentIndex],
      bottomNavigationBar: BottomNavigationBar(
        onTap: onTappedBar,
        currentIndex: _currentIndex,
        items: [
          BottomNavigationBarItem(icon: Icon(Icons.home), title: Text('Home')),
          BottomNavigationBarItem(
              icon: Icon(Icons.bookmark), title: Text('BookMark')),
        ],
      ),
    );
  }
}

Body:
Yep, it will throw an error because the constructor of the Cart class is expecting one parameter to be passed in. You could use a named constructor instead like this:

class Cart extends StatefulWidget {
  final List<Dish> _cart;

  Cart(this._cart);

That way, you can call it like so:

Cart(cart: _cartList),

But if you actually need the cart list, I would recommend that you write a provider to keep track of the cart data across screens.


问:
Testing solution from Exercism
I just installed Exercism and would like to test if I managed to complete the hello-world assignment.
I changed the hello_world.dart file in the lib folder to print the solution, but now I am struggling with running the test file.

In the guide it says to simply run

```<code>$ pub run test
</code>```

Is the $-sign meant to mean something to me? Cause all I am getting is: "'$' is not recognized as an internal or external command,operable program or batch file." I have the same issue with running "pub get" or "pub run test". (What does pub mean?)

To summarize, I ran:

```<code>exercism configure "my token"
exercism download --exercise=hello-world --track=dart
cd C:\Users\Martin\exercism\dart\hello-world
</code>```

I changed the file in C:\Users\Martin\Exercism\dart\hello-world\lib
And then I tried

```<code>$ pub run test
pub run test
pub get
</code>```

And none of these seem to do anything. So, I don't know how to test my file.

I do have flutter installed and run is fine with Android Studio, if that is relevant. It seems to me that I can choose to write the solution in both notepad++ or Android Studio.

Thanks for any help

答:
pub is package manager for dart programming language, just like npm for javascript. Since you've installed it on WINDOWS i'm guessing you used choco - package manager to install the dart-sdk. https://dart.dev/get-dart.

Once installed make sure you've set dart-sdk the path in Environment variable.

Title: Testing solution from Exercism

Body:
I just installed Exercism and would like to test if I managed to complete the hello-world assignment.
I changed the hello_world.dart file in the lib folder to print the solution, but now I am struggling with running the test file.

In the guide it says to simply run

$ pub run test

Is the $-sign meant to mean something to me? Cause all I am getting is: "'$' is not recognized as an internal or external command,operable program or batch file." I have the same issue with running "pub get" or "pub run test". (What does pub mean?)

To summarize, I ran:

exercism configure "my token"
exercism download --exercise=hello-world --track=dart
cd C:\Users\Martin\exercism\dart\hello-world

I changed the file in C:\Users\Martin\Exercism\dart\hello-world\lib
And then I tried

$ pub run test
pub run test
pub get

And none of these seem to do anything. So, I don't know how to test my file.

I do have flutter installed and run is fine with Android Studio, if that is relevant. It seems to me that I can choose to write the solution in both notepad++ or Android Studio.

Thanks for any help


问:
enumeration for reference variable in Java
I am learning reference variables. If I have two classes: let’s say one is Person and the other is Minnesotan which extends Person class. The Person class is abstract. In the Person class, there is a reference variable called Gender which can be female, male and others. How can I write the reference variable Gender which has enumeration? how the reference variable can be extended in child class? Sorry if it is duplicate question and thank you in advance for your help. </p>

```<code>public abstract class Person{
   public static Gender gender;
   class Gender{

   }
   public enum Gender{
       female,male,others;
   }
}
public class Minnesotan extends Person{
    public Minnesotan(Gender gender){
        super(gender);
    }

}
</code>```

答:
Let's start with the enumeration,

```<code>public enum Gender{
 Male,
 Female
}
</code>```

You can use references of that enumeration which will be of type Gender and can be either Male or Female like any other variables, for example,

```<code>Gender male = Gender.MALE;
if (male == Gender.MALE){
 System.out.println("Variable male has value Gender.MALE");
}else{
 System.out.println("Variable male has value Gender.FEMALE");
}
</code>```

Now the Person class,

```<code>public abstract class Person{
 public Gender gender;
}
</code>```

Static modifier is removed because each instance of Person should have each own gender.

And finally an actual implementation of Person, a Minessotan,

```<code>public class Minnesotan extends Person{
 public Minnesotan(Gender gender){
     this.gender = gender;
 }
}
</code>```

In order to create a Minnesotan, which is a Person, you must provide it's gender, which is of type Gender. That's it.

Body:
I am learning reference variables. If I have two classes: let’s say one is Person and the other is Minnesotan which extends Person class. The Person class is abstract. In the Person class, there is a reference variable called Gender which can be female, male and others. How can I write the reference variable Gender which has enumeration? how the reference variable can be extended in child class? Sorry if it is duplicate question and thank you in advance for your help.

public abstract class Person{
   public static Gender gender;
   class Gender{

   }
   public enum Gender{
       female,male,others;
   }
}
public class Minnesotan extends Person{
    public Minnesotan(Gender gender){
        super(gender);
    }

}

Body:
Let's start with the enumeration,

public enum Gender{
 Male,
 Female
}

You can use references of that enumeration which will be of type Gender and can be either Male or Female like any other variables, for example,

Gender male = Gender.MALE;
if (male == Gender.MALE){
 System.out.println("Variable male has value Gender.MALE");
}else{
 System.out.println("Variable male has value Gender.FEMALE");
}

Now the Person class,

public abstract class Person{
 public Gender gender;
}

Static modifier is removed because each instance of Person should have each own gender.

And finally an actual implementation of Person, a Minessotan,

public class Minnesotan extends Person{
 public Minnesotan(Gender gender){
     this.gender = gender;
 }
}

In order to create a Minnesotan, which is a Person, you must provide it's gender, which is of type Gender. That's it.


问:
Image should not use full-width in element
At the moment I am trying to program the wireframe I have made, but experience some problems with specially the left side of the element:

The problem is that the 200x200px image is going full width in the left column. Therefore I cannot center the image.

I can see it can be changed with overwriting the following CSS, and set the width to none;.

```<code>.cms-area img {
    width: 100%;
}
</code>```

But as I see it will break the reponsive on the images?

Can anybody help me in goal here?

See the [Testpage here][2].

The site is still using Bootstrap 3, and I do not have access to change the main CSS. Therefore I need to overwrite CSS if I need that.

Best regards

```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="wrapper">
    <!-- Section 7 -->
    <div class="section padding-twocolumn-bg">
        <div class="row">
            <div class="text-center col-md-6">
                <div class="classWithPad">
                    <p style="padding:75px;">Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</p>
                    <a><img src="https://placehold.it/200x200" class="img-responsive test"></a>
                </div>
            </div>
            <div class="text-center col-md-6">
                <div class="classWithPad">
                    <div class="row">
                        <div class="col-sm-12">
                            <h3 class="sbp-align">Headline</h3>
                            <hr>
                        </div>
                        <div class="col-sm-6">
                            <img src="https://placehold.it/250x150" style="padding:10px;">
                            <h4 class="sbp-align">Subline</h4>
                            <p class="sbp-align">Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</p>
                            <hr id="sbp-hr">
                            Read more
                        </div>
                        <div class="col-sm-6">
                            <img src="https://placehold.it/250x150" style="padding:10px;">
                            <h4 class="sbp-align">Subline</h4>
                            <p class="sbp-align">Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</p>
                            <hr id="sbp-hr">
                            Read more
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div></code>```

答:
If you make width=200px to the left column the uploaded image will always be at center and there are lots of padding you are using for centering the images, you can use various classes of bootstrap for that!

<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">

Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.

Headline

Subline

Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.

              Read more

Subline

Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.

              Read more

```

Body:
At the moment I am trying to program the wireframe I have made, but experience some problems with specially the left side of the element:

The problem is that the 200x200px image is going full width in the left column. Therefore I cannot center the image.

I can see it can be changed with overwriting the following CSS, and set the width to none;.

.cms-area img {
    width: 100%;
}

But as I see it will break the reponsive on the images?

Can anybody help me in goal here?

See the [Testpage here][2].

The site is still using Bootstrap 3, and I do not have access to change the main CSS. Therefore I need to overwrite CSS if I need that.

Best regards

Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.

Headline

Subline

Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.

                            Read more

Subline

Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.

                            Read more

Body:
If you make width=200px to the left column the uploaded image will always be at center and there are lots of padding you are using for centering the images, you can use various classes of bootstrap for that!

<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">

<div class="container-fluid">
  <!-- Section 7 -->
  <div class="section padding-two column-bg">
    <div class="row align-items-center">
      <div class="text-center col-md-6 col-12">
        <div class="classWithPad">
          <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</p>
          <a><img src="https://placehold.it/200x200" width="200px"></a>
        </div>
      </div>
      <div class="text-center col-md-6">
        <div class="classWithPad">
          <div class="row p-3">
            <div class="col-sm-12">
              <h3 class="sbp-align">Headline</h3>
              <hr>
            </div>
            <div class="col-sm-6">
              <img src="https://placehold.it/250x150" width="100%" class="pb-2">
              <h4 class="sbp-align pb-2">Subline</h4>
              <p class="sbp-align">Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</p>
              <hr id="sbp-hr">
              <a href="#">Read more</a>
            </div>
            <div class="col-sm-6">
              <img src="https://placehold.it/250x150" width="100%" class="pb-2">
              <h4 class="sbp-align">Subline</h4>
              <p class="sbp-align">Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</p>
              <hr id="sbp-hr">
              <a href="#">Read more</a>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</div>


问:
How to group similar strings together in a database in R
I have a tibble of just 1 column called 'title'.

```<code>> dat
# A tibble: 13 x 1
   title
   <chr>
 1 lymphoedema clinic
 2 zostavax shingles vaccine
 3 xray operator
 4 workplace mental health wellbeing workshop
 5 zostavax recall toolkit
 6 xray meetint
 7 workplace mental health and wellbeing
 8 lymphoedema early intervenstion
 9 lymphoedema expo
10 lymphoedema for breast care nurses
11 xray meeting and case studies
12 xray online examination
13 xray operator in service paediatric extremities
</code>```

I wish to find similar records and group them together as such (all the while keeping their indices):

```<code>> dat
# A tibble: 13 x 1
   title
   <chr>
 1 lymphoedema clinic
 8 lymphoedema early intervenstion
 9 lymphoedema expo
10 lymphoedema for breast care nurses
 2 zostavax shingles vaccine
 5 zostavax recall toolkit
 3 xray operator
 6 xray meetint
11 xray meeting and case studies
12 xray online examination
13 xray operator in service paediatric extremities
 4 workplace mental health wellbeing workshop
 7 workplace mental health and wellbeing
</code>```

I'm using the below function to find strings that are close enough to each other (cutoff = 0.75)

```<code>compareJW <- function(string1, string2, cutoff)
{
  require(RecordLinkage)
  jarowinkler(string1, string2) > cutoff
}
</code>```

I've implemented the loop below to 'send' similar records together in a new dataframe but it's not working properly, I've tried a few variations but nothing is working yet.

```<code># create new database
newDB <- data.frame(matrix(ncol = ncol(dat), nrow = 0))
colnames(newDB) <- names(dat)
newDB <- as_tibble(newDB)

for(i in 1:nrow(dat))
{
  # print(dat$title[i])

  for(j in 1:nrow(dat))
  {
    print(dat$title[i])
    print(dat$title[j])
    # score <- jarowinkler(dat$title[i], dat$title[j])

    if(dat$title[i] != dat$title[j]
       &&
       compareJW(dat$title[i], dat$title[j], 0.75))
    {
      print("if")

      # newDB <- rbind(newDB,
      #                dat$title[i],
      #                dat$title[j])
    }
    else
    {
      print("else")
      # newDB <- rbind(newDB, dat$title[i])
    }
  }
}
</code>```

(I've inserted prints in the loop 'to see what's happening')

REPRODUCIBLE DAT:

```<code>dat <-
structure(list(title = c("lymphoedema clinic", "zostavax shingles vaccine",
                         "xray operator", "workplace mental health wellbeing workshop",
                         "zostavax recall toolkit", "xray meetint", "workplace mental health and wellbeing",
                         "lymphoedema early intervenstion", "lymphoedema expo", "lymphoedema for breast care nurses",
                         "xray meeting and case studies", "xray online examination", "xray operator in service paediatric extremities"
)), row.names = c(NA, -13L), class = c("tbl_df", "tbl", "data.frame"
))
</code>```

Any suggestions please?
EDIT: I'd also like a new index column called 'group' as below:

```<code>> dat
# A tibble: 13 x 1
index   group    title
                 <chr>
 1       1   lymphoedema clinic
 8       1   lymphoedema early intervenstion
 9       1   lymphoedema expo
10       1   lymphoedema for breast care nurses
 2       2   zostavax shingles vaccine
 5       2   zostavax recall toolkit
 3       3   xray operator
 6       3   xray meetint
11       3   xray meeting and case studies
12       3   xray online examination
13       3   xray operator in service paediatric extremities
 4       4   workplace mental health wellbeing workshop
 7       4   workplace mental health and wellbeing
</code>```

答:
I'm afraid I've never tried RecordLinkage, but if you're just using the Jaro-Winkler distance it should also be fairly easy to cluster similar strings with the stringdist package. Using your dput above:

library(tidyverse)
library(stringdist)

map_dfr(dat$title, ~ {
    i <- which(stringdist(., dat$title, "jw") < 0.40)
    tibble(index = i, title = dat$title[i])
}, .id = "group") %>%
    distinct(index, .keep_all = T) %>%
    mutate(group = as.integer(group))
```

<p><strong>Explanation</strong>:
<code>map_dfr</code> iterates over each string in <code>dat$title</code>, extracts the indices of the closest matches computed by <code>stringdist</code> (constrained by 0.40, i.e. your "threshold"), creates a tibble with the indices and matches, then stacks these tibbles with a <code>group</code> variable corresponding to the integer position (and row number) of the original string. <code>distinct</code> then drops any cluster duplicates based on repeats of <code>index</code>.</p>

<p><strong>Output</strong>:</p>

```# A tibble: 13 x 3
   group index title
   <int> <int> <chr>
 1     1     1 lymphoedema clinic
 2     1     8 lymphoedema early intervenstion
 3     1     9 lymphoedema expo
 4     1    10 lymphoedema for breast care nurses
 5     2     2 zostavax shingles vaccine
 6     2     5 zostavax recall toolkit
 7     2    11 xray meeting and case studies
 8     3     3 xray operator
 9     3     6 xray meetint
10     3    12 xray online examination
11     3    13 xray operator in service paediatric extremities
12     4     4 workplace mental health wellbeing workshop
13     4     7 workplace mental health and wellbeing
```

An interesting alternative would be to use tidytext with widyr to tokenize by word and compute the cosine similarity of the titles based on similar words, rather than characters as above.

Body:
I have a tibble of just 1 column called 'title'.

> dat
# A tibble: 13 x 1
   title
   <chr>
 1 lymphoedema clinic
 2 zostavax shingles vaccine
 3 xray operator
 4 workplace mental health wellbeing workshop
 5 zostavax recall toolkit
 6 xray meetint
 7 workplace mental health and wellbeing
 8 lymphoedema early intervenstion
 9 lymphoedema expo
10 lymphoedema for breast care nurses
11 xray meeting and case studies
12 xray online examination
13 xray operator in service paediatric extremities

I wish to find similar records and group them together as such (all the while keeping their indices):

> dat
# A tibble: 13 x 1
   title
   <chr>
 1 lymphoedema clinic
 8 lymphoedema early intervenstion
 9 lymphoedema expo
10 lymphoedema for breast care nurses
 2 zostavax shingles vaccine
 5 zostavax recall toolkit
 3 xray operator
 6 xray meetint
11 xray meeting and case studies
12 xray online examination
13 xray operator in service paediatric extremities
 4 workplace mental health wellbeing workshop
 7 workplace mental health and wellbeing

I'm using the below function to find strings that are close enough to each other (cutoff = 0.75)

compareJW <- function(string1, string2, cutoff)
{
  require(RecordLinkage)
  jarowinkler(string1, string2) > cutoff
}

I've implemented the loop below to 'send' similar records together in a new dataframe but it's not working properly, I've tried a few variations but nothing is working yet.

# create new database
newDB <- data.frame(matrix(ncol = ncol(dat), nrow = 0))
colnames(newDB) <- names(dat)
newDB <- as_tibble(newDB)

for(i in 1:nrow(dat))
{
  # print(dat$title[i])

  for(j in 1:nrow(dat))
  {
    print(dat$title[i])
    print(dat$title[j])
    # score <- jarowinkler(dat$title[i], dat$title[j])

    if(dat$title[i] != dat$title[j]
       &&
       compareJW(dat$title[i], dat$title[j], 0.75))
    {
      print("if")

      # newDB <- rbind(newDB,
      #                dat$title[i],
      #                dat$title[j])
    }
    else
    {
      print("else")
      # newDB <- rbind(newDB, dat$title[i])
    }
  }
}

(I've inserted prints in the loop 'to see what's happening')

REPRODUCIBLE DAT:

dat <-
structure(list(title = c("lymphoedema clinic", "zostavax shingles vaccine",
                         "xray operator", "workplace mental health wellbeing workshop",
                         "zostavax recall toolkit", "xray meetint", "workplace mental health and wellbeing",
                         "lymphoedema early intervenstion", "lymphoedema expo", "lymphoedema for breast care nurses",
                         "xray meeting and case studies", "xray online examination", "xray operator in service paediatric extremities"
)), row.names = c(NA, -13L), class = c("tbl_df", "tbl", "data.frame"
))

Any suggestions please?
EDIT: I'd also like a new index column called 'group' as below:

> dat
# A tibble: 13 x 1
index   group    title
                 <chr>
 1       1   lymphoedema clinic
 8       1   lymphoedema early intervenstion
 9       1   lymphoedema expo
10       1   lymphoedema for breast care nurses
 2       2   zostavax shingles vaccine
 5       2   zostavax recall toolkit
 3       3   xray operator
 6       3   xray meetint
11       3   xray meeting and case studies
12       3   xray online examination
13       3   xray operator in service paediatric extremities
 4       4   workplace mental health wellbeing workshop
 7       4   workplace mental health and wellbeing

Body:
I'm afraid I've never tried RecordLinkage, but if you're just using the Jaro-Winkler distance it should also be fairly easy to cluster similar strings with the stringdist package. Using your dput above:

library(tidyverse)
library(stringdist)

map_dfr(dat$title, ~ {
    i <- which(stringdist(., dat$title, "jw") < 0.40)
    tibble(index = i, title = dat$title[i])
}, .id = "group") %>%
    distinct(index, .keep_all = T) %>%
    mutate(group = as.integer(group))

Explanation:
map_dfr iterates over each string in dat$title, extracts the indices of the closest matches computed by stringdist (constrained by 0.40, i.e. your "threshold"), creates a tibble with the indices and matches, then stacks these tibbles with a group variable corresponding to the integer position (and row number) of the original string. distinct then drops any cluster duplicates based on repeats of index.

Output:

# A tibble: 13 x 3
   group index title
   <int> <int> <chr>
 1     1     1 lymphoedema clinic
 2     1     8 lymphoedema early intervenstion
 3     1     9 lymphoedema expo
 4     1    10 lymphoedema for breast care nurses
 5     2     2 zostavax shingles vaccine
 6     2     5 zostavax recall toolkit
 7     2    11 xray meeting and case studies
 8     3     3 xray operator
 9     3     6 xray meetint
10     3    12 xray online examination
11     3    13 xray operator in service paediatric extremities
12     4     4 workplace mental health wellbeing workshop
13     4     7 workplace mental health and wellbeing

An interesting alternative would be to use tidytext with widyr to tokenize by word and compute the cosine similarity of the titles based on similar words, rather than characters as above.