问:
django.db.utils.ProgrammingError: column accounts_account.username does not exist
I am getting this error after I was customizing my Customer User Model. and now I get this error when I try to login into the admin panel and when I try to create a superuser.

I tried to drop the postgresql database called skincareryland... but am getting an error on the password login... when I try to change the password I get this error.. ERROR:  role "postgres" does not exist

I also tried going through these steps from an overstack post, but not having any luck fixing the problem... Comment out 'django.contrib.admin' from INSTALLED_APPS in settings.py and comment out # path('admin/', admin.site.urls) in urls.py

here is a better snapshot of my models.py code

here is a better snapshot of my settings.py code

```<code>from django.db import models
from django.contrib.auth.models import AbstractBaseUser,
BaseUserManager

class MyAccountManager(BaseUserManager):
   def create_user(self, first_name, last_name, username, email,
     password=None):
    if not email:
        raise ValueError('User must have an email address')

    if not username:
        raise ValueError('User must have an username')

    user = self.model(
        email=self.normalize_email(email),
        username=username,
        first_name=first_name,
        last_name=last_name,
    )

    user.set_password(password)
    user.save(using=self._db)
    return user

def create_superuser(self, first_name, last_name, email, username,
password):
    user = self.create_user(
        email=self.normalize_email(email),
        username=username,
        password=password,
        first_name=first_name,
        last_name=last_name,
    )
    user.is_admin = True
    user.is_active = True
    user.is_staff = True
    user.is_superadmin = True
    user.save(using=self._db)
    return user

    class Account(AbstractBaseUser):
       first_name = models.CharField(max_length=50)
       last_name = models.CharField(max_length=50)
       username = models.CharField(max_length=50, unique=True)
       email = models.EmailField(max_length=100, unique=True)
       phone_number = models.CharField(max_length=50)

      # required
      date_joined = models.DateTimeField(auto_now_add=True)
      last_login = models.DateTimeField(auto_now_add=True)
      is_admin = models.BooleanField(default=False)
      is_staff = models.BooleanField(default=False)
      is_active = models.BooleanField(default=False)
      is_superadmin = models.BooleanField(default=False)

     USERNAME_FIELD = 'email'
     REQUIRED_FIELDS = ['username', 'first_name', 'last_name']

     objects = MyAccountManager()

     def full_name(self):
       return f'{self.first_name} {self.last_name}'

    def __str__(self):
       return self.email

    def has_perm(self, perm, obj=None):
       return self.is_admin

   def has_module_perms(self, add_label):
       return True

class UserProfile(models.Model):
   user = models.OneToOneField(Account, on_delete=models.CASCADE)
   address_line_1 = models.CharField(blank=True, max_length=100)
   address_line_2 = models.CharField(blank=True, max_length=100)
   profile_picture = models.ImageField(blank=True,
   upload_to='userprofile')
   city = models.CharField(blank=True, max_length=20)
   state = models.CharField(blank=True, max_length=20)
   country = models.CharField(blank=True, max_length=20)

def __str__(self):
    return self.user.first_name

def full_address(self):
    return f'{self.address_line_1} {self.address_line_2}'
</code>```

Here is my Traceback error:

答:
Maybe in your settings.py you need to add the line

AUTH_USER_MODEL = 'your_app.Account'
```
<p>or</p>
<pre class="lang-py prettyprint-override"><code>AUTH_USER_MODEL = 'Account'
</code>```

depending on how you set up the project.

Also remove all migrations and drop the database, then do them again.

Body:
I am getting this error after I was customizing my Customer User Model. and now I get this error when I try to login into the admin panel and when I try to create a superuser.

I tried to drop the postgresql database called skincareryland... but am getting an error on the password login... when I try to change the password I get this error.. ERROR:  role "postgres" does not exist

I also tried going through these steps from an overstack post, but not having any luck fixing the problem... Comment out 'django.contrib.admin' from INSTALLED_APPS in settings.py and comment out # path('admin/', admin.site.urls) in urls.py

here is a better snapshot of my models.py code

here is a better snapshot of my settings.py code

from django.db import models
from django.contrib.auth.models import AbstractBaseUser,
BaseUserManager

class MyAccountManager(BaseUserManager):
   def create_user(self, first_name, last_name, username, email,
     password=None):
    if not email:
        raise ValueError('User must have an email address')

    if not username:
        raise ValueError('User must have an username')

    user = self.model(
        email=self.normalize_email(email),
        username=username,
        first_name=first_name,
        last_name=last_name,
    )

    user.set_password(password)
    user.save(using=self._db)
    return user

def create_superuser(self, first_name, last_name, email, username,
password):
    user = self.create_user(
        email=self.normalize_email(email),
        username=username,
        password=password,
        first_name=first_name,
        last_name=last_name,
    )
    user.is_admin = True
    user.is_active = True
    user.is_staff = True
    user.is_superadmin = True
    user.save(using=self._db)
    return user

    class Account(AbstractBaseUser):
       first_name = models.CharField(max_length=50)
       last_name = models.CharField(max_length=50)
       username = models.CharField(max_length=50, unique=True)
       email = models.EmailField(max_length=100, unique=True)
       phone_number = models.CharField(max_length=50)

      # required
      date_joined = models.DateTimeField(auto_now_add=True)
      last_login = models.DateTimeField(auto_now_add=True)
      is_admin = models.BooleanField(default=False)
      is_staff = models.BooleanField(default=False)
      is_active = models.BooleanField(default=False)
      is_superadmin = models.BooleanField(default=False)

     USERNAME_FIELD = 'email'
     REQUIRED_FIELDS = ['username', 'first_name', 'last_name']

     objects = MyAccountManager()

     def full_name(self):
       return f'{self.first_name} {self.last_name}'

    def __str__(self):
       return self.email

    def has_perm(self, perm, obj=None):
       return self.is_admin

   def has_module_perms(self, add_label):
       return True

class UserProfile(models.Model):
   user = models.OneToOneField(Account, on_delete=models.CASCADE)
   address_line_1 = models.CharField(blank=True, max_length=100)
   address_line_2 = models.CharField(blank=True, max_length=100)
   profile_picture = models.ImageField(blank=True,
   upload_to='userprofile')
   city = models.CharField(blank=True, max_length=20)
   state = models.CharField(blank=True, max_length=20)
   country = models.CharField(blank=True, max_length=20)

def __str__(self):
    return self.user.first_name

def full_address(self):
    return f'{self.address_line_1} {self.address_line_2}'

Here is my Traceback error:

Body:
Maybe in your settings.py you need to add the line

AUTH_USER_MODEL = 'your_app.Account'

or

AUTH_USER_MODEL = 'Account'

depending on how you set up the project.

Also remove all migrations and drop the database, then do them again.


来源: stackexchange

问:
How to handle mongoose error with nestjs
I followed the example from https://docs.nestjs.com/techniques/mongodb

