问:
ASP.NET Identity User Manager Error "User Already In Role" (Not In Role)
Hello I'm using Identity to authenticate my applications, to mange users/roles I have an REST API in .NET 6 which has a Seeder class to ensure data, but when seeds UserRole table I am getting an error with the second user (just the second one) at AddToRoleAsync saying "User Already In Role" (obviously the user is not in role).

Here is my Seeder class:

```<code>private static async Task EnsureSecurityDataAsync()
{
    //I clear the data just for testing
    await _securityContext.Database.EnsureDeletedAsync();
    await _securityContext.Database.EnsureCreatedAsync();
    await _securityContext.Database.OpenConnectionAsync();
    /* Roles */
    if (!_securityContext.Roles.Any())
    {
        Log.Information($"Populating Roles...");
        foreach (var role in SecurityData.Roles)
        {
            await _securityContext.Database.ExecuteSqlRawAsync($"SET IDENTITY_INSERT [CIM4_Security].[Roles] ON");
            var result = await _roleManager.CreateAsync(role);
            Log.Debug($"Role {role.Name} - {result.Succeeded}");
            await _securityContext.Database.ExecuteSqlRawAsync($"SET IDENTITY_INSERT [CIM4_Security].[Roles] OFF");
        }
        Log.Information($"Roles Populated Successful!");
    }
    else
        Log.Information("Roles already populated");
    /* Users */
    if (!_securityContext.Users.Any())
    {
        Log.Information($"Populating Users...");
        foreach (var user in SecurityData.Users)
        {
            await _securityContext.Database.ExecuteSqlRawAsync($"SET IDENTITY_INSERT [CIM4_Security].[Users] ON");
            var result = await _userManager.CreateAsync(user, SecurityData.DEFAULT_PASSWORD);
            Log.Debug($"User {user.UserName} - {result.Succeeded}");
            await _securityContext.Database.ExecuteSqlRawAsync($"SET IDENTITY_INSERT [CIM4_Security].[Users] OFF");
        }
        Log.Information($"Users Populated Successful!");
    }
    else
        Log.Information("Users already populated");
    /* UserRoles */
    if (!_securityContext.UserRoles.Any())
    {
        Log.Information($"Populating UserRoles...");
        foreach (var userRole in SecurityData.UserRoles)
        {
            var user = await _userManager.FindByIdAsync(userRole.UserId.ToString());
            var role = await _roleManager.FindByIdAsync(userRole.RoleId.ToString());
            if (await _userManager.IsInRoleAsync(user, role.Name))
                await _userManager.RemoveFromRoleAsync(user, role.Name);
            //Here Is The Error: User Is Already In Role!
            await _userManager.AddToRoleAsync(user, role.Name);
        }
    }
    else
        Log.Information("UserRoles already populated");
}
</code>```

Also my Identity Builder

```<code>#region Identity Configuration
builder.Services.AddIdentity<User, Role>()
    .AddRoleManager<RoleManager<Role>>()
    .AddUserManager<UserManager<User>>()
    .AddEntityFrameworkStores<SecurityContext>();
builder.Services.Configure<IdentityOptions>(options =>
{
    options.User.RequireUniqueEmail = false;
    options.Password.RequireDigit = true;
    options.Password.RequireLowercase = true;
    options.Password.RequireUppercase = true;
    options.Password.RequireNonAlphanumeric = true;
    options.Password.RequiredLength = 8;
});
#endregion
</code>```

And the Role, User & UserRole entities

```<code>[Table("Users", Schema = "Security")]
public class User : IdentityUser<int>
{
    public User(string userName) : base(userName) { }

    [Key]
    public override int Id { get; set; }
    [Required]
    [MaxLength(50)]
    public string FirstName { get; set; }
    [Required]
    [MaxLength(50)]
    public string LastName { get; set; }
    [NotMapped]
    public string FullName { get { return FirstName + " " + LastName; } }
    [MaxLength(50)]
    [Required]
    public override string UserName { get; set; }

    [JsonIgnore]
    public virtual ICollection<UserClaim> Claims { get; }
    [JsonIgnore]
    public virtual ICollection<UserLogin> Logins { get; }
    [JsonIgnore]
    public virtual ICollection<UserToken> Tokens { get; }
    [JsonIgnore]
    [InverseProperty(nameof(UserRole.User))]
    public virtual ICollection<UserRole> UserRoles { get; }
}

[Table("Roles", Schema = "Security")]
public class Role : IdentityRole<int>
{
    public Role() : base() { }
    public Role(string roleName) : base(roleName) { }

    [Key]
    public override int Id { get; set; }
    public int ApplicationId { get; set; }
    public int Level { get; set; }
    [Range(0, 2)]
    [Column(TypeName = "tinyint")]
    public EntityStatus Active { get; set; }

    [ForeignKey(nameof(ApplicationId))]
    [InverseProperty("Roles")]
    public virtual Application Application { get; set; }
    [InverseProperty(nameof(ObjectAccess.Role))]
    [JsonIgnore]
    public virtual ICollection<ObjectAccess> ObjectAccesses { get; }
    [InverseProperty(nameof(UserRole.Role))]
    [JsonIgnore]
    public virtual ICollection<UserRole> UserRoles { get; }
    [JsonIgnore]
    public virtual ICollection<RoleClaim> RoleClaims { get; }
}

[Table("UserRoles", Schema = "Security")]
public class UserRole : IdentityUserRole<int>
{
    public UserRole() { }

    [ForeignKey(nameof(UserId))]
    [InverseProperty("UserRoles")]
    public virtual User User { get; set; }

    [ForeignKey(nameof(RoleId))]
    [InverseProperty("UserRoles")]
    public virtual Role Role { get; set; }
}
</code>```

I tried to use RemoveFromRoleAsync before AddToRoleAsync but I notice that the user role removed was the first one, instead the second.

I'm thinking that is something related with the Role or User entities or at the Identity Builder.

The user role sequence assigned is:
UserId = 1, RoleId = 2 <- Succeed
UserId = 2, RoleId = 1 <- Error User Is Already In Role

If I use RemoveFromRoleAsync it removes UserId = 1, RoleId = 2.

Body:
Hello I'm using Identity to authenticate my applications, to mange users/roles I have an REST API in .NET 6 which has a Seeder class to ensure data, but when seeds UserRole table I am getting an error with the second user (just the second one) at AddToRoleAsync saying "User Already In Role" (obviously the user is not in role).

Here is my Seeder class:

private static async Task EnsureSecurityDataAsync()
{
    //I clear the data just for testing
    await _securityContext.Database.EnsureDeletedAsync();
    await _securityContext.Database.EnsureCreatedAsync();
    await _securityContext.Database.OpenConnectionAsync();
    /* Roles */
    if (!_securityContext.Roles.Any())
    {
        Log.Information($"Populating Roles...");
        foreach (var role in SecurityData.Roles)
        {
            await _securityContext.Database.ExecuteSqlRawAsync($"SET IDENTITY_INSERT [CIM4_Security].[Roles] ON");
            var result = await _roleManager.CreateAsync(role);
            Log.Debug($"Role {role.Name} - {result.Succeeded}");
            await _securityContext.Database.ExecuteSqlRawAsync($"SET IDENTITY_INSERT [CIM4_Security].[Roles] OFF");
        }
        Log.Information($"Roles Populated Successful!");
    }
    else
        Log.Information("Roles already populated");
    /* Users */
    if (!_securityContext.Users.Any())
    {
        Log.Information($"Populating Users...");
        foreach (var user in SecurityData.Users)
        {
            await _securityContext.Database.ExecuteSqlRawAsync($"SET IDENTITY_INSERT [CIM4_Security].[Users] ON");
            var result = await _userManager.CreateAsync(user, SecurityData.DEFAULT_PASSWORD);
            Log.Debug($"User {user.UserName} - {result.Succeeded}");
            await _securityContext.Database.ExecuteSqlRawAsync($"SET IDENTITY_INSERT [CIM4_Security].[Users] OFF");
        }
        Log.Information($"Users Populated Successful!");
    }
    else
        Log.Information("Users already populated");
    /* UserRoles */
    if (!_securityContext.UserRoles.Any())
    {
        Log.Information($"Populating UserRoles...");
        foreach (var userRole in SecurityData.UserRoles)
        {
            var user = await _userManager.FindByIdAsync(userRole.UserId.ToString());
            var role = await _roleManager.FindByIdAsync(userRole.RoleId.ToString());
            if (await _userManager.IsInRoleAsync(user, role.Name))
                await _userManager.RemoveFromRoleAsync(user, role.Name);
            //Here Is The Error: User Is Already In Role!
            await _userManager.AddToRoleAsync(user, role.Name);
        }
    }
    else
        Log.Information("UserRoles already populated");
}

Also my Identity Builder

#region Identity Configuration
builder.Services.AddIdentity<User, Role>()
    .AddRoleManager<RoleManager<Role>>()
    .AddUserManager<UserManager<User>>()
    .AddEntityFrameworkStores<SecurityContext>();
builder.Services.Configure<IdentityOptions>(options =>
{
    options.User.RequireUniqueEmail = false;
    options.Password.RequireDigit = true;
    options.Password.RequireLowercase = true;
    options.Password.RequireUppercase = true;
    options.Password.RequireNonAlphanumeric = true;
    options.Password.RequiredLength = 8;
});
#endregion

And the Role, User & UserRole entities

[Table("Users", Schema = "Security")]
public class User : IdentityUser<int>
{
    public User(string userName) : base(userName) { }

    [Key]
    public override int Id { get; set; }
    [Required]
    [MaxLength(50)]
    public string FirstName { get; set; }
    [Required]
    [MaxLength(50)]
    public string LastName { get; set; }
    [NotMapped]
    public string FullName { get { return FirstName + " " + LastName; } }
    [MaxLength(50)]
    [Required]
    public override string UserName { get; set; }

    [JsonIgnore]
    public virtual ICollection<UserClaim> Claims { get; }
    [JsonIgnore]
    public virtual ICollection<UserLogin> Logins { get; }
    [JsonIgnore]
    public virtual ICollection<UserToken> Tokens { get; }
    [JsonIgnore]
    [InverseProperty(nameof(UserRole.User))]
    public virtual ICollection<UserRole> UserRoles { get; }
}

[Table("Roles", Schema = "Security")]
public class Role : IdentityRole<int>
{
    public Role() : base() { }
    public Role(string roleName) : base(roleName) { }

    [Key]
    public override int Id { get; set; }
    public int ApplicationId { get; set; }
    public int Level { get; set; }
    [Range(0, 2)]
    [Column(TypeName = "tinyint")]
    public EntityStatus Active { get; set; }

    [ForeignKey(nameof(ApplicationId))]
    [InverseProperty("Roles")]
    public virtual Application Application { get; set; }
    [InverseProperty(nameof(ObjectAccess.Role))]
    [JsonIgnore]
    public virtual ICollection<ObjectAccess> ObjectAccesses { get; }
    [InverseProperty(nameof(UserRole.Role))]
    [JsonIgnore]
    public virtual ICollection<UserRole> UserRoles { get; }
    [JsonIgnore]
    public virtual ICollection<RoleClaim> RoleClaims { get; }
}

