问:
Can't add params to Angular route
I am trying to use Angular Routing for a simple master-detail interface and I just can't manage to get my routing working whenever there are parameters in it.

I have this Master component

```<code>    export class PersonMasterComponent extends MasterExtentionService implements OnInit {
       constructor(
           private _snackBar: MatSnackBar,
           private _router: Router,
           private contService: ContactService)
            { super(contService, _snackBar, null, _router) }
}
</code>```

Which inherits from:

```<code>        Injectable()
        export class MasterExtentionService {

        constructor(private dataService: DataService,
                private snackBar: MatSnackBar,
                private matDialog?: MatDialog
                , private router?: Router
            ) { }
        ...
            edit(id: number) {
        ...
                    this.router.navigate(['crm', 'contacts','detail', id]); // I just type the URL directly for
                                                                            // this example, this
                                                                            // will be a variable.
                                                                            // i've trie navigateByUrl as
                                                                            //  well
                }
            }
}
</code>```

edit() gets called whenever a row gets clicked on the master component.

I've done this a thousand times before, but I just can't seem to find whats wrong here. (I had been stuck in Angular 7, just switched to 9)

Here are my app routes:

```<code>const routes: Routes = [
  { path: 'crm', loadChildren: () => import('./crm/crm.module').then(m => m.CrmModule), canActivate: [AuthGuard] },
}
</code>```

Here are my CRM module routes:

```<code>const routes: Routes = [
  { path: 'contacts/detail/:id', component: PersonDetailComponent }, // I am trying to call this guy
                                                                     // from PersonMasterComponent

  { path: 'contacts', component: PersonMasterComponent, children: [
    // { path: 'detail/:id', component: PersonDetailComponent,  }, // tried doing this didn't work
  ] },

  { path: 'businesses/:id', component: PersonMasterComponent },
  { path: '', component: CrmComponent }

];
</code>```

Whenever I try to navigate the router does recognize the route as existing, but it just quickly comes back to the initial route and reloads the master component.

The problem only seems to happen whenever there are parameters on my route.  I have a feeling that I am missing something very basic.

I came across this problem yesterday and it's driving me nuts.  Any help will be deeply appreciated.

--EDIT
Here are the logs the router gives when subscribing to router.events
https://docs.google.com/document/d/1rpQRIQJ6UifEsAzIRaWIFbnly4ttljLrOxejuExXVbs/edit

It does seem like the correct route is found, but just immediately goes back.
This only seems to happen when I try to load the component from a component that is in the same lazy loaded module, I was able to load it from other parts of the app.

Cheers.

答:
the verify first item in the navigate should start with the leading /, otherwise it doesn't respect the root.

this.router.navigate(['/crm', 'contacts','detail', id]); // <- /crm
```

Title: Can't add params to Angular route

Body:
I am trying to use Angular Routing for a simple master-detail interface and I just can't manage to get my routing working whenever there are parameters in it.

I have this Master component

    export class PersonMasterComponent extends MasterExtentionService implements OnInit {
       constructor(
           private _snackBar: MatSnackBar,
           private _router: Router,
           private contService: ContactService)
            { super(contService, _snackBar, null, _router) }
}

Which inherits from:

        Injectable()
        export class MasterExtentionService {

        constructor(private dataService: DataService,
                private snackBar: MatSnackBar,
                private matDialog?: MatDialog
                , private router?: Router
            ) { }
        ...
            edit(id: number) {
        ...
                    this.router.navigate(['crm', 'contacts','detail', id]); // I just type the URL directly for
                                                                            // this example, this
                                                                            // will be a variable.
                                                                            // i've trie navigateByUrl as
                                                                            //  well
                }
            }
}

edit() gets called whenever a row gets clicked on the master component.

I've done this a thousand times before, but I just can't seem to find whats wrong here. (I had been stuck in Angular 7, just switched to 9)

Here are my app routes:

const routes: Routes = [
  { path: 'crm', loadChildren: () => import('./crm/crm.module').then(m => m.CrmModule), canActivate: [AuthGuard] },
}

Here are my CRM module routes:

const routes: Routes = [
  { path: 'contacts/detail/:id', component: PersonDetailComponent }, // I am trying to call this guy
                                                                     // from PersonMasterComponent

  { path: 'contacts', component: PersonMasterComponent, children: [
    // { path: 'detail/:id', component: PersonDetailComponent,  }, // tried doing this didn't work
  ] },

  { path: 'businesses/:id', component: PersonMasterComponent },
  { path: '', component: CrmComponent }

];

Whenever I try to navigate the router does recognize the route as existing, but it just quickly comes back to the initial route and reloads the master component.

The problem only seems to happen whenever there are parameters on my route.  I have a feeling that I am missing something very basic.

I came across this problem yesterday and it's driving me nuts.  Any help will be deeply appreciated.

--EDIT
Here are the logs the router gives when subscribing to router.events
https://docs.google.com/document/d/1rpQRIQJ6UifEsAzIRaWIFbnly4ttljLrOxejuExXVbs/edit

It does seem like the correct route is found, but just immediately goes back.
This only seems to happen when I try to load the component from a component that is in the same lazy loaded module, I was able to load it from other parts of the app.

Cheers.


来源: stackexchange

问:
dynamic values in tags object of swagger
I want to provide values from properties file in tags section of the swagger for ex:  tags = "${metric.tags}" but not able to pickup from properties file. for values it is working fine value = "${metric.value}".</p>

答:
```<code>I have made plugin configuration in swagger configuration file and it started working as per my requirement.

@Bean
    public TranslationOperationBuilderPlugin translationPlugin() {
        return new TranslationOperationBuilderPlugin();
    }

    @Order(Ordered.LOWEST_PRECEDENCE)
    public static class TranslationOperationBuilderPlugin implements OperationBuilderPlugin {

        @Autowired
        Environment environment;

        @Override
        public boolean supports(DocumentationType delimiter) {
            return true;
        }

        @Override
        public void apply(OperationContext context) {

            String summary = context.operationBuilder().build().getSummary();
            String notes = context.operationBuilder().build().getNotes();
            Set<String>tags = context.operationBuilder().build().getTags();
            Set<String>translatedTags= new HashSet<>();
            for(String tag:tags) {
                if(environment.getProperty(tag)!=null) {
                    translatedTags.add(environment.getProperty(tag));
                }else {
                    translatedTags.add(tag);
                }
            }

            ModelReference modelReference= context.operationBuilder().build().getResponseModel();
            AllowableListValues allowableValues=(AllowableListValues) modelReference.getAllowableValues();
            if(allowableValues!=null && allowableValues.getValues()!=null) {
                List<String> translatedAllowables=new ArrayList<>();
                for(String value:allowableValues.getValues()) {
                    if(environment.getProperty(value)!=null) {
                        translatedAllowables.add(environment.getProperty(value));
                    }else {
                        translatedAllowables.add(value);
                    }
                }
                allowableValues.getValues().removeAll(allowableValues.getValues());
                allowableValues.getValues().addAll(translatedAllowables);
            }

            //String summaryTranslated = apiDescriptionPropertiesReader.getProperty(summary);
            //String notesTranslated = apiDescriptionPropertiesReader.getProperty(notes);
            //context.operationBuilder().summary(summaryTranslated);
            //context.operationBuilder().notes(notesTranslated);
            context.operationBuilder().tags(translatedTags);

        }
</code>```

ContentLicense: CC BY-SA 4.0


问:
Android SQLiteDatabase Query SQL Logic Error or Missing Database
So I created a database using SQLiteOpenHelper and I'm trying to query it. It returns the cursor but when I call moveToFirst() it crashes with the error SQL Logic Error or Missing Database.

I follow this websites code to create and query my database: http://www.vogella.de/articles/AndroidSQLite/article.html

EDIT:

My Database:

```<code>public class Database{
     private static final String DATABASE_NAME = "MyDatabase";
     private static final int DATABASE_VERSION = 1;
     private static final String TABLE_NAME = "MyTable";

     // Column Names
     public static final String ID = "_id";                 // INTEGER
     public static final String NUMBER = "number";          // TEXT

     private SQLiteDatabase database;
     private DatabaseHelper mDatabaseOpenHelper;

     public Database(Context context){
          mDatabaseOpenHelper = new DatabaseHelper(context);
          database = mDatabaseOpenHelper.getWritableDatabase();
     }

     public void close(){
          database.close();
     }

     public long addNumber(String number){
          ContentValues values = new ContentValues();
          values.put(NUMBER, number);
          return database.insert(TABLE_NAME, null, values);
     }

     public Cursor getNumber(String number){
          String selection = NUMBER + " MATCH ?";
          String[] selectionArgs = new String[] {number};
          return database.query(TABLE_NAME, null, selection, selectionArgs, null, null, null);
     }

     private class DatabaseHelper extends SQLiteOpenHelper{

          private static final String CREATE_TABLE = "CREATE TABLE " + TABLE_NAME + "(_id INTEGER PRIMARY KEY AUTOINCREMENT, " + NUMBER + " TEXT)";

          public DatabaseHelper(Context context){
               super(context, DATABASE_NAME, null, DATABASE_VERSION);
          }

          public void onCreate(SQLiteDatabase db) {
               db.execSQL(CREATE_TABLE);
          }

          public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
               db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
               onCreate(db);
          }
      }
 }
</code>```

And this is how I query:

```<code> Database database = new Database(this);

 Cursor cursor = database.getTrUpdate("1234");

 if (cursor.moveToFirst()){
      do{
           int d = cursor.getInt(cursor.getColumnIndex(Database.ID));
      } while(cursor.moveToNext());
 }