The issue is when there is a mongoose validation error (e.g i have a schema with a required field and it isn't provided):

From games.service.ts:

```<code>  async create(createGameDto: CreateGameDto): Promise<IGame> {
    const createdGame = new this.gameModel(createGameDto);
    return await createdGame.save();
  }
</code>```

The save() function returns a Promise.

Now i have this in the game.controller.ts

```<code>  @Post()
  async create(@Body() createGameDto: CreateGameDto) {
    this.gamesService.create(createGameDto);
  }
</code>```

What is the best way to handle an error and then return a response with a different http status and maybe a json text?
You would usually throw a HttpException but from where? I can't do that if i handle the errors using .catch() in the promise.

(Just started using the nestjs framework)

答:
Am using a global Exception filter with a logger:(WINSTON), that catch all most every Error, including MongoDB error's, Don't know whether it's up to the standard but works for me, I followed Nest Js Doc with some of my custom needs!

```<code>import {
  ArgumentsHost,
  Catch,
  ExceptionFilter,
  HttpException,
  HttpStatus,
  Inject,
  LoggerService,
} from '@nestjs/common';
import { Response } from 'express';
import { WINSTON_MODULE_NEST_PROVIDER } from 'nest-winston';

@Catch()
export class HttpExceptionFilter implements ExceptionFilter {
  constructor(
    @Inject(WINSTON_MODULE_NEST_PROVIDER)
    private readonly logger: LoggerService,
  ) {}
  catch(exp: any, host: ArgumentsHost) {
    console.log(exp);
    this.logger.error(exp);
    const context = host.switchToHttp();
    const response = context.getResponse<Response>();
    const request = context.getRequest<Request>();

    const hasKey = Object.keys(exp).length > 0 && exp.hasOwnProperty('response') ? true : false;
    const isHttpInstance = exp instanceof HttpException ? true : false;

    const validErrors = hasKey && Array.isArray(exp.response.message) ? exp.response.message : [];
    const statusCode = isHttpInstance ? exp.getStatus() : HttpStatus.INTERNAL_SERVER_ERROR;
    const type = hasKey && exp.response.type ? exp.response.type : 'some_thing_went_error';
    const message = isHttpInstance ? exp.message : 'Oops Something went wrong!';
    const error = hasKey ? exp.response.error : exp;

    response.status(statusCode).json({
      message,
      type,
      validationErrors: validErrors,
      statusCode,
      error,
      timestamp: new Date().toISOString(),
      path: request.url,
    });
  }
}
</code>```

This will be the response be like on MongoDB Error:

```<code>    {
    "message": "Oops Something went wrong!",
    "type": "some_thing_went_error",
    "validationErrors": [],
    "statusCode": 500,
    "error": {
        "errors": {
            "subRegion": {
                "name": "ValidatorError",
                "message": "Path `subRegion` is required.",
                "properties": {
                    "message": "Path `subRegion` is required.",
                    "type": "required",
                    "path": "subRegion"
                },
                "kind": "required",
                "path": "subRegion"
            }
        },
        "_message": "ServiceRequest validation failed",
        "name": "ValidationError",
        "message": "ServiceRequest validation failed: subRegion: Path `subRegion` is required."
    },
    "timestamp": "2022-02-08T07:43:35.962Z",
    "path": "/v1/service-request"
}
</code>```

This will be the response be like on Normal Error:

```<code>{
    "message": "Bad Request Exception",
    "type": "some_thing_went_error",
    "validationErrors": [
        "isEmergency must be one of the following values: true, false",
        "isEmergency must be a string",
        "isEmergency should not be empty"
    ],
    "statusCode": 400,
    "error": "Bad Request",
    "timestamp": "2022-02-08T07:47:25.183Z",
    "path": "/v1/service-request"
}
</code>```

If you want the type to be a custom one, that can be thrown from the application you can use the below code

```<code>    throw new HttpException(
      {
        status: HttpStatus.FORBIDDEN,
        type: 'otp_verification_error',
        message: 'Please verify your mobile number to complete the signUp process!',
      },
      HttpStatus.FORBIDDEN,
    );
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I followed the example from https://docs.nestjs.com/techniques/mongodb

The issue is when there is a mongoose validation error (e.g i have a schema with a required field and it isn't provided):

From games.service.ts:

  async create(createGameDto: CreateGameDto): Promise<IGame> {
    const createdGame = new this.gameModel(createGameDto);
    return await createdGame.save();
  }

The save() function returns a Promise.

Now i have this in the game.controller.ts

  @Post()
  async create(@Body() createGameDto: CreateGameDto) {
    this.gamesService.create(createGameDto);
  }

What is the best way to handle an error and then return a response with a different http status and maybe a json text?
You would usually throw a HttpException but from where? I can't do that if i handle the errors using .catch() in the promise.

(Just started using the nestjs framework)

Body:
Am using a global Exception filter with a logger:(WINSTON), that catch all most every Error, including MongoDB error's, Don't know whether it's up to the standard but works for me, I followed Nest Js Doc with some of my custom needs!

import {
  ArgumentsHost,
  Catch,
  ExceptionFilter,
  HttpException,
  HttpStatus,
  Inject,
  LoggerService,
} from '@nestjs/common';
import { Response } from 'express';
import { WINSTON_MODULE_NEST_PROVIDER } from 'nest-winston';

@Catch()
export class HttpExceptionFilter implements ExceptionFilter {
  constructor(
    @Inject(WINSTON_MODULE_NEST_PROVIDER)
    private readonly logger: LoggerService,
  ) {}
  catch(exp: any, host: ArgumentsHost) {
    console.log(exp);
    this.logger.error(exp);
    const context = host.switchToHttp();
    const response = context.getResponse<Response>();
    const request = context.getRequest<Request>();

    const hasKey = Object.keys(exp).length > 0 && exp.hasOwnProperty('response') ? true : false;
    const isHttpInstance = exp instanceof HttpException ? true : false;

    const validErrors = hasKey && Array.isArray(exp.response.message) ? exp.response.message : [];
    const statusCode = isHttpInstance ? exp.getStatus() : HttpStatus.INTERNAL_SERVER_ERROR;
    const type = hasKey && exp.response.type ? exp.response.type : 'some_thing_went_error';
    const message = isHttpInstance ? exp.message : 'Oops Something went wrong!';
    const error = hasKey ? exp.response.error : exp;

    response.status(statusCode).json({
      message,
      type,
      validationErrors: validErrors,
      statusCode,
      error,
      timestamp: new Date().toISOString(),
      path: request.url,
    });
  }
}

This will be the response be like on MongoDB Error:

    {
    "message": "Oops Something went wrong!",
    "type": "some_thing_went_error",
    "validationErrors": [],
    "statusCode": 500,
    "error": {
        "errors": {
            "subRegion": {
                "name": "ValidatorError",
                "message": "Path `subRegion` is required.",
                "properties": {
                    "message": "Path `subRegion` is required.",
                    "type": "required",
                    "path": "subRegion"
                },
                "kind": "required",
                "path": "subRegion"
            }
        },
        "_message": "ServiceRequest validation failed",
        "name": "ValidationError",
        "message": "ServiceRequest validation failed: subRegion: Path `subRegion` is required."
    },
    "timestamp": "2022-02-08T07:43:35.962Z",
    "path": "/v1/service-request"
}

This will be the response be like on Normal Error:

{
    "message": "Bad Request Exception",
    "type": "some_thing_went_error",
    "validationErrors": [
        "isEmergency must be one of the following values: true, false",
        "isEmergency must be a string",
        "isEmergency should not be empty"
    ],
    "statusCode": 400,
    "error": "Bad Request",
    "timestamp": "2022-02-08T07:47:25.183Z",
    "path": "/v1/service-request"
}

If you want the type to be a custom one, that can be thrown from the application you can use the below code

    throw new HttpException(
      {
        status: HttpStatus.FORBIDDEN,
        type: 'otp_verification_error',
        message: 'Please verify your mobile number to complete the signUp process!',
      },
      HttpStatus.FORBIDDEN,
    );


问:
Getting Undefined error at the end of sets Iteration in JavaScript
I am getting an undefined error after logging each element of the set.
please have a look at the code snippet bellow</p>
```<code>  let arrayFruits = ['apple', 'banana', 'orange', 'plum', 'peach', 'strawberry', 'raspberry'];

const fruits = new Set(arrayFruits);

const itrate = fruits.forEach(fruit =>{
    console.log(fruit);

});

console.log(itrate);
</code>```

答: forEach do not have any return value. Undefined is printed as part of iteration even if you remove console.log(fruit) from iteration you will still see undefined printed in console.</p>

Body:
I am getting an undefined error after logging each element of the set.
please have a look at the code snippet bellow

  let arrayFruits = ['apple', 'banana', 'orange', 'plum', 'peach', 'strawberry', 'raspberry'];

const fruits = new Set(arrayFruits);

const itrate = fruits.forEach(fruit =>{
    console.log(fruit);

});

console.log(itrate);


问:
Console App updates database but will not connect to data source when querying
I have created a console app to connect to an Oracle ADW database. When I did the initial migration, it created the tables exactly as I expected.  Now when I try to query a table on that database, I get the error: "ORA-12154: TNS:could not resolve the connect identifier specified"

I know it can connect as the update-database succeeded.  Here is my context:

```<code>using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WCONSftpFileUploadChecks.Models;

namespace WCONSftpFileUploadChecks.Data
{
    public class OracleDBContext : DbContext
    {
        public OracleDBContext() : base()
        {
        }

        public virtual DbSet<FileDet> FileDetails { get; set; }
        public virtual DbSet<RemotePath> RemotePaths { get; set; }
        public virtual DbSet<Peter> Peters { get; set; }

        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            optionsBuilder.UseOracle(@"User Id=<USER>;Password=<PASSWORD>;Data Source=<SOURCENAME>");
        }

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);
            modelBuilder.Entity<FileDet>()
                .Property(p => p.value)
                .HasColumnType("decimal(18,4)");
        }
    }
}
</code>```

Here is the project structure:

And here is how I am trying to retrieve the data:

```<code>using WCONSftpFileUploadChecks.Code;
using WCONSftpFileUploadChecks.Data;
using WCONSftpFileUploadChecks.Models;

namespace WCONSftpFileUploadChecks
{
    public class Program
    {
        public static void Main(string[] args)
        {
            using(var ctx = new OracleDBContext())
            {
                foreach (RemotePath p in ctx.RemotePaths)
                {
                    Console.WriteLine(p.remote_path);
                }

            }
            Console.ReadLine();
            return;
        }
    }
}
</code>```

And here is where it throws the error:

I deliberately haven't included the Model as I don't believe it's relevant.  I just cannot see what is wrong.

答:
The answer was straightforward, just two lines added to OnModelCreating method in my context file:</p>
```<code>OracleConfiguration.TnsAdmin = @"C:\path\to\wallet\file";