[Table("UserRoles", Schema = "Security")]
public class UserRole : IdentityUserRole<int>
{
    public UserRole() { }

    [ForeignKey(nameof(UserId))]
    [InverseProperty("UserRoles")]
    public virtual User User { get; set; }

    [ForeignKey(nameof(RoleId))]
    [InverseProperty("UserRoles")]
    public virtual Role Role { get; set; }
}

I tried to use RemoveFromRoleAsync before AddToRoleAsync but I notice that the user role removed was the first one, instead the second.

I'm thinking that is something related with the Role or User entities or at the Identity Builder.

The user role sequence assigned is:
UserId = 1, RoleId = 2 <- Succeed
UserId = 2, RoleId = 1 <- Error User Is Already In Role

If I use RemoveFromRoleAsync it removes UserId = 1, RoleId = 2.


来源: stackexchange

问:
Autocomplete options not properly updating on user input - Angular 14
My problem is that I am updating options for a autocomplete input field based off the user's input. If the user has typed at least three characters in the textbox and the user hasn't typed in the last half second, I'll make an API call based off the input. Basically I want to recreate the autocomplete overview from here: https://material.angular.io/components/autocomplete/examples#autocomplete-filter

But instead of hard-coded values, I want the values to be dynamically changing as the user types. Now to my problem, once I have at least three characters and I stop typing, I receive the information and put it into my options array, but it doesn't get shown in the textbox until I update the field again by typing or backspacing. filteredOptions is the actual array being displayed to the user.

Code

TS

```<code>filteredOptions?: Observable<any[]>
options: any[] = []
localForm!: FormGroup

// Component Stuff

  async ngOnInit() {
    this.localForm = this.fb.group({
      search: ['']
    })

    this.localForm.get('search')?.valueChanges.subscribe(() => onChangeTimeout())
    this.subscribeToChanges()
  }

  onChangeTimeout() {
    clearTimeout(this.timer);
    this.timer = setTimeout(this.inputHandler.bind(this), 500)
  }

  async inputHandler() {
    if (this.localForm.get('search')?.value !== null && this.localForm.get('search')?.value !== '') {
      if (this.localForm.get('search')?.value.length >= 3) {

       // API CALL THAT RESETS options AND THEN PUSHES ALL RECORDS FROM CALL INTO options
        await this.getEmployeeInformation()
      }
    }
  }

  private subscribeToChanges() {
    if (this.localForm.get('search')?.value !== null) {
      this.filteredOptions = this.localForm.get('search')?.valueChanges.pipe(startWith(''), map((value) => this._filter(value)))
    }
  }

  private _filter(value: any): any[] {
    if (value !== null) {
      const filterValue = this.toTitleCase(value)
      return this.options?.filter((option) => this.toTitleCase(option.lastName).includes(filterValue))
    } else {
      return []
    }
  }

  toTitleCase(str: string) {
    return str.replace(
      /\w\S*/g,
      txt => ( txt.charAt(0).toUpperCase() + txt.substring(1).toLowerCase())
    )
  }
</code>```

HTML

```<code><form [formGroup]="localForm" (ngSubmit)="NA">
            <mat-form-field class="form-field" appearance="outline">
                <mat-label>Search By Last Name (BMCD EOs)</mat-label>
                <input matInput type="text" placeholder="Testing" autocomplete="off" name="search"
                    formControlName="search" [matAutocomplete]="auto">
                <mat-autocomplete autoActiveFirstOption #auto="matAutocomplete">
                    <mat-option *ngFor="let option of filteredOptions | async" [value]="option.fullName">
                        {{ option.fullName }}
                    </mat-option>
                </mat-autocomplete>
            </mat-form-field>
</form>
</code>```

ContentLicense: CC BY-SA 4.0

Body:
My problem is that I am updating options for a autocomplete input field based off the user's input. If the user has typed at least three characters in the textbox and the user hasn't typed in the last half second, I'll make an API call based off the input. Basically I want to recreate the autocomplete overview from here: https://material.angular.io/components/autocomplete/examples#autocomplete-filter

But instead of hard-coded values, I want the values to be dynamically changing as the user types. Now to my problem, once I have at least three characters and I stop typing, I receive the information and put it into my options array, but it doesn't get shown in the textbox until I update the field again by typing or backspacing. filteredOptions is the actual array being displayed to the user.

Code

TS

filteredOptions?: Observable<any[]>
options: any[] = []
localForm!: FormGroup

// Component Stuff

  async ngOnInit() {
    this.localForm = this.fb.group({
      search: ['']
    })

    this.localForm.get('search')?.valueChanges.subscribe(() => onChangeTimeout())
    this.subscribeToChanges()
  }

  onChangeTimeout() {
    clearTimeout(this.timer);
    this.timer = setTimeout(this.inputHandler.bind(this), 500)
  }

  async inputHandler() {
    if (this.localForm.get('search')?.value !== null && this.localForm.get('search')?.value !== '') {
      if (this.localForm.get('search')?.value.length >= 3) {

       // API CALL THAT RESETS options AND THEN PUSHES ALL RECORDS FROM CALL INTO options
        await this.getEmployeeInformation()
      }
    }
  }

  private subscribeToChanges() {
    if (this.localForm.get('search')?.value !== null) {
      this.filteredOptions = this.localForm.get('search')?.valueChanges.pipe(startWith(''), map((value) => this._filter(value)))
    }
  }

  private _filter(value: any): any[] {
    if (value !== null) {
      const filterValue = this.toTitleCase(value)
      return this.options?.filter((option) => this.toTitleCase(option.lastName).includes(filterValue))
    } else {
      return []
    }
  }

  toTitleCase(str: string) {
    return str.replace(
      /\w\S*/g,
      txt => ( txt.charAt(0).toUpperCase() + txt.substring(1).toLowerCase())
    )
  }

HTML

<form [formGroup]="localForm" (ngSubmit)="NA">
            <mat-form-field class="form-field" appearance="outline">
                <mat-label>Search By Last Name (BMCD EOs)</mat-label>
                <input matInput type="text" placeholder="Testing" autocomplete="off" name="search"
                    formControlName="search" [matAutocomplete]="auto">
                <mat-autocomplete autoActiveFirstOption #auto="matAutocomplete">
                    <mat-option *ngFor="let option of filteredOptions | async" [value]="option.fullName">
                        {{ option.fullName }}
                    </mat-option>
                </mat-autocomplete>
            </mat-form-field>
</form>


问:
line break with array
I would like to put the arry RG:

a) 21.000

b) teste1

a) 22.000

b) teste2

which property do i use? what should i search?

```<code>

var i;
var out = document.getElementById("output");
var most = [
    { name: "number 01 test?", rg: ["a) 21.000", " b) teste1"]},
    { name: "number 02 test?", rg: ["a) 22.000", " b) teste2"]}

    ];
function displayMost() {
    "use strict";
    for (i = 0; i < most.length; i++) {

    out.appendChild(document.createTextNode(most[i].name));
    out.appendChild(document.createElement("br"));
    out.appendChild(document.createTextNode(most[i].rg));                       out.appendChild(document.createElement("br"));

    }

    }
displayMost(most);
</code>```

Title: line break with array

Body:
I would like to put the arry RG:

a) 21.000

b) teste1

a) 22.000

b) teste2

which property do i use? what should i search?

var i;
var out = document.getElementById("output");
var most = [
    { name: "number 01 test?", rg: ["a) 21.000", " b) teste1"]},
    { name: "number 02 test?", rg: ["a) 22.000", " b) teste2"]}

    ];
function displayMost() {
    "use strict";
    for (i = 0; i < most.length; i++) {

    out.appendChild(document.createTextNode(most[i].name));
    out.appendChild(document.createElement("br"));
    out.appendChild(document.createTextNode(most[i].rg));                       out.appendChild(document.createElement("br"));

    }

    }
displayMost(most);


问:
Android Virtual Keyboard affect screen rotation ( Using Cocos Creator to build )
I using Cocos Creator 3.5.2 for this project.
When I start testing input text field in android phone either in app or web browser, after the virtual keyboard appear and I try rotate screen from landscape to portrait, the keyboard got change but the screen layout dint resize still is landscape but only smaller n at top.
It need to close the keyboard then the screen layout will start resize and this is in app.

Any idea that can cause this happen?
And any solution for it.


问:
VS Code API: How can I detect if the file currently opened is part of a GitHub, GitLab, or Bitbucket repo?
In my extension.ts file I want to check if the file that's currently open is part of a GitHub, Bitbucket, or GitLab repo.

I tried doing this with: let localWorkspacePath = vscode.workspace.workspaceFolders?.[0].uri.fsPath; and do an if statement to check if the string contains the name of one of the 3 systems.

However, this prints the filepath, without giving the required info.

What's the way to do this?


问:
Got the error error: ld returned 1 exit status when linking C++ files together
I am new to c++, and I am trying to link two c++ files together, but received the error error: ld returned 1 exit status when trying to use the run build task on vs code. I am confused because neither of the files are allowing me to build.
Here is my code in the files:

```<code>int add(int x, int y)
{
    return x + y;
}
</code>```
```<code>#include <iostream>

int add(int x, int y); // needed so main.cpp knows that add() is a function defined elsewhere

int main()
{
    std::cout << "The sum of 3 and 4 is: " << add(3, 4) << '\n';
    return 0;
}
</code>```

I've tried using cmake however couldn't get the set up to work, I've tried redoing the files from the beginning which gave the same error

Body:
I am new to c++, and I am trying to link two c++ files together, but received the error error: ld returned 1 exit status when trying to use the run build task on vs code. I am confused because neither of the files are allowing me to build.
Here is my code in the files:

int add(int x, int y)
{
    return x + y;
}

#include <iostream>

int add(int x, int y); // needed so main.cpp knows that add() is a function defined elsewhere

int main()
{
    std::cout << "The sum of 3 and 4 is: " << add(3, 4) << '\n';
    return 0;
}

I've tried using cmake however couldn't get the set up to work, I've tried redoing the files from the beginning which gave the same error


问:
How To Properly Pass Model Class In Navigation Of Jetpack Compose
I have a pretty basic application in Jetpack Compose, where:

First screen has a lazyColumn with many items

Users can click on an item and be moved to a screen with details about the clicked item

Each item is modeled using a data class that is serializable

I've tried passing in the model class with the navigation using:

```<code>val modelDataAsString = Json.encodeToString(MODEL_CLASS.serializer(), modelData)
navController.currentBackStackEntry?.arguments?.putString("KEY", modelDataAsString)
navController.navigate("ROUTE/${modelDataAsString}")
</code>```

But when I do this, I get the following exception:

```<code>java.lang.IllegalArgumentException: Navigation destination that matches request NavDeepLinkRequest{ uri=android-app://androidx.navigation/... cannot be found in the navigation graph NavGraph(0x0) startDestination={Destination(0x78da56c6) route=main}
</code>```

Now, I understood that this is because my Model class in String form is way too long (relevant SO question).

So, searching SO, I found that the solution provided was using a SharedViewModel.

I have done this and everything works well, but something doesn't feel right passing around the viewModel.

What I want to know (and understand) if this is the proper way of
solving this issue. I am not looking for an opinion or a
recommendation, but a definitive answer.