</code>```

答: Have you checked if the array it returns is not empty?</p>

ContentLicense: CC BY-SA 3.0

Body:
So I created a database using SQLiteOpenHelper and I'm trying to query it. It returns the cursor but when I call moveToFirst() it crashes with the error SQL Logic Error or Missing Database.

I follow this websites code to create and query my database: http://www.vogella.de/articles/AndroidSQLite/article.html

EDIT:

My Database:

public class Database{
     private static final String DATABASE_NAME = "MyDatabase";
     private static final int DATABASE_VERSION = 1;
     private static final String TABLE_NAME = "MyTable";

     // Column Names
     public static final String ID = "_id";                 // INTEGER
     public static final String NUMBER = "number";          // TEXT

     private SQLiteDatabase database;
     private DatabaseHelper mDatabaseOpenHelper;

     public Database(Context context){
          mDatabaseOpenHelper = new DatabaseHelper(context);
          database = mDatabaseOpenHelper.getWritableDatabase();
     }

     public void close(){
          database.close();
     }

     public long addNumber(String number){
          ContentValues values = new ContentValues();
          values.put(NUMBER, number);
          return database.insert(TABLE_NAME, null, values);
     }

     public Cursor getNumber(String number){
          String selection = NUMBER + " MATCH ?";
          String[] selectionArgs = new String[] {number};
          return database.query(TABLE_NAME, null, selection, selectionArgs, null, null, null);
     }

     private class DatabaseHelper extends SQLiteOpenHelper{

          private static final String CREATE_TABLE = "CREATE TABLE " + TABLE_NAME + "(_id INTEGER PRIMARY KEY AUTOINCREMENT, " + NUMBER + " TEXT)";

          public DatabaseHelper(Context context){
               super(context, DATABASE_NAME, null, DATABASE_VERSION);
          }

          public void onCreate(SQLiteDatabase db) {
               db.execSQL(CREATE_TABLE);
          }

          public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
               db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
               onCreate(db);
          }
      }
 }

And this is how I query:

 Database database = new Database(this);

 Cursor cursor = database.getTrUpdate("1234");

 if (cursor.moveToFirst()){
      do{
           int d = cursor.getInt(cursor.getColumnIndex(Database.ID));
      } while(cursor.moveToNext());
 }


问:
How do I sort a list based on a given sequence of one field?
I have a list read from database, something like:

```<code>var managers = _repo.Where(xxxx).ToList();
</code>```

data of managers displays in json is

```<code>[
    {
        "id":"b2071b2d-3d1a-4403-b044-0a59514c4431",
        "name":"Lucy",
        "mobile":"xxx"
    },
    {
        "id":"639c108f-ec00-4fcd-814a-c3859930b1c1",
        "name":"Franck",
        "mobile":"xxx2"
    },
    {
        "id":"943b2ad4-8ef0-4cf7-824e-de3a7837a1cd",
        "name":"Jerry",
        "mobile":"xxx3"
    }
]
</code>```

Now I need to reorder this list by a given name sequence, for example:

```<code>    var orderByName = _svc.GetManagerSortOrder(); // ["Jerry","Lucy","Franck"]
</code>```

Right now I'm using foreach to do this, it's too much to code. Is there any better way?

Here is my current solution:

```<code>var orderByName = new List<string>() { "Franck", "Jerry" };
var sortedManagers = new List<Manager>();
foreach(string orderName in orderByName) // loop, and sort manager list based on a given name list
{
    var manager = managers.Where(a => a.name == orderName).FirstOrDefault();
    if (manager == null)
        continue;
    sortedManagers.Add(manager);
}

if(sortedManagers.Count != managers.Count) // if counts not equal, there is someone not on the name list, so these men need to be appended to the sortedManagers list
{
    var sortedManagersId = sortedManagers.Select(s => s.id);
    var managersNotInclude = managers.Where(a => !sortedManagersId.Contains(a.id)).ToList();
    sortedManagers = sortedManagers.Concat(managersNotInclude).ToList();
}
</code>```

答:
Unfortunately the following answer would help you, if it wasn't for handling names in your source list, that don't exist in your target list since IndexOf() returns -1 for undiscovered elements: Sort a list from another list IDs

What you need to do is write a customer Comparer that implements ICompare. This could look something like this:

```<code>class DependentComparer<T> : IComparer<T>
{
    // Backing field to contain the order dependent list
    List<T> lookUpTable;

    public DependentComparer(List<T> lookUpTable)
    {
        this.lookUpTable = lookUpTable;
    }

    public int Compare(T x, T y)
    {
        // Determine the index of the compared elements in the dependent list
        int xIndex = lookUpTable.IndexOf(x);
        int yIndex = lookUpTable.IndexOf(y);

        // If neither were in the dependent list, they are equal
        if ((xIndex == -1) && (yIndex == -1)) return 0;

        // If only the y was found, then y is greater than the x element
        if (xIndex == -1) return 1;
        // If only the x was found, then y is less than the x element
        if (yIndex == -1) return -1;

        // If both were found, then return the delta of their indicies
        return xIndex - yIndex;
    }
}
</code>```

This can be used as:

```<code>var orderByName = new List<string>() { "Frank", "Jerry" };
var managersNames = new List<string>() { "Jerry", "Frank", "Lucy" };