OracleConfiguration.WalletLocation= @"C:\path\to\wallet\file";
</code>```

Body:
I have created a console app to connect to an Oracle ADW database. When I did the initial migration, it created the tables exactly as I expected.  Now when I try to query a table on that database, I get the error: "ORA-12154: TNS:could not resolve the connect identifier specified"

I know it can connect as the update-database succeeded.  Here is my context:

using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WCONSftpFileUploadChecks.Models;

namespace WCONSftpFileUploadChecks.Data
{
    public class OracleDBContext : DbContext
    {
        public OracleDBContext() : base()
        {
        }

        public virtual DbSet<FileDet> FileDetails { get; set; }
        public virtual DbSet<RemotePath> RemotePaths { get; set; }
        public virtual DbSet<Peter> Peters { get; set; }

        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            optionsBuilder.UseOracle(@"User Id=<USER>;Password=<PASSWORD>;Data Source=<SOURCENAME>");
        }

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);
            modelBuilder.Entity<FileDet>()
                .Property(p => p.value)
                .HasColumnType("decimal(18,4)");
        }
    }
}

Here is the project structure:

And here is how I am trying to retrieve the data:

using WCONSftpFileUploadChecks.Code;
using WCONSftpFileUploadChecks.Data;
using WCONSftpFileUploadChecks.Models;

namespace WCONSftpFileUploadChecks
{
    public class Program
    {
        public static void Main(string[] args)
        {
            using(var ctx = new OracleDBContext())
            {
                foreach (RemotePath p in ctx.RemotePaths)
                {
                    Console.WriteLine(p.remote_path);
                }

            }
            Console.ReadLine();
            return;
        }
    }
}

And here is where it throws the error:

I deliberately haven't included the Model as I don't believe it's relevant.  I just cannot see what is wrong.

Body:
The answer was straightforward, just two lines added to OnModelCreating method in my context file:

OracleConfiguration.TnsAdmin = @"C:\path\to\wallet\file";

OracleConfiguration.WalletLocation= @"C:\path\to\wallet\file";


问:
com.google.firebase.FirebaseException: An internal error has occurred. [ CONFIGURATION_NOT_FOUND ]
Ok so I get the following exception. No idea why it is happening. I have followed the guides how to set up auth for google account. I tried to search the google but no success of any solution for this. I haved tried to search for the CONFIGURATION_NOT_FOUND but I could not find it in the firebase docs. I don't know what configuration he can't find. Exception is basically useless. Signing in trough firebase is going great until authenticating it with firebase:

```<code>private void authenticateGoogleAccount(GoogleSignInAccount account) {
    AuthCredential credential = GoogleAuthProvider.getCredential(account.getIdToken(), null);
    mAuth.signInWithCredential(credential)
            .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
                @Override
                public void onComplete(@NonNull Task<AuthResult> task) {
                    if (!task.isSuccessful()) {
                        Log.w(TAG, "signInWithCredential", task.getException());
                        Toast.makeText(MainActivity.this, "Authentication failed.",
                                Toast.LENGTH_SHORT).show();
                    }
                    else {
                        Log.d(TAG, "signInWithCredential");
                    }
                }
            });
}
</code>```

Google sign-in-method is enabled in the firebase console.
yes I have found a duplicate of this answer but has 0 answers and one unanswered comment 5 months ago.

答: I was having the same issue with my MacBook with M1 chip my emulator date and time were not correct. Setting up them manually saved my day.</p>

ContentLicense: CC BY-SA 3.0

Body:
Ok so I get the following exception. No idea why it is happening. I have followed the guides how to set up auth for google account. I tried to search the google but no success of any solution for this. I haved tried to search for the CONFIGURATION_NOT_FOUND but I could not find it in the firebase docs. I don't know what configuration he can't find. Exception is basically useless. Signing in trough firebase is going great until authenticating it with firebase:

private void authenticateGoogleAccount(GoogleSignInAccount account) {
    AuthCredential credential = GoogleAuthProvider.getCredential(account.getIdToken(), null);
    mAuth.signInWithCredential(credential)
            .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
                @Override
                public void onComplete(@NonNull Task<AuthResult> task) {
                    if (!task.isSuccessful()) {
                        Log.w(TAG, "signInWithCredential", task.getException());
                        Toast.makeText(MainActivity.this, "Authentication failed.",
                                Toast.LENGTH_SHORT).show();
                    }
                    else {
                        Log.d(TAG, "signInWithCredential");
                    }
                }
            });
}

Google sign-in-method is enabled in the firebase console.
yes I have found a duplicate of this answer but has 0 answers and one unanswered comment 5 months ago.


问:
RabbitMQ: how a Queue can be auto-deleted?
I have N customers, each of them has its own Queue using fanout exchange:
Que-1
Que-2
...
Que-N

Publishers published messages to to fanout exchange, i.e. Publisher->pub msg->(to all Que-1 - Que-N)

Each customer reads its own queue
customer i - reads -Que-i

The question is:

How can I solve this problem: if no customer reads this Que-* in K minutes then this Que should be deleted with messages.
I.e. publishers can publish messages, but if no customer reads it then it should be dropped.

答:
TTL can also be set on queues, not just queue contents. Queues will expire after a period of time only when they are not used (e.g. do not have consumers). This feature can be used together with the auto-delete queue property.

Expiry time can be set for a given queue by setting the x-expires argument to queue.declare, or by setting the expires policy. This controls for how long a queue can be unused before it is automatically deleted. Unused means the queue has no consumers, the queue has not been recently redeclared (redeclaring renews the lease), and basic.get has not been invoked for a duration of at least the expiration period.

The value of the x-expires argument or expires policy describes the expiration period in milliseconds. It must be a positive integer (unlike message TTL it cannot be 0). Thus a value of 1000 means a queue which is unused for 1 second will be deleted.

Define Queue TTL for Queues Using a Policy

The following policy makes all queues expire after 30 minutes since last use:

```<code>rabbitmqctl set_policy expiry ".*" '{"expires":1800000}' --apply-to queues
</code>```

Define Queue TTL for Queues Using x-arguments During Declaration

This example in Java creates a queue which expires after it has been unused for 30 minutes.

```<code>Map<String, Object> args = new HashMap<String, Object>();
args.put("x-expires", 1800000);
channel.queueDeclare("myqueue", false, false, false, args);
</code>```

See the link below for more details:

https://www.rabbitmq.com/ttl.html

Body:
TTL can also be set on queues, not just queue contents. Queues will expire after a period of time only when they are not used (e.g. do not have consumers). This feature can be used together with the auto-delete queue property.

Expiry time can be set for a given queue by setting the x-expires argument to queue.declare, or by setting the expires policy. This controls for how long a queue can be unused before it is automatically deleted. Unused means the queue has no consumers, the queue has not been recently redeclared (redeclaring renews the lease), and basic.get has not been invoked for a duration of at least the expiration period.

The value of the x-expires argument or expires policy describes the expiration period in milliseconds. It must be a positive integer (unlike message TTL it cannot be 0). Thus a value of 1000 means a queue which is unused for 1 second will be deleted.

Define Queue TTL for Queues Using a Policy

The following policy makes all queues expire after 30 minutes since last use:

rabbitmqctl set_policy expiry ".*" '{"expires":1800000}' --apply-to queues

Define Queue TTL for Queues Using x-arguments During Declaration

This example in Java creates a queue which expires after it has been unused for 30 minutes.

Map<String, Object> args = new HashMap<String, Object>();
args.put("x-expires", 1800000);
channel.queueDeclare("myqueue", false, false, false, args);

See the link below for more details:

https://www.rabbitmq.com/ttl.html


问:
How to solve ElementUI unknown element warning in unit tests?
I'm testing a component using <el-buton> from element-plus

I am not using directly, <el-button> is inside of my Connect component

```<code>import { shallowMount } from '@vue/test-utils'
import { createApp } from 'vue'
import { createStore } from 'vuex'
import App from '@/components/connect'

const store = createStore({
  state() {
    return {
      user: {},
    }
  },
  mutations: {},
})

let wrapper
const app = createApp(App)
app.use(store)

beforeEach(() => {
  wrapper = shallowMount(App, {
    propsData: {},
    global: {
      plugins: [store],
    },

  })
})
</code>```

I am getting this warning in all test of my components:

If this is a native custom element, make sure to exclude it from component resolution via compilerOptions.isCustomElement.

Asked on github as well: https://github.com/element-plus/element-plus/issues/5830

答:
I don't know what you mean by "I'm not using directly", but the warning tells you Jest found this tag when traversing the component's DOM, during shallow mounting, and it doesn't know how to resolve it, as it's neither a native DOM tag, nor a known component.

Important note: the fact that Jest stubs sub-components when shallow mounting doesn't mean it doesn't resolve them.

If <el-button> is not relevant for the current test, simply ignore this warning.

Jest: "but I don't know what <el-button> is!"

You: "That's fine, you don't need to."

If <el-button> is not relevant for the test, but the warning annoys you, either declare <el-button> a web component (which is false, but it tells Jest to ignore it), by following the link and the instructions shown in the warning; or stub it manually (replace it with an empty
) in this test suite:

import { config } from '@vue/test-utils'

config.stubs['el-button'] = '
'
```
<ol start="3">
<li>If <code><el-button></code> is relevant for the current test, you have to add ElementUI to the wrapper instance's globals.<br />
This will make your wrapper know what each of ElementUI's components and directives are. It doesn't mean they won't get stubbed. They will be, but Jest will know what it's stubbing and, most importantly, it will resolve their dependencies:</li>
</ol>
<pre class="lang-js prettyprint-override"><code>import ElementUI from 'element-ui';

beforeEach(() => {
  wrapper = shallowMount(App, {
    propsData: {},
    global: {
      plugins: [store, ElementUI],
    },
  });
});
</code>```

This is, in fact, the correct way to provide them, because it's how they're provided to the instance in the real app, when you're installing them on the root instance, using app.use(SomePlugin).

You should do this for all other plugins used in app. If it gets too repetitive, create a helper function, pass the currently tested component and its setup as arguments, returning a wrapper which has all the bells and whistles of your app.

Some purists might say: "but I don't want to test my component with all the global plugins, I want to only test it with the ones it uses."

IMHO, that's wrong. even if the component only uses a few of the global provided plugins, it runs (on live) in a context where they are all provided. So, should there be any conflict between some global plugin and the current component, you probably want to learn about it from this test, not from a github issue.

Generic wrapper factory example:

import { shallowMount, mount } from '@vue/test-utils'
import SomePlugin from 'some-library';
import SomeOtherPlugin from 'some-other-library';
import { createStore } from 'vuex'

export const useWrapper = (component, setup, shallow = true) => {
  const store = createStore({ /* ... */ });
  return (shallow ? shallowMount : mount)(component, {
    globals: {
      plugins: [SomePlugin, SomeOtherPlugin, store]
    },
    ...setup,
  })
}
```
<p><strong>Note</strong> this even allows you to override <code>globals</code>, through <code>setup</code>, should you want to but, IMHO, that's not a good idea, for the reason outlined above.</p>
<p>And now you can import <code>useWrapper</code> in all your tests, which are a bit more boilerplate-free:</p>
<pre class="lang-js prettyprint-override"><code>import { useWrapper } from '../path-to-helpers';
import SomeComponent from '@/components/SomeComponent.vue'

//...
describe('SomeComponent', () => {
  let wrapper;

  beforeEach(() => {
    wrapper = useWrapper(SomeComponent, {
      propsData: {} // extend as needed
    });
  });

  it('should do stuff...', () => {
    // expect it does stuff...
  })
});
</code>```

When you need to mount instead of shallowMount, pass false as third argument to useWrapper.

Body:
I'm testing a component using <el-buton> from element-plus

I am not using directly, <el-button> is inside of my Connect component

import { shallowMount } from '@vue/test-utils'
import { createApp } from 'vue'
import { createStore } from 'vuex'
import App from '@/components/connect'

const store = createStore({
  state() {
    return {
      user: {},
    }
  },
  mutations: {},
})

let wrapper
const app = createApp(App)
app.use(store)

beforeEach(() => {
  wrapper = shallowMount(App, {
    propsData: {},
    global: {
      plugins: [store],
    },

  })
})

I am getting this warning in all test of my components:

If this is a native custom element, make sure to exclude it from component resolution via compilerOptions.isCustomElement.

Asked on github as well: https://github.com/element-plus/element-plus/issues/5830

Body:
I don't know what you mean by "I'm not using directly", but the warning tells you Jest found this tag when traversing the component's DOM, during shallow mounting, and it doesn't know how to resolve it, as it's neither a native DOM tag, nor a known component.

Important note: the fact that Jest stubs sub-components when shallow mounting doesn't mean it doesn't resolve them.

If <el-button> is not relevant for the current test, simply ignore this warning.

Jest: "but I don't know what <el-button> is!"

You: "That's fine, you don't need to."

If <el-button> is not relevant for the test, but the warning annoys you, either declare <el-button> a web component (which is false, but it tells Jest to ignore it), by following the link and the instructions shown in the warning; or stub it manually (replace it with an empty <div />) in this test suite:

import { config } from '@vue/test-utils'

config.stubs['el-button'] = '<div />'

If <el-button> is relevant for the current test, you have to add ElementUI to the wrapper instance's globals.

This will make your wrapper know what each of ElementUI's components and directives are. It doesn't mean they won't get stubbed. They will be, but Jest will know what it's stubbing and, most importantly, it will resolve their dependencies:

import ElementUI from 'element-ui';

beforeEach(() => {
  wrapper = shallowMount(App, {
    propsData: {},
    global: {
      plugins: [store, ElementUI],
    },
  });
});

This is, in fact, the correct way to provide them, because it's how they're provided to the instance in the real app, when you're installing them on the root instance, using app.use(SomePlugin).

You should do this for all other plugins used in app. If it gets too repetitive, create a helper function, pass the currently tested component and its setup as arguments, returning a wrapper which has all the bells and whistles of your app.

Some purists might say: "but I don't want to test my component with all the global plugins, I want to only test it with the ones it uses."

IMHO, that's wrong. even if the component only uses a few of the global provided plugins, it runs (on live) in a context where they are all provided. So, should there be any conflict between some global plugin and the current component, you probably want to learn about it from this test, not from a github issue.

Generic wrapper factory example:

import { shallowMount, mount } from '@vue/test-utils'
import SomePlugin from 'some-library';
import SomeOtherPlugin from 'some-other-library';
import { createStore } from 'vuex'

export const useWrapper = (component, setup, shallow = true) => {
  const store = createStore({ /* ... */ });
  return (shallow ? shallowMount : mount)(component, {
    globals: {
      plugins: [SomePlugin, SomeOtherPlugin, store]
    },
    ...setup,
  })
}

Note this even allows you to override globals, through setup, should you want to but, IMHO, that's not a good idea, for the reason outlined above.

And now you can import useWrapper in all your tests, which are a bit more boilerplate-free:

import { useWrapper } from '../path-to-helpers';
import SomeComponent from '@/components/SomeComponent.vue'

//...
describe('SomeComponent', () => {
  let wrapper;

  beforeEach(() => {
    wrapper = useWrapper(SomeComponent, {
      propsData: {} // extend as needed
    });
  });

  it('should do stuff...', () => {
    // expect it does stuff...
  })
});

When you need to mount instead of shallowMount, pass false as third argument to useWrapper.


问:
Node - how to run app.js?
I am very new to Node.js and I tried to run a project (made by other developer) by having a command in terminal node app.js. But I encountered below error, do you have any idea how to run this project?

I followed few instructions here to run a project.

Error logs below:

```<code>Junryls-Mac-mini:app junrylmaraviles$ node app.js