At the bottom line, what I want to achieve is the ability to allow the onClick method on an item in my LazyColumn move the user to a screen of the item clicked.

Body:
I have a pretty basic application in Jetpack Compose, where:

First screen has a lazyColumn with many items

Users can click on an item and be moved to a screen with details about the clicked item

Each item is modeled using a data class that is serializable

I've tried passing in the model class with the navigation using:

val modelDataAsString = Json.encodeToString(MODEL_CLASS.serializer(), modelData)
navController.currentBackStackEntry?.arguments?.putString("KEY", modelDataAsString)
navController.navigate("ROUTE/${modelDataAsString}")

But when I do this, I get the following exception:

java.lang.IllegalArgumentException: Navigation destination that matches request NavDeepLinkRequest{ uri=android-app://androidx.navigation/... cannot be found in the navigation graph NavGraph(0x0) startDestination={Destination(0x78da56c6) route=main}

Now, I understood that this is because my Model class in String form is way too long (relevant SO question).

So, searching SO, I found that the solution provided was using a SharedViewModel.

I have done this and everything works well, but something doesn't feel right passing around the viewModel.

What I want to know (and understand) if this is the proper way of
solving this issue. I am not looking for an opinion or a
recommendation, but a definitive answer.

At the bottom line, what I want to achieve is the ability to allow the onClick method on an item in my LazyColumn move the user to a screen of the item clicked.


问:
Viewing objects in Amazon Cloud Directory
I'm new to Amazon Cloud Directory. I've been experimenting with adding objects via SDK (Javascript v3 SDK).
Is there way to see the objects in either the AWS Console or via some kind of developer client tool. I'm talking about a tool that does the same job as Compass does for MongoDB or SQLAce does for MySql etc.
Not being able to visually confirm the results of my experiments is frustrating.</p>


问:
How do I prevent adding and deleting rows while allowing cell content edits?
Some of my code relies on uniform structure of a set of workbooks. As such, I want people to be able to edit the contents of cells, but not add or delete rows. I know there are more sophisticated solutions, such as disabling the keystroke associated with deleting rows, but I've found that just allowing edits to a range, while protecting the sheet with otherwise default settings, fills the bill. But why isn't this code accomplishing it?</p>
```<code>Sheets("Sheet1").Select
ActiveSheet.Protection.AllowEditRanges.ADD Range:=Range("$1:$10485")
ActiveSheet.Protect "secret"
</code>```

Body:
Some of my code relies on uniform structure of a set of workbooks. As such, I want people to be able to edit the contents of cells, but not add or delete rows. I know there are more sophisticated solutions, such as disabling the keystroke associated with deleting rows, but I've found that just allowing edits to a range, while protecting the sheet with otherwise default settings, fills the bill. But why isn't this code accomplishing it?

Sheets("Sheet1").Select
ActiveSheet.Protection.AllowEditRanges.ADD Range:=Range("$1:$10485")
ActiveSheet.Protect "secret"


问:
Re-send a transaction using Alchemy to speed up erc20 transaction
I am building a crypto wallet app on the ethereum chain and have set it up so that I can send transactions.  Next I would like to be able to speed up transactions and understand how this is done.  As far as I know you send another transaction with the same nonce but more gas.  To sped up a transaction where I am sending ETH this is straightforward.

Here is the original function to send the transaction:

```<code>export const sendTransaction = async (currentWallet, toAddress, value) => {
    // // Create Provider
    const url = "https://eth-mainnet.g.alchemy.com/v2/" + ALCHEMY_API_KEY;
    const customHttpProvider = await new ethers.providers.JsonRpcProvider(url);

    // // Create wallet and connect to provider
    const wallet = await new Wallet(currentWallet.pk, customHttpProvider);

    const currentChainId = await getChainId();

    const feeData = await customHttpProvider.getFeeData();
    let gasPrice = feeData.maxFeePerGas;

    const transaction = {
        to: toAddress,
        value: Utils.parseEther(value),
        gasLimit: "21000",
        maxPriorityFeePerGas: feeData.maxPriorityFeePerGas,
        maxFeePerGas: feeData.maxFeePerGas,
        nonce: await alchemy.core.getTransactionCount(currentWallet.walletInstance.address),
        type: 2,
        chainId: currentChainId
        // chainId: 5
    }

    const rawTransaction = await wallet.signTransaction(transaction);

    try {
        const sentTransaction = await alchemy.core.sendTransaction(rawTransaction);

        return sentTransaction;
    } catch (err) {
        return null;
    }

}
</code>```

and then to speed this up I would run the same function but replace the gas and set the same nonce.

However, with erc20 tokens my function to transfer the amount specified like so:

```<code>export const sendErc20Transaction = async (token, currentWallet, toAddress, value) => {
    try {
        // Create Provider
        const url = "https://eth-mainnet.g.alchemy.com/v2/" + ALCHEMY_API_KEY;
        const customHttpProvider = await new ethers.providers.JsonRpcProvider(url);

        // Create wallet and connect to provider
        const wallet = await new Wallet(currentWallet.pk, customHttpProvider);

        // Dynamically get ABI
        const abi = await getTokenABI(token, 'erc20');

        // Create Smart Contract
        const currentContract = new Contract(token.contractAddress, abi, wallet);

        // // Send Transaction
        const transaction = await currentContract.transfer(toAddress, Utils.parseUnits(value));
        return transaction;
    } catch (err) {
        return null;
    }
}
</code>```

I don't see anywhere within this function where I can specify the gas or the nonce.
How would I resend this same transaction, still sending the same token, with higher gas and the same nonce?

Body:
I am building a crypto wallet app on the ethereum chain and have set it up so that I can send transactions.  Next I would like to be able to speed up transactions and understand how this is done.  As far as I know you send another transaction with the same nonce but more gas.  To sped up a transaction where I am sending ETH this is straightforward.

Here is the original function to send the transaction:

export const sendTransaction = async (currentWallet, toAddress, value) => {
    // // Create Provider
    const url = "https://eth-mainnet.g.alchemy.com/v2/" + ALCHEMY_API_KEY;
    const customHttpProvider = await new ethers.providers.JsonRpcProvider(url);

    // // Create wallet and connect to provider
    const wallet = await new Wallet(currentWallet.pk, customHttpProvider);

    const currentChainId = await getChainId();

    const feeData = await customHttpProvider.getFeeData();
    let gasPrice = feeData.maxFeePerGas;

    const transaction = {
        to: toAddress,
        value: Utils.parseEther(value),
        gasLimit: "21000",
        maxPriorityFeePerGas: feeData.maxPriorityFeePerGas,
        maxFeePerGas: feeData.maxFeePerGas,
        nonce: await alchemy.core.getTransactionCount(currentWallet.walletInstance.address),
        type: 2,
        chainId: currentChainId
        // chainId: 5
    }

    const rawTransaction = await wallet.signTransaction(transaction);

    try {
        const sentTransaction = await alchemy.core.sendTransaction(rawTransaction);

        return sentTransaction;
    } catch (err) {
        return null;
    }

}

and then to speed this up I would run the same function but replace the gas and set the same nonce.

However, with erc20 tokens my function to transfer the amount specified like so:

export const sendErc20Transaction = async (token, currentWallet, toAddress, value) => {
    try {
        // Create Provider
        const url = "https://eth-mainnet.g.alchemy.com/v2/" + ALCHEMY_API_KEY;
        const customHttpProvider = await new ethers.providers.JsonRpcProvider(url);

        // Create wallet and connect to provider
        const wallet = await new Wallet(currentWallet.pk, customHttpProvider);

        // Dynamically get ABI
        const abi = await getTokenABI(token, 'erc20');

        // Create Smart Contract
        const currentContract = new Contract(token.contractAddress, abi, wallet);

        // // Send Transaction
        const transaction = await currentContract.transfer(toAddress, Utils.parseUnits(value));
        return transaction;
    } catch (err) {
        return null;
    }
}

I don't see anywhere within this function where I can specify the gas or the nonce.
How would I resend this same transaction, still sending the same token, with higher gas and the same nonce?


问:
Can't get soft keyboard to go away, constantly shows up in android app despite calling InputMethodManager hideSoftInputFromWindow() method
In each of my activities that extend AppCompatActivity, my Android tablet's(Galaxy Tab A7) soft key board automatically shows up due to edit text and search views being in the layouts. In the respective activities I have a hideSoftKeyboard() method (as seen below) which I am calling in the onCreate() of each class to prevent the keyboard from showing up automatically until someone hits a search view/edit text.

```<code> public void hideSoftKeyboard(Activity activity) {
    InputMethodManager imm = (InputMethodManager) activity.getSystemService(Activity.INPUT_METHOD_SERVICE);
    //Find the currently focused view, so we can grab the correct window token from it.
    View view = this.getCurrentFocus();
    //If no view currently has focus, create a new one, just so we can grab a window token from it
    if (view == null) {
        view = new View(activity);
    }
    getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
    imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
    System.out.println("made it hideSoftKeyboard");
}
</code>```

how I call it in onCreate()

```<code>  hideSoftKeyboard(this);
</code>```

I have also tried adding the android:windowSoftInputMode="stateHidden" in my Android Manifest file's application tag (and in each individual activity tag at one point)

```<code><?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.android.receiptreader">
    <uses-permission android:name="android.permission.RECORD_AUDIO" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:windowSoftInputMode="stateAlwaysHidden"
        android:theme="@style/Theme.ReceiptReader">
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name"
            android:windowSoftInputMode="stateHidden"

            android:theme="@style/Theme.ReceiptReader.ActionBar">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:windowSoftInputMode="stateHidden"
            android:name=".StoreUserItemsActivity"
            android:label="@string/store_user_items_activity"
            android:theme="@style/Theme.ReceiptReader.ActionBar">
        </activity>
        <activity
            android:windowSoftInputMode="stateHidden"
            android:name=".ShoppingListUserItemsActivity"
            android:label="@string/store_user_items_activity"
            android:theme="@style/Theme.ReceiptReader.ActionBar">
        </activity>
        <activity
            android:windowSoftInputMode="stateHidden"
            android:name=".ShoppingListUserItemHistoryActivity"
            android:label="@string/shopping_list_user_item_history"
            android:theme="@style/Theme.ReceiptReader.ActionBar">
        </activity>
        <activity
            android:windowSoftInputMode="stateHidden"
            android:name=".ShoppingListsHistoryActivity"
            android:label="@string/shopping_lists_history"
            android:theme="@style/Theme.ReceiptReader.ActionBar">
        </activity>
        <activity
            android:windowSoftInputMode="stateHidden"
            android:name=".AddShoppingListUserItemActivity"
            android:label="@string/add_shopping_list_user_item_activity"
            android:theme="@style/Theme.ReceiptReader.ActionBar">
        </activity>
    </application>

</manifest>
</code>```

As well as make the search views in my landing page(and edit texts and search views in my other layouts) not focusable by default

```<code>                    <SearchView
                    android:id="@+id/shopping_list_search_bar"
                    android:layout_width="wrap_content"
                    android:layout_height="33dp"
                    android:layout_gravity="center_vertical"
                    android:layout_marginEnd="5dp"
                    android:layout_weight="2"
                    android:background="@color/white_two"
                    android:focusable="false"
                    android:focusableInTouchMode="true"
                    android:focusedByDefault="false"
                    android:inputType="text"
                    android:queryHint="Search For a Shopping List" />
</code>```

None of this seems to make it go away and everytime I navigate within the app it shows up again and I have to keep telling it to go down manually. I cannot have such an annoying issue for good UI design and have tried various solutions on stack overflow. Please let me know how to fix this issue or if you have any ideas to solve this or reasons for why this is happening. If anyone needs more or the full code for my classes/XML layouts let me know.

Body:
In each of my activities that extend AppCompatActivity, my Android tablet's(Galaxy Tab A7) soft key board automatically shows up due to edit text and search views being in the layouts. In the respective activities I have a hideSoftKeyboard() method (as seen below) which I am calling in the onCreate() of each class to prevent the keyboard from showing up automatically until someone hits a search view/edit text.

 public void hideSoftKeyboard(Activity activity) {
    InputMethodManager imm = (InputMethodManager) activity.getSystemService(Activity.INPUT_METHOD_SERVICE);
    //Find the currently focused view, so we can grab the correct window token from it.
    View view = this.getCurrentFocus();
    //If no view currently has focus, create a new one, just so we can grab a window token from it
    if (view == null) {
        view = new View(activity);
    }
    getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
    imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
    System.out.println("made it hideSoftKeyboard");
}

how I call it in onCreate()

  hideSoftKeyboard(this);

I have also tried adding the android:windowSoftInputMode="stateHidden" in my Android Manifest file's application tag (and in each individual activity tag at one point)

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.android.receiptreader">
    <uses-permission android:name="android.permission.RECORD_AUDIO" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:windowSoftInputMode="stateAlwaysHidden"
        android:theme="@style/Theme.ReceiptReader">
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name"
            android:windowSoftInputMode="stateHidden"

            android:theme="@style/Theme.ReceiptReader.ActionBar">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:windowSoftInputMode="stateHidden"
            android:name=".StoreUserItemsActivity"
            android:label="@string/store_user_items_activity"
            android:theme="@style/Theme.ReceiptReader.ActionBar">
        </activity>
        <activity
            android:windowSoftInputMode="stateHidden"
            android:name=".ShoppingListUserItemsActivity"
            android:label="@string/store_user_items_activity"
            android:theme="@style/Theme.ReceiptReader.ActionBar">
        </activity>
        <activity
            android:windowSoftInputMode="stateHidden"
            android:name=".ShoppingListUserItemHistoryActivity"
            android:label="@string/shopping_list_user_item_history"
            android:theme="@style/Theme.ReceiptReader.ActionBar">
        </activity>
        <activity
            android:windowSoftInputMode="stateHidden"
            android:name=".ShoppingListsHistoryActivity"
            android:label="@string/shopping_lists_history"
            android:theme="@style/Theme.ReceiptReader.ActionBar">
        </activity>
        <activity
            android:windowSoftInputMode="stateHidden"
            android:name=".AddShoppingListUserItemActivity"
            android:label="@string/add_shopping_list_user_item_activity"
            android:theme="@style/Theme.ReceiptReader.ActionBar">
        </activity>
    </application>

</manifest>

As well as make the search views in my landing page(and edit texts and search views in my other layouts) not focusable by default

                    <SearchView
                    android:id="@+id/shopping_list_search_bar"
                    android:layout_width="wrap_content"
                    android:layout_height="33dp"
                    android:layout_gravity="center_vertical"
                    android:layout_marginEnd="5dp"
                    android:layout_weight="2"
                    android:background="@color/white_two"
                    android:focusable="false"
                    android:focusableInTouchMode="true"
                    android:focusedByDefault="false"
                    android:inputType="text"
                    android:queryHint="Search For a Shopping List" />

None of this seems to make it go away and everytime I navigate within the app it shows up again and I have to keep telling it to go down manually. I cannot have such an annoying issue for good UI design and have tried various solutions on stack overflow. Please let me know how to fix this issue or if you have any ideas to solve this or reasons for why this is happening. If anyone needs more or the full code for my classes/XML layouts let me know.


问:
wave or curve effect in bottom tab react native
I'm new to react-native and I'm trying to make the bottom tabs with a custom style. I have to achieve something like this ->

I can only do a basic structure by styling it with react-native-bottom-tabs

this is my result so far->

but I can't get it, since the library I'm using, rn-wave-bottom-bar, is not very flexible with style changes and I would need some idea or help please!!!

React-Native 0.70.6
react => 18.1.0

Thank you


问:
how to sent plain object as action?
making delete request to mongodb database and getting an error message action must be plain object. but if i refresh the store object is deleted. but i want do it live. i have implmented get edit and create request using the same method but when using delete its not happening. what i am doing wrong.import React from "react";

error message : redux.js:278 Uncaught Error: Actions must be plain objects. Instead, the actual type was: 'Promise'. You may need to add middleware to your store setup to handle dispatching other values, such as 'redux-thunk' to handle dispatching functions.

i am dipatching the action from post.js button component as onClick={() => dispatch(deletePost(post._id))}

```<code> const Post = ({ post, setCurrentId }) => {
 const classes = useStyles();
 const dispatch = useDispatch();

 const editHandeler = () => {
setCurrentId(post._id);
 };

             return (
               <Card className={classes.card}>
                 <CardMedia
                   className={classes.media}
                   image={
                     post.selectedFile ||
                     "https://user-images.githubusercontent.com/194400/49531010-48dad180-f8b1-
                       11e8-8d89-1e61320e1d82.png"
                   }
                   title={post.title}
                 />
                 <div className={classes.overlay}>
                   <Typography variant="h6">{post.creator}</Typography>
                   <Typography variant="body2">
                     {moment(post.createdAt).fromNow()}
                   </Typography>
                 </div>
                 <div className={classes.overlay2}>
                   <Button style={{ color: "white" }} size="small" onClick={editHandeler}>
                     <MoreHorizIcon fontSize="default" />
                   </Button>
                 </div>
                 <div className={classes.details}>
                   <Typography variant="body2" color="textSecondary" component="h2">
                     {post.tags.map((tag) => `#${tag} `)}
                   </Typography>
                 </div>
                 <Typography
                   className={classes.title}
                   gutterBottom
                   variant="h5"
                   component="h2"
                 >
                   {post.title}
                 </Typography>
                 <CardContent>
                   <Typography variant="body2" color="textSecondary" component="p">
                     {post.message}
                   </Typography>
                 </CardContent>

                 <CardActions className={classes.cardActions}>
                   <Button size="small" color="primary" onClick={() => {}}>
                     <ThumbUpAltIcon fontSize="small" /> Like {post.likeCount}{" "}
                   </Button>
                   <Button
                     size="small"
                     color="primary"
                     onClick={() => dispatch(deletePost(post._id))}
                   >
                     <DeleteIcon fontSize="small" /> Delete
                   </Button>
                 </CardActions>
               </Card>
             );
           };

       export default Post;