managersNames.Sort(new DependentComparer<string>(orderByName));
</code>```

Output: Frank, Jerry, Lucy

NOTES: This method will take no sorting action on the elements not pressent in the lookUpTable. They will be appended to the end of result in the order in which they were in the source. Also, the example is given as if the lists were of string, not manager. The conversion is easy enough, but let me know if you need an edit.

Body:
I have a list read from database, something like:

var managers = _repo.Where(xxxx).ToList();

data of managers displays in json is

[
    {
        "id":"b2071b2d-3d1a-4403-b044-0a59514c4431",
        "name":"Lucy",
        "mobile":"xxx"
    },
    {
        "id":"639c108f-ec00-4fcd-814a-c3859930b1c1",
        "name":"Franck",
        "mobile":"xxx2"
    },
    {
        "id":"943b2ad4-8ef0-4cf7-824e-de3a7837a1cd",
        "name":"Jerry",
        "mobile":"xxx3"
    }
]

Now I need to reorder this list by a given name sequence, for example:

    var orderByName = _svc.GetManagerSortOrder(); // ["Jerry","Lucy","Franck"]

Right now I'm using foreach to do this, it's too much to code. Is there any better way?

Here is my current solution:

var orderByName = new List<string>() { "Franck", "Jerry" };
var sortedManagers = new List<Manager>();
foreach(string orderName in orderByName) // loop, and sort manager list based on a given name list
{
    var manager = managers.Where(a => a.name == orderName).FirstOrDefault();
    if (manager == null)
        continue;
    sortedManagers.Add(manager);
}

if(sortedManagers.Count != managers.Count) // if counts not equal, there is someone not on the name list, so these men need to be appended to the sortedManagers list
{
    var sortedManagersId = sortedManagers.Select(s => s.id);
    var managersNotInclude = managers.Where(a => !sortedManagersId.Contains(a.id)).ToList();
    sortedManagers = sortedManagers.Concat(managersNotInclude).ToList();
}

Body:
Unfortunately the following answer would help you, if it wasn't for handling names in your source list, that don't exist in your target list since IndexOf() returns -1 for undiscovered elements: Sort a list from another list IDs

What you need to do is write a customer Comparer that implements ICompare. This could look something like this:

class DependentComparer<T> : IComparer<T>
{
    // Backing field to contain the order dependent list
    List<T> lookUpTable;

    public DependentComparer(List<T> lookUpTable)
    {
        this.lookUpTable = lookUpTable;
    }

    public int Compare(T x, T y)
    {
        // Determine the index of the compared elements in the dependent list
        int xIndex = lookUpTable.IndexOf(x);
        int yIndex = lookUpTable.IndexOf(y);

        // If neither were in the dependent list, they are equal
        if ((xIndex == -1) && (yIndex == -1)) return 0;

        // If only the y was found, then y is greater than the x element
        if (xIndex == -1) return 1;
        // If only the x was found, then y is less than the x element
        if (yIndex == -1) return -1;

        // If both were found, then return the delta of their indicies
        return xIndex - yIndex;
    }
}

This can be used as:

var orderByName = new List<string>() { "Frank", "Jerry" };
var managersNames = new List<string>() { "Jerry", "Frank", "Lucy" };

managersNames.Sort(new DependentComparer<string>(orderByName));

Output: Frank, Jerry, Lucy

NOTES: This method will take no sorting action on the elements not pressent in the lookUpTable. They will be appended to the end of result in the order in which they were in the source. Also, the example is given as if the lists were of string, not manager. The conversion is easy enough, but let me know if you need an edit.


问:
How can I use TypefaceSpan or StyleSpan with a custom Typeface?
I have not found a way to do this. Is it possible?</p>

答:
Spannable typeface: In order to set a different font typeface to some portion of text, a custom TypefaceSpan can be used, as shown in the following example:

```<code>spannable.setSpan( new CustomTypefaceSpan("SFUIText-Bold.otf",fontBold), 0,
firstWord.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
spannable.setSpan( new CustomTypefaceSpan("SFUIText-Regular.otf",fontRegular),
firstWord.length(), firstWord.length() + lastWord.length(),
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
text.setText( spannable );
</code>```

However, in order to make the above code working, the class CustomTypefaceSpan has to be derived from the class TypefaceSpan. This can be done as follows:

```<code>public class CustomTypefaceSpan extends TypefaceSpan {
    private final Typeface newType;

    public CustomTypefaceSpan(String family, Typeface type) {
        super(family);
        newType = type;
    }

    @Override
    public void updateDrawState(TextPaint ds) {
        applyCustomTypeFace(ds, newType);
    }

    @Override
    public void updateMeasureState(TextPaint paint) {
        applyCustomTypeFace(paint, newType);
    }

    private static void applyCustomTypeFace(Paint paint, Typeface tf) {
        int oldStyle;
        Typeface old = paint.getTypeface();
        if (old == null) {
            oldStyle = 0;
        } else {
            oldStyle = old.getStyle();
        }
        int fake = oldStyle & ~tf.getStyle();
        if ((fake & Typeface.BOLD) != 0) {
            paint.setFakeBoldText(true);
        }
        if ((fake & Typeface.ITALIC) != 0) {
            paint.setTextSkewX(-0.25f);
        }
        paint.setTypeface(tf);
    }
}
</code>```

Body:
Spannable typeface: In order to set a different font typeface to some portion of text, a custom TypefaceSpan can be used, as shown in the following example:

spannable.setSpan( new CustomTypefaceSpan("SFUIText-Bold.otf",fontBold), 0,
firstWord.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
spannable.setSpan( new CustomTypefaceSpan("SFUIText-Regular.otf",fontRegular),
firstWord.length(), firstWord.length() + lastWord.length(),
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
text.setText( spannable );

However, in order to make the above code working, the class CustomTypefaceSpan has to be derived from the class TypefaceSpan. This can be done as follows:

public class CustomTypefaceSpan extends TypefaceSpan {
    private final Typeface newType;

    public CustomTypefaceSpan(String family, Typeface type) {
        super(family);
        newType = type;
    }

    @Override
    public void updateDrawState(TextPaint ds) {
        applyCustomTypeFace(ds, newType);
    }

    @Override
    public void updateMeasureState(TextPaint paint) {
        applyCustomTypeFace(paint, newType);
    }

    private static void applyCustomTypeFace(Paint paint, Typeface tf) {
        int oldStyle;
        Typeface old = paint.getTypeface();
        if (old == null) {
            oldStyle = 0;
        } else {
            oldStyle = old.getStyle();
        }
        int fake = oldStyle & ~tf.getStyle();
        if ((fake & Typeface.BOLD) != 0) {
            paint.setFakeBoldText(true);
        }
        if ((fake & Typeface.ITALIC) != 0) {
            paint.setTextSkewX(-0.25f);
        }
        paint.setTypeface(tf);
    }
}


问:
How to update Athena output location using Cloudformation
Can someone help me write a Cloud formation script to update output location of Athena primary workgroup. When i run below code, getting error message "Invalid request provided: primary workGroup could not be created (Service: Athena, Status Code: 400, Request ID: 9945209c-6999-4e8b-bd3d-a3af13b4ac4f)"</p>

```<code>Resources:
  MyAthenaWorkGroup:
    Type: AWS::Athena::WorkGroup
    Properties:
      Name: primary
      Description: My WorkGroup Updated
      State: DISABLED
      WorkGroupConfigurationUpdates:
        BytesScannedCutoffPerQuery: 10000000
        EnforceWorkGroupConfiguration: true
        PublishCloudWatchMetricsEnabled: true
        RequesterPaysEnabled: false
        ResultConfigurationUpdates:
          EncryptionConfiguration:
            EncryptionOption: SSE_S3
          OutputLocation: s3://test/
</code>```

答:
you need to "create a change set to import an existing resource into a new or existing stack.", because the 'primary' workgroup was created outside your stack.
So you need to use the option: "Create stack with existing resources":

You also need to add DeletionPolicy/UpdateReplacePolicy.
An complete working example is:

```<code>  Resources:
    AthenaPrimaryWorkGroup:
      Type: AWS::Athena::WorkGroup
      Properties:
        Name: primary
        State: ENABLED
        WorkGroupConfigurationUpdates:
          BytesScannedCutoffPerQuery: 1000000000
          EnforceWorkGroupConfiguration: true
          PublishCloudWatchMetricsEnabled: true
          RequesterPaysEnabled: false
          ResultConfigurationUpdates:
            OutputLocation: s3://MY-Athena-results
      DeletionPolicy: Retain
      UpdateReplacePolicy: Retain
</code>```

More detail at: https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/resource-import.html

Body:
Can someone help me write a Cloud formation script to update output location of Athena primary workgroup. When i run below code, getting error message "Invalid request provided: primary workGroup could not be created (Service: Athena, Status Code: 400, Request ID: 9945209c-6999-4e8b-bd3d-a3af13b4ac4f)"

Resources:
  MyAthenaWorkGroup:
    Type: AWS::Athena::WorkGroup
    Properties:
      Name: primary
      Description: My WorkGroup Updated
      State: DISABLED
      WorkGroupConfigurationUpdates:
        BytesScannedCutoffPerQuery: 10000000
        EnforceWorkGroupConfiguration: true
        PublishCloudWatchMetricsEnabled: true
        RequesterPaysEnabled: false
        ResultConfigurationUpdates:
          EncryptionConfiguration:
            EncryptionOption: SSE_S3
          OutputLocation: s3://test/

Body:
you need to "create a change set to import an existing resource into a new or existing stack.", because the 'primary' workgroup was created outside your stack.
So you need to use the option: "Create stack with existing resources":

You also need to add DeletionPolicy/UpdateReplacePolicy.
An complete working example is:

  Resources:
    AthenaPrimaryWorkGroup:
      Type: AWS::Athena::WorkGroup
      Properties:
        Name: primary
        State: ENABLED
        WorkGroupConfigurationUpdates:
          BytesScannedCutoffPerQuery: 1000000000
          EnforceWorkGroupConfiguration: true
          PublishCloudWatchMetricsEnabled: true
          RequesterPaysEnabled: false
          ResultConfigurationUpdates:
            OutputLocation: s3://MY-Athena-results
      DeletionPolicy: Retain
      UpdateReplacePolicy: Retain

More detail at: https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/resource-import.html


问:
python pandas.Series.str.contains WHOLE WORD
df (Pandas Dataframe) has three rows.

```<code>col_name
"This is Donald."
"His hands are so small"
"Why are his fingers so short?"
</code>```

I'd like to extract the row that contains "is" and "small".

If I do

```<code>df.col_name.str.contains("is|small", case=False)
</code>```

Then it catches "His" as well- which I don't want.

Is below query is the right way to catch the whole word in df.series?

```<code>df.col_name.str.contains("\bis\b|\bsmall\b", case=False)
</code>```

答:
In extension to the discussion, I want to use a variable inside the regex as follows:

```<code>df = df_w[df_w['Country/Region'].str.match("\b(location.loc[i]['country'])\b",case=False)]
</code>```

If I do not put \b\b, the code returns all the columns with both Sudan and South Sudan. While, when I use "\b(location.loc[i]['country'])\b", it returns empty dataframes. Kindly tell me the correct usage.

Body:
df (Pandas Dataframe) has three rows.

col_name
"This is Donald."
"His hands are so small"
"Why are his fingers so short?"

I'd like to extract the row that contains "is" and "small".

If I do

df.col_name.str.contains("is|small", case=False)

Then it catches "His" as well- which I don't want.

Is below query is the right way to catch the whole word in df.series?

df.col_name.str.contains("\bis\b|\bsmall\b", case=False)

Body:
In extension to the discussion, I want to use a variable inside the regex as follows:

df = df_w[df_w['Country/Region'].str.match("\b(location.loc[i]['country'])\b",case=False)]

If I do not put \b\b, the code returns all the columns with both Sudan and South Sudan. While, when I use "\b(location.loc[i]['country'])\b", it returns empty dataframes. Kindly tell me the correct usage.


问:
Using Storybook to show React components in both React & Plain HTML/CSS
so if I have a React Button component that uses styled component like so:

```<code>import styled, { css } from "styled-components";
import React from "react";

const Button = ({ theme, children }) => {
  const StyledButton = styled.a`
    padding: 10px 20px;
    border-radius: 20px;
    ${theme === "primary" &&
    css`
      color: black;
      background: white;
    `}
    ${theme === "secondary" &&
    css`
      color: white;
      background: black;
    `}
  `;

  return <StyledButton>{children}</StyledButton>;
};

export default Button;
</code>```

Is it possible to display this component, alongside its React code & HTML/CSS code on Storybook? (Without having to hard code the HTML/CSS code in)

I was thinking of using React's renderToString() to convert it into HTML and using the styled component's string for the CSS. Not sure if this is possible?

答:
Yes, it is a storybook addon, not a React API.

See storysource addon.

Body:
so if I have a React Button component that uses styled component like so:

import styled, { css } from "styled-components";
import React from "react";

const Button = ({ theme, children }) => {
  const StyledButton = styled.a`
    padding: 10px 20px;
    border-radius: 20px;
    ${theme === "primary" &&
    css`
      color: black;
      background: white;
    `}
    ${theme === "secondary" &&
    css`
      color: white;
      background: black;
    `}
  `;

  return ;
};

export default Button;

Is it possible to display this component, alongside its React code & HTML/CSS code on Storybook? (Without having to hard code the HTML/CSS code in)

I was thinking of using React's renderToString() to convert it into HTML and using the styled component's string for the CSS. Not sure if this is possible?


问:
Gulp: How to change modification time of file
I have gulp task below and with every run of this task (before browsersync) I want to change last modification time of one file (nothing changes in that file, I just need to change time of last modification - alternative to shell "touch" command). Can somebody tell me what's the easiest way to do that please? Thanks!</p>

```<code>gulp.task('sass', function() {

    return sass(pkg.sass.dir, {sourcemap: true, precision: 10})
        .on('error', function (err) {
            onError(err);
        })
        .pipe(autoprefixer({
            browsers: ['last 2 version', 'safari 5', 'ie 8', 'ie 9', 'opera 12.1', 'ios 6', 'android 4'],
            cascade: true
        }))
        .pipe(gulp.dest(pkg.css.dir))
        .pipe(browsersync.reload({stream:true}));
});
</code>```

Body:
I have gulp task below and with every run of this task (before browsersync) I want to change last modification time of one file (nothing changes in that file, I just need to change time of last modification - alternative to shell "touch" command). Can somebody tell me what's the easiest way to do that please? Thanks!

gulp.task('sass', function() {

    return sass(pkg.sass.dir, {sourcemap: true, precision: 10})
        .on('error', function (err) {
            onError(err);
        })
        .pipe(autoprefixer({
            browsers: ['last 2 version', 'safari 5', 'ie 8', 'ie 9', 'opera 12.1', 'ios 6', 'android 4'],
            cascade: true
        }))
        .pipe(gulp.dest(pkg.css.dir))
        .pipe(browsersync.reload({stream:true}));
});

Body: fs.writeFileSync('sporks','','utf8','a')


问:
Scatter/Gather like Numpy in ArrayFire
I want to scatter and gather elements from an array X at specific indices along one axis.
So given an array of indices idx, I want to select the idx(0)th element along the 0th column, the idx(1)th element along the 1st column, etc..

In Numpy, the following statement:

```<code>X = np.array([[1, 2, 3], [4, 5, 6]])
print(X[[0, 1, 1], range(3)])
</code>```

prints [1, 5, 6].

Furthermore, I can do this process in reverse:

```<code>Y = np.zeros((2, 3))
Y[[0, 1, 1], range(3)] = [1, 5, 6]
print(Y)
</code>```

This will print

```<code>[[1. 0. 0.]
 [0. 5. 6.]]
</code>```

However, when I try to replicate this behavior in ArrayFire:

```<code>float elements[] = {1, 2, 3, 4, 5, 6};
af::array X = af::array(3, 2, elements);
int idx_elements[] = {0, 1, 1};
af::array idx = af::array(3, idx_elements);
af::print("", X(af::span, idx));
</code>```

I get an array of shape [3, 3, 1, 1] with the elements

```<code>1.0000     4.0000     4.0000
2.0000     5.0000     5.0000
3.0000     6.0000     6.0000
</code>```

So how can I achieve the desired numpy-like behavior for scattering and gathering elements in ArrayFire?

To perform the gather operation on a matrix, I can extract the diagonal of the resulting matrix but that may not work in the multidimensional case and it doesn't work in the other (scatter) direction.

答:
```<code>X
[3 2 1 1]
    1.0000     4.0000
    2.0000     5.0000
    3.0000     6.0000

idx
[3 1 1 1]
         0
         1
         1
</code>```

ArrayFire does Cartesian product when af::array are involved. Hence, the output.
Please see the below indices because of that.

```<code>Col\Row   0       1        1   from array

   0    (0, 0)  (0,1)  (0, 1)
   1    (1, 0)  (1,1)  (1, 1)
   2    (2, 0)  (2,1)  (2, 1)
   ^
   ^ from sequence
</code>```

Thus, the output of X(af::span, idx)) is a 3x3 matrix.

To gather elements based on coordinates, you would need different function
approx2. Note that this function takes it's indices as floating point arrays only.

```<code>float idx_elements[] = {0, 1, 1}; // changed the idx to floats
af::array colIdx = af::array(3, idx_elements);
af::array rowIdx = af::iota(3); // same effect as span

af::array out = approx2(X, rowIdx, colIdx);
af_print(out);
// out
// [3 1 1 1]
//     1.0000
//     5.0000
//     6.0000
</code>```

To set the values for given indices, you would have to flatten the array because of very reason
that array::operator() considers cartesian product when af::array is involved.

```<code>af::array A = af::constant(0, 3, 2); // same size as X
af::array B = af::flat(A); // flatten the array, this involves meta data modification only

B(rowIdx + 3 * colIdx) = out; // use row & col indices to fetch linear indices
// rowIdx + 3 * colIdx
// [3 1 1 1]
//     0.0000
//     4.0000
//     5.0000

B = moddims(B, A.dims()); // reset the dimensions to original A dims

af_print(B);
// B
// [3 2 1 1]
//     1.0000     0.0000
//     0.0000     5.0000
//     0.0000     6.0000
</code>```

You can look more details in our indexing tutorial.

Title: Scatter/Gather like Numpy in ArrayFire

Body:
I want to scatter and gather elements from an array X at specific indices along one axis.
So given an array of indices idx, I want to select the idx(0)th element along the 0th column, the idx(1)th element along the 1st column, etc..

In Numpy, the following statement:

X = np.array([[1, 2, 3], [4, 5, 6]])
print(X[[0, 1, 1], range(3)])

prints [1, 5, 6].

Furthermore, I can do this process in reverse:

Y = np.zeros((2, 3))
Y[[0, 1, 1], range(3)] = [1, 5, 6]
print(Y)

This will print

[[1. 0. 0.]
 [0. 5. 6.]]

However, when I try to replicate this behavior in ArrayFire:

float elements[] = {1, 2, 3, 4, 5, 6};
af::array X = af::array(3, 2, elements);
int idx_elements[] = {0, 1, 1};
af::array idx = af::array(3, idx_elements);
af::print("", X(af::span, idx));

I get an array of shape [3, 3, 1, 1] with the elements

1.0000     4.0000     4.0000
2.0000     5.0000     5.0000
3.0000     6.0000     6.0000

So how can I achieve the desired numpy-like behavior for scattering and gathering elements in ArrayFire?

To perform the gather operation on a matrix, I can extract the diagonal of the resulting matrix but that may not work in the multidimensional case and it doesn't work in the other (scatter) direction.

Body:
X
[3 2 1 1]
    1.0000     4.0000
    2.0000     5.0000
    3.0000     6.0000

idx
[3 1 1 1]
         0
         1
         1

ArrayFire does Cartesian product when af::array are involved. Hence, the output.
Please see the below indices because of that.

Col\Row   0       1        1   from array

   0    (0, 0)  (0,1)  (0, 1)
   1    (1, 0)  (1,1)  (1, 1)
   2    (2, 0)  (2,1)  (2, 1)
   ^
   ^ from sequence

Thus, the output of X(af::span, idx)) is a 3x3 matrix.

To gather elements based on coordinates, you would need different function
approx2. Note that this function takes it's indices as floating point arrays only.

float idx_elements[] = {0, 1, 1}; // changed the idx to floats
af::array colIdx = af::array(3, idx_elements);
af::array rowIdx = af::iota(3); // same effect as span

af::array out = approx2(X, rowIdx, colIdx);
af_print(out);
// out
// [3 1 1 1]
//     1.0000
//     5.0000
//     6.0000

To set the values for given indices, you would have to flatten the array because of very reason
that array::operator() considers cartesian product when af::array is involved.

af::array A = af::constant(0, 3, 2); // same size as X
af::array B = af::flat(A); // flatten the array, this involves meta data modification only

B(rowIdx + 3 * colIdx) = out; // use row & col indices to fetch linear indices
// rowIdx + 3 * colIdx
// [3 1 1 1]
//     0.0000
//     4.0000
//     5.0000

B = moddims(B, A.dims()); // reset the dimensions to original A dims

af_print(B);
// B
// [3 2 1 1]
//     1.0000     0.0000
//     0.0000     5.0000
//     0.0000     6.0000

You can look more details in our indexing tutorial.


问:
Customize .NET framework generated exception messages?
I was wondering if there was a reasonable way to customize messages on exceptions that are thrown by the .NET framework?  Below is a chunk of code that I write often, in many different scenarios to achieve the effect of providing reasonable exception messages to my users.

```<code>public string GetMetadata(string metaDataKey)
{
  // As you can see, I am doing what the dictionary itself will normally do, but my exception message has some context, and is therefore more descriptive of the actual problem.
  if (!_Metadata.ContainsKey(metaDataKey))
  {
    throw new KeyNotFoundException(string.Format("There is no metadata that contains the key '{0}'!", metaDataKey));
  }

  // This will throw a 'KeyNotFoundException' in normal cases, which I want, but the message "The key is not present in the dictionary" is not very informative.  This is the exception who's message I wish to alter.
  string val = _Metadata[metaDataKey].TrimEnd();
  return val;
}
</code>```

As you can see, I am essentially producing duplicate code just to use a different (better) message.

Edit:

What I am looking for, essentially is something like this:

```<code>KeyNotFoundException.SetMessage("this is my custom message!")
{
// OK, now this will send off the message I want when the exception appears!
// Now I can avoid all of that silly boilerplate!
string val = _Metadata[metaDataKey].TrimEnd();
}
</code>```

At any rate, i don't think that such a feature exists, but if it did I would be very pleased indeed.  Has anyone tackled this type of problem before?  It's looking like I am going to wind up needed some type of extension method in the end...

答: Unless I'm missing something in your question, this is exactly what you're supposed to be doing.  I'm pretty sure every exception includes an overload that takes string message as a parameter.  If you want to provide information above and beyond the "default" provided by .NET, you need to set the specific message.

Body:
I was wondering if there was a reasonable way to customize messages on exceptions that are thrown by the .NET framework?  Below is a chunk of code that I write often, in many different scenarios to achieve the effect of providing reasonable exception messages to my users.

public string GetMetadata(string metaDataKey)
{
  // As you can see, I am doing what the dictionary itself will normally do, but my exception message has some context, and is therefore more descriptive of the actual problem.
  if (!_Metadata.ContainsKey(metaDataKey))
  {
    throw new KeyNotFoundException(string.Format("There is no metadata that contains the key '{0}'!", metaDataKey));
  }

  // This will throw a 'KeyNotFoundException' in normal cases, which I want, but the message "The key is not present in the dictionary" is not very informative.  This is the exception who's message I wish to alter.
  string val = _Metadata[metaDataKey].TrimEnd();
  return val;
}

As you can see, I am essentially producing duplicate code just to use a different (better) message.

Edit:

What I am looking for, essentially is something like this:

KeyNotFoundException.SetMessage("this is my custom message!")
{
// OK, now this will send off the message I want when the exception appears!
// Now I can avoid all of that silly boilerplate!
string val = _Metadata[metaDataKey].TrimEnd();
}

At any rate, i don't think that such a feature exists, but if it did I would be very pleased indeed.  Has anyone tackled this type of problem before?  It's looking like I am going to wind up needed some type of extension method in the end...


问:
Getting error while installing `pandas-profiling`
Need Help I want to install pandas-profiling in python 3.8.2 but when i try to install the package i am facing errors.

pip install pandas-profiling

I am getting this error

error: Microsoft Visual C++ 14.0 is required. Get it with "Microsoft Visual C++ Build Tools": https://visualstudio.microsoft.com/downloads/
    ----------------------------------------
ERROR: Command errored out with exit status 1: 'f:\data analaysis\fbi crime rate\newenv\scripts\python.exe' -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\\Users\\Manish\\AppData\\Local\\Temp\\pip-install-vz1xsz_s\\astropy\\setup.py'"'"'; __file__='"'"'C:\\Users\\Manish\\AppData\\Local\\Temp\\pip-install-vz1xsz_s\\astropy\\setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' install --record 'C:\Users\Manish\AppData\Local\Temp\pip-record-011lkvam\install-record.txt' --single-version-externally-managed --compile --install-headers 'f:\data analaysis\fbi crime rate\newenv\include\site\python3.8\astropy' Check the logs for full command output.

答:
Visual Studio changed the Build Tools from being C++ specific in late 2017. Thus newer Visual Studio versions work in place of older versions.

Install using any ONE of these choices:

Microsoft Build Tools for Visual Studio.

Alternative link to Microsoft Build Tools for Visual Studio.

Offline installer: vs_buildtools.exe

Visual C++ 2015 Build Tools

Select: Workloads → Desktop development with C++, then for Individual Components, select only:

Windows 10 SDK

C++ x64/x86 build tools

The build tools allow using MSVC “cl.exe” C / C++ compiler from the command line.

Why this is necessary?

Windows Python needs Visual C++ libraries installed via the SDK to build code, such as via setuptools.extension.Extension or numpy.distutils.core.Extension. For example, building f2py modules in Windows with Python requires Visual C++ SDK as installed above. On Linux and Mac, the C++ libraries are installed with the compiler.


问:
Can't calculate total price > 30

For the order items table, get the items for order #6 where the total price is greater than 30

```<code>USE sql_store;

{ SELECT order_id, product_id,quantity, unit_price,
quantity*unit_price AS total_price

FROM order_items
WHERE order_id = 6 AND total_price > 30

}
</code>```

ERROR CODE:

答:
Karl was nearly right;

```<code>SELECT order_id
     , product_id
     , quantity
     , unit_price
     , quantity*unit_price subtotal
  FROM order_items
 WHERE order_id = 6
   AND quantity*unit_price > 30
</code>```

You could also say HAVING subtotal > 30, but this would be less efficient

Title: Can't calculate total price > 30

Body:
For the order items table, get the items for order #6 where the total price is greater than 30

USE sql_store;

{ SELECT order_id, product_id,quantity, unit_price,
quantity*unit_price AS total_price

FROM order_items
WHERE order_id = 6 AND total_price > 30

}

ERROR CODE:

Body:
Karl was nearly right;

SELECT order_id
     , product_id
     , quantity
     , unit_price
     , quantity*unit_price subtotal
  FROM order_items
 WHERE order_id = 6
   AND quantity*unit_price > 30

You could also say HAVING subtotal > 30, but this would be less efficient


问:
How to render in React an entire HTML string returned from an RSS feed request?
I have an app that gets RSS/Atom feeds in the backend (Ruby on Rails) and sends the feeds as JSON to the frontend. A parsed feed (obtained using a library such as simpleRSS or Feedjira in the backend) is an object with keys being things like title, summary, content, etc, and values being the associated strings.

I send the parsed feed to the frontend as JSON. Then I would like to render, specifically, the "content" of the feed in a React component. The content of a feed is a big string of HTML.

I tried to use JQuery to turn the string into an object of HTML elements, then turn it into an array, and then render the array:

```<code>var FeedItem = react.createClass({
  render: function() {
    var content = $(this.props.feed.content);
    content = Object.keys(content).map(function(key) {
      return content[key];
    });
    return (
      <div>
        {content}
      </div>
    )
  }
})
</code>```

I get the error:

```<code>Uncaught Error: Invariant Violation: Objects are not valid as a React child (found: [object HTMLDivElement]). If you meant to render a collection of children, use an array instead or wrap the object using createFragment(object) from the React add-ons. Check the render method of `FeedItem`.
</code>```

How do I render a big string of HTML of a whole page into a react component?

Here is an an example of a string of content, obtained from Google Analytics Blog (below is the content from a single feed obtained from the blog).

```<code>"<div dir=\"ltr\" style=\"text-align: left;\" trbidi=\"on\"><div style=\"-webkit-text-stroke-color: rgb(0, 0, 0); -webkit-text-stroke-width: initial; font-family: Arial; font-size: 12px; line-height: normal;\">When Google was a few years old, we wrote up a list of <a href=\"https://www.google.com/about/company/philosophy/\"><span style=\"-webkit-text-stroke-color: rgb(18, 85, 204); color: #1255cc;\">Ten things we know to be true</span></a>. The list includes items like “Focus on the user and all else will follow” as well as “Fast is better than slow.” It would be tough to say that much of the mobile web has adhered to these principles. Users often get frustrated by poor experiences in which sites load slowly or will lock up trying to load resources that clog their data connections.</div><div style=\"-webkit-text-stroke-color: rgb(0, 0, 0); -webkit-text-stroke-width: initial; font-family: Arial; font-size: 12px; line-height: normal; min-height: 14px;\"><br /></div><div style=\"-webkit-text-stroke-color: rgb(0, 0, 0); -webkit-text-stroke-width: initial; font-family: Arial; font-size: 12px; line-height: normal;\"><span style=\"-webkit-text-stroke-color: rgb(18, 85, 204); color: #1255cc; text-decoration: underline;\"><a href=\"https://www.ampproject.org/\">The Accelerated Mobile Pages Project</a></span> (AMP) is an open source initiative that aims to address these problems by enabling content to load instantaneously and provide a better web experience for all. AMP introduces a new format that is a flavor of HTML. It’s built to prioritize speed and a fantastic user experience. One way that AMP provides reliably good page loading performance is by restricting the ability to add custom JavaScript to pages and instead relying on built in, reusable components.</div><div style=\"-webkit-text-stroke-color: rgb(0, 0, 0); -webkit-text-stroke-width: initial; font-family: Arial; font-size: 12px; line-height: normal; min-height: 14px;\"><br /></div><div style=\"-webkit-text-stroke-color: rgb(0, 0, 0); -webkit-text-stroke-width: initial; font-family: Arial; font-size: 12px; line-height: normal;\">Today, the AMP team <a href=\"https://amphtml.wordpress.com/2016/01/28/analytics-and-measurement-for-amp-pages\"><span style=\"-webkit-text-stroke-color: rgb(18, 85, 204); color: #1255cc;\">announced the launch of an analytics component</span></a> that will enable measurement on AMP pages. The Google Analytics team is committed to helping our users measure their content wherever it appears. So, for publishers looking to use AMP to provide an improved user experience, we’ve released Google Analytics measurement capabilities for Accelerated Mobile Pages. AMP support in Google Analytics makes it easy to identify your best content and optimize your user experience.</div><div style=\"-webkit-text-stroke-color: rgb(0, 0, 0); -webkit-text-stroke-width: initial; font-family: Arial; font-size: 12px; line-height: normal; min-height: 14px;\"><br /></div><div style=\"-webkit-text-stroke-color: rgb(0, 0, 0); -webkit-text-stroke-width: initial; font-family: Arial; font-size: 12px; line-height: normal;\"><b>How Google Analytics Support Works</b></div><div style=\"-webkit-text-stroke-color: rgb(0, 0, 0); -webkit-text-stroke-width: initial; font-family: Arial; font-size: 12px; line-height: normal; min-height: 14px;\"><br /></div><div style=\"-webkit-text-stroke-color: rgb(0, 0, 0); -webkit-text-stroke-width: initial; font-family: Arial; font-size: 12px; line-height: normal;\">Analytics on AMP is handled by an open source, reusable component that the Google Analytics team helped build. The <amp-analytics> component can be configured with Google Analytics specific configuration parameters to record pageviews, events, and even custom dimensions. That configuration works hand in hand with a global event listener that automatically detects triggers like button presses. As a result, there’s no need to scatter custom JavaScript throughout your page to detect actions that should trigger events and hits. Instead, you can define which actions should trigger hits within the configuration section and let the magic of AMP do the rest.</div><div style=\"-webkit-text-stroke-color: rgb(0, 0, 0); -webkit-text-stroke-width: initial; font-family: Arial; font-size: 12px; line-height: normal; min-height: 14px;\"><br /></div><div style=\"-webkit-text-stroke-color: rgb(0, 0, 0); -webkit-text-stroke-width: initial; font-family: Arial; font-size: 12px; line-height: normal;\"><b>How to Get Started</b></div><div style=\"-webkit-text-stroke-color: rgb(0, 0, 0); -webkit-text-stroke-width: initial; font-family: Arial; font-size: 12px; line-height: normal; min-height: 14px;\"><br /></div><div style=\"-webkit-text-stroke-color: rgb(0, 0, 0); -webkit-text-stroke-width: initial; font-family: Arial; font-size: 12px; line-height: normal;\">Before you get started with AMP Analytics, you’ll need to get started with AMP itself. The <a href=\"http://ampproject.org/\"><span style=\"-webkit-text-stroke-color: rgb(18, 85, 204); color: #1255cc;\">AMP website</span></a> contains <a href=\"https://www.ampproject.org/docs/get_started/create_page.html\"><span style=\"-webkit-text-stroke-color: rgb(18, 85, 204); color: #1255cc;\">a great introduction to getting started</span></a>. Once you have an AMP page up, it’s time to start thinking about how you’d like to measure its performance. </div><div style=\"-webkit-text-stroke-color: rgb(0, 0, 0); -webkit-text-stroke-width: initial; font-family: Arial; font-size: 12px; line-height: normal; min-height: 14px;\"><br /></div><div style=\"-webkit-text-stroke-color: rgb(0, 0, 0); -webkit-text-stroke-width: initial; font-family: Arial; font-size: 12px; line-height: normal;\">We recommend that you use a separate Google Analytics property to measure your AMP pages. AMP is a new technology that’s going to mature over time. As such, some of the functionality that you’re used to in web analytics won’t immediately be available in AMP analytics right away. AMP pages can appear in multiple contexts, including through different syndication caches. Because of that, a single user that visits an AMP version of a page and a HTML version of a page can end up being treated as two distinct users. Using a separate Google Analytics property to measure AMP pages makes it easier to handle these issues.</div><div style=\"-webkit-text-stroke-color: rgb(0, 0, 0); -webkit-text-stroke-width: initial; font-family: Arial; font-size: 12px; line-height: normal; min-height: 14px;\"><br /></div><div style=\"-webkit-text-stroke-color: rgb(0, 0, 0); -webkit-text-stroke-width: initial; font-family: Arial; font-size: 12px; line-height: normal;\">Once you have your AMP page and new Google Analytics property set up, you’ll want to reference <a href=\"https://support.google.com/analytics/answer/6343176\"><span style=\"-webkit-text-stroke-color: rgb(18, 85, 204); color: #1255cc;\">the requirements for using Analytics on AMP pages</span></a> as well as the <a href=\"https://developers.google.com/analytics/devguides/collection/amp-analytics/\"><span style=\"-webkit-text-stroke-color: rgb(18, 85, 204); color: #1255cc;\">developers guide for instrumenting measurement</span></a>.</div><div style=\"-webkit-text-stroke-color: rgb(0, 0, 0); -webkit-text-stroke-width: initial; font-family: Arial; font-size: 12px; line-height: normal; min-height: 14px;\"><br /></div><div style=\"-webkit-text-stroke-color: rgb(0, 0, 0); -webkit-text-stroke-width: initial; font-family: Arial; font-size: 12px; line-height: normal;\"><b>What’s Next</b></div><div style=\"-webkit-text-stroke-color: rgb(0, 0, 0); -webkit-text-stroke-width: initial; font-family: Arial; font-size: 12px; line-height: normal; min-height: 14px;\"><br /></div><div style=\"-webkit-text-stroke-color: rgb(0, 0, 0); -webkit-text-stroke-width: initial; font-family: Arial; font-size: 12px; line-height: normal;\">Multiple technology partners, including Google Search, Twitter, Pinterest, and LinkedIn have announced that they’ll start surfacing AMP pages in the coming months. The Google Analytics team is excited to support AMP from day one and look forward to growing our offering as AMP’s capabilities expand.</div><div style=\"-webkit-text-stroke-color: rgb(0, 0, 0); -webkit-text-stroke-width: initial; font-family: Arial; font-size: 12px; line-height: normal; min-height: 14px;\"><br /></div><br /><div style=\"-webkit-text-stroke-color: rgb(0, 0, 0); -webkit-text-stroke-width: initial; font-family: Arial; font-size: 12px; line-height: normal;\"><i>Posted by Dan Cary, Product Manager and Avi Mehta, Software Engineer</i></div></div><div class=\"feedflare\">\n<a href=\"http://feeds.feedburner.com/~ff/blogspot/tRaA?a=LxtIVDKQw_w:GPFyrUXb_LI:yIl2AUoC8zA\"><img src=\"http://feeds.feedburner.com/~ff/blogspot/tRaA?d=yIl2AUoC8zA\" border=\"0\"></img></a> <a href=\"http://feeds.feedburner.com/~ff/blogspot/tRaA?a=LxtIVDKQw_w:GPFyrUXb_LI:-BTjWOF_DHI\"><img src=\"http://feeds.feedburner.com/~ff/blogspot/tRaA?i=LxtIVDKQw_w:GPFyrUXb_LI:-BTjWOF_DHI\" border=\"0\"></img></a>\n</div><img src=\"http://feeds.feedburner.com/~r/blogspot/tRaA/~4/LxtIVDKQw_w\" height=\"1\" width=\"1\" alt=\"\"/>"
</code>```

答:
You can use dangerouslySetInnerHTML but we aware of the risks (possible cross-site scripting (XSS) attack). You only need to change your return statement to:

```<code>return <div dangerouslySetInnerHTML={{ __html: content }}></div>
</code>```

Body:
I have an app that gets RSS/Atom feeds in the backend (Ruby on Rails) and sends the feeds as JSON to the frontend. A parsed feed (obtained using a library such as simpleRSS or Feedjira in the backend) is an object with keys being things like title, summary, content, etc, and values being the associated strings.

I send the parsed feed to the frontend as JSON. Then I would like to render, specifically, the "content" of the feed in a React component. The content of a feed is a big string of HTML.

I tried to use JQuery to turn the string into an object of HTML elements, then turn it into an array, and then render the array:

var FeedItem = react.createClass({
  render: function() {
    var content = $(this.props.feed.content);
    content = Object.keys(content).map(function(key) {
      return content[key];
    });
    return (

        {content}

    )
  }
})

I get the error:

Uncaught Error: Invariant Violation: Objects are not valid as a React child (found: [object HTMLDivElement]). If you meant to render a collection of children, use an array instead or wrap the object using createFragment(object) from the React add-ons. Check the render method of `FeedItem`.

How do I render a big string of HTML of a whole page into a react component?

Here is an an example of a string of content, obtained from Google Analytics Blog (below is the content from a single feed obtained from the blog).

"

When Google was a few years old, we wrote up a list of Ten things we know to be true. The list includes items like “Focus on the user and all else will follow” as well as “Fast is better than slow.” It would be tough to say that much of the mobile web has adhered to these principles. Users often get frustrated by poor experiences in which sites load slowly or will lock up trying to load resources that clog their data connections.

The Accelerated Mobile Pages Project (AMP) is an open source initiative that aims to address these problems by enabling content to load instantaneously and provide a better web experience for all. AMP introduces a new format that is a flavor of HTML. It’s built to prioritize speed and a fantastic user experience. One way that AMP provides reliably good page loading performance is by restricting the ability to add custom JavaScript to pages and instead relying on built in, reusable components.

Today, the AMP team announced the launch of an analytics component that will enable measurement on AMP pages. The Google Analytics team is committed to helping our users measure their content wherever it appears. So, for publishers looking to use AMP to provide an improved user experience, we’ve released Google Analytics measurement capabilities for Accelerated Mobile Pages. AMP support in Google Analytics makes it easy to identify your best content and optimize your user experience.

How Google Analytics Support Works

Analytics on AMP is handled by an open source, reusable component that the Google Analytics team helped build. The <amp-analytics> component can be configured with Google Analytics specific configuration parameters to record pageviews, events, and even custom dimensions. That configuration works hand in hand with a global event listener that automatically detects triggers like button presses. As a result, there’s no need to scatter custom JavaScript throughout your page to detect actions that should trigger events and hits. Instead, you can define which actions should trigger hits within the configuration section and let the magic of AMP do the rest.

How to Get Started

Before you get started with AMP Analytics, you’ll need to get started with AMP itself. The AMP website contains a great introduction to getting started. Once you have an AMP page up, it’s time to start thinking about how you’d like to measure its performance.

We recommend that you use a separate Google Analytics property to measure your AMP pages. AMP is a new technology that’s going to mature over time. As such, some of the functionality that you’re used to in web analytics won’t immediately be available in AMP analytics right away. AMP pages can appear in multiple contexts, including through different syndication caches. Because of that, a single user that visits an AMP version of a page and a HTML version of a page can end up being treated as two distinct users. Using a separate Google Analytics property to measure AMP pages makes it easier to handle these issues.

Once you have your AMP page and new Google Analytics property set up, you’ll want to reference the requirements for using Analytics on AMP pages as well as the developers guide for instrumenting measurement.

What’s Next

Multiple technology partners, including Google Search, Twitter, Pinterest, and LinkedIn have announced that they’ll start surfacing AMP pages in the coming months. The Google Analytics team is excited to support AMP from day one and look forward to growing our offering as AMP’s capabilities expand.

Posted by Dan Cary, Product Manager and Avi Mehta, Software Engineer

\n \n
"

Body:
You can use dangerouslySetInnerHTML but we aware of the risks (possible cross-site scripting (XSS) attack). You only need to change your return statement to:

return <div dangerouslySetInnerHTML={{ __html: content }}></div>


问:
List comprehention with 2 variable
Is there any way to use list comprehension in this case ?

```<code>l=[]
for i in range(-1,2):
    for j in range(-1,2):
        l.append([i,j])
</code>```

Output:

```<code>[[-1, -1], [-1, 0], [-1, 1], [0, -1], [0, 0], [0, 1], [1, -1], [1, 0], [1, 1]]
</code>```

Title: List comprehention with 2 variable

Body:
Is there any way to use list comprehension in this case ?

l=[]
for i in range(-1,2):
    for j in range(-1,2):
        l.append([i,j])

Output:

[[-1, -1], [-1, 0], [-1, 1], [0, -1], [0, 0], [0, 1], [1, -1], [1, 0], [1, 1]]

Body:
You can use:

l = [[i, j] for i in range(-1, 2) for j in range(-1, 2)]

Result:

# print(l)
[[-1, -1], [-1, 0], [-1, 1], [0, -1], [0, 0], [0, 1], [1, -1], [1, 0], [1, 1]]


问:
"Can't bind to 'ngModel' since it isn't a known property of 'input' "
My project was completely running fine but I don't how, when, Where What happened that it's giving error

Can't bind to 'ngModel' since it isn't a known property of 'input'

and also

If 'mat-error' is an Angular component, then verify that it is part of this module.

If 'mat-error' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to the '@NgModule.schemas' of this component to suppress this message.

I have already imported FormsModule and it wasn't giving error before but I don't why it suddenly started giving this error.

Also include into imports array

Error showing. I have already inserted the angular material as well as all the necessary imports

Also included FormsModule in app.component.spec.ts

答:
Looks like you have lazy loaded modules, for them you need to import FormsModule in the related module, not in the app.module. try to import them in EventRegiterModule.

If it's Angular 2+ you should use [ngModel]="Email_id" (ngModelChange)="Email_id = $event" instead of [(ngModel)]="Email_id"


问:
How can I "think OOP" when using R?
I am a statistics graduate student who works a lot with R.  I am familiar with OOP in other programming contexts.  I even see its use in various statistical packages that define new classes for storing data.

At this stage in my graduate career, I am usually coding some algorithm for some class assignment--something that takes in raw data and gives some kind of output.  I would like to make it easier to reuse code, and establish good coding habits, especially before I move on to more involved research.  Please offer some advice on how to "think OOP" when doing statistical programming in R.

答:
You may want to check these links out: first one, second one.

And if you want to see some serious OO code in R, read manual page for ReferenceClasses (so called R5 object orientation), and take a look at Rook package, since it relies heavily on ReferenceClasses. BTW, Rook is a good example of reasonable usage of R5 in R coding. Previous experience with JAVA or C++ could be helpful, since R5 method dispatching differs from S3. Actually, S3 OO is very primitive, since the actuall "class" is saved as an object attribute, so you can change it quite easily.

```<code>S3: <method>.<class>(<object>)
R5: <object>$<method>
</code>```

Anyway, if you can grab a copy, I recommend: "R in a Nutshell", chapter 10.

Title: How can I "think OOP" when using R?

Body:
You may want to check these links out: first one, second one.

And if you want to see some serious OO code in R, read manual page for ReferenceClasses (so called R5 object orientation), and take a look at Rook package, since it relies heavily on ReferenceClasses. BTW, Rook is a good example of reasonable usage of R5 in R coding. Previous experience with JAVA or C++ could be helpful, since R5 method dispatching differs from S3. Actually, S3 OO is very primitive, since the actuall "class" is saved as an object attribute, so you can change it quite easily.

S3: <method>.<class>(<object>)
R5: <object>$<method>

Anyway, if you can grab a copy, I recommend: "R in a Nutshell", chapter 10.


问:
Why java.util.logging is not writing logs to file?
I have prepared a logger for a class.
Code is as follows:

public class MyClass {

    FileHandler handler;
    Logger logger;

    // SINGLETON PATTERN
    private static final MyClass SINGLE_INSTANCE = new MyClass();
    private MyClass() {

      try {
        handler = new FileHandler("MyClass.log", false);
        logger = Logger.getLogger(MyClass.class.getName());
        handler.setLevel(Level.ALL);
        logger.setLevel(Level.ALL);
      } catch (IOException ioe) {
        System.err.println("Initialization of logger threw");
        ioe.printStackTrace();
        throw new RuntimeException("Initialization of logger threw", ioe);
      }

    }
    public static MyClass getInstance() {
      return SINGLE_INSTANCE;
    }

    public void doStuff() {

        Logger.getLogger(MyClass.class.getName()).log(Level.FINE, "Log Text");

    }

}
```

To enable the logging for Level.FINE I have invoked method .setLevel both on logger and on handler. But when I execute the code and invoke doStuff() no output appears on the log.

Notes that could be relevant:

The file is there but it has size 0.

I am stopping the program with CONTROL+C (it is a console application).

答:
Add Handler </p>

```<code>     logger = Logger.getLogger(MyClass.class.getName());
     logger.addHandler(handler);
</code>```

Body:
I have prepared a logger for a class.
Code is as follows:

public class MyClass {

    FileHandler handler;
    Logger logger;

    // SINGLETON PATTERN
    private static final MyClass SINGLE_INSTANCE = new MyClass();
    private MyClass() {

      try {
        handler = new FileHandler("MyClass.log", false);
        logger = Logger.getLogger(MyClass.class.getName());
        handler.setLevel(Level.ALL);
        logger.setLevel(Level.ALL);
      } catch (IOException ioe) {
        System.err.println("Initialization of logger threw");
        ioe.printStackTrace();
        throw new RuntimeException("Initialization of logger threw", ioe);
      }

    }
    public static MyClass getInstance() {
      return SINGLE_INSTANCE;
    }

    public void doStuff() {

        Logger.getLogger(MyClass.class.getName()).log(Level.FINE, "Log Text");

    }

}

To enable the logging for Level.FINE I have invoked method .setLevel both on logger and on handler. But when I execute the code and invoke doStuff() no output appears on the log.

Notes that could be relevant:

The file is there but it has size 0.

I am stopping the program with CONTROL+C (it is a console application).

Body:
Add Handler

     logger = Logger.getLogger(MyClass.class.getName());
     logger.addHandler(handler);


问:
How to return the in Widgets from FutureBuilder
```<code> alreadyJoinedArray = [3KpUkg7flNLHF5RkMoij, 1qFqcGGeSGnoQO2BMrue];
 FutureBuilder(
    future: getData(),
    builder: (_, AsyncSnapshot<List<DocumentSnapshot>> snapshot) {
      if (snapshot.connectionState == ConnectionState.waiting) {
        return Padding(
          padding: const EdgeInsets.only(
            top: 50,
          ),
          child: Column(
            mainAxisAlignment: MainAxisAlignment.spaceEvenly,
            children: <Widget>[
              Center(
                child: SpinKitCircle(
                  color: Color.fromRGBO(91, 74, 127, 10),
                  size: 50.0,
                ),
              ),
            ],
          ),
        );
      } else {
        alreadyJoinedArray.forEach((gameids) {
            return RaisedButton(onpressed: () {});
        });

      }
    },
  ),
</code>```

i am getting an error how to solve this problem
The following assertion was thrown building FutureBuilder>(dirty, state: _FutureBuilderState>#2437c):
A build function returned null.

According to my logic it have to return 2 buttons but i am getting the error

答:
You can use a ListView.builder rather than that foreach loop. Try like this,</p>

```<code>return ListView.builder(
itemCount: alreadyJoinedArray.length,
itemBuilder:( context, index){
    return RaisedButton( child: Text("Button $index"), onPressed: (){});
  }
);
</code>```

Body:
 alreadyJoinedArray = [3KpUkg7flNLHF5RkMoij, 1qFqcGGeSGnoQO2BMrue];
 FutureBuilder(
    future: getData(),
    builder: (_, AsyncSnapshot<List<DocumentSnapshot>> snapshot) {
      if (snapshot.connectionState == ConnectionState.waiting) {
        return Padding(
          padding: const EdgeInsets.only(
            top: 50,
          ),
          child: Column(
            mainAxisAlignment: MainAxisAlignment.spaceEvenly,
            children: <Widget>[
              Center(
                child: SpinKitCircle(
                  color: Color.fromRGBO(91, 74, 127, 10),
                  size: 50.0,
                ),
              ),
            ],
          ),
        );
      } else {
        alreadyJoinedArray.forEach((gameids) {
            return RaisedButton(onpressed: () {});
        });

      }
    },
  ),

i am getting an error how to solve this problem
The following assertion was thrown building FutureBuilder>(dirty, state: _FutureBuilderState>#2437c):
A build function returned null.

According to my logic it have to return 2 buttons but i am getting the error

Body:
You can use a ListView.builder rather than that foreach loop. Try like this,

return ListView.builder(
itemCount: alreadyJoinedArray.length,
itemBuilder:( context, index){
    return RaisedButton( child: Text("Button $index"), onPressed: (){});
  }
);


问:
Unable to add an array index
I would like to allocate names for the index in an array while using for loop. how can i achieve this. please guide me.

```<code>// using in a http response
   for (let i = 0; i <= 6; i++) {
            this.sf.push({f(i) : // do something)
          };
</code>```

i want to get something like

```<code>f0: 1,
f1: 5,
f2: 9
</code>```

答:
You will need to transform the array into an object. Here is a sample code:

let test = [1,5,9,10,15,25];
let obj  = {};
for (let i = 0; i<test.length; i++) {
  obj["f" + i] = test[i];
}
console.log(JSON.stringify(obj)); // prints {"f0":1, "f1":5, "f2":9, "f3":10, "f4":15, "f5":25}```

Title: Unable to add an array index

Body:
I would like to allocate names for the index in an array while using for loop. how can i achieve this. please guide me.

// using in a http response
   for (let i = 0; i <= 6; i++) {
            this.sf.push({f(i) : // do something)
          };

i want to get something like

f0: 1,
f1: 5,
f2: 9


问:
How to reset “Reserved Space for Replicas” without restart Hadoop services
How to find why "Reserved Space for Replicas" constantly increasing and how to limit space for this type of cache?

We found that the "Reserved Space for Replicas" relate to "Non DFS" space and it can increase constantly up to rebooting Data Node-s. We didn't find how to limit space allocated for the "Reserved Space for Replicas"  :(

We thought that dfs.datanode.du.reserved can control "Reserved Space for Replicas" but it is not.

So our question is How to control a space size allocated for the "Reserved Space for Replicas" in Hadoop ?

答:
For people who faced with that type of problem. First of all you should understand the nature of the problem. To do that please read the description of the following issues:

https://issues.apache.org/jira/browse/HDFS-8072

https://issues.apache.org/jira/browse/HDFS-9530

https://issues.apache.org/jira/browse/HDFS-6489

The following links will be useful to understand what block replica is:

https://blog.cloudera.com/understanding-hdfs-recovery-processes-part-1/

https://blog.cloudera.com/understanding-hdfs-recovery-processes-part-2/

Solutions

Find the wrong software which often broke connection with Hadoop during the write or append processes

Try to change replication policy (risky)

Update Hadoop up to late version

You can't reset “Reserved Space for Replicas” without restart Hadoop services!


问:
Flutter Duplicate pageview widgets
The error is generated every time I click the shopping cart and then return to the product, the views are duplicated and when I click return the duplicate pages appear
I do not know why the page is duplicated each time I browse and then return to the previous page, here I leave the code of

Error Image

```<code>Widget build(BuildContext context) {
return SizedBox(
  width: 60,
  height: 60,
  child: RaisedButton(
    padding: EdgeInsets.all(0),
    color: Theme.of(context).accentColor,
    shape: StadiumBorder(),
    onPressed: () {
      if (currentUser.value.apiToken != null) {
        Navigator.of(context)
            .pushNamed('/Cart', arguments: RouteArgument(param: '/Product', id: widget.product.id));
      } else {
        Navigator.of(context).pushNamed('/Login');
      }
    },
    child: Stack(
      alignment: AlignmentDirectional.bottomEnd,
      children: <Widget>[
        Icon(
          Icons.shopping_cart,
          color: this.widget.iconColor,
          size: 28,
        ),
        Container(
          child: Text(
            _con.cartCount.toString(),
            textAlign: TextAlign.center,
            style: Theme.of(context).textTheme.caption.merge(
                  TextStyle(color: Theme.of(context).primaryColor, fontSize: 10),
                ),
          ),
          padding: EdgeInsets.all(0),
          decoration:
              BoxDecoration(color: this.widget.labelColor, borderRadius: BorderRadius.all(Radius.circular(10))),
          constraints: BoxConstraints(minWidth: 15, maxWidth: 15, minHeight: 15, maxHeight: 15),
        ),
      ],
    ),
  ),
);
</code>```

}
}

cart code.

```<code> void initState() {
_con.listenForCarts();
_isButtonDisabled = false;
super.initState();
</code>```

}

```<code> Widget build(BuildContext context) {
return WillPopScope(
  onWillPop: () async => false,
  child: Scaffold(
    key: _con.scaffoldKey,
    appBar: AppBar(
      automaticallyImplyLeading: false,
      leading: IconButton(
        onPressed: () {
          if (widget.routeArgument.param == '/Product') {
            Navigator.of(context).pushReplacementNamed('/Product', arguments: RouteArgument(id: widget.routeArgument.id));
          } else {
            Navigator.of(context).pushReplacementNamed('/Pages', arguments: 2);
          }
        },
        icon: Icon(Icons.arrow_back),
        color: Theme.of(context).hintColor,
      ),
      backgroundColor: Colors.transparent,
      elevation: 0,
      centerTitle: true,
      title: Text(
        S.of(context).cart,
        style: Theme.of(context).textTheme.headline6.merge(TextStyle(letterSpacing: 1.3)),
      ),
    ),
    body: RefreshIndicator(
      onRefresh: _con.refreshCarts,
      child: _con.carts.isEmpty
          ? EmptyCartWidget()
          : Stack(
              fit: StackFit.expand,
              children: <Widget>[
                Container(
                  margin: EdgeInsets.only(bottom: 150),
                  padding: EdgeInsets.only(bottom: 15),
                  child: SingleChildScrollView(
                    padding: EdgeInsets.symmetric(vertical: 10),
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      mainAxisAlignment: MainAxisAlignment.start,
                      mainAxisSize: MainAxisSize.max,
                      children: <Widget>[
                        Padding(
                          padding: const EdgeInsets.only(left: 20, right: 10),
                          child: ListTile(
                            contentPadding: EdgeInsets.symmetric(vertical: 0),
                            leading: Icon(
                              Icons.shopping_cart,
                              color: Theme.of(context).hintColor,
                            ),
                            title: Text(
                              S.of(context).shopping_cart,
                              maxLines: 1,
                              overflow: TextOverflow.ellipsis,
                              style: Theme.of(context).textTheme.headline4,
                            ),
                            subtitle: Text(
                              S.of(context).verify_your_quantity_and_click_checkout,
                              maxLines: 1,
                              overflow: TextOverflow.ellipsis,
                              style: Theme.of(context).textTheme.caption,
                            ),
                          ),
                        ),
                        ListView.separated(
                          padding: EdgeInsets.symmetric(vertical: 15),
                          scrollDirection: Axis.vertical,
                          shrinkWrap: true,
                          primary: false,
                          itemCount: _con.carts.length,
                          separatorBuilder: (context, index) {
                            return SizedBox(height: 15);
                          },
                          itemBuilder: (context, index) {
                            return CartItemWidget(
                              cart: _con.carts.elementAt(index),
                              heroTag: 'cart',
                              increment: () {
                                _con.incrementQuantity(_con.carts.elementAt(index));
                              },
                              decrement: () {
                                _con.decrementQuantity(_con.carts.elementAt(index));
                              },
                              onDismissed: () {
                                _con.removeFromCart(_con.carts.elementAt(index));
                              },
                            );
                          },
                        ),
                      ],
                    ),
                  ),
                ),
                Positioned(
                  bottom: 0,
                  child: Container(
                    height: 185,
                    padding: EdgeInsets.symmetric(horizontal: 20, vertical: 15),
                    decoration: BoxDecoration(
                        color: Theme.of(context).primaryColor,
                        borderRadius: BorderRadius.only(topRight: Radius.circular(20), topLeft: Radius.circular(20)),
                        boxShadow: [BoxShadow(color: Theme.of(context).focusColor.withOpacity(0.15), offset: Offset(0, -2), blurRadius: 5.0)]),
                    child: SizedBox(
                      width: MediaQuery.of(context).size.width - 40,
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.center,
                        mainAxisSize: MainAxisSize.max,
                        children: <Widget>[
                          Row(
                            children: <Widget>[
                              Expanded(
                                child: Text(
                                  S.of(context).subtotal,
                                  style: Theme.of(context).textTheme.bodyText1,
                                ),
                              ),
                              Helper.getPrice(_con.subTotal, context, style: Theme.of(context).textTheme.subtitle1)
                            ],
                          ),
                          SizedBox(height: 5),
                          Row(
                            children: <Widget>[
                              Expanded(
                                child: Text(
                                  S.of(context).delivery_fee,
                                  style: Theme.of(context).textTheme.bodyText1,
                                ),
                              ),
                              Helper.getPrice(_con.carts[0].product.market.deliveryFee, context, style: Theme.of(context).textTheme.subtitle1)
                            ],
                          ),
                          Row(
                            children: <Widget>[
                              Expanded(
                                child: Text(
                                  '${S.of(context).tax} (${_con.carts[0].product.market.defaultTax}%)',
                                  style: Theme.of(context).textTheme.bodyText1,
                                ),
                              ),
                              Helper.getPrice(_con.taxAmount, context, style: Theme.of(context).textTheme.subtitle1)
                            ],
                          ),
                          SizedBox(height: 10),
                          Stack(
                            fit: StackFit.loose,
                            alignment: AlignmentDirectional.centerEnd,
                            children: <Widget>[
                              SizedBox(
                                width: MediaQuery.of(context).size.width - 40,
                                child: FlatButton(
                                  onPressed: _isButtonDisabled ? null : () async {
                                    setState(() => _isButtonDisabled = !_isButtonDisabled);
                                    await _con.updateItemsProduct();
                                     List<Cart>  stockminimo = _con.carts.where((data) => data.quantity > int.tryParse(data.product.packageItemsCount)).toList();
                                      if(stockminimo.length == 0){
                                        if(_con.total < _con.carts[0].product.market.minimumamount){
                                            _showDialog();
                                        }else{
                                            _con.goCheckout(context);
                                        }
                                      }else{
                                         _onButtonPressed(stockminimo);
                                      }
                                     setState(() => _isButtonDisabled = !_isButtonDisabled);
                                  },
                                  disabledColor: Theme.of(context).focusColor.withOpacity(0.5),
                                  padding: EdgeInsets.symmetric(vertical: 14),
                                  color:
                                      !_con.carts[0].product.market.closed ? Theme.of(context).accentColor : Theme.of(context).focusColor.withOpacity(0.5),
                                  shape: StadiumBorder(),
                                  child: Text(
                                    S.of(context).checkout,
                                    textAlign: TextAlign.start,
                                    style: TextStyle(color: Theme.of(context).primaryColor),
                                  ),
                                ),
                              ),
                              Padding(
                                padding: const EdgeInsets.symmetric(horizontal: 20),
                                child: Helper.getPrice(
                                  _con.total,
                                  context,
                                  style: Theme.of(context).textTheme.headline4.merge(TextStyle(color: Theme.of(context).primaryColor)),
                                ),
                              )
                            ],
                          ),
                          SizedBox(height: 10),
                        ],
                      ),
                    ),
                  ),
                )
              ],
            ),
    ),
  ),
);
</code>```

}

答:
Try using PushReplacementNamed here:</p>

```<code>shape: StadiumBorder(),
onPressed: () {
  if (currentUser.value.apiToken != null) {
    Navigator.of(context)
        .pushNamed('/Cart', arguments: RouteArgument(param: '/Product', id: widget.product.id));
  } else {
    Navigator.of(context).pushNamed('/Login');
  }
},
</code>```

Title: Flutter Duplicate pageview widgets

Body:
The error is generated every time I click the shopping cart and then return to the product, the views are duplicated and when I click return the duplicate pages appear
I do not know why the page is duplicated each time I browse and then return to the previous page, here I leave the code of

Error Image

Widget build(BuildContext context) {
return SizedBox(
  width: 60,
  height: 60,
  child: RaisedButton(
    padding: EdgeInsets.all(0),
    color: Theme.of(context).accentColor,
    shape: StadiumBorder(),
    onPressed: () {
      if (currentUser.value.apiToken != null) {
        Navigator.of(context)
            .pushNamed('/Cart', arguments: RouteArgument(param: '/Product', id: widget.product.id));
      } else {
        Navigator.of(context).pushNamed('/Login');
      }
    },
    child: Stack(
      alignment: AlignmentDirectional.bottomEnd,
      children: <Widget>[
        Icon(
          Icons.shopping_cart,
          color: this.widget.iconColor,
          size: 28,
        ),
        Container(
          child: Text(
            _con.cartCount.toString(),
            textAlign: TextAlign.center,
            style: Theme.of(context).textTheme.caption.merge(
                  TextStyle(color: Theme.of(context).primaryColor, fontSize: 10),
                ),
          ),
          padding: EdgeInsets.all(0),
          decoration:
              BoxDecoration(color: this.widget.labelColor, borderRadius: BorderRadius.all(Radius.circular(10))),
          constraints: BoxConstraints(minWidth: 15, maxWidth: 15, minHeight: 15, maxHeight: 15),
        ),
      ],
    ),
  ),
);

}
}

cart code.

 void initState() {
_con.listenForCarts();
_isButtonDisabled = false;
super.initState();

}

 Widget build(BuildContext context) {
return WillPopScope(
  onWillPop: () async => false,
  child: Scaffold(
    key: _con.scaffoldKey,
    appBar: AppBar(
      automaticallyImplyLeading: false,
      leading: IconButton(
        onPressed: () {
          if (widget.routeArgument.param == '/Product') {
            Navigator.of(context).pushReplacementNamed('/Product', arguments: RouteArgument(id: widget.routeArgument.id));
          } else {
            Navigator.of(context).pushReplacementNamed('/Pages', arguments: 2);
          }
        },
        icon: Icon(Icons.arrow_back),
        color: Theme.of(context).hintColor,
      ),
      backgroundColor: Colors.transparent,
      elevation: 0,
      centerTitle: true,
      title: Text(
        S.of(context).cart,
        style: Theme.of(context).textTheme.headline6.merge(TextStyle(letterSpacing: 1.3)),
      ),
    ),
    body: RefreshIndicator(
      onRefresh: _con.refreshCarts,
      child: _con.carts.isEmpty
          ? EmptyCartWidget()
          : Stack(
              fit: StackFit.expand,
              children: <Widget>[
                Container(
                  margin: EdgeInsets.only(bottom: 150),
                  padding: EdgeInsets.only(bottom: 15),
                  child: SingleChildScrollView(
                    padding: EdgeInsets.symmetric(vertical: 10),
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      mainAxisAlignment: MainAxisAlignment.start,
                      mainAxisSize: MainAxisSize.max,
                      children: <Widget>[
                        Padding(
                          padding: const EdgeInsets.only(left: 20, right: 10),
                          child: ListTile(
                            contentPadding: EdgeInsets.symmetric(vertical: 0),
                            leading: Icon(
                              Icons.shopping_cart,
                              color: Theme.of(context).hintColor,
                            ),
                            title: Text(
                              S.of(context).shopping_cart,
                              maxLines: 1,
                              overflow: TextOverflow.ellipsis,
                              style: Theme.of(context).textTheme.headline4,
                            ),
                            subtitle: Text(
                              S.of(context).verify_your_quantity_and_click_checkout,
                              maxLines: 1,
                              overflow: TextOverflow.ellipsis,
                              style: Theme.of(context).textTheme.caption,
                            ),
                          ),
                        ),
                        ListView.separated(
                          padding: EdgeInsets.symmetric(vertical: 15),
                          scrollDirection: Axis.vertical,
                          shrinkWrap: true,
                          primary: false,
                          itemCount: _con.carts.length,
                          separatorBuilder: (context, index) {
                            return SizedBox(height: 15);
                          },
                          itemBuilder: (context, index) {
                            return CartItemWidget(
                              cart: _con.carts.elementAt(index),
                              heroTag: 'cart',
                              increment: () {
                                _con.incrementQuantity(_con.carts.elementAt(index));
                              },
                              decrement: () {
                                _con.decrementQuantity(_con.carts.elementAt(index));
                              },
                              onDismissed: () {
                                _con.removeFromCart(_con.carts.elementAt(index));
                              },
                            );
                          },
                        ),
                      ],
                    ),
                  ),
                ),
                Positioned(
                  bottom: 0,
                  child: Container(
                    height: 185,
                    padding: EdgeInsets.symmetric(horizontal: 20, vertical: 15),
                    decoration: BoxDecoration(
                        color: Theme.of(context).primaryColor,
                        borderRadius: BorderRadius.only(topRight: Radius.circular(20), topLeft: Radius.circular(20)),
                        boxShadow: [BoxShadow(color: Theme.of(context).focusColor.withOpacity(0.15), offset: Offset(0, -2), blurRadius: 5.0)]),
                    child: SizedBox(
                      width: MediaQuery.of(context).size.width - 40,
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.center,
                        mainAxisSize: MainAxisSize.max,
                        children: <Widget>[
                          Row(
                            children: <Widget>[
                              Expanded(
                                child: Text(
                                  S.of(context).subtotal,
                                  style: Theme.of(context).textTheme.bodyText1,
                                ),
                              ),
                              Helper.getPrice(_con.subTotal, context, style: Theme.of(context).textTheme.subtitle1)
                            ],
                          ),
                          SizedBox(height: 5),
                          Row(
                            children: <Widget>[
                              Expanded(
                                child: Text(
                                  S.of(context).delivery_fee,
                                  style: Theme.of(context).textTheme.bodyText1,
                                ),
                              ),
                              Helper.getPrice(_con.carts[0].product.market.deliveryFee, context, style: Theme.of(context).textTheme.subtitle1)
                            ],
                          ),
                          Row(
                            children: <Widget>[
                              Expanded(
                                child: Text(
                                  '${S.of(context).tax} (${_con.carts[0].product.market.defaultTax}%)',
                                  style: Theme.of(context).textTheme.bodyText1,
                                ),
                              ),
                              Helper.getPrice(_con.taxAmount, context, style: Theme.of(context).textTheme.subtitle1)
                            ],
                          ),
                          SizedBox(height: 10),
                          Stack(
                            fit: StackFit.loose,
                            alignment: AlignmentDirectional.centerEnd,
                            children: <Widget>[
                              SizedBox(
                                width: MediaQuery.of(context).size.width - 40,
                                child: FlatButton(
                                  onPressed: _isButtonDisabled ? null : () async {
                                    setState(() => _isButtonDisabled = !_isButtonDisabled);
                                    await _con.updateItemsProduct();
                                     List<Cart>  stockminimo = _con.carts.where((data) => data.quantity > int.tryParse(data.product.packageItemsCount)).toList();
                                      if(stockminimo.length == 0){
                                        if(_con.total < _con.carts[0].product.market.minimumamount){
                                            _showDialog();
                                        }else{
                                            _con.goCheckout(context);
                                        }
                                      }else{
                                         _onButtonPressed(stockminimo);
                                      }
                                     setState(() => _isButtonDisabled = !_isButtonDisabled);
                                  },
                                  disabledColor: Theme.of(context).focusColor.withOpacity(0.5),
                                  padding: EdgeInsets.symmetric(vertical: 14),
                                  color:
                                      !_con.carts[0].product.market.closed ? Theme.of(context).accentColor : Theme.of(context).focusColor.withOpacity(0.5),
                                  shape: StadiumBorder(),
                                  child: Text(
                                    S.of(context).checkout,
                                    textAlign: TextAlign.start,
                                    style: TextStyle(color: Theme.of(context).primaryColor),
                                  ),
                                ),
                              ),
                              Padding(
                                padding: const EdgeInsets.symmetric(horizontal: 20),
                                child: Helper.getPrice(
                                  _con.total,
                                  context,
                                  style: Theme.of(context).textTheme.headline4.merge(TextStyle(color: Theme.of(context).primaryColor)),
                                ),
                              )
                            ],
                          ),
                          SizedBox(height: 10),
                        ],
                      ),
                    ),
                  ),
                )
              ],
            ),
    ),
  ),
);

}

Body:
Try using PushReplacementNamed here:

shape: StadiumBorder(),
onPressed: () {
  if (currentUser.value.apiToken != null) {
    Navigator.of(context)
        .pushNamed('/Cart', arguments: RouteArgument(param: '/Product', id: widget.product.id));
  } else {
    Navigator.of(context).pushNamed('/Login');
  }
},