/Users/junrylmaraviles/Desktop/myfolder/mysubfolder/app/app.js:1
(function (exports, require, module, __filename, __dirname) { define('src/app'
                                                              ^
ReferenceError: define is not defined
    at Object.<anonymous> (/Users/junrylmaraviles/Desktop/myfolder/mysubfolder/app/app.js:1:63)
    at Module._compile (module.js:456:26)
    at Object.Module._extensions..js (module.js:474:10)
    at Module.load (module.js:356:32)
    at Function.Module._load (module.js:312:12)
    at Function.Module.runMain (module.js:497:10)
    at startup (node.js:119:16)
    at node.js:902:3
</code>```

答:
To run a node js project you can run the project by below commands

```<code>node app.js
</code>```

But if you want to run your project with npm start then you need to pass "start": "Node app.js" in the scripts of the package.json file

So, your package.json file will look like below

```<code>"scripts": { "start": "node app.js", "test": "test" }
</code>```

Once you are done with the changes then you just need to save the file and then go to the terminal hit the npm start command you will see that the project started as its working on the node app.js command

Refer to below image for clarification

You can also see in the below image that your project runs on both command node app.js as well as npm start

Title: Node - how to run app.js?

Body:
I am very new to Node.js and I tried to run a project (made by other developer) by having a command in terminal node app.js. But I encountered below error, do you have any idea how to run this project?

I followed few instructions here to run a project.

Error logs below:

Junryls-Mac-mini:app junrylmaraviles$ node app.js

/Users/junrylmaraviles/Desktop/myfolder/mysubfolder/app/app.js:1
(function (exports, require, module, __filename, __dirname) { define('src/app'
                                                              ^
ReferenceError: define is not defined
    at Object.<anonymous> (/Users/junrylmaraviles/Desktop/myfolder/mysubfolder/app/app.js:1:63)
    at Module._compile (module.js:456:26)
    at Object.Module._extensions..js (module.js:474:10)
    at Module.load (module.js:356:32)
    at Function.Module._load (module.js:312:12)
    at Function.Module.runMain (module.js:497:10)
    at startup (node.js:119:16)
    at node.js:902:3

Body:
To run a node js project you can run the project by below commands

node app.js

But if you want to run your project with npm start then you need to pass "start": "Node app.js" in the scripts of the package.json file

So, your package.json file will look like below

"scripts": { "start": "node app.js", "test": "test" }

Once you are done with the changes then you just need to save the file and then go to the terminal hit the npm start command you will see that the project started as its working on the node app.js command

Refer to below image for clarification

You can also see in the below image that your project runs on both command node app.js as well as npm start


问:
Bad UTF-8 without BOM encoding
I converted all my files to UTF-8 without BOM encoding using Notepad++. I have no problem with BOMs anymore but the UTF without BOM encoding is simply not working, it's as if my site was encoded in ANSI. All special characters display either as: Â, Ãš or Ã¡.

What can be the reason for this and how can I fix it?

http://chusmix.com/?ciudad=Pilar

Thanks

答: The HTML code doesn't contain any encoding, so the browser probably interprets it as ISO-LATIN, not UTF-8.  Check out Setting the HTTP charset parameter at the W3 consortium.</p>

Title: Bad UTF-8 without BOM encoding


问:
Pandas DataFrame Table Vertical Scrollbars
I have a large (vertically) pandas dataframe that I would like to display as a nice table with scrollbars.  I can get it to display the table with all the rows but I cannot get the scrollbars to display.

```<code>def data(x):
    strData = strData[['Data1','Data2','Data3']]
    display(strData)
</code>```

output: No vertical scrollbars

答:
Just pass the dataframe and observe the magic.</p>
```<code>def table(df):
    import plotly.graph_objs as go
    fig = go.Figure(data=[go.Table(
    header=dict(values=list(df.columns),
                align='left'),
    cells=dict(values=[df[i] for i in df.columns],
                align='left'))
    ])
    return fig
</code>```

Body:
I have a large (vertically) pandas dataframe that I would like to display as a nice table with scrollbars.  I can get it to display the table with all the rows but I cannot get the scrollbars to display.

def data(x):
    strData = strData[['Data1','Data2','Data3']]
    display(strData)

output: No vertical scrollbars

Body:
Just pass the dataframe and observe the magic.

def table(df):
    import plotly.graph_objs as go
    fig = go.Figure(data=[go.Table(
    header=dict(values=list(df.columns),
                align='left'),
    cells=dict(values=[df[i] for i in df.columns],
                align='left'))
    ])
    return fig


问:
R update a tibble using data from a second tibble as row and column
I have an empty tibble full of NA's with the rows and columns, respectively named for id numbers and all the dates in a period of time.  For example, this code:

```<code>tbl <- tibble(PERSONAL_ID = c("A", "B", "C", "D"))
dates = as.character((seq(as.Date("2016-01-01"), as.Date("2016-01-05"), by="days")))
tbl[dates] <- NA
tbl <- column_to_rownames(tbl, var = "PERSONAL_ID")
</code>```

I have a second tibble that contains columns matching up one ID number with one date, as in this example:

```<code>enrollments <- tibble(ID = c("D", "B", "C", "D"),
                      date = c("2016-01-01", "2016-01-03", "2016-01-05", "2016-01-02"))
</code>```

What I would like to do is add "1" to the row and column of the first tibble (tbl) corresponding to the ID and date listed in the second tibble (enrollments).  For the example code above, the desired output would be:

```<code>  2016-01-01 2016-01-02 2016-01-03 2016-01-04 2016-01-05
A       <NA>       <NA>       <NA>        <NA>      <NA>
B       <NA>       <NA>          1        <NA>      <NA>
C       <NA>       <NA>       <NA>        <NA>         1
D          1          1       <NA>        <NA>      <NA>
</code>```

Thank you!

答:
Here is a base R approach. For enrollments, I combine the date and ID into one string for each row. Then, for tbl, I create a table that is filled with the date and rowname. Then, I use match to match the values from enrollment with those in tbl. I use arrayInd to get the column and row index. Finally, I replace the NA values in tbl with 1 for the extracted column-row indices.

```<code>replace(tbl, arrayInd(match(do.call(
  paste, subset(enrollments, select = c("date", "ID"))),
t(outer(colnames(tbl), rownames(tbl), FUN = paste)
)), .dim = dim(tbl)), 1)
</code>```

Here is a slightly different tidyverse approach by using rows_update. Here, I pivot enrollments to a wide format, then bind to tbl (but with no rows) in order to have the same columns. Then, I update the rows in tbl with the new format from enrollments.

```<code>library(tidyverse)

rows_update(tbl %>% rownames_to_column("ID"), enrollments %>%
              mutate(value = 1) %>%
              pivot_wider(names_from = "date", values_from = "value") %>%
              bind_rows(tbl[0,])) %>%
  column_to_rownames("ID")
</code>```

Output

```<code>  2016-01-01 2016-01-02 2016-01-03 2016-01-04 2016-01-05
A         NA         NA         NA         NA         NA
B         NA         NA          1         NA         NA
C         NA         NA         NA         NA          1
D          1          1         NA         NA         NA
</code>```

Body:
I have an empty tibble full of NA's with the rows and columns, respectively named for id numbers and all the dates in a period of time.  For example, this code:

tbl <- tibble(PERSONAL_ID = c("A", "B", "C", "D"))
dates = as.character((seq(as.Date("2016-01-01"), as.Date("2016-01-05"), by="days")))
tbl[dates] <- NA
tbl <- column_to_rownames(tbl, var = "PERSONAL_ID")

I have a second tibble that contains columns matching up one ID number with one date, as in this example:

enrollments <- tibble(ID = c("D", "B", "C", "D"),
                      date = c("2016-01-01", "2016-01-03", "2016-01-05", "2016-01-02"))

What I would like to do is add "1" to the row and column of the first tibble (tbl) corresponding to the ID and date listed in the second tibble (enrollments).  For the example code above, the desired output would be:

  2016-01-01 2016-01-02 2016-01-03 2016-01-04 2016-01-05
A       <NA>       <NA>       <NA>        <NA>      <NA>
B       <NA>       <NA>          1        <NA>      <NA>
C       <NA>       <NA>       <NA>        <NA>         1
D          1          1       <NA>        <NA>      <NA>

Thank you!

Body:
Here is a base R approach. For enrollments, I combine the date and ID into one string for each row. Then, for tbl, I create a table that is filled with the date and rowname. Then, I use match to match the values from enrollment with those in tbl. I use arrayInd to get the column and row index. Finally, I replace the NA values in tbl with 1 for the extracted column-row indices.

replace(tbl, arrayInd(match(do.call(
  paste, subset(enrollments, select = c("date", "ID"))),
t(outer(colnames(tbl), rownames(tbl), FUN = paste)
)), .dim = dim(tbl)), 1)

Here is a slightly different tidyverse approach by using rows_update. Here, I pivot enrollments to a wide format, then bind to tbl (but with no rows) in order to have the same columns. Then, I update the rows in tbl with the new format from enrollments.

library(tidyverse)

rows_update(tbl %>% rownames_to_column("ID"), enrollments %>%
              mutate(value = 1) %>%
              pivot_wider(names_from = "date", values_from = "value") %>%
              bind_rows(tbl[0,])) %>%
  column_to_rownames("ID")

Output

  2016-01-01 2016-01-02 2016-01-03 2016-01-04 2016-01-05
A         NA         NA         NA         NA         NA
B         NA         NA          1         NA         NA
C         NA         NA         NA         NA          1
D          1          1         NA         NA         NA


问:
Batch concatenate ffmpeg
I'm using colab to automate the concatenation of large numbers of video. i download the video directly from youtube into a batch footage folder in google drive. I am trying to build a script that will automatically resize and concatenate all videos in this folder. Any suggestions?

here is my c

```<code>
!ffmpeg -i tearcash1.mov -i whiteflower1.mp4 -i peta.mp4 -filter_complex \
"[0:v]scale=1024:576:force_original_aspect_ratio=decrease,pad=1024:576:-1:-1,setsar=1[v0]; \
[1:v]scale=1024:576:force_original_aspect_ratio=decrease,pad=1024:576:-1:-1,setsar=1[v1]; \
[2:v]scale=1024:576:force_original_aspect_ratio=decrease,pad=1024:576:-1:-1,setsar=1[v2]; \
[v0][0:a][v1][1:a][v2][2:a]concat=n=3:v=1:a=1[v][a]" -map [v] -map [a] testconcat.mp4
</code>```

答:
tested on local, not colab, so can be errors:</p>
```<code>import os
path="/mnt/public/upload/videos/"
WID=720
HEI=480
INP=""
FCT=0
SCA=""
FIL=""

for filename in os.listdir(path):
  if (filename.endswith(".mp4")):
    INP+=f' -i "{path}{filename}"'
    PAD=f"[{FCT}v]"
    SCA+=f"[{FCT}:v]scale={WID}:{HEI}:force_original_aspect_ratio=decrease,pad={WID}:{HEI}:-1:-1,setsar=1{PAD};"
    FIL+=f"{PAD}[{FCT}:a]"
    FCT+=1
  else:
    continue

os.system(f'ffmpeg {INP} -filter_complex "{SCA}{FIL}concat=n={FCT}:v=1:a=1[v][a]" -map [v] -map [a] -c:v h264_nvenc -cq 18 -c:a aac -q:a 4 /tmp/output.mkv -y -hide_banner')
</code>```

Title: Batch concatenate ffmpeg

Body:
I'm using colab to automate the concatenation of large numbers of video. i download the video directly from youtube into a batch footage folder in google drive. I am trying to build a script that will automatically resize and concatenate all videos in this folder. Any suggestions?

here is my c

!ffmpeg -i tearcash1.mov -i whiteflower1.mp4 -i peta.mp4 -filter_complex \
"[0:v]scale=1024:576:force_original_aspect_ratio=decrease,pad=1024:576:-1:-1,setsar=1[v0]; \
[1:v]scale=1024:576:force_original_aspect_ratio=decrease,pad=1024:576:-1:-1,setsar=1[v1]; \
[2:v]scale=1024:576:force_original_aspect_ratio=decrease,pad=1024:576:-1:-1,setsar=1[v2]; \
[v0][0:a][v1][1:a][v2][2:a]concat=n=3:v=1:a=1[v][a]" -map [v] -map [a] testconcat.mp4

Body:
tested on local, not colab, so can be errors:

import os
path="/mnt/public/upload/videos/"
WID=720
HEI=480
INP=""
FCT=0
SCA=""
FIL=""

for filename in os.listdir(path):
  if (filename.endswith(".mp4")):
    INP+=f' -i "{path}{filename}"'
    PAD=f"[{FCT}v]"
    SCA+=f"[{FCT}:v]scale={WID}:{HEI}:force_original_aspect_ratio=decrease,pad={WID}:{HEI}:-1:-1,setsar=1{PAD};"
    FIL+=f"{PAD}[{FCT}:a]"
    FCT+=1
  else:
    continue

os.system(f'ffmpeg {INP} -filter_complex "{SCA}{FIL}concat=n={FCT}:v=1:a=1[v][a]" -map [v] -map [a] -c:v h264_nvenc -cq 18 -c:a aac -q:a 4 /tmp/output.mkv -y -hide_banner')


问:
One dimensional array but multiple string
I want to make a multiple string of array but with just a one dimensional array, Is it possible?

```<code>#include <stdio.h>

int main()
{
    char name1[10];
    char name2[10];

    printf("Enter name1: ");
    scanf("%s", name1);

    printf("Enter name2: ");
    scanf("%s", name2);

    printf("\n%s", name1);
    printf("\n%s", name2);

    return 0;
}
</code>```

I just started to learn array and I wanted to try to get multiple input from user and display only specific of the elements.
This is one of the code I tried before but it does not run.

```<code>int main()
{
    char *name[10];

    int i = 1, input;
    printf("How many days a week: ");
    scanf("%d", &input);

    do{
        printf("enter day %d: ", i);
        scanf("%s", name[i]);
        i++;
    }while(i < input);

    //output wanted
    printf("\n%s", name[0]);
    printf("\n%s", name[4]);

    return 0;
}
</code>```

答:
A rather peculiar demand, but it could be achieved like this:

```<code>#include <stdio.h>

int main()
{
    char names[256];

    printf("Enter name1: ");
    scanf("%s", names);

    printf("Enter name2: ");
    scanf("%s", names + strlen(names) + 1);

    printf("\n%s", names);
    printf("\n%s", names + strlen(names) + 1);

    return 0;
}
</code>```

This way, the strings are concatenated in the array and separated by the terminating 0.

Body:
I want to make a multiple string of array but with just a one dimensional array, Is it possible?

#include <stdio.h>

int main()
{
    char name1[10];
    char name2[10];

    printf("Enter name1: ");
    scanf("%s", name1);

    printf("Enter name2: ");
    scanf("%s", name2);

    printf("\n%s", name1);
    printf("\n%s", name2);

    return 0;
}

I just started to learn array and I wanted to try to get multiple input from user and display only specific of the elements.
This is one of the code I tried before but it does not run.

int main()
{
    char *name[10];

    int i = 1, input;
    printf("How many days a week: ");
    scanf("%d", &input);

    do{
        printf("enter day %d: ", i);
        scanf("%s", name[i]);
        i++;
    }while(i < input);

    //output wanted
    printf("\n%s", name[0]);
    printf("\n%s", name[4]);

    return 0;
}

Body:
A rather peculiar demand, but it could be achieved like this:

#include <stdio.h>

int main()
{
    char names[256];

    printf("Enter name1: ");
    scanf("%s", names);

    printf("Enter name2: ");
    scanf("%s", names + strlen(names) + 1);

    printf("\n%s", names);
    printf("\n%s", names + strlen(names) + 1);

    return 0;
}

This way, the strings are concatenated in the array and separated by the terminating 0.


问:
Reading values from test fixture Cypress
I'm new to Cypress and started playing around with fixtures.I'm trying to read values from a JSON file and then assert the values in a test.

Here is my code

```<code>it('Fixture test' ,() => {
    cy.fixture('AllNotificationStates').then(notifications => {
        for(let n in notifications) {
            cy.intercept('GET', '**/api', { fixture: 'AllNotificationStates.json' });

            cy.wrap(notifications[n])
            .should('be.an', 'object')
            .and('contain', {
                rowId: 1,
                streamId: "33e24004-04ff-4c44-8d59-c8752b0f43d7",
                notificationStatus: "Sent",
              });
        }
    });
})
</code>```

What this does is assert that the properties within the JSON file match the values I expect. What I'm trying to do is read the values from the fixture file save them to an object and then assert them in my test. So for example the property rowId in the contain should not be hard coded but read from the fixture file.

Edit here is my JSON file:

```<code>[
    {
      "rowId": 1,
      "streamId": "33e24004-04ff-4c44-8d59-c8752b0f43d7",
      "notificationStatus": "Sent",
      "details": {
        "name": "Notification",
        "createdTime": "2022-02-07T11:59:15.423Z",
        "createdBy": "test@test.com",
      }
]
</code>```

答:
As a supplement to the answers already given:

In the Cypress Docs there are two ways described how you can handle JSON files from the fixtures folder: https://docs.cypress.io/api/commands/fixture#Examples

1. Option: cy.fixture

As described in the other answers, you can load your JSON files using cy.fixture():

```<code>cy.fixture('AllNotificationStates.json').as('AllNotificationStates');

cy.get('@AllNotificationStates').then(() => {
   // assert something
});
</code>```

2. Option: import

You can alternatively import your JSON files directly, treat them in the code like normal objects and make your assertions:

```<code>import AllNotificationStates from '../fixtures/AllNotificationStates.json';
</code>```

Body:
I'm new to Cypress and started playing around with fixtures.I'm trying to read values from a JSON file and then assert the values in a test.

Here is my code

it('Fixture test' ,() => {
    cy.fixture('AllNotificationStates').then(notifications => {
        for(let n in notifications) {
            cy.intercept('GET', '**/api', { fixture: 'AllNotificationStates.json' });

            cy.wrap(notifications[n])
            .should('be.an', 'object')
            .and('contain', {
                rowId: 1,
                streamId: "33e24004-04ff-4c44-8d59-c8752b0f43d7",
                notificationStatus: "Sent",
              });
        }
    });
})

What this does is assert that the properties within the JSON file match the values I expect. What I'm trying to do is read the values from the fixture file save them to an object and then assert them in my test. So for example the property rowId in the contain should not be hard coded but read from the fixture file.

Edit here is my JSON file:

[
    {
      "rowId": 1,
      "streamId": "33e24004-04ff-4c44-8d59-c8752b0f43d7",
      "notificationStatus": "Sent",
      "details": {
        "name": "Notification",
        "createdTime": "2022-02-07T11:59:15.423Z",
        "createdBy": "test@test.com",
      }
]

Body:
As a supplement to the answers already given:

In the Cypress Docs there are two ways described how you can handle JSON files from the fixtures folder: https://docs.cypress.io/api/commands/fixture#Examples

1. Option: cy.fixture

As described in the other answers, you can load your JSON files using cy.fixture():

cy.fixture('AllNotificationStates.json').as('AllNotificationStates');

cy.get('@AllNotificationStates').then(() => {
   // assert something
});

2. Option: import

You can alternatively import your JSON files directly, treat them in the code like normal objects and make your assertions:

import AllNotificationStates from '../fixtures/AllNotificationStates.json';


问:
ViewModel: Error on loading long list in IO Dispatcher
I want to load a long list inside my ViewModel class, queried from database. Data will then be shown using LazyColumn. When loading in IO Dispatcher using kotlin coroutine it throws exception but no problem when loading in Main Dispatcher.

ViewModel Class:

```<code>class TestViewModel: ViewModel() {
val itemList = mutableStateListOf<TestModel>()

init {
    viewModelScope.launch(Dispatchers.IO){
        loadList()
    }
}
</code>```

Error Message:

```<code>E/AndroidRuntime: FATAL EXCEPTION: DefaultDispatcher-worker-1
Process: in.rachika.composetest2, PID: 19469
java.lang.IllegalStateException: Reading a state that was created after the snapshot was taken or in a snapshot that has not yet been applied
    at androidx.compose.runtime.snapshots.SnapshotKt.readError(Snapshot.kt:1518)
    at androidx.compose.runtime.snapshots.SnapshotKt.current(Snapshot.kt:1758)
    at androidx.compose.runtime.snapshots.SnapshotStateList.add(SnapshotStateList.kt:374)
    at in.rachika.composetest2.Tests.ViewModel.TestViewModel.loadList(TestViewModel.kt:24)
    at in.rachika.composetest2.Tests.ViewModel.TestViewModel.access$loadList(TestViewModel.kt:13)
    at in.rachika.composetest2.Tests.ViewModel.TestViewModel$1.invokeSuspend(TestViewModel.kt:19)
    at kotlin.coroutines.jvm.internal.BaseContinuationImpl.resumeWith(ContinuationImpl.kt:33)
    at kotlinx.coroutines.DispatchedTask.run(DispatchedTask.kt:106)
    at kotlinx.coroutines.scheduling.CoroutineScheduler.runSafely(CoroutineScheduler.kt:571)
    at kotlinx.coroutines.scheduling.CoroutineScheduler$Worker.executeTask(CoroutineScheduler.kt:750)
    at kotlinx.coroutines.scheduling.CoroutineScheduler$Worker.runWorker(CoroutineScheduler.kt:678)
    at kotlinx.coroutines.scheduling.CoroutineScheduler$Worker.run(CoroutineScheduler.kt:665)
</code>```

答:
Based on the suggestion made by @Johann I have solved my problem below is my updated code:

```<code>class TestViewModel: ViewModel() {
val itemList = mutableStateListOf<TestModel>()

init {
    viewModelScope.launch(Dispatchers.IO){
        loadList()
    }

}

private fun loadList() {
    for(i in 0..20){
        val groupName = "${i + 1}. STICKY HEADER #"

        val childList = mutableListOf<TestModel>()
        for(t in 0..Random.nextInt(10, 20)){
            childList.add(TestModel(
                isHeader = false,
                GroupId = UUID.randomUUID(),
                GroupName = groupName,
                ItemName = "${t + 1}. This is an CHILD ITEM... #${i + 1} - ${Random.nextInt(1001, 5001)}",
                children = ArrayList()
            )
            )
        }

        //change the scope just before adding data class to mutableStateList
        //because mutableStateList automatically notifies LazyColumn about this data update.
        viewModelScope.launch(Dispatchers.Main){
            itemList.add(TestModel(
                isHeader = true,
                GroupId = UUID.randomUUID(),
                GroupName = groupName,
                ItemName = "",
                children = childList
            ))
        }
    }
}
</code>```

Thanks @Johann, I am marking your answer as accepted.

Body:
I want to load a long list inside my ViewModel class, queried from database. Data will then be shown using LazyColumn. When loading in IO Dispatcher using kotlin coroutine it throws exception but no problem when loading in Main Dispatcher.

ViewModel Class:

class TestViewModel: ViewModel() {
val itemList = mutableStateListOf<TestModel>()

init {
    viewModelScope.launch(Dispatchers.IO){
        loadList()
    }
}

Error Message:

E/AndroidRuntime: FATAL EXCEPTION: DefaultDispatcher-worker-1
Process: in.rachika.composetest2, PID: 19469
java.lang.IllegalStateException: Reading a state that was created after the snapshot was taken or in a snapshot that has not yet been applied
    at androidx.compose.runtime.snapshots.SnapshotKt.readError(Snapshot.kt:1518)
    at androidx.compose.runtime.snapshots.SnapshotKt.current(Snapshot.kt:1758)
    at androidx.compose.runtime.snapshots.SnapshotStateList.add(SnapshotStateList.kt:374)
    at in.rachika.composetest2.Tests.ViewModel.TestViewModel.loadList(TestViewModel.kt:24)
    at in.rachika.composetest2.Tests.ViewModel.TestViewModel.access$loadList(TestViewModel.kt:13)
    at in.rachika.composetest2.Tests.ViewModel.TestViewModel$1.invokeSuspend(TestViewModel.kt:19)
    at kotlin.coroutines.jvm.internal.BaseContinuationImpl.resumeWith(ContinuationImpl.kt:33)
    at kotlinx.coroutines.DispatchedTask.run(DispatchedTask.kt:106)
    at kotlinx.coroutines.scheduling.CoroutineScheduler.runSafely(CoroutineScheduler.kt:571)
    at kotlinx.coroutines.scheduling.CoroutineScheduler$Worker.executeTask(CoroutineScheduler.kt:750)
    at kotlinx.coroutines.scheduling.CoroutineScheduler$Worker.runWorker(CoroutineScheduler.kt:678)
    at kotlinx.coroutines.scheduling.CoroutineScheduler$Worker.run(CoroutineScheduler.kt:665)

Body:
Based on the suggestion made by @Johann I have solved my problem below is my updated code:

class TestViewModel: ViewModel() {
val itemList = mutableStateListOf<TestModel>()

init {
    viewModelScope.launch(Dispatchers.IO){
        loadList()
    }

}

private fun loadList() {
    for(i in 0..20){
        val groupName = "${i + 1}. STICKY HEADER #"

        val childList = mutableListOf<TestModel>()
        for(t in 0..Random.nextInt(10, 20)){
            childList.add(TestModel(
                isHeader = false,
                GroupId = UUID.randomUUID(),
                GroupName = groupName,
                ItemName = "${t + 1}. This is an CHILD ITEM... #${i + 1} - ${Random.nextInt(1001, 5001)}",
                children = ArrayList()
            )
            )
        }

        //change the scope just before adding data class to mutableStateList
        //because mutableStateList automatically notifies LazyColumn about this data update.
        viewModelScope.launch(Dispatchers.Main){
            itemList.add(TestModel(
                isHeader = true,
                GroupId = UUID.randomUUID(),
                GroupName = groupName,
                ItemName = "",
                children = childList
            ))
        }
    }
}

Thanks @Johann, I am marking your answer as accepted.


问:
How to add album art with ffmpeg while converting webm to mp3
I have been trying trying to add an album  art while converting webm to mp3 at one go

The code below works but doesn't add the album art. Any help

ffmpeg -i file.webm  -i it.jpeg   -c:v copy -map 1 -map 0    -f mp3 -vn audio-out.mp3

答:
Well I found a way to do this</p>
```<code>ffmpeg -i  file.webm -i it.jpeg -map 0 -map 1 audio-out.mp3

</code>```

Body:
Well I found a way to do this

ffmpeg -i  file.webm -i it.jpeg -map 0 -map 1 audio-out.mp3


问:
Creating Azure Storage Containers in a storage account with network rules, with Terraform
I am trying to write Terraform that will create an Azure Storage account and then a bunch of storage containers inside it. An important detail is that the storage account has network rules that restrict access to a specific address space. This was causing the container creation to fail.

I managed to get around this by using azurerm_storage_account_network_rules, depending on the containers so not to block their creation. Something like this:

```<code>resource "azurerm_storage_account" "this" {
  name                = local.storage_name
  resource_group_name = azurerm_resource_group.this.name
  location            = var.location

  account_tier             = "Standard"
  account_kind             = "StorageV2"
  is_hns_enabled           = true
  account_replication_type = "LRS"
}

resource "azurerm_storage_container" "data" {
  for_each = toset(var.storage_containers)

  name                  = each.value
  storage_account_name  = azurerm_storage_account.this.name
  container_access_type = "private"
}

# FIXME This order prevents destruction of infrastructure :(
resource "azurerm_storage_account_network_rules" "this" {
  storage_account_id   = azurerm_storage_account.this.id

  default_action = "Deny"
  bypass         = ["AzureServices"]

  virtual_network_subnet_ids = [
    # Some address space here...
  ]

  # NOTE The order here matters: We cannot create storage
  # containers once the network rules are locked down
  depends_on = [
    azurerm_storage_container.data
  ]
}
</code>```

This works for creating the infrastructure, but when I try to terraform destroy, I get a 403 authentication error:

Error: retrieving Container "data" (Account "XXX" / Resource Group "XXX"): containers.Client#GetProperties: Failure responding to request: StatusCode=403 -- Original Error: autorest/azure: Service returned an error. Status=403 Code="AuthorizationFailure" Message="This request is not authorized to perform this operation.\nRequestId:XXX\nTime:XXX"

This is with my Service Principal, which has Contributor and User Access Administrator roles on the same subscription. Interestingly, when I'm logged in to the Azure Portal as myself (with the Owner role), I can add and remove storage containers regardless of the network rules being present.

So, is there a way of setting the Terraform dependencies such that they can both be built and destroyed without hitting any authentication conflicts? Alternatively, would upgrading my SP's role to Owner (or adding another, more targeted role) solve the problem?

答:
This is an expected behavior as you are setting up the network rules for the storage account to deny and only bypassing the Azure Services.

When you deny and bypass Azure Services the Azure Services like Azure Portal's IP gets the access to the storage account and you are able to delete it . But at the same time , when you use terraform to perform a destroy , then it denies because your IP which is being used by your machine to send terraform requests to Azure is not bypassed .

I tested your code like below with the same permissions :

As a Solution you will have to add ip rules while creating the storage account to the add the client_ip like below :

```<code>provider "azurerm" {
    features{}
  client_id="f6a2f33d-xxxx-xxxx-xxxx-xxxx"
  client_secret= "GZ67Q~xxxx~3N-qLT"
  tenant_id = "72f988bf-xxxx-xxxx-xxxx-2d7cd011db47"
  subscription_id="948d4068-xxxx-xxxx-xxxx-xxxx"
}

locals {
  storage_name = "ansumantestsacc12"
  subnet_id_list = [
      "/subscriptions/xxxx/resourceGroups/xxxx/providers/Microsoft.Network/virtualNetworks/xxxx/subnets/xxxx"
  ]
  my_ip = ["xx.xx.xx.xxx"] # IP used by me
}
variable "storage_containers" {
  default = [
      "test",
      "terraform"
  ]
}
data "azurerm_resource_group" "this" {
  name = "ansumantest"
}

resource "azurerm_storage_account" "this" {
  name                = local.storage_name
  resource_group_name = data.azurerm_resource_group.this.name
  location            = data.azurerm_resource_group.this.location

  account_tier             = "Standard"
  account_kind             = "StorageV2"
  is_hns_enabled           = true
  account_replication_type = "LRS"
}

resource "azurerm_storage_container" "data" {
  for_each = toset(var.storage_containers)

  name                  = each.value
  storage_account_name  = azurerm_storage_account.this.name
  container_access_type = "private"
}

# FIXED
resource "azurerm_storage_account_network_rules" "this" {
  storage_account_id   = azurerm_storage_account.this.id

  default_action = "Deny"
  bypass         = ["AzureServices"]
  ip_rules       = local.my_ip # need to set this to use terraform in our machine
  virtual_network_subnet_ids = local.subnet_id_list

  # NOTE The order here matters: We cannot create storage
  # containers once the network rules are locked down
  depends_on = [
    azurerm_storage_container.data
  ]
}
</code>```

Output:

Body:
I am trying to write Terraform that will create an Azure Storage account and then a bunch of storage containers inside it. An important detail is that the storage account has network rules that restrict access to a specific address space. This was causing the container creation to fail.

I managed to get around this by using azurerm_storage_account_network_rules, depending on the containers so not to block their creation. Something like this:

resource "azurerm_storage_account" "this" {
  name                = local.storage_name
  resource_group_name = azurerm_resource_group.this.name
  location            = var.location

  account_tier             = "Standard"
  account_kind             = "StorageV2"
  is_hns_enabled           = true
  account_replication_type = "LRS"
}

resource "azurerm_storage_container" "data" {
  for_each = toset(var.storage_containers)

  name                  = each.value
  storage_account_name  = azurerm_storage_account.this.name
  container_access_type = "private"
}

# FIXME This order prevents destruction of infrastructure :(
resource "azurerm_storage_account_network_rules" "this" {
  storage_account_id   = azurerm_storage_account.this.id

  default_action = "Deny"
  bypass         = ["AzureServices"]

  virtual_network_subnet_ids = [
    # Some address space here...
  ]

  # NOTE The order here matters: We cannot create storage
  # containers once the network rules are locked down
  depends_on = [
    azurerm_storage_container.data
  ]
}

This works for creating the infrastructure, but when I try to terraform destroy, I get a 403 authentication error:

Error: retrieving Container "data" (Account "XXX" / Resource Group "XXX"): containers.Client#GetProperties: Failure responding to request: StatusCode=403 -- Original Error: autorest/azure: Service returned an error. Status=403 Code="AuthorizationFailure" Message="This request is not authorized to perform this operation.\nRequestId:XXX\nTime:XXX"

This is with my Service Principal, which has Contributor and User Access Administrator roles on the same subscription. Interestingly, when I'm logged in to the Azure Portal as myself (with the Owner role), I can add and remove storage containers regardless of the network rules being present.

So, is there a way of setting the Terraform dependencies such that they can both be built and destroyed without hitting any authentication conflicts? Alternatively, would upgrading my SP's role to Owner (or adding another, more targeted role) solve the problem?

Body:
This is an expected behavior as you are setting up the network rules for the storage account to deny and only bypassing the Azure Services.

When you deny and bypass Azure Services the Azure Services like Azure Portal's IP gets the access to the storage account and you are able to delete it . But at the same time , when you use terraform to perform a destroy , then it denies because your IP which is being used by your machine to send terraform requests to Azure is not bypassed .

I tested your code like below with the same permissions :

As a Solution you will have to add ip rules while creating the storage account to the add the client_ip like below :

provider "azurerm" {
    features{}
  client_id="f6a2f33d-xxxx-xxxx-xxxx-xxxx"
  client_secret= "GZ67Q~xxxx~3N-qLT"
  tenant_id = "72f988bf-xxxx-xxxx-xxxx-2d7cd011db47"
  subscription_id="948d4068-xxxx-xxxx-xxxx-xxxx"
}

locals {
  storage_name = "ansumantestsacc12"
  subnet_id_list = [
      "/subscriptions/xxxx/resourceGroups/xxxx/providers/Microsoft.Network/virtualNetworks/xxxx/subnets/xxxx"
  ]
  my_ip = ["xx.xx.xx.xxx"] # IP used by me
}
variable "storage_containers" {
  default = [
      "test",
      "terraform"
  ]
}
data "azurerm_resource_group" "this" {
  name = "ansumantest"
}

resource "azurerm_storage_account" "this" {
  name                = local.storage_name
  resource_group_name = data.azurerm_resource_group.this.name
  location            = data.azurerm_resource_group.this.location

  account_tier             = "Standard"
  account_kind             = "StorageV2"
  is_hns_enabled           = true
  account_replication_type = "LRS"
}

resource "azurerm_storage_container" "data" {
  for_each = toset(var.storage_containers)

  name                  = each.value
  storage_account_name  = azurerm_storage_account.this.name
  container_access_type = "private"
}

# FIXED
resource "azurerm_storage_account_network_rules" "this" {
  storage_account_id   = azurerm_storage_account.this.id

  default_action = "Deny"
  bypass         = ["AzureServices"]
  ip_rules       = local.my_ip # need to set this to use terraform in our machine
  virtual_network_subnet_ids = local.subnet_id_list

  # NOTE The order here matters: We cannot create storage
  # containers once the network rules are locked down
  depends_on = [
    azurerm_storage_container.data
  ]
}

Output:


问:
How to debug Android build that crashes instantly?
I have a React Native Android app (.67) that works perfectly on emulator and in debug mode (through Android Studio). However, when I build the app, it just instantly crashes on startup. I have zero clue where to even start troubleshooting. How do you access the stacktrace? How do you troubleshoot apps that don't give any meaningful errors at all?

What files should I post here for inspection? I'm not even sure where to start.

答:
The best debugging tool you can use for Android is the logcat in the Android Studio.
Connect your phone to the system via a USB
open the logcat terminal
Add the filter of your app's package name (so that it only shows logs of your app.)
Check the logs for crashes.</p>


问:
generate html and json reports for selenium python automation test using pytest
I have a selenium python automation test, it works fine, now I want to generate Html and JSON reports and have screenshots in the report using pytest. I am new to automation and python so I am not much aware of how its done.

following is my code

test_screenshot.py

```<code>from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import pytest_html
from selenium.common.exceptions import InvalidSessionIdException

def test_Openurl(setup):
    driver = setup["driver"]
    url = setup["url"]
    try:
        driver.get(url)
    except Exception as e:
        print(e.message)

    assert driver.current_url == URL
    driver.save_screenshot("ss.png")
    driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
    driver.save_screenshot("ss1.png")
    driver.close()
</code>```

conftest.py

```<code>import pytest
from selenium import webdriver
from webdriver_manager.chrome import ChromeDriverManager
from selenium.webdriver.chrome.service import Service

def pytest_addoption(parser):
    parser.addoption("--url", action="store", default="https://google.com/")

@pytest.fixture()
def setup(pytestconfig):
    s = Service("C:/Users/Yash/Downloads/chromedriver_win32/chromedriver.exe")
    driver = webdriver.Chrome(service=s)
    driver.maximize_window()
    yield {"driver":driver, "url": pytestconfig.getoption("url")}
</code>```

I ran this using

pytest test_screenshot.py --url "https://www.netflix.com/in/"

Test case is passed. How do I generate HTML and JSON report?
I tried this

pytest -v -s --json-report --json-report-indent=4 --json-report-file=report/report.json --html=report/report.html test_screenshot.py

but got this error

ERROR: usage: pytest [options] [file_or_dir] [file_or_dir] [...]
pytest: error: unrecognized arguments: --json-report --json-report-indent=4 --json-report-file=report/report.json
inifile: None

答: You need to install these two libraries : https://pypi.org/project/pytest-json-report/ & https://pypi.org/project/pytest-html/</p>

Body:
I have a selenium python automation test, it works fine, now I want to generate Html and JSON reports and have screenshots in the report using pytest. I am new to automation and python so I am not much aware of how its done.

following is my code

test_screenshot.py

from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import pytest_html
from selenium.common.exceptions import InvalidSessionIdException

def test_Openurl(setup):
    driver = setup["driver"]
    url = setup["url"]
    try:
        driver.get(url)
    except Exception as e:
        print(e.message)

    assert driver.current_url == URL
    driver.save_screenshot("ss.png")
    driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
    driver.save_screenshot("ss1.png")
    driver.close()

conftest.py

import pytest
from selenium import webdriver
from webdriver_manager.chrome import ChromeDriverManager
from selenium.webdriver.chrome.service import Service

def pytest_addoption(parser):
    parser.addoption("--url", action="store", default="https://google.com/")

@pytest.fixture()
def setup(pytestconfig):
    s = Service("C:/Users/Yash/Downloads/chromedriver_win32/chromedriver.exe")
    driver = webdriver.Chrome(service=s)
    driver.maximize_window()
    yield {"driver":driver, "url": pytestconfig.getoption("url")}

I ran this using

pytest test_screenshot.py --url "https://www.netflix.com/in/"

Test case is passed. How do I generate HTML and JSON report?
I tried this

pytest -v -s --json-report --json-report-indent=4 --json-report-file=report/report.json --html=report/report.html test_screenshot.py

but got this error

ERROR: usage: pytest [options] [file_or_dir] [file_or_dir] [...]
pytest: error: unrecognized arguments: --json-report --json-report-indent=4 --json-report-file=report/report.json
inifile: None


问:
Make a program to solve this question using python:
Find the number of 6 digit numbers such that each digit appears atleast twice

I tried the below code but it doesn't work:

```<code>count = 0
for n in range(10**5,(10**6)-1):
    n = str(n).split()

for i in range(len(n)):

    n[i] = int(n[i])
    if n.count(i) >= 2:

        count+=1
print(count)
</code>```

The original question is of Permutation and Combinations but I want to solve this using python...

答:
Here are some of the mistakes in your code -

The range needs to be range(10**5, 10**6) to cover all 6 digit numbers

str(n).split() won't split the n into a list of characters since there is no delimiter between the string representation of the number. You can use [letter for letter in str(n)] instead.

You want to run the second loop for each of the numbers in the first loop, so the second loop needs to be inside the first loop.

Within the second loop, you are increasing the count if one of the digits occurs more than twice in the number, so you might end up increasing the count multiple times for a single number. e.g. for 112233 you would end up increasing the count by 3 instead of just 1.

here's a simplified code which does what you want in a similar format -

```<code>count = 0
for n in range(10**5, 10**6):
    n = [letter for letter in str(n)]
    count += 1
    for letter in n:
        if n.count(letter) < 2:
            count -= 1
            break

print(count)
</code>```

outputs -

```<code>11754
</code>```

You can use all() function along with list comprehension to simplify the code -

```<code>count = 0
for n in range(10**5, 10**6):
    n = [letter for letter in str(n)]
    count += all(n.count(letter) >= 2 for letter in n)
</code>```

Body:
Find the number of 6 digit numbers such that each digit appears atleast twice

I tried the below code but it doesn't work:

count = 0
for n in range(10**5,(10**6)-1):
    n = str(n).split()

for i in range(len(n)):

    n[i] = int(n[i])
    if n.count(i) >= 2:

        count+=1
print(count)

The original question is of Permutation and Combinations but I want to solve this using python...

Body:
Here are some of the mistakes in your code -

The range needs to be range(10**5, 10**6) to cover all 6 digit numbers

str(n).split() won't split the n into a list of characters since there is no delimiter between the string representation of the number. You can use [letter for letter in str(n)] instead.

You want to run the second loop for each of the numbers in the first loop, so the second loop needs to be inside the first loop.

Within the second loop, you are increasing the count if one of the digits occurs more than twice in the number, so you might end up increasing the count multiple times for a single number. e.g. for 112233 you would end up increasing the count by 3 instead of just 1.

here's a simplified code which does what you want in a similar format -

count = 0
for n in range(10**5, 10**6):
    n = [letter for letter in str(n)]
    count += 1
    for letter in n:
        if n.count(letter) < 2:
            count -= 1
            break

print(count)

outputs -

11754

You can use all() function along with list comprehension to simplify the code -

count = 0
for n in range(10**5, 10**6):
    n = [letter for letter in str(n)]
    count += all(n.count(letter) >= 2 for letter in n)


问:
how to take encrypted database backup in mysql
i am using mysql-5.5 and rhel5 and my intention is to use mysqldump to take the encrypted backup and compressed backup

as i am using mysqldump as below

```<code>mysqldump -u root -p db_name | gzip >file_name.sql.gz
</code>```

it will give compressed backup but not encrypted one

答:
Backup one database, change what is inside [..]

```<code>mysqldump -u root --single-transaction [DataBaseName] | gzip | openssl enc -pbkdf2 -k [MyPassword] > database.sql.zip.enc
</code>```

Backup all databases separately:

```<code>date=`date "+%Y%m%d"`
for DB in $(mysql -u root -e 'show databases' -s --skip-column-names); do
        mysqldump -u root --single-transaction $DB | gzip | openssl enc -pbkdf2 -k [MyPassword] > db-$DB-$date.sql.gz.enc;
done
</code>```

Body:
i am using mysql-5.5 and rhel5 and my intention is to use mysqldump to take the encrypted backup and compressed backup

as i am using mysqldump as below

mysqldump -u root -p db_name | gzip >file_name.sql.gz

it will give compressed backup but not encrypted one

Body:
Backup one database, change what is inside [..]

mysqldump -u root --single-transaction [DataBaseName] | gzip | openssl enc -pbkdf2 -k [MyPassword] > database.sql.zip.enc

Backup all databases separately:

date=`date "+%Y%m%d"`
for DB in $(mysql -u root -e 'show databases' -s --skip-column-names); do
        mysqldump -u root --single-transaction $DB | gzip | openssl enc -pbkdf2 -k [MyPassword] > db-$DB-$date.sql.gz.enc;
done


答:
Send a header informing the browser what character set a document is encoded in:</p>

```<code>header('Content-Type: text/html; charset=UTF-8');
</code>```

Title: Bad UTF-8 without BOM encoding

Body:
I converted all my files to UTF-8 without BOM encoding using Notepad++. I have no problem with BOMs anymore but the UTF without BOM encoding is simply not working, it's as if my site was encoded in ANSI. All special characters display either as: Â, Ãš or Ã¡.

What can be the reason for this and how can I fix it?

http://chusmix.com/?ciudad=Pilar

Thanks

Body:
Send a header informing the browser what character set a document is encoded in:

header('Content-Type: text/html; charset=UTF-8');


问:
Why are certain variables marked as final in flutter custom classes?
I noticed in some of the examples online that classes that extend StatefulWidget have instance variables marked with final. Why is that?
I understand what the final keyword does. I do not understand why it is being declared with each instance variable that extends the widget class.

答:
Why do we use final and what benefits can we get from it.

The core concept of Flutter's three-tree model (widget, element, render) is to avoid complicated computer restart during frame updating. So element and render tree will avoid rebuild, and widget tree as config will frequently be rebuild (widget object will frequently be create).

Therefore, the question is just like creating some object frequently, what kind of design concept are suitable for it. That's an immutable object. Think of the String class of java. The benefit is thread safe (unsafe is to share and mutable variable), no invalid state, more readable and maintainable code.

And if you have some variable state, then you should write that in your state object. The state is saved by an element object.
So the element and render object is the minmum create times, they use state object to corresponding change. The widget is often created, but it is simple and immutable every time. Just like general, make command "turn right, turn left", they never say "turn ri, left".

Finally, you can read this Why are flutter widgets immutable?


问:
Flutter convert Byte to String
So that you have all the context... in python I run the following code:
https://www.delftstack.com/es/howto/python/convert-string-to-ascii-python/

```<code>def to_ascii(text):
    ascii_values = [ord(character) for character in text]
    return ascii_values
text = input("Enter a string: ")
print(to_ascii(text))
</code>```

If I write "hello" it throws me the following:
[104, 101, 108, 108, 111]

My problem is with Flutter. I get that value and since I don't know flutter I don't know how to put it to text (utf8).

```<code>builder: (c, snapshot) {
   final value = snapshot.data;

...

subtitle: Text(value.toString()),
</code>```

value.toString() return [104, 101, 108, 108, 111]

How do I put it in utf8 ("Hello")?

Complete code:

```<code>@override
  Widget build(BuildContext context) {
    return StreamBuilder<List<int>>(
      stream: characteristic.value,
      initialData: characteristic.lastValue,
      builder: (c, snapshot) {
        final value = snapshot.data;

        //convert value ascii to utf8
        //var decoded = utf8.decode(value);

        return ExpansionTile(
          title: ListTile(
            title: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              crossAxisAlignment: CrossAxisAlignment.start,
              children: <Widget>[
                Text('Characteristic'),
                Text(
                    '0x${characteristic.uuid.toString().toUpperCase().substring(4, 8)}',
                    style: Theme.of(context).textTheme.bodyText1?.copyWith(
                        color: Theme.of(context).textTheme.caption?.color))
              ],
            ),
            subtitle: Text(value),
            contentPadding: EdgeInsets.all(0.0),
          ),
          trailing: Row(
            mainAxisSize: MainAxisSize.min,
            children: <Widget>[
              IconButton(
                icon: Icon(
                  Icons.lightbulb_outline,
                  color: Theme.of(context).iconTheme.color?.withOpacity(0.5),
                ),
                onPressed: turnOff,
              ),
              IconButton(
                icon: Icon(Icons.lightbulb,
                    color: Theme.of(context).iconTheme.color?.withOpacity(0.5)),
                onPressed: turnOn,
              ),
              //iconButton for add
              IconButton(
                icon: Icon(
                  Icons.add_circle,
                  color: Theme.of(context).iconTheme.color?.withOpacity(0.5),
                ),
                onPressed: extraButton,
              ),
              IconButton(
                icon: Icon(
                    characteristic.isNotifying
                        ? Icons.sync_disabled
                        : Icons.sync,
                    color: Theme.of(context).iconTheme.color?.withOpacity(0.5)),
                onPressed: onNotificationPressed,
              )
            ],
          ),
          children: descriptorTiles,
        );
      },
    );
  }
}
</code>```

答:
The demo:

```<code>import 'dart:convert';
void main() {
  const asciiDecoder = AsciiDecoder();
  final asciiValues = [104, 101, 108, 108, 111];
  final result = asciiDecoder.convert(asciiValues);
  print(result);  //hello
}
</code>```

see the ref.

Because maxium ascii code is 127, use Base64Decoder instead.

Title: Flutter convert Byte to String

Body:
So that you have all the context... in python I run the following code:
https://www.delftstack.com/es/howto/python/convert-string-to-ascii-python/

def to_ascii(text):
    ascii_values = [ord(character) for character in text]
    return ascii_values
text = input("Enter a string: ")
print(to_ascii(text))

If I write "hello" it throws me the following:
[104, 101, 108, 108, 111]

My problem is with Flutter. I get that value and since I don't know flutter I don't know how to put it to text (utf8).

builder: (c, snapshot) {
   final value = snapshot.data;

...

subtitle: Text(value.toString()),

value.toString() return [104, 101, 108, 108, 111]

How do I put it in utf8 ("Hello")?

Complete code:

@override
  Widget build(BuildContext context) {
    return StreamBuilder<List<int>>(
      stream: characteristic.value,
      initialData: characteristic.lastValue,
      builder: (c, snapshot) {
        final value = snapshot.data;

        //convert value ascii to utf8
        //var decoded = utf8.decode(value);

        return ExpansionTile(
          title: ListTile(
            title: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              crossAxisAlignment: CrossAxisAlignment.start,
              children: <Widget>[
                Text('Characteristic'),
                Text(
                    '0x${characteristic.uuid.toString().toUpperCase().substring(4, 8)}',
                    style: Theme.of(context).textTheme.bodyText1?.copyWith(
                        color: Theme.of(context).textTheme.caption?.color))
              ],
            ),
            subtitle: Text(value),
            contentPadding: EdgeInsets.all(0.0),
          ),
          trailing: Row(
            mainAxisSize: MainAxisSize.min,
            children: <Widget>[
              IconButton(
                icon: Icon(
                  Icons.lightbulb_outline,
                  color: Theme.of(context).iconTheme.color?.withOpacity(0.5),
                ),
                onPressed: turnOff,
              ),
              IconButton(
                icon: Icon(Icons.lightbulb,
                    color: Theme.of(context).iconTheme.color?.withOpacity(0.5)),
                onPressed: turnOn,
              ),
              //iconButton for add
              IconButton(
                icon: Icon(
                  Icons.add_circle,
                  color: Theme.of(context).iconTheme.color?.withOpacity(0.5),
                ),
                onPressed: extraButton,
              ),
              IconButton(
                icon: Icon(
                    characteristic.isNotifying
                        ? Icons.sync_disabled
                        : Icons.sync,
                    color: Theme.of(context).iconTheme.color?.withOpacity(0.5)),
                onPressed: onNotificationPressed,
              )
            ],
          ),
          children: descriptorTiles,
        );
      },
    );
  }
}

Body:
The demo:

import 'dart:convert';
void main() {
  const asciiDecoder = AsciiDecoder();
  final asciiValues = [104, 101, 108, 108, 111];
  final result = asciiDecoder.convert(asciiValues);
  print(result);  //hello
}

see the ref.

Because maxium ascii code is 127, use Base64Decoder instead.