</code>```

delete post function

```<code>export const deletePost = (id) => async (dispatch) => {
  try {
    await api.deletePost(id);

    dispatch({ type: DELETE, payload: id });
  } catch (error) {
    console.log(error.message);
  }
};
</code>```

api

```<code>const url = "http://localhost:5000/posts";

export const fetchPosts = () => axios.get(url);
export const createPost = (newPost) => axios.post(url, newPost);
export const updatePost = (id, updatedPost) =>
axios.patch(`${url}/${id}`, updatedPost);

export const deletePost = (id) => axios.delete(`${url}/${id}`);
</code>```

reducer

```<code>import { FETCH_ALL, CREATE, UPDATE, DELETE, LIKE } from "../actions/constants";

const reducer = (posts = [], action) => {
  switch (action.type) {
    case FETCH_ALL:
      return action.payload;
    case CREATE:
      return [...posts, action.payload];
    case UPDATE:
      return posts.map((post) =>
        post._id === action.payload._id ? action.payload : post
      );
    case DELETE:
      return posts.filter((post) => post.id !== action.payload);

    default:
      return posts;
  }
};
export default reducer;
</code>```

store

```<code>import { configureStore } from "@reduxjs/toolkit";
import { reducers } from "./rootreducer";
import { applyMiddleware, compose } from "redux";
import thunk from "redux-thunk";

const store = configureStore(
  { reducer: reducers },
  compose(applyMiddleware(thunk))
);

export default store;
</code>```

rootreducer

```<code>export const reducers = combineReducers({
posts: posts,
});
</code>```

Title: how to sent plain object as action?

Body:
making delete request to mongodb database and getting an error message action must be plain object. but if i refresh the store object is deleted. but i want do it live. i have implmented get edit and create request using the same method but when using delete its not happening. what i am doing wrong.import React from "react";

error message : redux.js:278 Uncaught Error: Actions must be plain objects. Instead, the actual type was: 'Promise'. You may need to add middleware to your store setup to handle dispatching other values, such as 'redux-thunk' to handle dispatching functions.

i am dipatching the action from post.js button component as onClick={() => dispatch(deletePost(post._id))}

 const Post = ({ post, setCurrentId }) => {
 const classes = useStyles();
 const dispatch = useDispatch();

 const editHandeler = () => {
setCurrentId(post._id);
 };

             return (
               <Card className={classes.card}>
                 <CardMedia
                   className={classes.media}
                   image={
                     post.selectedFile ||
                     "https://user-images.githubusercontent.com/194400/49531010-48dad180-f8b1-
                       11e8-8d89-1e61320e1d82.png"
                   }
                   title={post.title}
                 />

                   <Typography variant="h6">{post.creator}</Typography>
                   <Typography variant="body2">
                     {moment(post.createdAt).fromNow()}
                   </Typography>

                   <Button style={{ color: "white" }} size="small" onClick={editHandeler}>
                     <MoreHorizIcon fontSize="default" />
                   </Button>

                   <Typography variant="body2" color="textSecondary" component="h2">
                     {post.tags.map((tag) => `#${tag} `)}
                   </Typography>

                 <Typography
                   className={classes.title}
                   gutterBottom
                   variant="h5"
                   component="h2"
                 >
                   {post.title}
                 </Typography>
                 <CardContent>
                   <Typography variant="body2" color="textSecondary" component="p">
                     {post.message}
                   </Typography>
                 </CardContent>

                 <CardActions className={classes.cardActions}>
                   <Button size="small" color="primary" onClick={() => {}}>
                     <ThumbUpAltIcon fontSize="small" /> Like {post.likeCount}{" "}
                   </Button>
                   <Button
                     size="small"
                     color="primary"
                     onClick={() => dispatch(deletePost(post._id))}
                   >
                     <DeleteIcon fontSize="small" /> Delete
                   </Button>
                 </CardActions>
               </Card>
             );
           };

       export default Post;

delete post function

export const deletePost = (id) => async (dispatch) => {
  try {
    await api.deletePost(id);

    dispatch({ type: DELETE, payload: id });
  } catch (error) {
    console.log(error.message);
  }
};

api

const url = "http://localhost:5000/posts";

export const fetchPosts = () => axios.get(url);
export const createPost = (newPost) => axios.post(url, newPost);
export const updatePost = (id, updatedPost) =>
axios.patch(`${url}/${id}`, updatedPost);

export const deletePost = (id) => axios.delete(`${url}/${id}`);

reducer

import { FETCH_ALL, CREATE, UPDATE, DELETE, LIKE } from "../actions/constants";

const reducer = (posts = [], action) => {
  switch (action.type) {
    case FETCH_ALL:
      return action.payload;
    case CREATE:
      return [...posts, action.payload];
    case UPDATE:
      return posts.map((post) =>
        post._id === action.payload._id ? action.payload : post
      );
    case DELETE:
      return posts.filter((post) => post.id !== action.payload);

    default:
      return posts;
  }
};
export default reducer;

store

import { configureStore } from "@reduxjs/toolkit";
import { reducers } from "./rootreducer";
import { applyMiddleware, compose } from "redux";
import thunk from "redux-thunk";

const store = configureStore(
  { reducer: reducers },
  compose(applyMiddleware(thunk))
);

export default store;

rootreducer

export const reducers = combineReducers({
posts: posts,
});


问:
Is there a way to wordWrap a QRadioButton text in PyQt6?
I'm developing an MCQ app with long text options and just now discovered that the QRadioButton doesn't have Wordwrap option like QLabel. I'm getting my sentences truncated. Is there any way to implement this?

I tried using CSS with word wrap = "break-word" but it didn't work.

I also tried to use QTextBrowser with html but it does not support Radio Buttons input type="radio"

Thx,


问:
How do I get warnings for uninitialized member variables? (clang, c++17)
I understand that c++ variable initialization is extremely complicated and not all compilers 100% conform to the standard, if it's well defined in the first place. Therefore, I want to generate warnings in our whole codebase wherever a variable is not explicitly initialized.

Through my search, I came across these two flags: -Wmissing-field-initializers and -Wconditional-uninitialized, which look promising. So, I tried the following test code:

```<code>#include <iostream>

class Foo {
private:
  int bar;

public:
  Foo() {}
  int Bar() { return bar; }
};

int main () {
  Foo foo;
  std::cout << foo.Bar();
  return 0;
}
</code>```

where Foo::bar is not initialized anywhere: it's not value initialized, the constructor is user defined and does not initialize bar. However, when I compiled it with clang++ -std=c++17 -Wmissing-field-initializers -Wmissing-field-initializers, I'm not getting any warnings.

What am I missing here? Thanks.

Body:
I understand that c++ variable initialization is extremely complicated and not all compilers 100% conform to the standard, if it's well defined in the first place. Therefore, I want to generate warnings in our whole codebase wherever a variable is not explicitly initialized.

Through my search, I came across these two flags: -Wmissing-field-initializers and -Wconditional-uninitialized, which look promising. So, I tried the following test code:

#include <iostream>

class Foo {
private:
  int bar;

public:
  Foo() {}
  int Bar() { return bar; }
};

int main () {
  Foo foo;
  std::cout << foo.Bar();
  return 0;
}

where Foo::bar is not initialized anywhere: it's not value initialized, the constructor is user defined and does not initialize bar. However, when I compiled it with clang++ -std=c++17 -Wmissing-field-initializers -Wmissing-field-initializers, I'm not getting any warnings.

What am I missing here? Thanks.


问:
How to make an elastic search query with a blank space
I am making queries in kibana and am getting errors. Specifically, I want my search query to be just one blank space. Here is an example: request.query(" "). However, I keep getting an error where it says it there is a parsing exception. Does anyone know how to properly format a string query with one blank space properly so that no error is returned? Thank you in advance!</p>
```<code>                     {
                        "query_string":{
                           "query":"( ) OR (* *)",
                           "default_field":"contentTitle",
                           "fields":[

                           ],
                           "type":"best_fields",
                           "default_operator":"or",
                           "max_determinized_states":10000,
                           "enable_position_increments":true,
                           "fuzziness":"AUTO",
                           "fuzzy_prefix_length":0,
                           "fuzzy_max_expansions":50,
                           "phrase_slop":0,
                           "escape":false,
                           "auto_generate_synonyms_phrase_query":true,
                           "fuzzy_transpositions":true,
                           "boost":1.5
                        }
                     }
The exception is "type" : "query_shard_exception", "reason" : "Failed to parse query [( ) OR (* *)]",

I have tried using escape characters to no avail.
</code>```

Body:
I am making queries in kibana and am getting errors. Specifically, I want my search query to be just one blank space. Here is an example: request.query(" "). However, I keep getting an error where it says it there is a parsing exception. Does anyone know how to properly format a string query with one blank space properly so that no error is returned? Thank you in advance!

                     {
                        "query_string":{
                           "query":"( ) OR (* *)",
                           "default_field":"contentTitle",
                           "fields":[

                           ],
                           "type":"best_fields",
                           "default_operator":"or",
                           "max_determinized_states":10000,
                           "enable_position_increments":true,
                           "fuzziness":"AUTO",
                           "fuzzy_prefix_length":0,
                           "fuzzy_max_expansions":50,
                           "phrase_slop":0,
                           "escape":false,
                           "auto_generate_synonyms_phrase_query":true,
                           "fuzzy_transpositions":true,
                           "boost":1.5
                        }
                     }
The exception is "type" : "query_shard_exception", "reason" : "Failed to parse query [( ) OR (* *)]",

I have tried using escape characters to no avail.


问:
Net Maui android app shows blank page after login (Azure B2C) the next time after a successful login and logout
I am doing a login flow in .net maui, first time I try the flow works properly showing the landing page, after a successful logout, I try login again and one blank page is shown instead of the landing page.

I am using shell and the login code is the following

```<code> public partial class LoginPageViewModel : BaseViewModel
{
    private readonly IAuthNService _authNService;

    public LoginPageViewModel(IAuthNService authNService)
    {
        _authNService = authNService;
    }

    [ICommand]
    async void Login()
    {
        try
        {
            var result = await _authNService.LoginAsync(CancellationToken.None);
            var token = result?.IdToken;
            if (token != null)
            {
                var handler = new JwtSecurityTokenHandler();
                var data = handler.ReadJwtToken(token);
                var claims = data.Claims.ToList();
                if (data != null)
                {
                    await Shell.Current.GoToAsync($"//{nameof(DashboardPage)}", true);
                }
            }
        }
        catch (MsalClientException ex)
        {
            await Toast.Make(ex.Message).Show();
        }
        catch (Exception ex)
        {
            await Toast.Make(ex.Message).Show();
        }
    }
}
</code>```

Body:
I am doing a login flow in .net maui, first time I try the flow works properly showing the landing page, after a successful logout, I try login again and one blank page is shown instead of the landing page.

I am using shell and the login code is the following

 public partial class LoginPageViewModel : BaseViewModel
{
    private readonly IAuthNService _authNService;

    public LoginPageViewModel(IAuthNService authNService)
    {
        _authNService = authNService;
    }

    [ICommand]
    async void Login()
    {
        try
        {
            var result = await _authNService.LoginAsync(CancellationToken.None);
            var token = result?.IdToken;
            if (token != null)
            {
                var handler = new JwtSecurityTokenHandler();
                var data = handler.ReadJwtToken(token);
                var claims = data.Claims.ToList();
                if (data != null)
                {
                    await Shell.Current.GoToAsync($"//{nameof(DashboardPage)}", true);
                }
            }
        }
        catch (MsalClientException ex)
        {
            await Toast.Make(ex.Message).Show();
        }
        catch (Exception ex)
        {
            await Toast.Make(ex.Message).Show();
        }
    }
}


问:
Jest mocking / spying not working when verifying the usage of console.log
Hello so I am doing a coding-style checker and to have great code I am doing so unit_tests.
Here is my code :

CO1.test.js

const CO1 = require('../rules/C-O1');
const CG1 = require("../rules/C-G1.cjs");

test("passing1", () => {
    const logSpy = jest.spyOn(global.console, 'log');

    CO1.checkCO1("../testFiles/C-O1/Passing", "main.c")
    expect(logSpy).not.toHaveBeenCalled();
})

test("passing2", () => {
    const logSpy = jest.spyOn(global.console, 'log');

    CO1.checkCO1("../testFiles/C-O1/Passing", "test.c")
    expect(logSpy).not.toHaveBeenCalled();
})

test('failing 1', () => {
    global.console.log = jest.fn();

    CG1.checkCG1("../testFiles/C-O1/Failling", "a.out")
    expect(console.log).toHaveBeenCalled();
    expect(console.log).toHaveBeenCalledTimes(1);
});

test('failling 2', () => {
    const logSpy = jest.spyOn(global.console, 'error').mockImplementation(() => {});

    CG1.checkCG1("../testFiles/C-O1/Failling", "libmy.a")
    expect(logSpy).toHaveBeenCalled();
    expect(logSpy).toHaveBeenCalledTimes(1);
    logSpy.mockReset();
});

```
<p>CO1.cjs</p>
<pre class="lang-js prettyprint-override"><code>module.exports.checkCO1 = function (dirSrc, file) {
    if (file.endsWith(".a") || file.endsWith(".out")) {
        console.error(dirSrc + "/" + file + `:C-O1`);
    }
}

</code>```

I tried to verify if my code is printing.
I tried with .log also.

Body:
Hello so I am doing a coding-style checker and to have great code I am doing so unit_tests.
Here is my code :

CO1.test.js

const CO1 = require('../rules/C-O1');
const CG1 = require("../rules/C-G1.cjs");

test("passing1", () => {
    const logSpy = jest.spyOn(global.console, 'log');

    CO1.checkCO1("../testFiles/C-O1/Passing", "main.c")
    expect(logSpy).not.toHaveBeenCalled();
})

test("passing2", () => {
    const logSpy = jest.spyOn(global.console, 'log');

    CO1.checkCO1("../testFiles/C-O1/Passing", "test.c")
    expect(logSpy).not.toHaveBeenCalled();
})

test('failing 1', () => {
    global.console.log = jest.fn();

    CG1.checkCG1("../testFiles/C-O1/Failling", "a.out")
    expect(console.log).toHaveBeenCalled();
    expect(console.log).toHaveBeenCalledTimes(1);
});

test('failling 2', () => {
    const logSpy = jest.spyOn(global.console, 'error').mockImplementation(() => {});

    CG1.checkCG1("../testFiles/C-O1/Failling", "libmy.a")
    expect(logSpy).toHaveBeenCalled();
    expect(logSpy).toHaveBeenCalledTimes(1);
    logSpy.mockReset();
});

CO1.cjs

module.exports.checkCO1 = function (dirSrc, file) {
    if (file.endsWith(".a") || file.endsWith(".out")) {
        console.error(dirSrc + "/" + file + `:C-O1`);
    }
}

I tried to verify if my code is printing.
I tried with .log also.


问:
Google Chrome not running when Chromedriver tries to access it - EC2 instance
I've looked at so many suggested solutions to this issue, and yet none apply or have worked for me. I'm trying to test updating chromedriver and google-chrome on our staging server and having no luck.

We were using an older version of selenium-webdriver, so I updated as far as we could go (we are on Ruby 2.3.6), so our versions stand at:

```<code>selenium-webdriver: 3.142.7
capybara: 2.7.1
Operating System: Ubuntu 18.04.4 LTS
Kernel: Linux 5.4.0-1093-aws
Architecture: x86-64

$ which chromedriver
/usr/bin/chromedriver
$ which google-chrome
/usr/bin/google-chrome
$ chromedriver --version
ChromeDriver 109.0.5414.74 (e7c5703604daa9cc128ccf5a5d3e993513758913-refs/branch-heads/5414@{#1172})
$ google-chrome --version
Google Chrome 109.0.5414.74
</code>```

I've been running it somewhat like this. I added the Service instance after moving to selenium webdriver 3.142.7

```<code>def set_defaults
  options = set_options
  capabilities = Selenium::WebDriver::Remote::Capabilities.chrome(chromeOptions: options)
  service = Selenium::WebDriver::Service.chrome(path: '/usr/bin/chromedriver')
  selenium_options = { browser: :chrome, desired_capabilities: capabilities, service: service }
  Capybara.register_driver :chrome do |app|
    Capybara::Selenium::Driver.new(app, selenium_options)
  end
  Capybara.javascript_driver = :chrome
end

def set_options
  user_agent = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.10; rv:36.0) Gecko/20100101 Firefox/36.0'
  options = Selenium::WebDriver::Chrome::Options.new
  options.add_argument('--no-sandbox')
  options.add_argument('--headless')
  options.add_argument("--user-agent='#{user_agent}'")
  options.add_argument('--disable-popup-blocking')
  options.add_argument('--disable-gpu')
  options.add_argument('--window-size=1280,1024')
  options.add_argument('--disable-dev-shm-usage') # I added this after reading other answers on SO, but it didn't make a difference
  options
end
</code>```

The vast majority of this was set up previously and working until we needed to update our chromedriver/google-chrome versions, which is what I'm testing.

Here is the error I'm seeing when trying to run the above code:

```<code>Selenium::WebDriver::Error::UnknownError: unknown error: Chrome failed to start: exited abnormally.
  (unknown error: DevToolsActivePort file doesn't exist)
  (The process started from chrome location /usr/bin/google-chrome is no longer running, so ChromeDriver is assuming that Chrome has crashed.)
    from #0 0x55b693029303 <unknown>
    from #1 0x55b692dfdd37 <unknown>
    from #2 0x55b692e26157 <unknown>
    from #3 0x55b692e22330 <unknown>
    from #4 0x55b692e634a6 <unknown>
    from #5 0x55b692e5a753 <unknown>
    from #6 0x55b692e2da14 <unknown>
    from #7 0x55b692e2eb7e <unknown>
    from #8 0x55b69307832e <unknown>
    from #9 0x55b69307bc0e <unknown>
    from #10 0x55b69305e610 <unknown>
    from #11 0x55b69307cc23 <unknown>
    from #12 0x55b693050545 <unknown>
    from #13 0x55b69309d6a8 <unknown>
    from #14 0x55b69309d836 <unknown>
    from #15 0x55b6930b8d13 <unknown>
... 7 levels...
    from /var/www/apps/einstein_staging/shared/bundle/ruby/2.3.0/gems/selenium-webdriver-3.142.7/lib/selenium/webdriver/remote/bridge.rb:167:in `execute'
    from /var/www/apps/einstein_staging/shared/bundle/ruby/2.3.0/gems/selenium-webdriver-3.142.7/lib/selenium/webdriver/remote/bridge.rb:102:in `create_session'
    from /var/www/apps/einstein_staging/shared/bundle/ruby/2.3.0/gems/selenium-webdriver-3.142.7/lib/selenium/webdriver/remote/bridge.rb:56:in `handshake'
    from /var/www/apps/einstein_staging/shared/bundle/ruby/2.3.0/gems/selenium-webdriver-3.142.7/lib/selenium/webdriver/chrome/driver.rb:43:in `initialize'
    from /var/www/apps/einstein_staging/shared/bundle/ruby/2.3.0/gems/selenium-webdriver-3.142.7/lib/selenium/webdriver/common/driver.rb:46:in `new'
    from /var/www/apps/einstein_staging/shared/bundle/ruby/2.3.0/gems/selenium-webdriver-3.142.7/lib/selenium/webdriver/common/driver.rb:46:in `for'
    from /var/www/apps/einstein_staging/shared/bundle/ruby/2.3.0/gems/selenium-webdriver-3.142.7/lib/selenium/webdriver.rb:88:in `for'
    from /var/www/apps/einstein_staging/shared/bundle/ruby/2.3.0/gems/capybara-2.7.1/lib/capybara/selenium/driver.rb:14:in `browser'
    from /var/www/apps/einstein_staging/shared/bundle/ruby/2.3.0/gems/capybara-2.7.1/lib/capybara/selenium/driver.rb:46:in `visit'
    from /var/www/apps/einstein_staging/shared/bundle/ruby/2.3.0/gems/capybara-2.7.1/lib/capybara/session.rb:233:in `visit'
    from (irb):21
    from /var/www/apps/einstein_staging/shared/bundle/ruby/2.3.0/gems/railties-3.2.22.5/lib/rails/commands/console.rb:47:in `start'
    from /var/www/apps/einstein_staging/shared/bundle/ruby/2.3.0/gems/railties-3.2.22.5/lib/rails/commands/console.rb:8:in `start'
    from /var/www/apps/einstein_staging/shared/bundle/ruby/2.3.0/gems/railties-3.2.22.5/lib/rails/commands.rb:41:in `<top (required)>'
    from script/rails:21:in `require'
    from script/rails:21:in `<main>'
</code>```

Body:
I've looked at so many suggested solutions to this issue, and yet none apply or have worked for me. I'm trying to test updating chromedriver and google-chrome on our staging server and having no luck.

We were using an older version of selenium-webdriver, so I updated as far as we could go (we are on Ruby 2.3.6), so our versions stand at:

selenium-webdriver: 3.142.7
capybara: 2.7.1
Operating System: Ubuntu 18.04.4 LTS
Kernel: Linux 5.4.0-1093-aws
Architecture: x86-64

$ which chromedriver
/usr/bin/chromedriver
$ which google-chrome
/usr/bin/google-chrome
$ chromedriver --version
ChromeDriver 109.0.5414.74 (e7c5703604daa9cc128ccf5a5d3e993513758913-refs/branch-heads/5414@{#1172})
$ google-chrome --version
Google Chrome 109.0.5414.74

I've been running it somewhat like this. I added the Service instance after moving to selenium webdriver 3.142.7

def set_defaults
  options = set_options
  capabilities = Selenium::WebDriver::Remote::Capabilities.chrome(chromeOptions: options)
  service = Selenium::WebDriver::Service.chrome(path: '/usr/bin/chromedriver')
  selenium_options = { browser: :chrome, desired_capabilities: capabilities, service: service }
  Capybara.register_driver :chrome do |app|
    Capybara::Selenium::Driver.new(app, selenium_options)
  end
  Capybara.javascript_driver = :chrome
end

def set_options
  user_agent = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.10; rv:36.0) Gecko/20100101 Firefox/36.0'
  options = Selenium::WebDriver::Chrome::Options.new
  options.add_argument('--no-sandbox')
  options.add_argument('--headless')
  options.add_argument("--user-agent='#{user_agent}'")
  options.add_argument('--disable-popup-blocking')
  options.add_argument('--disable-gpu')
  options.add_argument('--window-size=1280,1024')
  options.add_argument('--disable-dev-shm-usage') # I added this after reading other answers on SO, but it didn't make a difference
  options
end

The vast majority of this was set up previously and working until we needed to update our chromedriver/google-chrome versions, which is what I'm testing.

Here is the error I'm seeing when trying to run the above code:

Selenium::WebDriver::Error::UnknownError: unknown error: Chrome failed to start: exited abnormally.
  (unknown error: DevToolsActivePort file doesn't exist)
  (The process started from chrome location /usr/bin/google-chrome is no longer running, so ChromeDriver is assuming that Chrome has crashed.)
    from #0 0x55b693029303 <unknown>
    from #1 0x55b692dfdd37 <unknown>
    from #2 0x55b692e26157 <unknown>
    from #3 0x55b692e22330 <unknown>
    from #4 0x55b692e634a6 <unknown>
    from #5 0x55b692e5a753 <unknown>
    from #6 0x55b692e2da14 <unknown>
    from #7 0x55b692e2eb7e <unknown>
    from #8 0x55b69307832e <unknown>
    from #9 0x55b69307bc0e <unknown>
    from #10 0x55b69305e610 <unknown>
    from #11 0x55b69307cc23 <unknown>
    from #12 0x55b693050545 <unknown>
    from #13 0x55b69309d6a8 <unknown>
    from #14 0x55b69309d836 <unknown>
    from #15 0x55b6930b8d13 <unknown>
... 7 levels...
    from /var/www/apps/einstein_staging/shared/bundle/ruby/2.3.0/gems/selenium-webdriver-3.142.7/lib/selenium/webdriver/remote/bridge.rb:167:in `execute'
    from /var/www/apps/einstein_staging/shared/bundle/ruby/2.3.0/gems/selenium-webdriver-3.142.7/lib/selenium/webdriver/remote/bridge.rb:102:in `create_session'
    from /var/www/apps/einstein_staging/shared/bundle/ruby/2.3.0/gems/selenium-webdriver-3.142.7/lib/selenium/webdriver/remote/bridge.rb:56:in `handshake'
    from /var/www/apps/einstein_staging/shared/bundle/ruby/2.3.0/gems/selenium-webdriver-3.142.7/lib/selenium/webdriver/chrome/driver.rb:43:in `initialize'
    from /var/www/apps/einstein_staging/shared/bundle/ruby/2.3.0/gems/selenium-webdriver-3.142.7/lib/selenium/webdriver/common/driver.rb:46:in `new'
    from /var/www/apps/einstein_staging/shared/bundle/ruby/2.3.0/gems/selenium-webdriver-3.142.7/lib/selenium/webdriver/common/driver.rb:46:in `for'
    from /var/www/apps/einstein_staging/shared/bundle/ruby/2.3.0/gems/selenium-webdriver-3.142.7/lib/selenium/webdriver.rb:88:in `for'
    from /var/www/apps/einstein_staging/shared/bundle/ruby/2.3.0/gems/capybara-2.7.1/lib/capybara/selenium/driver.rb:14:in `browser'
    from /var/www/apps/einstein_staging/shared/bundle/ruby/2.3.0/gems/capybara-2.7.1/lib/capybara/selenium/driver.rb:46:in `visit'
    from /var/www/apps/einstein_staging/shared/bundle/ruby/2.3.0/gems/capybara-2.7.1/lib/capybara/session.rb:233:in `visit'
    from (irb):21
    from /var/www/apps/einstein_staging/shared/bundle/ruby/2.3.0/gems/railties-3.2.22.5/lib/rails/commands/console.rb:47:in `start'
    from /var/www/apps/einstein_staging/shared/bundle/ruby/2.3.0/gems/railties-3.2.22.5/lib/rails/commands/console.rb:8:in `start'
    from /var/www/apps/einstein_staging/shared/bundle/ruby/2.3.0/gems/railties-3.2.22.5/lib/rails/commands.rb:41:in `<top (required)>'
    from script/rails:21:in `require'
    from script/rails:21:in `'


问:
Flet Colours Behave Differently In Bottom Navigation
I'm currently writing a small app using flet but I've run into a weird UI issue where I'm using the same colour in two different places and they are coming out looking different to one another. The code I'm running looks like this:

import flet

def main(page: flet.Page):
    page.bgcolor = "#535D6C"
    page.window_title_bar_hidden = True
    page.spacing = 0
    page.padding = 0

    width_screen = page.window_width

    def maximise_window(e):
        page.window_maximized = not page.window_maximized
        page.update()

    def minimise_window(e):
        page.window_minimized = not page.window_minimized
        page.update()

    file_bar = flet.ResponsiveRow([
        flet.WindowDragArea(
            flet.Container(
                width=width_screen,
                bgcolor=flet.colors.BLUE_GREY_900,
                padding=3,
                content=flet.Row([
                    flet.Text(
                        "Home",
                        size=12,
                        color=flet.colors.WHITE60,
                    ),
                    flet.Container(
                        content=flet.Row([
                            flet.IconButton(flet.icons.MINIMIZE_ROUNDED,
                                            icon_color=flet.colors.WHITE60,
                                            on_click=minimise_window,
                                            ),
                            flet.IconButton(flet.icons.CHECK_BOX_OUTLINE_BLANK,
                                            icon_color=flet.colors.WHITE60,
                                            on_click=maximise_window,
                                            ),
                            flet.IconButton(flet.icons.CLOSE,
                                            icon_color=flet.colors.WHITE60,
                                            on_click=lambda e: page.window_close(),
                                            ),
                        ])
                    )
                ], alignment="spaceBetween")
            )
        )
    ])

    page.navigation_bar = flet.NavigationBar(
        bgcolor=flet.colors.BLUE_GREY_900,
        destinations=[
            flet.NavigationDestination(icon=flet.icons.HOME),
            flet.NavigationDestination(icon=flet.icons.EXPLORE),
            flet.NavigationDestination(icon=flet.icons.SETTINGS),
        ]
    )

    page.add(
        file_bar,
    )

flet.app(target=main)
```

Display with different colours

I've added in multiple different colours including custom ones and the behaviour doesn't change. It seems as though this only happens in the bottom navigation bar though and I'm not sure how to fix it.

Thanks,
Mitchell

Body:
I'm currently writing a small app using flet but I've run into a weird UI issue where I'm using the same colour in two different places and they are coming out looking different to one another. The code I'm running looks like this:

import flet

def main(page: flet.Page):
    page.bgcolor = "#535D6C"
    page.window_title_bar_hidden = True
    page.spacing = 0
    page.padding = 0

    width_screen = page.window_width

    def maximise_window(e):
        page.window_maximized = not page.window_maximized
        page.update()

    def minimise_window(e):
        page.window_minimized = not page.window_minimized
        page.update()

    file_bar = flet.ResponsiveRow([
        flet.WindowDragArea(
            flet.Container(
                width=width_screen,
                bgcolor=flet.colors.BLUE_GREY_900,
                padding=3,
                content=flet.Row([
                    flet.Text(
                        "Home",
                        size=12,
                        color=flet.colors.WHITE60,
                    ),
                    flet.Container(
                        content=flet.Row([
                            flet.IconButton(flet.icons.MINIMIZE_ROUNDED,
                                            icon_color=flet.colors.WHITE60,
                                            on_click=minimise_window,
                                            ),
                            flet.IconButton(flet.icons.CHECK_BOX_OUTLINE_BLANK,
                                            icon_color=flet.colors.WHITE60,
                                            on_click=maximise_window,
                                            ),
                            flet.IconButton(flet.icons.CLOSE,
                                            icon_color=flet.colors.WHITE60,
                                            on_click=lambda e: page.window_close(),
                                            ),
                        ])
                    )
                ], alignment="spaceBetween")
            )
        )
    ])

    page.navigation_bar = flet.NavigationBar(
        bgcolor=flet.colors.BLUE_GREY_900,
        destinations=[
            flet.NavigationDestination(icon=flet.icons.HOME),
            flet.NavigationDestination(icon=flet.icons.EXPLORE),
            flet.NavigationDestination(icon=flet.icons.SETTINGS),
        ]
    )

    page.add(
        file_bar,
    )

flet.app(target=main)

Display with different colours

I've added in multiple different colours including custom ones and the behaviour doesn't change. It seems as though this only happens in the bottom navigation bar though and I'm not sure how to fix it.

Thanks,
Mitchell


问:
Unable to show a different value after detecting an undefined variable in javascript
I'm using the script below to detect city and state from geo.js, but sometimes city comes back as 'undefined' because city is not returned in the array response. How can I detect if json.city is undefined and show something else in "citybody" if city is not detected?

```

I've tried using json.city != 'undefined' but does not work.

Body:
I'm using the script below to detect city and state from geo.js, but sometimes city comes back as 'undefined' because city is not returned in the array response. How can I detect if json.city is undefined and show something else in "citybody" if city is not detected?

I've tried using json.city != 'undefined' but does not work.


问:
Problem with precision qualifiers in a shader for android
I had a problem rendering with a shader for Android on Löve2d due to the precision of the floats, so I wanted to add these precompilation instructions so that the floats are automatically highp if possible.

#ifdef GL_ES
#ifdef GL_FRAGMENT_PRECISION_HIGH
precision highp float;
#else
precision mediump float;
#endif
#endif
```
<p>But I get this error:</p>
```ERROR: highp : overloaded functions must have the same parameter precision qualifiers for argument 1
ERROR: highp : overloaded functions must have the same parameter precision qualifiers for argument 3
ERROR: highp : overloaded functions must have the same parameter precision qualifiers for argument 4
```
<p>Which matches this line:</p>
<pre class="lang-c prettyprint-override"><code>vec4 effect(vec4 color, Image texture, vec2 texture_coords, vec2 screen_coords)
</code>```

My question is why and how to fix it? Because on the examples I saw on the Löve2d forum it seemed to work.

The version of OpenGL ES on the device that produces this error is 3.2 if that helps.

Body:
I had a problem rendering with a shader for Android on Löve2d due to the precision of the floats, so I wanted to add these precompilation instructions so that the floats are automatically highp if possible.

#ifdef GL_ES
#ifdef GL_FRAGMENT_PRECISION_HIGH
precision highp float;
#else
precision mediump float;
#endif
#endif

But I get this error:

ERROR: highp : overloaded functions must have the same parameter precision qualifiers for argument 1
ERROR: highp : overloaded functions must have the same parameter precision qualifiers for argument 3
ERROR: highp : overloaded functions must have the same parameter precision qualifiers for argument 4

Which matches this line:

vec4 effect(vec4 color, Image texture, vec2 texture_coords, vec2 screen_coords)

My question is why and how to fix it? Because on the examples I saw on the Löve2d forum it seemed to work.

The version of OpenGL ES on the device that produces this error is 3.2 if that helps.


问:
Why the structural similarity index measure decreases with decreasing image resolution?
I computed the structural similarity index (SSIM) value between a ground truth mask and its corresponding predicted mask in an image segmentation task using a UNet model. Both the ground truth and predicted masks are of 1024 x 1024 resolution. I got an SSIM value of 0.9544. I resized the ground truth and predicted mask to 512 x 512 using bicubic interpolation and measured its SSIM value to be 0.9444. I repeated the process for 256 x 256, 128 x128, and 64 x 64 image resolutions and found the SSIM values as 0.9259, 0.8593, and 0.8376. I observed that the equations for luminance, structure, and contrast components in the SSIM formula appear to be normalized and does not seem to vary with image resolution. My question is for the same pair of ground truth and predicted mask, why the SSIM values keep decreasing with decreasing image resolution?</p>


问:
Podman Build Gives 404 with Private Registry Image
I am running GitLab CI on an EC2. In one of my steps, I pull an image from my private nexus registry.

I am able to login to registry

podman login --tls-verify=false -u {user}

I am also able to pull an image from that registry

podman pull --tls-verify=false private/nexus/repo/image:1

If, however, I try to build a dockerfile with the same image, I get an error.

```<code>FROM private/nexus/repo/image:1

...
</code>```

Trying to build the above image results in invalid status code from registry 404 not found.

I have no idea what the issue is.

Body:
I am running GitLab CI on an EC2. In one of my steps, I pull an image from my private nexus registry.

I am able to login to registry

podman login --tls-verify=false -u {user}

I am also able to pull an image from that registry

podman pull --tls-verify=false private/nexus/repo/image:1

If, however, I try to build a dockerfile with the same image, I get an error.

FROM private/nexus/repo/image:1

...

Trying to build the above image results in invalid status code from registry 404 not found.

I have no idea what the issue is.


问:
Search across multiple fields in the table view
Let's say I don't want the text "Winter" across any of the fields in my current table. I can find and replace, but is there a way to find out, before replacing the values, whether they even exist, and how many exist?

Using find and replace is useful, but it doesn't help me understand if the data is present in the dataset, and it doesn't give an indication even after finishing, whether any data was replaced.


问:
How to make it so that when pressed hotkey + anything else the hotkey worked?
I'm writing a script for game, i need to bind some key for pressing right click for three times. I can do it, but if i will use it in game i can press WASD or something else when i using hotkey and it doesn't work.

My code here :

```<code>import keyboard
import mouse
import time

iswork = False
def work():
    global iswork
    if iswork:
        iswork = False
        print("Script deactivated")
    else:
        iswork = True
        print("Script activated")

keyboard.add_hotkey("F4",work)
def RRR():
  if iswork :
      for i in range(3):
          mouse.right_click()
          time.sleep(0.05)

bind = input("Bind for Right - Right - Right :")
#keyboard.add_hotkey(bind,RRR)
while iswork:
    if keyboard.is_pressed("x") and len(keyboard._pressed_events) >= 1:
        RRR()
    elif keyboard.is_pressed("x"):
        RRR()

while True :
    count = 0
</code>```

Body:
I'm writing a script for game, i need to bind some key for pressing right click for three times. I can do it, but if i will use it in game i can press WASD or something else when i using hotkey and it doesn't work.

My code here :

import keyboard
import mouse
import time

iswork = False
def work():
    global iswork
    if iswork:
        iswork = False
        print("Script deactivated")
    else:
        iswork = True
        print("Script activated")

keyboard.add_hotkey("F4",work)
def RRR():
  if iswork :
      for i in range(3):
          mouse.right_click()
          time.sleep(0.05)

bind = input("Bind for Right - Right - Right :")
#keyboard.add_hotkey(bind,RRR)
while iswork:
    if keyboard.is_pressed("x") and len(keyboard._pressed_events) >= 1:
        RRR()
    elif keyboard.is_pressed("x"):
        RRR()

while True :
    count = 0


问:
how to use font-awesome icons with their unicode in JavaScript (disable the escabe characters)
I am trying to use font-awesome icon with their unicodes but backslach is recognized as a escabe character.

```<code>switch (description) {
        case "sunny":
          icon = 'f112';
          break;
        case "rainy":
          icon = "\f185";
          break;
        default:
          icon = '';
      }
</code>```

I want to get \f185; unicoded icon but because of the escape character it returns another unicode.
how can i get the exact unicode. you can see the screenshoot in the link below
sunny unicode

Body:
I am trying to use font-awesome icon with their unicodes but backslach is recognized as a escabe character.

switch (description) {
        case "sunny":
          icon = 'f112';
          break;
        case "rainy":
          icon = "\f185";
          break;
        default:
          icon = '';
      }

I want to get \f185; unicoded icon but because of the escape character it returns another unicode.
how can i get the exact unicode. you can see the screenshoot in the link below
sunny unicode


问:
Why electron-app it's not working in production env?
I have an application which I have used the @azure/msal-node authentication Library for Node JS
everything works well on localhost env when I click to login it took me to a web page in browser to enter credentials and when I came back to the application authorized me to use the app as expected.

BUT when I build with npm run electron-builder and access the application from .exe it took me to a web page and even if I do my same credentials and return back to the application it still in home page which means I am not authorized to use the app.

I think the problem came from this block of code:

// Event handlers
ipcMain.on(IPC_MESSAGES.LOGIN, async () => {
  const account = await authProvider.login(); //<- stop here and didn't complete to the next line
  await mainWindow.loadFile(path.join(__dirname, "./form.html"));
  mainWindow.webContents.send(IPC_MESSAGES.SHOW_WELCOME_MESSAGE, account);
});
```
<pre class="lang-js prettyprint-override"><code>async login() {
    const authResponse = await this.getToken({
      // If there are scopes that you would like users to consent up front, add them below
      // by default, MSAL will add the OIDC scopes to every token request, so we omit those here
      scopes: ["------------------------------------------"],
    });

    var https = require("follow-redirects").https;
    var fs = require("fs");

    var options = {
      method: "GET",
      hostname: "----------------------------------",
      path: "------------------------------------",
      headers: {
        "Content-Type": "application/json",
        Authorization: `Bearer ${authResponse.accessToken}`,
      },
      maxRedirects: 20,
    };

    var req = https.request(options, function (res) {
      var chunks = [];

      res.on("data", function (chunk) {
        chunks.push(chunk);
      });

      res.on("end", function (chunk) {
        var body = Buffer.concat(chunks);
      });

      res.on("error", function (error) {
        console.error(error);
      });
    });

    req.end();

    return this.handleResponse(authResponse);
  }
</code>```

Any help would be greatly appreciated!

Body:
I have an application which I have used the @azure/msal-node authentication Library for Node JS
everything works well on localhost env when I click to login it took me to a web page in browser to enter credentials and when I came back to the application authorized me to use the app as expected.

BUT when I build with npm run electron-builder and access the application from .exe it took me to a web page and even if I do my same credentials and return back to the application it still in home page which means I am not authorized to use the app.

I think the problem came from this block of code:

// Event handlers
ipcMain.on(IPC_MESSAGES.LOGIN, async () => {
  const account = await authProvider.login(); //<- stop here and didn't complete to the next line
  await mainWindow.loadFile(path.join(__dirname, "./form.html"));
  mainWindow.webContents.send(IPC_MESSAGES.SHOW_WELCOME_MESSAGE, account);
});

async login() {
    const authResponse = await this.getToken({
      // If there are scopes that you would like users to consent up front, add them below
      // by default, MSAL will add the OIDC scopes to every token request, so we omit those here
      scopes: ["------------------------------------------"],
    });

    var https = require("follow-redirects").https;
    var fs = require("fs");

    var options = {
      method: "GET",
      hostname: "----------------------------------",
      path: "------------------------------------",
      headers: {
        "Content-Type": "application/json",
        Authorization: `Bearer ${authResponse.accessToken}`,
      },
      maxRedirects: 20,
    };

    var req = https.request(options, function (res) {
      var chunks = [];

      res.on("data", function (chunk) {
        chunks.push(chunk);
      });

      res.on("end", function (chunk) {
        var body = Buffer.concat(chunks);
      });

      res.on("error", function (error) {
        console.error(error);
      });
    });

    req.end();

    return this.handleResponse(authResponse);
  }

Any help would be greatly appreciated!


问:
How to handle ProblemDetails response from API in .NET MAUI app
I am developing a .NET MAUI app using this excellent reference app produced by Microsoft (h/t Michael Stonis):

https://github.com/dotnet-architecture/eshop-mobile-client

I highly recommend this reference app and its PDF guide for new .NET MAUI programmers (sorry for the auto-download on the MSFT site):

https://dotnet.microsoft.com/en-us/download/e-book/maui/pdf

In it, there is a RequestProvider service that handles the Get/Put/Post/Delete methods that interact with the API, very handy. However, it looks like the methods can only accept or return a single TResult - here is the PutAsync method:

```<code>public async Task<TResult> PutAsync<TResult>(string uri, TResult data, string token = "", string header = "")
{
    HttpClient httpClient = GetOrCreateHttpClient(token);

    if (!string.IsNullOrEmpty(header))
    {
        RequestProvider.AddHeaderParameter(httpClient, header);
    }

    var content = new StringContent(JsonSerializer.Serialize(data));
    content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
    HttpResponseMessage response = await httpClient.PutAsync(uri, content).ConfigureAwait(false);

    await RequestProvider.HandleResponse(response).ConfigureAwait(false);
    TResult result = await response.Content.ReadFromJsonAsync<TResult>();

    return result;
}
</code>```

Here is my call into this method. 'profile' is a MyProfileClass object to be updated in the API:

```<code>var response = await _requestProvider.PutAsync(uri, profile, authToken);
</code>```

The response variable is of MyProfileClass type in this case. But if there is a validation or other error in my API, I respond back with an ObjectResult of type Microsoft.AspNetCore.Mvc.ProblemDetails.  Here is my API code that sends it back:

```<code>return Problem("Error: " + ex.Message, null, 400, "Error Updating Profile");
</code>```

So I want to capture the error message and pass it back from the PutAsync method to throw up an alert to show the user what the problem is. I built a ProblemDetailsWithErrors class to hold this type of result:

```<code>public class ProblemDetailsWithErrors
{
    public string Detail { get; set; }
    public string Type { get; set; }
    public string Title { get; set; }
    public int Status { get; set; }
    public string TraceId { get; set; }
    public Dictionary<string, string[]> Errors { get; set; }
}
</code>```

My issue is the PutAsync method as it's designed only returns a TResult object. I'm not an expert with C#, but is there a way to return the ProblemDetailsWithErrors object instead of MyProfileClass from PutAsync? Or maybe a way to return both? Maybe it's a simple change to the PutAsync method... any ideas?

Body:
I am developing a .NET MAUI app using this excellent reference app produced by Microsoft (h/t Michael Stonis):

https://github.com/dotnet-architecture/eshop-mobile-client

I highly recommend this reference app and its PDF guide for new .NET MAUI programmers (sorry for the auto-download on the MSFT site):

https://dotnet.microsoft.com/en-us/download/e-book/maui/pdf

In it, there is a RequestProvider service that handles the Get/Put/Post/Delete methods that interact with the API, very handy. However, it looks like the methods can only accept or return a single TResult - here is the PutAsync method:

public async Task<TResult> PutAsync<TResult>(string uri, TResult data, string token = "", string header = "")
{
    HttpClient httpClient = GetOrCreateHttpClient(token);

    if (!string.IsNullOrEmpty(header))
    {
        RequestProvider.AddHeaderParameter(httpClient, header);
    }

    var content = new StringContent(JsonSerializer.Serialize(data));
    content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
    HttpResponseMessage response = await httpClient.PutAsync(uri, content).ConfigureAwait(false);

    await RequestProvider.HandleResponse(response).ConfigureAwait(false);
    TResult result = await response.Content.ReadFromJsonAsync<TResult>();

    return result;
}

Here is my call into this method. 'profile' is a MyProfileClass object to be updated in the API:

var response = await _requestProvider.PutAsync(uri, profile, authToken);

The response variable is of MyProfileClass type in this case. But if there is a validation or other error in my API, I respond back with an ObjectResult of type Microsoft.AspNetCore.Mvc.ProblemDetails.  Here is my API code that sends it back:

return Problem("Error: " + ex.Message, null, 400, "Error Updating Profile");

So I want to capture the error message and pass it back from the PutAsync method to throw up an alert to show the user what the problem is. I built a ProblemDetailsWithErrors class to hold this type of result:

public class ProblemDetailsWithErrors
{
    public string Detail { get; set; }
    public string Type { get; set; }
    public string Title { get; set; }
    public int Status { get; set; }
    public string TraceId { get; set; }
    public Dictionary<string, string[]> Errors { get; set; }
}

My issue is the PutAsync method as it's designed only returns a TResult object. I'm not an expert with C#, but is there a way to return the ProblemDetailsWithErrors object instead of MyProfileClass from PutAsync? Or maybe a way to return both? Maybe it's a simple change to the PutAsync method... any ideas?


问:
Are there any downsides to using Pytorch's Lazy* modules?
PyTorch 1.8 introduced the Lazy* modules (i.e., LazyLinear) that alleviates the need to specify input sizes. This has tremendous benefits for optimizing hyperparameters of deep neural network models during the design & architecture phases.

Are there any downsides to using these modules versus the traditional implementations that require specifying input sizes? Why would one not use the Lazy version of the implementations, other than to be overly explicit?

Example with Lazy* layers

```<code>model = nn.Sequential(
            nn.Conv1d(in_channels=1, out_channels=32, kernel_size=2048, stride=128),
            nn.ReLU(),
            nn.MaxPool1d(kernel_size=8, stride=2),
            # note: input channels not required
            nn.LazyConv1d(out_channels=32, kernel_size=8, stride=2, padding=1),
            nn.ReLU(),
            nn.MaxPool1d(kernel_size=2, stride=2),
            nn.Flatten(),
            # note: input channels not required
            nn.LazyLinear(8)
</code>```

PyTorch 1.8 documentation

Body:
PyTorch 1.8 introduced the Lazy* modules (i.e., LazyLinear) that alleviates the need to specify input sizes. This has tremendous benefits for optimizing hyperparameters of deep neural network models during the design & architecture phases.

Are there any downsides to using these modules versus the traditional implementations that require specifying input sizes? Why would one not use the Lazy version of the implementations, other than to be overly explicit?

Example with Lazy* layers

model = nn.Sequential(
            nn.Conv1d(in_channels=1, out_channels=32, kernel_size=2048, stride=128),
            nn.ReLU(),
            nn.MaxPool1d(kernel_size=8, stride=2),
            # note: input channels not required
            nn.LazyConv1d(out_channels=32, kernel_size=8, stride=2, padding=1),
            nn.ReLU(),
            nn.MaxPool1d(kernel_size=2, stride=2),
            nn.Flatten(),
            # note: input channels not required
            nn.LazyLinear(8)

PyTorch 1.8 documentation


问:
ViewBinding dont work in android studio java
I have defined viewbinding in the build.gradle app section, but I am getting an error in the codes. my app is up to date.

```<code> MainActivity extends AppCompatActivity {
ActivityMainBinding
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(binding.root);
    }
}

build gradle:
    buildFeatures
            {
                viewBinding true;
            }
</code>```

i tried uptaded and rebuild project but it doesnt work

Body:
I have defined viewbinding in the build.gradle app section, but I am getting an error in the codes. my app is up to date.

 MainActivity extends AppCompatActivity {
ActivityMainBinding
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(binding.root);
    }
}

build gradle:
    buildFeatures
            {
                viewBinding true;
            }

i tried uptaded and rebuild project but it doesnt work