问:
Static method in generic class causes CA1000 warning
I'm working on a library to manage objects (Animals in my sample code). I have a base class named Animal and a generic class named SpecificAnimal. I also have Dog, Cat etc. which are implemented with the SpecificAnimal class.

If a user wants to create a dog, it is as simple as:

```<code>            var myDog = new Dog()
            {
                Name = "Rover",
                Age = 3
            };
            myDog.Add();
</code>```

The class hierarchy looks like this:

Animal Class

```<code>    public abstract class Animal
    {
        public static Animal GetByName(string animalName)
        {
            // Code that can read any kind of animal from a database
            // and create an instance of the correct type
            throw new NotImplementedException();
        }

        public static Animal GetById(int animalId)
        {
            // Code that can read any kind of animal from a database
            // and create an instance of the correct type
            throw new NotImplementedException();
        }

        public string Name { get; set; } = string.Empty;

        public int Age { get; set; }

        public void Add()
        {
            //  Add this Animal to the database
        }

        public void Update()
        {
            // Update this animal
        }
    }
</code>```

Generic SpecificAnimal class

```<code>    public abstract class SpecificAnimal<T> : Animal where T : SpecificAnimal<T>
    {
        public static string Genus { get; protected set; } = String.Empty;

        public new static T GetByName(string animalName)
        {
            // Code that can read an object of type T from a database
            return (T)Animal.GetByName(animalName);
        }

        public new static T GetId(int animalId)
        {
            // Code that can read an object of type T from a database
            return (T)Animal.GetById(animalId);
        }
    }
</code>```

Dog class

```<code>    public class Dog : SpecificAnimal<Dog>
    {
        public Dog()
        {
            Genus = "Canis";
        }

        //  Dog specific properties and methods
    }
</code>```

This code is working and (in my opinion) is easy for the consumer of the library to use.

My problem is that the static properties and methods in the SpecificAnimal class generate the warning:

```<code>CA1000: Do not declare static members on generic types
</code>```

https://learn.microsoft.com/en-us/dotnet/fundamentals/code-analysis/quality-rules/ca1000

The documentation for CA1000 says "Do not suppress..." but, it doesn't suggest a better solution. If I shouldn't have static members in a generic class, what should I be doing?
The documentation says that static methods in a generic type are bad because of this awkward syntax:

```<code>var myDog = SpecificAnimal<Dog>.GetByName("Rover");
</code>```

I agree but, my users should never do that. Although, I don't know of a way to prevent it.

How can I add static members to a generic class without generating CA1000? How can I protect the SpecificAnimal class so that the user only has access to Dog and Animal?

答:
The property can be rewritten as in the example.

```<code>public abstract class SpecificAnimal<T> : Animal where T : SpecificAnimal<T>
{
    public virtual string Genus { get; } = String.Empty;
}

public class Dog : SpecificAnimal<Dog>
{
    public override string Genus { get; } = "Canis";
}
</code>```

Note that implementing the static new method does not work in the same way as inheritance.

Body:
I'm working on a library to manage objects (Animals in my sample code). I have a base class named Animal and a generic class named SpecificAnimal. I also have Dog, Cat etc. which are implemented with the SpecificAnimal class.

If a user wants to create a dog, it is as simple as:

            var myDog = new Dog()
            {
                Name = "Rover",
                Age = 3
            };
            myDog.Add();

The class hierarchy looks like this:

Animal Class

    public abstract class Animal
    {
        public static Animal GetByName(string animalName)
        {
            // Code that can read any kind of animal from a database
            // and create an instance of the correct type
            throw new NotImplementedException();
        }

        public static Animal GetById(int animalId)
        {
            // Code that can read any kind of animal from a database
            // and create an instance of the correct type
            throw new NotImplementedException();
        }

        public string Name { get; set; } = string.Empty;

        public int Age { get; set; }

        public void Add()
        {
            //  Add this Animal to the database
        }

        public void Update()
        {
            // Update this animal
        }
    }

Generic SpecificAnimal class

    public abstract class SpecificAnimal<T> : Animal where T : SpecificAnimal<T>
    {
        public static string Genus { get; protected set; } = String.Empty;

        public new static T GetByName(string animalName)
        {
            // Code that can read an object of type T from a database
            return (T)Animal.GetByName(animalName);
        }

        public new static T GetId(int animalId)
        {
            // Code that can read an object of type T from a database
            return (T)Animal.GetById(animalId);
        }
    }

Dog class

    public class Dog : SpecificAnimal<Dog>
    {
        public Dog()
        {
            Genus = "Canis";
        }

        //  Dog specific properties and methods
    }

This code is working and (in my opinion) is easy for the consumer of the library to use.

My problem is that the static properties and methods in the SpecificAnimal class generate the warning:

CA1000: Do not declare static members on generic types

https://learn.microsoft.com/en-us/dotnet/fundamentals/code-analysis/quality-rules/ca1000

The documentation for CA1000 says "Do not suppress..." but, it doesn't suggest a better solution. If I shouldn't have static members in a generic class, what should I be doing?
The documentation says that static methods in a generic type are bad because of this awkward syntax:

var myDog = SpecificAnimal<Dog>.GetByName("Rover");

I agree but, my users should never do that. Although, I don't know of a way to prevent it.

How can I add static members to a generic class without generating CA1000? How can I protect the SpecificAnimal class so that the user only has access to Dog and Animal?

Body:
The property can be rewritten as in the example.

public abstract class SpecificAnimal<T> : Animal where T : SpecificAnimal<T>
{
    public virtual string Genus { get; } = String.Empty;
}

public class Dog : SpecificAnimal<Dog>
{
    public override string Genus { get; } = "Canis";
}

Note that implementing the static new method does not work in the same way as inheritance.


来源: stackexchange

问:
ML.NET using MySQL as Data source
I tried using MySQL for ML.NET.
I installed MySQL driver for VisualStudio, and it gets displayed in the normal server explorer data sources but not in the ML.NET Setup?

Is there any way to use MySQL with ML.NET?

答:
There is no built-in way to use MySQL with ML.NET; from the ML.NET Model Builder documentation:

The current preview of Model Builder can work with csv files, tsv files, and SQL Server databases. As we work toward stable release, we'll be adding support for more file formats and databases, including non-relational data stores.

However, the DatabaseSource class appears to be fairly generic, and it should work if you write some custom code:

First, install MySqlConnector with dotnet add package MySqlConnector.

Then try the following code:

var source = new DatabaseSource(MySqlConnectorFactory.Instance,
    "server=myserver;user=myuser;password=pass",
    "select `Text`, Label from table");
var ctx = new MLContext();
var loader = ctx.Data.CreateDatabaseLoader(
    new("Text", DbType.String, 0),
    new("Label", DbType.Boolean, 1));
var view = loader.Load(source);
```

ContentLicense: CC BY-SA 4.0

Title: ML.NET using MySQL as Data source


问:
How to copy a particular row from xsls file and export it to new xlsx file using Apache poi?
I have a folder with 216 xsls files. My logic is to loop throw the folder and read every file, copy the first row of each file and write that row to a new .xsls file.

I want to copy the first row without iterating throw the row and read every cell? for example, if you copy the first line in the .txt file or .csv file.

Also, this is a very slow process. Do you have tips to speed up this process?

```<code> public static void listFilesForFolder(final File folder,final File exported, int skipLine) {
    try {
        for (final File fileEntry : folder.listFiles()) {

            String ext = fileEntry.getName().substring(fileEntry.getName().lastIndexOf('.') + 1);

            System.out.println("-->> " + fileEntry.getName() + "-->>");

            FileInputStream file = new FileInputStream(new File(fileEntry.getPath()));

            if (fileEntry.isDirectory()) {
                continue;
            } else if(ext.equals("xlsx")) {

                XSSFWorkbook myWorkBook = new XSSFWorkbook(file);
                XSSFSheet mySheet = myWorkBook.getSheetAt(0);

                Iterator<Row> rowIterator = mySheet.iterator();

                    Row row = rowIterator.next();

                    row = rowIterator.next();

                    Iterator<Cell> cellIterator = row.cellIterator();
                    while (cellIterator.hasNext()) {
                        Cell cell = cellIterator.next();
                        switch (cell.getCellType()){
                            case STRING:
                                System.out.print(cell.getStringCellValue() + "\t");
                                break;
                            case NUMERIC:
                                System.out.print(cell.getNumericCellValue() + "\t");
                                break;
                            default:
                        }
                    }
                    System.out.println("");
                file.close();
            }
        }
    }catch (Exception e){
        System.out.println(e.getMessage());
    }
    }
</code>```

答:
I found the answer to my question.
You can not copy the whole row. You need to loop and read cell by cell.
The solution is:

Declare rowInrecmenter, colIncremnter, xssfWorkbook = new XSSFWorkbook();,
XSSFSheet createdSheet = xssfWorkbook.createSheet("Put any name here");

The variables above need to be outside the loop.

The rest of the codes are:

```<code>XSSFRow rowCreated = createdSheet.createRow((short)incr);

while (cellIterator.hasNext()) {
                    Cell cell = cellIterator.next();
                    switch (cell.getCellType()) {
                        case STRING:
                            rowCreated.createCell(col).setCellValue(cell.getStringCellValue());
                            col++;
                            break;
                        case NUMERIC:
                            rowCreated.createCell(col).setCellValue(cell.getNumericCellValue());
                            col++;
                            break;
                        default:
                    }
                }
                xssfWorkbook.write(fileOut);
                incr++;
                col = 0;
                workbook.close();
                file.close();
            }
        }

    } catch (Exception e) {
        System.out.println(e.getMessage());
    }finally {
        fileOut.close();
        xssfWorkbook.close();

    }
</code>```

Body:
I have a folder with 216 xsls files. My logic is to loop throw the folder and read every file, copy the first row of each file and write that row to a new .xsls file.

I want to copy the first row without iterating throw the row and read every cell? for example, if you copy the first line in the .txt file or .csv file.

Also, this is a very slow process. Do you have tips to speed up this process?

 public static void listFilesForFolder(final File folder,final File exported, int skipLine) {
    try {
        for (final File fileEntry : folder.listFiles()) {

            String ext = fileEntry.getName().substring(fileEntry.getName().lastIndexOf('.') + 1);

            System.out.println("-->> " + fileEntry.getName() + "-->>");

            FileInputStream file = new FileInputStream(new File(fileEntry.getPath()));

            if (fileEntry.isDirectory()) {
                continue;
            } else if(ext.equals("xlsx")) {

                XSSFWorkbook myWorkBook = new XSSFWorkbook(file);
                XSSFSheet mySheet = myWorkBook.getSheetAt(0);

                Iterator<Row> rowIterator = mySheet.iterator();

                    Row row = rowIterator.next();

                    row = rowIterator.next();

                    Iterator<Cell> cellIterator = row.cellIterator();
                    while (cellIterator.hasNext()) {
                        Cell cell = cellIterator.next();
                        switch (cell.getCellType()){
                            case STRING:
                                System.out.print(cell.getStringCellValue() + "\t");
                                break;
                            case NUMERIC:
                                System.out.print(cell.getNumericCellValue() + "\t");
                                break;
                            default:
                        }
                    }
                    System.out.println("");
                file.close();
            }
        }
    }catch (Exception e){
        System.out.println(e.getMessage());
    }
    }

Body:
I found the answer to my question.
You can not copy the whole row. You need to loop and read cell by cell.
The solution is:

Declare rowInrecmenter, colIncremnter, xssfWorkbook = new XSSFWorkbook();,
XSSFSheet createdSheet = xssfWorkbook.createSheet("Put any name here");

The variables above need to be outside the loop.

The rest of the codes are:

XSSFRow rowCreated = createdSheet.createRow((short)incr);

while (cellIterator.hasNext()) {
                    Cell cell = cellIterator.next();
                    switch (cell.getCellType()) {
                        case STRING:
                            rowCreated.createCell(col).setCellValue(cell.getStringCellValue());
                            col++;
                            break;
                        case NUMERIC:
                            rowCreated.createCell(col).setCellValue(cell.getNumericCellValue());
                            col++;
                            break;
                        default:
                    }
                }
                xssfWorkbook.write(fileOut);
                incr++;
                col = 0;
                workbook.close();
                file.close();
            }
        }

    } catch (Exception e) {
        System.out.println(e.getMessage());
    }finally {
        fileOut.close();
        xssfWorkbook.close();

    }


问:
Flutter | Build functions must never return null
The error message is quite straightforward,
I have tried return Container(); in else still, it does not work out

FutureBuilder reviewFutureBuilder() {

```<code>return FutureBuilder<OrdersModel>(
  future: _futureReviewModel,
  builder: (context, snapshot) {
    if (snapshot.hasData) {

    } else if (snapshot.hasError) {
     return Center(
        child: Column(
          children: [
            Text('$snapshot.error'),
          ],
        ),
      );
    }
    return Center(
      child: Column(
        children: [
          CircularProgressIndicator(),
        ],
      ),
    );
  },
);
</code>```

this is my error in the studio

this my mobile UI error

答:
I solved my problem by wrapping snapshot.haserror and return CircularProgress in a container, here is how I solved it.</p>
```<code>else if (snapshot.hasError) {
      return SafeArea(
        child: Container(
          height: MediaQuery.of(context).size.height,
          width: MediaQuery.of(context).size.width,
          child: Column(
            children: [
              Text('$snapshot.error'),
            ],
          ),
        ),
      );
    } else {
      return SafeArea(
        child: Container(
          height: MediaQuery.of(context).size.height,
          width: MediaQuery.of(context).size.width,
          child: Column(
            children: [
              CircularProgressIndicator(),
            ],
          ),
        ),
      );
    }
</code>```

Body:
The error message is quite straightforward,
I have tried return Container(); in else still, it does not work out

FutureBuilder reviewFutureBuilder() {

return FutureBuilder<OrdersModel>(
  future: _futureReviewModel,
  builder: (context, snapshot) {
    if (snapshot.hasData) {

    } else if (snapshot.hasError) {
     return Center(
        child: Column(
          children: [
            Text('$snapshot.error'),
          ],
        ),
      );
    }
    return Center(
      child: Column(
        children: [
          CircularProgressIndicator(),
        ],
      ),
    );
  },
);

this is my error in the studio

this my mobile UI error

Body:
I solved my problem by wrapping snapshot.haserror and return CircularProgress in a container, here is how I solved it.

else if (snapshot.hasError) {
      return SafeArea(
        child: Container(
          height: MediaQuery.of(context).size.height,
          width: MediaQuery.of(context).size.width,
          child: Column(
            children: [
              Text('$snapshot.error'),
            ],
          ),
        ),
      );
    } else {
      return SafeArea(
        child: Container(
          height: MediaQuery.of(context).size.height,
          width: MediaQuery.of(context).size.width,
          child: Column(
            children: [
              CircularProgressIndicator(),
            ],
          ),
        ),
      );
    }


问:
CentOS 8 stream
dnf --enablerepo=centos-openstack-wallaby -y upgrade
CentOS-8 - Ceph Nautilus                                  63  B/s |  38  B     00:00
Error: Failed to download metadata for repo 'centos-ceph-nautilus': Cannot prepare internal mirrorlist: No URLs in mirrorlist</p>

答:
If you need to update your CentOS 8 Stream, you need to change the mirrors to vault.centos.org

Step 1: Go to the /etc/yum.repos.d/ directory

```<code># cd /etc/yum.repos.d/
</code>```

Step 2: Run the below commands

```<code># sed -i 's/mirrorlist/#mirrorlist/g' /etc/yum.repos.d/CentOS-*
# sed -i 's|#baseurl=http://mirror.centos.org|baseurl=http://vault.centos.org|g' /etc/yum.repos.d/CentOS-*
</code>```

Now run your dnf command.

Title: CentOS 8 stream

Body:
If you need to update your CentOS 8 Stream, you need to change the mirrors to vault.centos.org

Step 1: Go to the /etc/yum.repos.d/ directory

# cd /etc/yum.repos.d/

Step 2: Run the below commands

# sed -i 's/mirrorlist/#mirrorlist/g' /etc/yum.repos.d/CentOS-*
# sed -i 's|#baseurl=http://mirror.centos.org|baseurl=http://vault.centos.org|g' /etc/yum.repos.d/CentOS-*

Now run your dnf command.


问:
Generate Random Speed letters for Race Game in C#
I am creating a simple task just to keep practicing. Now I created a  non-interactive game. And the letter are the characters which is A, B, C. Now since I've position my 'C' to 3 it is always the first one to finish. How do you random the speed of each characters?</p>
```<code>static void Main()
        {

          Runner runnerA = new Runner('A');
            Runner runnerB = new Runner('B');
            Runner runnerC = new Runner('C');

            runnerA.Position = 1;
            runnerB.Position = 3;
            runnerC.Position = 3;

            string course = "---......------.......";

            while (true)
            {
                runnerA.Position++;
                runnerB.Position++;
                runnerC.Position++;

                if (runnerA.Position == course.Length)
                {
                }

                for (int i = 0; i < course.Length; i++)
                {
                    if (runnerA.Position == i)
                    {
                        Console.Write(runnerA.Glyph);
                    }
                    else if (runnerB.Position == i)
                    {
                        Console.Write(runnerB.Glyph);
                    }
                    else if (runnerB.Position == i) {
                        Console.Write(runnerB.Glyph);
                    }
                    else // No runners on this tile.
                    {
                        Console.Write(course[i]);
                    }
                }

                Console.Write('|');

                Console.WriteLine();

                Thread.Sleep(100);
                Console.SetCursorPosition(0, 0);

            }

        }
    }
</code>```

答:
Here is a solution which works like this:

Runner classes are instantiated with random positions and speeds

Runners have a Timer property which allows to indicate when they need to be moved according to the elapsed time

I made a speed factor appear depending on the terrain: 1 if "-" and 0.5 if "."

If two runners have the same position, only one will appear

The Main void:

```<code>internal class Program
{
    static void Main()
    {
        Random random = new Random();
        string map = "-----------............------..............-----------............|";
        int interval = 50;
        List<Runner> runners = new List<Runner>
        {
            new Runner('A', random.Next(1, 10), random.Next(1, 5) * interval),
            new Runner('B', random.Next(1, 10), random.Next(1, 5) * interval),
            new Runner('C', random.Next(1, 10), random.Next(1, 5) * interval)
        };

        while (true)
        {
            foreach (Runner runner in runners)
            {
                if (runner.Position == map.Length - 1)
                {
                    Console.SetCursorPosition(0, 1);
                    Console.WriteLine($"The winner is: {runner.Glyph} !");
                    Console.ReadKey();
                }
                double mapFactor = map[runner.Position].Equals('-') ? 1 : 0.5;
                runner.Update(interval, mapFactor);
            }

            for (int i = 0; i < map.Length; i++)
            {
                Runner matchingRunner = runners.Find(x => x.Position == i);
                Console.Write(matchingRunner != null ? matchingRunner.Glyph : map[i]);
            }

            Console.WriteLine();
            Thread.Sleep(interval);
            Console.SetCursorPosition(0, 0);
        }
    }
}
</code>```

And the associated Runner class:

```<code>public class Runner
{
    public char Glyph { get; set; }
    public int Position { get; set; }
    public int Speed { get; set; }
    public int Timer { get; set; }

    public Runner(char glyph, int position, int speed)
    {
        Glyph = glyph;
        Position = position;
        Speed = speed;
        Timer = 0;
    }

    public void Update(int interval, double mapFactor)
    {
        Timer += interval;
        if (Timer / mapFactor > Speed)
        {
            Timer = 0;
            Position++;
        }
    }
}
</code>```

Body:
I am creating a simple task just to keep practicing. Now I created a  non-interactive game. And the letter are the characters which is A, B, C. Now since I've position my 'C' to 3 it is always the first one to finish. How do you random the speed of each characters?

static void Main()
        {

          Runner runnerA = new Runner('A');
            Runner runnerB = new Runner('B');
            Runner runnerC = new Runner('C');

            runnerA.Position = 1;
            runnerB.Position = 3;
            runnerC.Position = 3;

            string course = "---......------.......";

            while (true)
            {
                runnerA.Position++;
                runnerB.Position++;
                runnerC.Position++;

                if (runnerA.Position == course.Length)
                {
                }

                for (int i = 0; i < course.Length; i++)
                {
                    if (runnerA.Position == i)
                    {
                        Console.Write(runnerA.Glyph);
                    }
                    else if (runnerB.Position == i)
                    {
                        Console.Write(runnerB.Glyph);
                    }
                    else if (runnerB.Position == i) {
                        Console.Write(runnerB.Glyph);
                    }
                    else // No runners on this tile.
                    {
                        Console.Write(course[i]);
                    }
                }

                Console.Write('|');

                Console.WriteLine();

                Thread.Sleep(100);
                Console.SetCursorPosition(0, 0);

            }

        }
    }

Body:
Here is a solution which works like this:

Runner classes are instantiated with random positions and speeds

Runners have a Timer property which allows to indicate when they need to be moved according to the elapsed time

I made a speed factor appear depending on the terrain: 1 if "-" and 0.5 if "."

If two runners have the same position, only one will appear

The Main void:

internal class Program
{
    static void Main()
    {
        Random random = new Random();
        string map = "-----------............------..............-----------............|";
        int interval = 50;
        List<Runner> runners = new List<Runner>
        {
            new Runner('A', random.Next(1, 10), random.Next(1, 5) * interval),
            new Runner('B', random.Next(1, 10), random.Next(1, 5) * interval),
            new Runner('C', random.Next(1, 10), random.Next(1, 5) * interval)
        };

        while (true)
        {
            foreach (Runner runner in runners)
            {
                if (runner.Position == map.Length - 1)
                {
                    Console.SetCursorPosition(0, 1);
                    Console.WriteLine($"The winner is: {runner.Glyph} !");
                    Console.ReadKey();
                }
                double mapFactor = map[runner.Position].Equals('-') ? 1 : 0.5;
                runner.Update(interval, mapFactor);
            }

            for (int i = 0; i < map.Length; i++)
            {
                Runner matchingRunner = runners.Find(x => x.Position == i);
                Console.Write(matchingRunner != null ? matchingRunner.Glyph : map[i]);
            }

            Console.WriteLine();
            Thread.Sleep(interval);
            Console.SetCursorPosition(0, 0);
        }
    }
}

And the associated Runner class:

public class Runner
{
    public char Glyph { get; set; }
    public int Position { get; set; }
    public int Speed { get; set; }
    public int Timer { get; set; }

    public Runner(char glyph, int position, int speed)
    {
        Glyph = glyph;
        Position = position;
        Speed = speed;
        Timer = 0;
    }

    public void Update(int interval, double mapFactor)
    {
        Timer += interval;
        if (Timer / mapFactor > Speed)
        {
            Timer = 0;
            Position++;
        }
    }
}


问:
Javascript Image onError not working when updating image src on hover
I have created a table that contains a list of Magic the Gathering cards. When the user hovers over the card name it displays the cards image. These images are stored in a AWS S3 buckets.

There is a cost involved to loading those images from the S3 bucket so rather than loading 20-50 images when the page loads, what I have done is saved the Image URL in a custom attribute - url - for the image element and then when the user hovers over the card name it replaces src with url. The works as expected when the card image exists in the S3 bucket.

However this seems to have broken the onError attribute so now when there is not an image in the S3 bucket for a particular card the broken card symbol appear rather than the placeholder image.

function hover(e) { let url = e.nextSibling.firstChild.getAttribute('url'); e.nextSibling.firstChild.setAttribute('src', url); e.nextSibling.classList.remove("hidden"); }
function unhover(e) { e.nextSibling.classList.add("hidden");
```
<pre class="lang-html prettyprint-override"><code><span onmouseover="hover(this);" onmouseout="unhover(this);" class="group cursor-pointer font-semibold hover:text-primary">
  Card Name
</span>
<span id="large" class="hidden">
  <img id="large-image" class="..." src="" url=".../card_image.jpg" height="500" onError="this.onerror=null;this.src=\'/static/img/placeholder.png\';">
</span>
</code>```

How do I get the placeholder image to work when there is not image found in the S3 bucket?

答:
There is a syntax error. You don't have to escape single quotes inside double quotes. Following will work:

```
<p>Demo:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>function hover(e) {
  if (!large_image.getAttribute('src')) {
    let url = large_image.getAttribute('url');
    large_image.setAttribute('src', url);
  }

  if (!large_image2.getAttribute('src')) {
    url = large_image2.getAttribute('url');
    large_image2.setAttribute('src', url);
  }

  large.classList.remove("hidden");
}

function unhover(e) {
  large.classList.add("hidden");
}

large_image.addEventListener('error', errorHandler);
large_image2.addEventListener('error', errorHandler);

function errorHandler(e) {
  e.target.removeEventListener('error', errorHandler);
  e.target.src = "data:image/svg+xml,%3Csvg width='32px' height='32px' viewBox='0 0 32 32' fill='none' xmlns='http://www.w3.org/2000/svg'%3E%3Cpath fill-rule='evenodd' clip-rule='evenodd' d='M11.7577 11.7574C12.1483 11.3669 12.7814 11.3669 13.172 11.7574L16.0004 14.5859L18.8288 11.7574C19.2193 11.3669 19.8525 11.3669 20.243 11.7574C20.6336 12.148 20.6336 12.7811 20.243 13.1716L17.4146 16.0001L20.243 18.8285C20.6335 19.219 20.6335 19.8522 20.243 20.2427C19.8525 20.6332 19.2193 20.6332 18.8288 20.2427L16.0004 17.4143L13.172 20.2427C12.7814 20.6332 12.1483 20.6332 11.7577 20.2427C11.3672 19.8522 11.3672 19.219 11.7577 18.8285L14.5862 16.0001L11.7577 13.1716C11.3672 12.7811 11.3672 12.148 11.7577 11.7574Z' fill='%233A52EE'/%3E%3C/svg%3E%0A";
}</code>```

    .hidden {
      visibility: hidden;
    }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><span onmouseover="hover(this);" onmouseout="unhover(this);" class="group cursor-pointer font-semibold hover:text-primary">
    Card Name
  </span>
<span id="large" class="hidden">
    <img id="large_image" class="" height="50" url="https://picsum.photos/200">
    <img id="large_image2" class="" height="50" url="./fakeImage.jpg">
  </span></code>```

In above demo first img has valid url and second one has fake url. So on hover second gets default svg image.

It's better to handle this in script tag instead of mixing JS with HTML markup.

```

Body:
I have created a table that contains a list of Magic the Gathering cards. When the user hovers over the card name it displays the cards image. These images are stored in a AWS S3 buckets.

There is a cost involved to loading those images from the S3 bucket so rather than loading 20-50 images when the page loads, what I have done is saved the Image URL in a custom attribute - url - for the image element and then when the user hovers over the card name it replaces src with url. The works as expected when the card image exists in the S3 bucket.

However this seems to have broken the onError attribute so now when there is not an image in the S3 bucket for a particular card the broken card symbol appear rather than the placeholder image.

function hover(e) { let url = e.nextSibling.firstChild.getAttribute('url'); e.nextSibling.firstChild.setAttribute('src', url); e.nextSibling.classList.remove("hidden"); }
function unhover(e) { e.nextSibling.classList.add("hidden");

  Card Name

How do I get the placeholder image to work when there is not image found in the S3 bucket?

Body:
There is a syntax error. You don't have to escape single quotes inside double quotes. Following will work:

<img id="large-image" src="./faultyImg.png" height="500" onError="this.onerror=null;this.src='./images/default.svg'">

Demo:

function hover(e) {
  if (!large_image.getAttribute('src')) {
    let url = large_image.getAttribute('url');
    large_image.setAttribute('src', url);
  }

  if (!large_image2.getAttribute('src')) {
    url = large_image2.getAttribute('url');
    large_image2.setAttribute('src', url);
  }

  large.classList.remove("hidden");
}

function unhover(e) {
  large.classList.add("hidden");
}

large_image.addEventListener('error', errorHandler);
large_image2.addEventListener('error', errorHandler);

function errorHandler(e) {
  e.target.removeEventListener('error', errorHandler);
  e.target.src = "data:image/svg+xml,%3Csvg width='32px' height='32px' viewBox='0 0 32 32' fill='none' xmlns='http://www.w3.org/2000/svg'%3E%3Cpath fill-rule='evenodd' clip-rule='evenodd' d='M11.7577 11.7574C12.1483 11.3669 12.7814 11.3669 13.172 11.7574L16.0004 14.5859L18.8288 11.7574C19.2193 11.3669 19.8525 11.3669 20.243 11.7574C20.6336 12.148 20.6336 12.7811 20.243 13.1716L17.4146 16.0001L20.243 18.8285C20.6335 19.219 20.6335 19.8522 20.243 20.2427C19.8525 20.6332 19.2193 20.6332 18.8288 20.2427L16.0004 17.4143L13.172 20.2427C12.7814 20.6332 12.1483 20.6332 11.7577 20.2427C11.3672 19.8522 11.3672 19.219 11.7577 18.8285L14.5862 16.0001L11.7577 13.1716C11.3672 12.7811 11.3672 12.148 11.7577 11.7574Z' fill='%233A52EE'/%3E%3C/svg%3E%0A";
}

    .hidden {
      visibility: hidden;
    }

<span onmouseover="hover(this);" onmouseout="unhover(this);" class="group cursor-pointer font-semibold hover:text-primary">
    <a href="">Card Name</a>
  </span>
<span id="large" class="hidden">
    <img id="large_image" class="" height="50" url="https://picsum.photos/200">
    <img id="large_image2" class="" height="50" url="./fakeImage.jpg">
  </span>

In above demo first img has valid url and second one has fake url. So on hover second gets default svg image.

It's better to handle this in script tag instead of mixing JS with HTML markup.

<img id="large_image" class="" src="./faultyImg.png" height="500">

<script>
    large_image.addEventListener('error',(e)=>{
      e.target.onerror = null;
      e.target.src = "data:image/svg+xml,%3Csvg width='32px' height='32px' viewBox='0 0 32 32' fill='none' xmlns='http://www.w3.org/2000/svg'%3E%3Cpath fill-rule='evenodd' clip-rule='evenodd' d='M11.7577 11.7574C12.1483 11.3669 12.7814 11.3669 13.172 11.7574L16.0004 14.5859L18.8288 11.7574C19.2193 11.3669 19.8525 11.3669 20.243 11.7574C20.6336 12.148 20.6336 12.7811 20.243 13.1716L17.4146 16.0001L20.243 18.8285C20.6335 19.219 20.6335 19.8522 20.243 20.2427C19.8525 20.6332 19.2193 20.6332 18.8288 20.2427L16.0004 17.4143L13.172 20.2427C12.7814 20.6332 12.1483 20.6332 11.7577 20.2427C11.3672 19.8522 11.3672 19.219 11.7577 18.8285L14.5862 16.0001L11.7577 13.1716C11.3672 12.7811 11.3672 12.148 11.7577 11.7574Z' fill='%233A52EE'/%3E%3C/svg%3E%0A";
    });
</script>


Title: Copy value to other NA cells based upon ID

Body:
I am trying to copy values from the diff column that has the value to the corresponding empty cells for the matching client_id. I am sure this is done easily in data.table, but I'm just unsure how.

So here is my data:

client_id <- c(1,1,1,2,2,3,3,3,3,4,4)
date <- c("1/1/2021","1/2/2021","1/3/2021","5/1/2021","10/1/2021","10/1/2021","11/1/2021","1/2/2021","10/9/2021","15/9/2021","16/10/2021")
date <- as.Date(date, '%d/%m/%Y')
score <- c(15,10,19,20,10,25,20,15,10,30,5)
diff <- c(NA, NA, -4, NA, 10, NA, NA, NA, 15, NA, 25)
df <- data.frame(client_id, date, score, diff)
df <-setDT(df)

And I'm wanting to end up with this:

client_id <- c(1,1,1,2,2,3,3,3,3,4,4)
date <- c("1/1/2021","1/2/2021","1/3/2021","5/1/2021","10/1/2021","10/1/2021","11/1/2021","1/2/2021","10/9/2021","15/9/2021","16/10/2021")
date <- as.Date(date, '%d/%m/%Y')
score <- c(15,10,19,20,10,25,20,15,10,30,5)
diff <- c(-4, -4, -4, 10, 10, 15, 15, 15, 15, 25, 25)
df <- data.frame(client_id, date, score, diff)
df <-setDT(df)

Thanks for any help!

Body:
Many ways to do this, depending on your data. This is a "next observation carried backward" form of nafill:

df[, diff := nafill(diff, type = "nocb"), by = .(client_id)][]
#     client_id       date score  diff
#         <num>     <Date> <num> <num>
#  1:         1 2021-01-01    15    -4
#  2:         1 2021-02-01    10    -4
#  3:         1 2021-03-01    19    -4
#  4:         2 2021-01-05    20    10
#  5:         2 2021-01-10    10    10
#  6:         3 2021-01-10    25    15
#  7:         3 2021-01-11    20    15
#  8:         3 2021-02-01    15    15
#  9:         3 2021-09-10    10    15
# 10:         4 2021-09-15    30    25
# 11:         4 2021-10-16     5    25


问:
Show/Hide Html sections on button click
I have 3 sections of code in the same page, in those 3 sections I have submit buttons.
Initially 1st section should be visible, 2nd and 3rd sections are hidden. On button click from 1st section, 2nd section should become visible and hide 1st and 3rd sections. On button click from 2nd section, 1st and 2nd sections should be hidden and 3rd section should be visible.
Can someone please help?</p>

答:
Suppose you've followed three-section within your body tag.

```<code><body>
    <section class="allSection firstTimeLoad">
        <form action="">
          First name 1: <input type="text" name="FirstName" value="Mickey"><br>
          Last name 1: <input type="text" name="LastName" value="Mouse"><br>
        </form>
        <button>Submit Button 1</button>
    </section>
    <section class="allSection">
        <form action="">
          First name 2: <input type="text" name="FirstName" value="Mickey"><br>
          Last name 2: <input type="text" name="LastName" value="Mouse"><br>
        </form>
        <button>Submit Button 2</button>
    </section>

    <section class="allSection">
        <form action="">
          First name 3: <input type="text" name="FirstName" value="Mickey"><br>
          Last name 3: <input type="text" name="LastName" value="Mouse"><br>
        </form>
        <button>Submit Button 3</button>
    </section>

</body>
</code>```

To hide & show the sections according to your explanation, the following should be your JS code.

```<code><script>
$(document).ready(function(){
  onPageLoad();

  $("button").click(function(){
    $(".allSection").hide();
    var parent=$('section');
    var element = $(this).parent().is(':last-child');
    if($(this).parent().is(':last-child'))
        $('.firstTimeLoad').show();
    else
       $(this).parent().next().show();

  });

});

function onPageLoad(){
    $(".allSection").hide();
    $(".firstTimeLoad").show();
  }
</script>
</code>```

Title: Show/Hide Html sections on button click

Body:
Suppose you've followed three-section within your body tag.

<body>
    <section class="allSection firstTimeLoad">
        <form action="">
          First name 1: <input type="text" name="FirstName" value="Mickey"><br>
          Last name 1: <input type="text" name="LastName" value="Mouse"><br>
        </form>
        <button>Submit Button 1</button>
    </section>
    <section class="allSection">
        <form action="">
          First name 2: <input type="text" name="FirstName" value="Mickey"><br>
          Last name 2: <input type="text" name="LastName" value="Mouse"><br>
        </form>
        <button>Submit Button 2</button>
    </section>

    <section class="allSection">
        <form action="">
          First name 3: <input type="text" name="FirstName" value="Mickey"><br>
          Last name 3: <input type="text" name="LastName" value="Mouse"><br>
        </form>
        <button>Submit Button 3</button>
    </section>

</body>

To hide & show the sections according to your explanation, the following should be your JS code.

<script>
$(document).ready(function(){
  onPageLoad();

  $("button").click(function(){
    $(".allSection").hide();
    var parent=$('section');
    var element = $(this).parent().is(':last-child');
    if($(this).parent().is(':last-child'))
        $('.firstTimeLoad').show();
    else
       $(this).parent().next().show();

  });

});

function onPageLoad(){
    $(".allSection").hide();
    $(".firstTimeLoad").show();
  }
</script>


问:
Flutter: retrieve dynamic data inside a parent screen
I made a button generator that can create a specified number of buttons and assign them titles/ determine if they are selected. I am trying to figure out how to pass the data back to the screen/ widget this widget is called on to run if/else statements based on what buttonNames[I] is returned and I am 100% stuck. I have been able to print the statement of selected but unable to pass that back to my initial widgets. Any thoughts?</p>
```<code>import 'package:flutter/material.dart';

class MakeButtons extends StatefulWidget {
  MakeButtons(this.buttonNames, this.number, {this.update});

  final List buttonNames;
  final int number;
  String update;

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

class _MakeButtonsState extends State<MakeButtons> {
  String selected;
  ValueChanged<String> onChanged;

  // void buttonPressed() {
  //   print(selected);
  // }

  Widget buildButton(
    List buttonNames,
    int num,
    String upd,
  ) {
    final buttonName = buttonNames;
    final buttonNamesMap = buttonName.asMap();

    return Row(
      children: [
        for (int i = 0; i < num; i++)
          GestureDetector(
            onTap: () async {
              setState(() {
                selected = buttonNamesMap[i];
              });
              // buttonPressed();
              return () => onChanged(buttonNamesMap[i]);
            },
            child: Container(
              padding: EdgeInsets.fromLTRB(12, 12, 12, 12),
              decoration: BoxDecoration(
                  shape: BoxShape.rectangle,
                  border: Border.all(width: 1, color: Colors.white),
                  color: selected == buttonNamesMap[i]
                      ? Colors.green
                      : Colors.yellow),
              child: Text(buttonNamesMap[i]),
            ),
          ),
      ],
    );
  }

  Widget build(BuildContext context) {
    return buildButton(
      widget.buttonNames,
      widget.number,
      widget.update,
    );
  }
}
</code>```

答:
Declare the onChanged function in contructor.

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

class MakeButtons extends StatefulWidget {
  MakeButtons(
    this.buttonNames,
    this.number, {
    this.update,
    this.onChanged,
  });

  final List buttonNames;
  final int number;
  String update;
  final ValueChanged<String> onChanged;

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

class _MakeButtonsState extends State<MakeButtons> {
  String selected;

  Widget buildButton(
    List buttonNames,
    int num,
    String upd,
  ) {
    final buttonName = buttonNames;
    final buttonNamesMap = buttonName.asMap();

    return Row(
      children: [
        for (int i = 0; i < num; i++)
          GestureDetector(
            onTap: () async {
              setState(() {
                selected = buttonNamesMap[i];
              });
              widget.onChanged(buttonNamesMap[i]);
            },
            child: Container(
              padding: EdgeInsets.fromLTRB(12, 12, 12, 12),
              decoration: BoxDecoration(
                  shape: BoxShape.rectangle,
                  border: Border.all(width: 1, color: Colors.white),
                  color: selected == buttonNamesMap[i]
                      ? Colors.green
                      : Colors.yellow),
              child: Text(buttonNamesMap[i]),
            ),
          ),
      ],
    );
  }

  Widget build(BuildContext context) {
    return buildButton(widget.buttonNames, widget.number, widget.update);
  }
}
</code>```

Body:
I made a button generator that can create a specified number of buttons and assign them titles/ determine if they are selected. I am trying to figure out how to pass the data back to the screen/ widget this widget is called on to run if/else statements based on what buttonNames[I] is returned and I am 100% stuck. I have been able to print the statement of selected but unable to pass that back to my initial widgets. Any thoughts?

import 'package:flutter/material.dart';

class MakeButtons extends StatefulWidget {
  MakeButtons(this.buttonNames, this.number, {this.update});

  final List buttonNames;
  final int number;
  String update;

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

class _MakeButtonsState extends State<MakeButtons> {
  String selected;
  ValueChanged<String> onChanged;

  // void buttonPressed() {
  //   print(selected);
  // }

  Widget buildButton(
    List buttonNames,
    int num,
    String upd,
  ) {
    final buttonName = buttonNames;
    final buttonNamesMap = buttonName.asMap();

    return Row(
      children: [
        for (int i = 0; i < num; i++)
          GestureDetector(
            onTap: () async {
              setState(() {
                selected = buttonNamesMap[i];
              });
              // buttonPressed();
              return () => onChanged(buttonNamesMap[i]);
            },
            child: Container(
              padding: EdgeInsets.fromLTRB(12, 12, 12, 12),
              decoration: BoxDecoration(
                  shape: BoxShape.rectangle,
                  border: Border.all(width: 1, color: Colors.white),
                  color: selected == buttonNamesMap[i]
                      ? Colors.green
                      : Colors.yellow),
              child: Text(buttonNamesMap[i]),
            ),
          ),
      ],
    );
  }

  Widget build(BuildContext context) {
    return buildButton(
      widget.buttonNames,
      widget.number,
      widget.update,
    );
  }
}

Body:
Declare the onChanged function in contructor.

import 'package:flutter/material.dart';

class MakeButtons extends StatefulWidget {
  MakeButtons(
    this.buttonNames,
    this.number, {
    this.update,
    this.onChanged,
  });

  final List buttonNames;
  final int number;
  String update;
  final ValueChanged<String> onChanged;

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

class _MakeButtonsState extends State<MakeButtons> {
  String selected;

  Widget buildButton(
    List buttonNames,
    int num,
    String upd,
  ) {
    final buttonName = buttonNames;
    final buttonNamesMap = buttonName.asMap();

    return Row(
      children: [
        for (int i = 0; i < num; i++)
          GestureDetector(
            onTap: () async {
              setState(() {
                selected = buttonNamesMap[i];
              });
              widget.onChanged(buttonNamesMap[i]);
            },
            child: Container(
              padding: EdgeInsets.fromLTRB(12, 12, 12, 12),
              decoration: BoxDecoration(
                  shape: BoxShape.rectangle,
                  border: Border.all(width: 1, color: Colors.white),
                  color: selected == buttonNamesMap[i]
                      ? Colors.green
                      : Colors.yellow),
              child: Text(buttonNamesMap[i]),
            ),
          ),
      ],
    );
  }

  Widget build(BuildContext context) {
    return buildButton(widget.buttonNames, widget.number, widget.update);
  }
}


问:
How do I revert a merge commit that has already been pushed to remote?
git revert <commit_hash> alone won't work. Apparently, -m must be specified.

答:
Ben has told you how to revert a merge commit, but it's very important you realize that in doing so

"...declares that you will never want the tree changes brought in by the merge. As a result, later merges will only bring in tree changes introduced by commits that are not ancestors of the previously reverted merge. This may or may not be what you want." (git-merge man page).

An article/mailing list message linked from the man page details the mechanisms and considerations that are involved. Just make sure you understand that if you revert the merge commit, you can't just merge the branch again later and expect the same changes to come back.


问:
props does not exist on type PropType
I have a prop ("author") which is passed from a parent component. I have typed the propType("AuthorProps") but it say Property 'author' does not exist on type 'AuthorProps' even though the structure look same.

AuthorProps:

```<code>export type AuthorProps = {
  _id: string;
  name: string;
  slug: string;
  authorId:string;
  img: string;
  createdAt?: string;
  updatedAt?: string;
  __v?: number;
}
</code>```

author props logged:

```<code>{
    _id: "61ffff139d0ad2a68738843a",
    name: "Chetan Bagat",
    slug: "chetan-bagat",
    authorId: "0",
    img: "https://img.etimg.com/thumb/msid-66099431,width-650,imgsize-149367,,resizemode-4,quality-100/chetan-bhagats-advice-for-students-its-all-about-knowing-how-to-market-yourself.jpg",
    createdAt: "2022-02-06T17:02:11.490Z",
    updatedAt: "2022-02-06T17:02:11.490Z",
    __v: 0
}
</code>```

Component:

```<code>function AuthorContainer({ author }: AuthorProps) { // }
</code>```

答:
In your component, you use object destructuring and try to get {author} from AuthorProps. The definition of AuthorProps does not contain this property.

Probably, you want to change your code to something like this:

```<code>export type AuthorProps = {
  author: {
    _id: string;
    name: string;
    slug: string;
    authorId:string;
    img: string;
    createdAt?: string;
    updatedAt?: string;
    __v?: number;
  }
}
</code>```

Title: props does not exist on type PropType

Body:
I have a prop ("author") which is passed from a parent component. I have typed the propType("AuthorProps") but it say Property 'author' does not exist on type 'AuthorProps' even though the structure look same.

AuthorProps:

export type AuthorProps = {
  _id: string;
  name: string;
  slug: string;
  authorId:string;
  img: string;
  createdAt?: string;
  updatedAt?: string;
  __v?: number;
}

author props logged:

{
    _id: "61ffff139d0ad2a68738843a",
    name: "Chetan Bagat",
    slug: "chetan-bagat",
    authorId: "0",
    img: "https://img.etimg.com/thumb/msid-66099431,width-650,imgsize-149367,,resizemode-4,quality-100/chetan-bhagats-advice-for-students-its-all-about-knowing-how-to-market-yourself.jpg",
    createdAt: "2022-02-06T17:02:11.490Z",
    updatedAt: "2022-02-06T17:02:11.490Z",
    __v: 0
}

Component:

function AuthorContainer({ author }: AuthorProps) { // }

Body:
In your component, you use object destructuring and try to get {author} from AuthorProps. The definition of AuthorProps does not contain this property.

Probably, you want to change your code to something like this:

export type AuthorProps = {
  author: {
    _id: string;
    name: string;
    slug: string;
    authorId:string;
    img: string;
    createdAt?: string;
    updatedAt?: string;
    __v?: number;
  }
}


问:
disable a button after being used
Recently i decided to rewrite my discord bot and add buttons also.
the main problem i encountered about this so far, i can't a disable a button just after being pressed people told be about button.disabled=True and in deed, it will disabling the button, but it's just sending it disabled, so it can't never be pressed. What i want is to be able to click it and do it's thing and then disable it.

As a reference i'll put some of the code

I use disnake, a discord.py fork, it does have the same syntaxes as dpy but we have buttons and slash commands, dropdown menus, etc

```<code>class BlurpleButton(Button):
    def __init__(self, label, emoji=None):
        super().__init__(label=label, style=discord.ButtonStyle.blurple, emoji=emoji)
</code>```

this is to use easier the buttons, i created a template and i can use it on any command

```<code>class CustomView(View):
    def __init__(self, member: disnake.Member):
        self.member = member
        super().__init__(timeout=180)

    async def interaction_check(self, inter: disnake.MessageInteraction) -> bool:
        if inter.author != self.member:
            await inter.response.send_message(content="You don't have permission to press this button.", ephemeral=True)
            return False
        return True
</code>```

and this is for buttons being able to be pressed just by a mentioned member for example if i do /test @member (i migrated to slash commands due to discord new privileged intent)  just the member will be able to press it and no one else.

So far so good all working fine, now after we "assemble" this in a command

```<code>@commands.slash_command(description='test')
    async def test(self, inter):

         (do stuff in there)
         . . .
        button1 = BlurpleButton("Button name")
        view=CustomView(member)
        view.add_item(button1)

        async def button_callback(inter):
            await inter.send(embed=embedname2)

        button1.callback = button_callback
        await inter.send(embed=embed1, view=view)

</code>```

Now again, this piece of code it's doing what it's intended to do, sends an embed (let's just say where i put the . . . are few embeds) and attached to that embed we have button1 when it's clicked it sends embedname2  and there is where things are not working anymore, i keep trying in any ways after the embedname2 it's being sent, the button to disable itself by being clicked one time if i add button1.disabled=True in the callback, the button it will just be sent disabled without any possibility of being clicked. The main reason i put the callback inside the command is to be able to use embeds when the button triggers, if i put it in the subclassed button or view i can't do that anymore.

So this is my whole problem, if you know a better resolving to thing that includes the embed using and just members can press the button, please tell me, i have over a week trying to solve this and i can't get it right

答:
Explanation

You can accomplish this by setting button.disabled to True in your button's callback. Then, you also would need to edit your original message to reflect this change.

Code

    @commands.slash_command(description='test')
    async def test(self, slash_inter: disnake.ApplicationCommandInteraction, member: disnake.Member):

        view = CustomView(member)
        button1 = BlurpleButton("TEST")
        view.add_item(button1)

        async def button_callback(button_inter: disnake.MessageInteraction):
            button1.disabled = True
            await button_inter.send(embed=embedname2)
            await slash_inter.edit_original_message(view=view)

        button1.callback = button_callback

        await slash_inter.send(embed=embed1, view=view)
```

Note: For /test @member to work, you need to add a disnake.Member parameter to your slash command.

Reference

disnake.MessageInteraction

disnake.ui.Button.callback

disnake slash commands

Title: disable a button after being used

Body:
Recently i decided to rewrite my discord bot and add buttons also.
the main problem i encountered about this so far, i can't a disable a button just after being pressed people told be about button.disabled=True and in deed, it will disabling the button, but it's just sending it disabled, so it can't never be pressed. What i want is to be able to click it and do it's thing and then disable it.

As a reference i'll put some of the code

I use disnake, a discord.py fork, it does have the same syntaxes as dpy but we have buttons and slash commands, dropdown menus, etc

class BlurpleButton(Button):
    def __init__(self, label, emoji=None):
        super().__init__(label=label, style=discord.ButtonStyle.blurple, emoji=emoji)

this is to use easier the buttons, i created a template and i can use it on any command

class CustomView(View):
    def __init__(self, member: disnake.Member):
        self.member = member
        super().__init__(timeout=180)

    async def interaction_check(self, inter: disnake.MessageInteraction) -> bool:
        if inter.author != self.member:
            await inter.response.send_message(content="You don't have permission to press this button.", ephemeral=True)
            return False
        return True

and this is for buttons being able to be pressed just by a mentioned member for example if i do /test @member (i migrated to slash commands due to discord new privileged intent)  just the member will be able to press it and no one else.

So far so good all working fine, now after we "assemble" this in a command

@commands.slash_command(description='test')
    async def test(self, inter):

         (do stuff in there)
         . . .
        button1 = BlurpleButton("Button name")
        view=CustomView(member)
        view.add_item(button1)

        async def button_callback(inter):
            await inter.send(embed=embedname2)

        button1.callback = button_callback
        await inter.send(embed=embed1, view=view)

Now again, this piece of code it's doing what it's intended to do, sends an embed (let's just say where i put the . . . are few embeds) and attached to that embed we have button1 when it's clicked it sends embedname2  and there is where things are not working anymore, i keep trying in any ways after the embedname2 it's being sent, the button to disable itself by being clicked one time if i add button1.disabled=True in the callback, the button it will just be sent disabled without any possibility of being clicked. The main reason i put the callback inside the command is to be able to use embeds when the button triggers, if i put it in the subclassed button or view i can't do that anymore.

So this is my whole problem, if you know a better resolving to thing that includes the embed using and just members can press the button, please tell me, i have over a week trying to solve this and i can't get it right

Body:
Explanation

You can accomplish this by setting button.disabled to True in your button's callback. Then, you also would need to edit your original message to reflect this change.

Code

    @commands.slash_command(description='test')
    async def test(self, slash_inter: disnake.ApplicationCommandInteraction, member: disnake.Member):

        view = CustomView(member)
        button1 = BlurpleButton("TEST")
        view.add_item(button1)

        async def button_callback(button_inter: disnake.MessageInteraction):
            button1.disabled = True
            await button_inter.send(embed=embedname2)
            await slash_inter.edit_original_message(view=view)

        button1.callback = button_callback

        await slash_inter.send(embed=embed1, view=view)

Note: For /test @member to work, you need to add a disnake.Member parameter to your slash command.

Reference

disnake.MessageInteraction

disnake.ui.Button.callback

disnake slash commands


问:
How can I nicely handle an ENOENT?
I've recently started making an Express project.
I made it so if someone goes to localhost:3000/games/tictactoe, they receive /games/tictactoe/index.html.
(Edit: I want the routes to be dynamic; if a user goes to /games/foo, it should send them the index.html of that directory.)
My directory structure is:

```<code>multiplayergames
├── games
│   └── tictactoe
│       └── index.html
└── src
    └── server.js
</code>```

server.js (so far)

```<code>const express = require("express")
const app = express()
app.get("/games/:game", (req, res) => {
    res.sendFile(`${req.params.game}/index.html`, {root: "games/"})
})

app.listen(3000, () => {
    console.log(`App is up! (${new Date().toLocaleTimeString()})`)
})
</code>```

The only problem is, if someone goes to, say, /games/foo, it says Error: ENOENT: no such file or directory, stat 'multiplayergames/games/foo/index.html'.
Is there any way to send the user a "nicer" response (an HTML page) when they go to a nonexistent game?

[also, if there's something wrong with how I dynamically serve the files, let me know; I threw it together pretty quickly]

答:
you can use node fs to check if file exist, and return the game, or a custom html file. https://nodejs.org/api/fs.html#fsexistssyncpath</p>
```<code>const fs = require('fs')
app.get("/games/:game", (req, res) => {
     if (fs.existsSync('/path/to/game/index.html')) {
       res.sendFile(`${req.params.game}/index.html`, {root: "games/"})
     } else {
       res.sendFile('custom 404 html file');
     }
})
</code>```

Title: How can I nicely handle an ENOENT?

Body:
I've recently started making an Express project.
I made it so if someone goes to localhost:3000/games/tictactoe, they receive /games/tictactoe/index.html.
(Edit: I want the routes to be dynamic; if a user goes to /games/foo, it should send them the index.html of that directory.)
My directory structure is:

multiplayergames
├── games
│   └── tictactoe
│       └── index.html
└── src
    └── server.js

server.js (so far)

const express = require("express")
const app = express()
app.get("/games/:game", (req, res) => {
    res.sendFile(`${req.params.game}/index.html`, {root: "games/"})
})

app.listen(3000, () => {
    console.log(`App is up! (${new Date().toLocaleTimeString()})`)
})

The only problem is, if someone goes to, say, /games/foo, it says Error: ENOENT: no such file or directory, stat 'multiplayergames/games/foo/index.html'.
Is there any way to send the user a "nicer" response (an HTML page) when they go to a nonexistent game?

[also, if there's something wrong with how I dynamically serve the files, let me know; I threw it together pretty quickly]

Body:
you can use node fs to check if file exist, and return the game, or a custom html file. https://nodejs.org/api/fs.html#fsexistssyncpath

const fs = require('fs')
app.get("/games/:game", (req, res) => {
     if (fs.existsSync('/path/to/game/index.html')) {
       res.sendFile(`${req.params.game}/index.html`, {root: "games/"})
     } else {
       res.sendFile('custom 404 html file');
     }
})


问:
Find each variable before comma
I am working with a QMK layout in emacs and would like to query-replace-regexp each variable before and including the comma with XXXXXXX,.

I have:

```<code>MO(RST), KC_1,    KC_2,    KC_3,    KC_4,    KC_5,                      KC_6,    KC_7,    KC_8,    KC_9,    KC_0,    RESET, \
</code>```

and would like to end up with:

```<code>XXXXXXX, XXXXXXX,    XXXXXXX,    XXXXXXX,    XXXXXXX,    XXXXXXX,                      XXXXXXX,    XXXXXXX,    XXXXXXX,    XXXXXXX,    XXXXXXX,    XXXXXXX, \
</code>```

I have tried entering .+, but that highlights everything up to the last comma.

I want to stop at each comma, ignoring white space. Meaning first MO(RST),, then KC_1,, etc.. Including the comma in the match is not a necessity.

As a bonus it would be nice to replace the whitespace within a 7-char
width to end up with the following spacing:

```<code>XXXXXXX, XXXXXXX, XXXXXXX, XXXXXXX, XXXXXXX, XXXXXXX,                   XXXXXXX, XXXXXXX, XXXXXXX, XXXXXXX, XXXXXXX, XXXXXXX, \
</code>```

答:
You may try the following find and replace, in regex mode:

Find:    \S+,
Replace: XXXXXXX,
```

Demo

Title: Find each variable before comma

Body:
I am working with a QMK layout in emacs and would like to query-replace-regexp each variable before and including the comma with XXXXXXX,.

I have:

MO(RST), KC_1,    KC_2,    KC_3,    KC_4,    KC_5,                      KC_6,    KC_7,    KC_8,    KC_9,    KC_0,    RESET, \

and would like to end up with:

XXXXXXX, XXXXXXX,    XXXXXXX,    XXXXXXX,    XXXXXXX,    XXXXXXX,                      XXXXXXX,    XXXXXXX,    XXXXXXX,    XXXXXXX,    XXXXXXX,    XXXXXXX, \

I have tried entering .+, but that highlights everything up to the last comma.

I want to stop at each comma, ignoring white space. Meaning first MO(RST),, then KC_1,, etc.. Including the comma in the match is not a necessity.

As a bonus it would be nice to replace the whitespace within a 7-char
width to end up with the following spacing:

XXXXXXX, XXXXXXX, XXXXXXX, XXXXXXX, XXXXXXX, XXXXXXX,                   XXXXXXX, XXXXXXX, XXXXXXX, XXXXXXX, XXXXXXX, XXXXXXX, \

Body:
You may try the following find and replace, in regex mode:

Find:    \S+,
Replace: XXXXXXX,

Demo


问:
Hanging/stuck reify:prettier: timing reifyNode:node_modules/@nrwl/workspace Completed in 12729ms
Details:

```<code>? Workspace name (e.g., org name)     swag
? What to create in the new workspace angular-nest      [a workspace with a full stack application (Angular + Nest)]
? Application name                    swag
? Default stylesheet format           SASS(.scss)  [ http://sass-lang.com   ]
? Default linter                      ESLint [ Modern linting tool ]
? Use Nx Cloud? (It's free and doesn't require registration.) No

>  NX  Nx is creating your workspace.

  To make sure the command works reliably in all environments, and that the preset is applied correctly,
  Nx will run "npm install" several times. Please wait.

[.....................] \ reify:prettier: timing reifyNode:node_modules/@nrwl/workspace Completed in 12729ms
</code>```

Tools versions

npm 7.6.1

yarn 1.22.5

node v15.12.0

答: Still a problem when using npm 8 when installing opencv-build package now, downgrade to npm 6 by npm install -g npm@6 works.

Body:
Details:

? Workspace name (e.g., org name)     swag
? What to create in the new workspace angular-nest      [a workspace with a full stack application (Angular + Nest)]
? Application name                    swag
? Default stylesheet format           SASS(.scss)  [ http://sass-lang.com   ]
? Default linter                      ESLint [ Modern linting tool ]
? Use Nx Cloud? (It's free and doesn't require registration.) No

>  NX  Nx is creating your workspace.

  To make sure the command works reliably in all environments, and that the preset is applied correctly,
  Nx will run "npm install" several times. Please wait.

[.....................] \ reify:prettier: timing reifyNode:node_modules/@nrwl/workspace Completed in 12729ms

Tools versions

npm 7.6.1

yarn 1.22.5

node v15.12.0


问:
How to setup integration runtime for SAP ABAP in Azure DataFactory
How to create SAP ABAP connection setup in Azure Datafactory so that the Dataset can point to this Linked service</p>

答:
Create a linked service to an SAP table using UI

Step1: Create Azure data factory resource and click on Dataset  New dataset

Step2:  Now type sap and select SAP Table

Step3: Now create New Linked Service

After above step you can follow this official doc for Connector configuration details.


问:
Setting field2=field1 in MongoDB
I am unable to update my document when I run
db.xx.updateOne({_id: ObjectId(""}, {$set: {lq: uq}) I get the error uncaught exception: ReferenceError: uq is not defined

uq field exists and contains integers, not sure why it don't work. Please help.

答:
```<code>db.collection.update({
  "_id": ObjectId("5a934e000102030405000000")
},
[
  {
    "$set": {
      "field1": "$field2"
    }
  }
])
</code>```

mongoplayground

Title: Setting field2=field1 in MongoDB

Body:
db.collection.update({
  "_id": ObjectId("5a934e000102030405000000")
},
[
  {
    "$set": {
      "field1": "$field2"
    }
  }
])

mongoplayground


问:
Python regex to get citations in a paper
I was adapting this code for extracting citations from a text:

#!/usr/bin/env python3
# https://stackoverflow.com/a/16826935

import re
from sys import stdin

text = stdin.read()

author = "(?:[A-Z][A-Za-z'`-]+)"
etal = "(?:et al.?)"
additional = "(?:,? (?:(?:and |& )?" + author + "|" + etal + "))"
year_num = "(?:19|20)[0-9][0-9]"
page_num = "(?:, p.? [0-9]+)?"  # Always optional
year = "(?:, *"+year_num+page_num+"| *\("+year_num+page_num+"\))"
regex = "(" + author + additional+"*" + year + ")"

matches = re.findall(regex, text)
matches = list( dict.fromkeys(matches) )
matches.sort()

#print(matches)
print ("\n".join(matches))
```
<p>However, it recognizes some uppercased words as author names. For example, in the text:</p>
```Although James (2020) recognized blablabla, Smith et al. (2020) found mimimi.
Those inconsistent results are a sign of lalala (Green, 2010; Grimm, 1990).
Also James (2020) ...
```
<p>The output would be</p>
```Also James (2020)
Although James (2020)
Green, 2010
Grimm, 1990
Smith et al. (2020)
```

Is there a way to "blacklist" some words in the above code without removing the entire match? I wish it recognized James' work but removed "Also" and "Although" from the citation.

Thanks in advance.

答:
Here is my answer, the previous answer did not work for some citations.

```<code>regexr.com/6er6n
</code>```

This answer I got from other source, but it did not work for one other type of citation text. My version fixes that:

```<code>citationsRegex = r"\b(?!(?:Although|Also)\b)(?:[A-Z][A-Za-z'`-]+)(?:,? (?:(?:and |& )?(?:[A-Z][A-Za-z'`-]+)|(?:et al.?)))*(?:,? *(?:19|20)[0-9][0-9](?:, p\.? [0-9]+)?| *\((?:19|20)[0-9][0-9](?:, p\.? [0-9]+)?\))"
</code>```

Body:
I was adapting this code for extracting citations from a text:

#!/usr/bin/env python3
# https://stackoverflow.com/a/16826935

import re
from sys import stdin

text = stdin.read()

author = "(?:[A-Z][A-Za-z'`-]+)"
etal = "(?:et al.?)"
additional = "(?:,? (?:(?:and |& )?" + author + "|" + etal + "))"
year_num = "(?:19|20)[0-9][0-9]"
page_num = "(?:, p.? [0-9]+)?"  # Always optional
year = "(?:, *"+year_num+page_num+"| *\("+year_num+page_num+"\))"
regex = "(" + author + additional+"*" + year + ")"

matches = re.findall(regex, text)
matches = list( dict.fromkeys(matches) )
matches.sort()

#print(matches)
print ("\n".join(matches))

However, it recognizes some uppercased words as author names. For example, in the text:

Although James (2020) recognized blablabla, Smith et al. (2020) found mimimi.
Those inconsistent results are a sign of lalala (Green, 2010; Grimm, 1990).
Also James (2020) ...

The output would be

Also James (2020)
Although James (2020)
Green, 2010
Grimm, 1990
Smith et al. (2020)

Is there a way to "blacklist" some words in the above code without removing the entire match? I wish it recognized James' work but removed "Also" and "Although" from the citation.

Thanks in advance.

Body:
Here is my answer, the previous answer did not work for some citations.

regexr.com/6er6n

This answer I got from other source, but it did not work for one other type of citation text. My version fixes that:

citationsRegex = r"\b(?!(?:Although|Also)\b)(?:[A-Z][A-Za-z'`-]+)(?:,? (?:(?:and |& )?(?:[A-Z][A-Za-z'`-]+)|(?:et al.?)))*(?:,? *(?:19|20)[0-9][0-9](?:, p\.? [0-9]+)?| *\((?:19|20)[0-9][0-9](?:, p\.? [0-9]+)?\))"


问:
Converting code using wmi to code using ffmpy
I have the following code that prints out the names of USB cameras connected to my PC:

```<code>import wmi
c = wmi.WMI()
wql = "Select * From Win32_USBControllerDevice"
for item in c.query(wql):
    a = item.Dependent.PNPClass
    b = item.Dependent.Name.upper()
    if (a.upper() == 'MEDIA' or a.upper() == 'CAMERA') and 'AUDIO' not in b:
        print(item.Dependent.Name)
</code>```

The problem with this code is that it only works in Windows. I want to alter this code so that it works on all operating systems. I know that I have to use something other than wmi, since wmi only works in Windows. So, I was thinking about using an ffmpeg wrapper called ffmpy. So maybe I could convert the code to use ffmpy? I got the code above from the following SO post: Associate USB Video Capture Device Friendly Name with OpenCV Port Number in Python. Any help would be much appreciated! Thanks!

答: The answer to this question is no; there is no OS-independent way of getting the names of USB cameras connected to your PC. However, there is platform-specific code that can get the job done: https://stackoverflow.com/a/68402011/13386603</p>

Body:
I have the following code that prints out the names of USB cameras connected to my PC:

import wmi
c = wmi.WMI()
wql = "Select * From Win32_USBControllerDevice"
for item in c.query(wql):
    a = item.Dependent.PNPClass
    b = item.Dependent.Name.upper()
    if (a.upper() == 'MEDIA' or a.upper() == 'CAMERA') and 'AUDIO' not in b:
        print(item.Dependent.Name)

The problem with this code is that it only works in Windows. I want to alter this code so that it works on all operating systems. I know that I have to use something other than wmi, since wmi only works in Windows. So, I was thinking about using an ffmpeg wrapper called ffmpy. So maybe I could convert the code to use ffmpy? I got the code above from the following SO post: Associate USB Video Capture Device Friendly Name with OpenCV Port Number in Python. Any help would be much appreciated! Thanks!


问:
Understanding the Sub-expression overflow reasoning
I am trying to understand the reasoning behind this particular suggestion in Visual Studio 2022, as it doesn't seem to make sense to me.  Here's the simple code:

```<code>static constexpr uint32_t MAX_ELEMENTS = 100000;
const std::vector<int> A{ some random ints };

std::vector<bool> found(MAX_ELEMENTS);
for (int value : A)
{
    if (value > 0 && value <= MAX_ELEMENTS)
        found[value - 1] = true;             // Problem it complains about is the value - 1.
}
</code>```

It suggests that a "sub-expression may overflow before being added to a wider type". Now obviously the condition-if prevents this from ever happening, but what's the reasoning here?

Now if this was a Spectre thing, I could understand that the compiler would add a memory fence to stop any speculative execution of the statement after the if, but I don't think that's the answer here.

My only thinking is that it has to do with the subscript operator on the vector; that its index is of a type larger than int and is implicitly cast to size_t?

Just seems a little unintuitive that the below is an issue:

```<code>found[value - 1]
</code>```

and its perfectly fine to do this,

```<code>int a = value - 1;
found[a];
</code>```

when the end result is the same.  What am I missing here in terms of understanding?

答:
In this case, it is a false positive, as you suspected. This is a rule that sometimes gets used in stricter code bases. (This particular warning is an error in MISRA, for example.)

A lot of warnings are like this... the compiler writers are trying to detect a situation where the behavior of the program is unexpected or unintentional, but the warnings are not always correct. For example,

```<code>uint64_t x = 0xffffffffu << 16;
</code>```

On a system with 32-bit int, the standard is very clear what the value of this is supposed to be... it's supposed to be:

```<code>uint64_t x = 0xffff0000u;
</code>```

However, it does look like someone meant to write this instead:

```<code>uint64_t x = (uint64_t)0xffff0000 << 16;
</code>```

That's what the warning is trying to catch. That's the reasoning behind this rule. In your case, the compiler is doing a bad job of it.

You can see a more detailed justification for the warning in the compiler documentation: Warning C26451.

Spectre has nothing to do with it.

It's perfectly fine...

To do this:

```<code>int a = value - 1;
found[a];
</code>```

In this case the "intent" is more obvious, because the programmer has explicitly written out "int" as the type.

Solutions

This is a code style issue, so there are a few different solutions and you pick whatever one you feel comfortable with.

Leave the warning on (noisy, may distract you from real warnings)

Assign the expression to an int first (verbose)

Disable the warning across the code base (if you don't think it's helpful)

Disable the warning around this location with a #pragma warning (very verbose)

Body:
I am trying to understand the reasoning behind this particular suggestion in Visual Studio 2022, as it doesn't seem to make sense to me.  Here's the simple code:

static constexpr uint32_t MAX_ELEMENTS = 100000;
const std::vector<int> A{ some random ints };

std::vector<bool> found(MAX_ELEMENTS);
for (int value : A)
{
    if (value > 0 && value <= MAX_ELEMENTS)
        found[value - 1] = true;             // Problem it complains about is the value - 1.
}

It suggests that a "sub-expression may overflow before being added to a wider type". Now obviously the condition-if prevents this from ever happening, but what's the reasoning here?

Now if this was a Spectre thing, I could understand that the compiler would add a memory fence to stop any speculative execution of the statement after the if, but I don't think that's the answer here.

My only thinking is that it has to do with the subscript operator on the vector; that its index is of a type larger than int and is implicitly cast to size_t?

Just seems a little unintuitive that the below is an issue:

found[value - 1]

and its perfectly fine to do this,

int a = value - 1;
found[a];

when the end result is the same.  What am I missing here in terms of understanding?

Body:
In this case, it is a false positive, as you suspected. This is a rule that sometimes gets used in stricter code bases. (This particular warning is an error in MISRA, for example.)

A lot of warnings are like this... the compiler writers are trying to detect a situation where the behavior of the program is unexpected or unintentional, but the warnings are not always correct. For example,

uint64_t x = 0xffffffffu << 16;

On a system with 32-bit int, the standard is very clear what the value of this is supposed to be... it's supposed to be:

uint64_t x = 0xffff0000u;

However, it does look like someone meant to write this instead:

uint64_t x = (uint64_t)0xffff0000 << 16;

That's what the warning is trying to catch. That's the reasoning behind this rule. In your case, the compiler is doing a bad job of it.

You can see a more detailed justification for the warning in the compiler documentation: Warning C26451.

Spectre has nothing to do with it.

It's perfectly fine...

To do this:

int a = value - 1;
found[a];

In this case the "intent" is more obvious, because the programmer has explicitly written out "int" as the type.

Solutions

This is a code style issue, so there are a few different solutions and you pick whatever one you feel comfortable with.

Leave the warning on (noisy, may distract you from real warnings)

Assign the expression to an int first (verbose)

Disable the warning across the code base (if you don't think it's helpful)

Disable the warning around this location with a #pragma warning (very verbose)


问:
How to access a value in a table connected by a Foreign Key
Currently I have a table called Load that has a relationship to a table called Container through a Foreign Key called Container_ID (the FK is just an integer). The foreign key lives in the Load table. Each row in the Load table has a Container_ID.

The table Container has a column called Container_Name.

What I want to do is to grab all rows from the Load table, and be able to tell what the actual container name is. Not the Container_ID, but the Container_Name that's in the Container table.

I tried doing something like var = Load.objects.values_list('container_ID') but that only returns the actual foreign key integer, and I'm not sure how to take it that one step further to dive into the actual Container table to grab that Container_Name field.

Just for clarification, I am working with Python and MYSQL here.

答:
You can access the Container name through field lookup. You can see it
here in the docs. In your example, you can access it as var=Load.objects.values_list('container__Container_Name')
The generic syntax for this is var=ModelName.objects.value_list('foreign_key_field__field_in_related_table')


问:
delete rows based on value in a column
I have a df like this;

```<code>NEW_df <- data.frame(CAR = c("YES","NO","MAYBE","YES","NO"),
                     BIKE = c(2,0,4,NA,9),
                     PLANE = c(8,0,6,7,9),
                     BOAT = c(0,0,0,4,0),
                     SCOOTER = c(2,3,6,9,0))
</code>```

I want to delete only rows where column BOAT is '0', when column CAR is "YES" or "MAYBE"
so I have something like this;

```<code>NEW_df2 <- data.frame(CAR = c("NO","YES","NO"),
                     BIKE = c(0,NA,9),
                     PLANE = c(0,7,9),
                     BOAT = c(0,4,0),
                     SCOOTER = c(3,9,0))
</code>```

I have tried this:

```<code>NEW_df[NEW_df$BOAT %in% subset(NEW_df, CAR == "YES")$BOAT, ]

NEW_df[NEW_df$BOAT %in% subset(NEW_df, CAR == "MAYBE")$BOAT, ]
</code>```

I'm sure I am doing something wrong.

答:
For subset, you don't need to wrap it in brackets. You can just include both conditions like so:

```<code>subset(NEW_df, !(BOAT ==0 & CAR %in% c("YES", "MAYBE")))

  CAR BIKE PLANE BOAT SCOOTER
2  NO    0     0    0       3
4 YES   NA     7    4       9
5  NO    9     9    0       0
</code>```

data.table option:

```<code>library(data.table)

dt <- NEW_df
setDT(dt)[!(CAR %in% c("YES", "MAYBE") & BOAT == 0)]

   CAR BIKE PLANE BOAT SCOOTER
1:  NO    0     0    0       3
2:  NO    9     9    0       0
3: YES   NA     7    4       9
</code>```

Title: delete rows based on value in a column

Body:
I have a df like this;

NEW_df <- data.frame(CAR = c("YES","NO","MAYBE","YES","NO"),
                     BIKE = c(2,0,4,NA,9),
                     PLANE = c(8,0,6,7,9),
                     BOAT = c(0,0,0,4,0),
                     SCOOTER = c(2,3,6,9,0))

I want to delete only rows where column BOAT is '0', when column CAR is "YES" or "MAYBE"
so I have something like this;

NEW_df2 <- data.frame(CAR = c("NO","YES","NO"),
                     BIKE = c(0,NA,9),
                     PLANE = c(0,7,9),
                     BOAT = c(0,4,0),
                     SCOOTER = c(3,9,0))

I have tried this:

NEW_df[NEW_df$BOAT %in% subset(NEW_df, CAR == "YES")$BOAT, ]

NEW_df[NEW_df$BOAT %in% subset(NEW_df, CAR == "MAYBE")$BOAT, ]

I'm sure I am doing something wrong.

Body:
For subset, you don't need to wrap it in brackets. You can just include both conditions like so:

subset(NEW_df, !(BOAT ==0 & CAR %in% c("YES", "MAYBE")))

  CAR BIKE PLANE BOAT SCOOTER
2  NO    0     0    0       3
4 YES   NA     7    4       9
5  NO    9     9    0       0

data.table option:

library(data.table)

dt <- NEW_df
setDT(dt)[!(CAR %in% c("YES", "MAYBE") & BOAT == 0)]

   CAR BIKE PLANE BOAT SCOOTER
1:  NO    0     0    0       3
2:  NO    9     9    0       0
3: YES   NA     7    4       9


问:
MySQL Query error using UNION/UNION ALL and Group By
Generate the following two result sets:

1). Query an alphabetically ordered list of all names in OCCUPATIONS, immediately followed by the first letter of each profession as a parenthetical (i.e.: enclosed in parentheses). For example: AnActorName(A), ADoctorName(D), AProfessorName(P), and ASingerName(S).

2). Query the number of ocurrences of each occupation in OCCUPATIONS. Sort the occurrences in ascending order, and output them in the following format:

There are total [occupation_count] [occupation]s.

Table Name: Occupations

Total Columns: Two = 'Name' and 'Occupation', demo table is shown below:

Sample Output:

```<code>Ashely(P)
Christeen(P)
Jane(A)
Jenny(D)
Julia(A)
Ketty(P)
Maria(A)
Meera(S)
Priya(S)
Samantha(D)
There are total 2 doctors.
There are total 2 singers.
There are total 3 actors.
There are total 3 professors.
</code>```

My Approach:

```<code>(SELECT NAME, '(', SUBSTRING(OCCUPATION, 1, 1), ')'
    FROM OCCUPATIONS ORDER BY NAME)
UNION ALL
(SELECT COUNT(*) FROM OCCUPATIONS GROUP BY OCCUPATION ORDER BY ASEC);
</code>```

Error:

```<code>ERROR 1222 (21000) at line 1:
    The used SELECT statements have a different number of columns
</code>```

Thank You!

答:
You can use in this way:</p>
```<code> SELECT CONCAT(NAME,"(",SUBSTRING(Occupation, 1, 1),")") FROM OCCUPATIONS ORDER BY NAME
    SELECT CONCAT("There are a total of"," ",COUNT(Occupation),
    " ",LOWER(Occupation),"s",".") FROM OCCUPATIONS GROUP BY Occupation ORDER BY COUNT(Occupation),Occupation
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Generate the following two result sets:

1). Query an alphabetically ordered list of all names in OCCUPATIONS, immediately followed by the first letter of each profession as a parenthetical (i.e.: enclosed in parentheses). For example: AnActorName(A), ADoctorName(D), AProfessorName(P), and ASingerName(S).

2). Query the number of ocurrences of each occupation in OCCUPATIONS. Sort the occurrences in ascending order, and output them in the following format:

There are total [occupation_count] [occupation]s.

Table Name: Occupations

Total Columns: Two = 'Name' and 'Occupation', demo table is shown below:

Sample Output:

Ashely(P)
Christeen(P)
Jane(A)
Jenny(D)
Julia(A)
Ketty(P)
Maria(A)
Meera(S)
Priya(S)
Samantha(D)
There are total 2 doctors.
There are total 2 singers.
There are total 3 actors.
There are total 3 professors.

My Approach:

(SELECT NAME, '(', SUBSTRING(OCCUPATION, 1, 1), ')'
    FROM OCCUPATIONS ORDER BY NAME)
UNION ALL
(SELECT COUNT(*) FROM OCCUPATIONS GROUP BY OCCUPATION ORDER BY ASEC);

Error:

ERROR 1222 (21000) at line 1:
    The used SELECT statements have a different number of columns

Thank You!

Body:
You can use in this way:

 SELECT CONCAT(NAME,"(",SUBSTRING(Occupation, 1, 1),")") FROM OCCUPATIONS ORDER BY NAME
    SELECT CONCAT("There are a total of"," ",COUNT(Occupation),
    " ",LOWER(Occupation),"s",".") FROM OCCUPATIONS GROUP BY Occupation ORDER BY COUNT(Occupation),Occupation


问:
Textarea: Size of a window with no border
How do you make a textarea with no border and takes up all of the space it can?

Thanks everybody!

答:
Here it is:</p>

```<code><style type="text/css">
textarea.test
{
width: 100%;
height: 100%;
border-color: Transparent;
}
</style>
<textarea class="test"></textarea>
</code>```

Body:
Here it is:

<style type="text/css">
textarea.test
{
width: 100%;
height: 100%;
border-color: Transparent;
}
</style>
<textarea class="test"></textarea>


问:
How do I save a timestamp to a mysql database?
I have a table in mysql for people's posts. But I'd like to be able to get the time the post was made? How do I do it? Any help will be appreciated. The language I'm using is PHP and I'm using prepared statements.
Is it as simple as specifying a column in the database with the datatype TIMESTAMP? And how do I read a timestamp and convert it to a date?</p>

答:
```<code>  $timestamp = date("Y-m-d H:i:s");
</code>```

check your table setup to confirm that the field is set to NOT NULL with a default of CURRENT_TIMESTAMP and above code will return you current date and time which will be in string format. Which you can push in to table.

Body:
  $timestamp = date("Y-m-d H:i:s");

check your table setup to confirm that the field is set to NOT NULL with a default of CURRENT_TIMESTAMP and above code will return you current date and time which will be in string format. Which you can push in to table.


问:
need to edit pod to allow communication with other pod without changing the netpol
I'm preparing for CKAD and found a question somewhere, I'm not sure how to approach :

you rolled out a new pod (pod A) you requested to edit pod (A) to allow ingress requests only from pod B and C. Similarly, A is allowed to send requests(Egress) only to B and C.

NOTE:

There are a few network policies already existing in the k8s cluster.
However, you're NOT allowed to create/update/delete a new/existing netpol.

Note - I know that we can create Network Policy and use pod A as Pod Selector. However, this question demands a different approach. Cant create new NetPol or update existing ones.
I'm thinking that we should change the labels of pod (A) so it will match the one or more policies that allow pod (A) to exchange traffic with only pod B & C, but not sure if it's the correct approach.

答:
As per your question - network policies are already there, so you only need to implement those.
How can you implement it in pod?
Ans - just check the selector in network policies, for example it is a podSelector with app=abc then add these labels in the pod where you want your network policies to get implemented.

Hope I have answered your question, if any further details needed then let me know.


问:
Can't connect to GPU when building PyTorch projects
Before this, I was able to connect to the GPU through CUDA runtime version 10.2. But then I ran into an error when setting up one of my projects.

```<code>Using torch 1.10.1+cu102 (NVIDIA GeForce RTX 3080)
UserWarning:
NVIDIA GeForce RTX 3080 with CUDA capability sm_86 is not compatible with the current PyTorch installation.
The current PyTorch install supports CUDA capabilities sm_37 sm_50 sm_60 sm_70.
</code>```

After some readings, it seems that sm_86 is only available for CUDA version 11.0 and above. That's the reason why I upgraded to the latest CUDA version and can't connect to the GPU after this.
I have tried many ways, reinstalling cuda toolkit, PyTorch, torchvision and stuff but nothing works.

CUDA Toolkit I've used:

```<code>$ wget https://developer.download.nvidia.com/compute/cuda/11.6.0/local_installers/cuda_11.6.0_510.39.01_linux.run
$ sudo sh cuda_11.6.0_510.39.01_linux.run
</code>```

PyTorch I've installed (tried both conda and pip):

```<code>$ conda install pytorch torchvision torchaudio cudatoolkit=11.3 -c pytorch

$ pip3 install torch==1.10.1+cu113 torchvision==0.11.2+cu113 torchaudio==0.10.1+cu113 -f https://download.pytorch.org/whl/cu113/torch_stable.html
</code>```

These are some basic info:

```<code>(base) ubuntu@DESKTOP:~$ python
Python 3.9.5 (default, Jun  4 2021, 12:28:51)
[GCC 7.5.0] :: Anaconda, Inc. on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import torch
>>> torch.__version__
'1.10.1+cu113'
>>> x = torch.rand(6,6)
>>> print(x)
tensor([[0.0228, 0.3868, 0.9742, 0.2234, 0.5682, 0.7747],
        [0.2643, 0.3911, 0.3464, 0.5072, 0.4041, 0.4268],
        [0.2247, 0.0936, 0.4250, 0.1128, 0.0261, 0.5199],
        [0.0224, 0.7463, 0.1391, 0.8092, 0.3742, 0.2054],
        [0.3951, 0.4205, 0.6270, 0.4561, 0.4784, 0.5958],
        [0.8430, 0.5078, 0.7759, 0.5266, 0.4925, 0.7557]])
>>> torch.cuda.get_arch_list()
[]
>>> torch.cuda.is_available()
False
>>> torch.version.cuda
'11.3'
>>> torch.cuda.device_count()
0
</code>```

Below are my configurations.

```<code>(base) ubuntu@DESKTOP:~$ ls -l /usr/local/ | grep cuda
lrwxrwxrwx  1 root root   21 Jan 24 13:47 cuda -> /usr/local/cuda-11.3/
lrwxrwxrwx  1 root root   25 Jan 17 10:52 cuda-11 -> /etc/alternatives/cuda-11
drwxr-xr-x 17 root root 4096 Jan 24 13:48 cuda-11.3
drwxr-xr-x 18 root root 4096 Jan 24 10:17 cuda-11.6
</code>```

ubuntu version:

```<code>(base) ubuntu@DESKTOP:~$ lsb_release -a
No LSB modules are available.
Distributor ID: Ubuntu
Description:    Ubuntu 20.04.3 LTS
Release:        20.04
Codename:       focal
</code>```

nvidia-smi:

```<code>(base) ubuntu@DESKTOP:~$ nvidia-smi
Mon Jan 24 17:22:42 2022
+-----------------------------------------------------------------------------+
| NVIDIA-SMI 510.39.01    Driver Version: 511.23       CUDA Version: 11.6     |
|-------------------------------+----------------------+----------------------+
| GPU  Name        Persistence-M| Bus-Id        Disp.A | Volatile Uncorr. ECC |
| Fan  Temp  Perf  Pwr:Usage/Cap|         Memory-Usage | GPU-Util  Compute M. |
|                               |                      |               MIG M. |
|===============================+======================+======================|
|   0  NVIDIA GeForce ...  On   | 00000000:02:00.0 Off |                  N/A |
|  0%   26C    P8     5W / 320W |    106MiB / 10240MiB |      0%      Default |
|                               |                      |                  N/A |
+-------------------------------+----------------------+----------------------+

+-----------------------------------------------------------------------------+
| Processes:                                                                  |
|  GPU   GI   CI        PID   Type   Process name                  GPU Memory |
|        ID   ID                                                   Usage      |
|=============================================================================|
|    0   N/A  N/A      4009      G   /Xorg                           N/A      |
|    0   N/A  N/A      4025      G   /xfce4-session                  N/A      |
|    0   N/A  N/A      4092      G   /xfwm4                          N/A      |
|    0   N/A  N/A     25903      G   /msedge                         N/A      |
+-----------------------------------------------------------------------------+
</code>```

nvcc --version:

```<code>(base) ubuntu@DESKTOP:~$ nvcc -V
nvcc: NVIDIA (R) Cuda compiler driver
Copyright (c) 2005-2021 NVIDIA Corporation
Built on Sun_Mar_21_19:15:46_PDT_2021
Cuda compilation tools, release 11.3, V11.3.58
Build cuda_11.3.r11.3/compiler.29745058_0
</code>```

答:
I'm answering my own question.

PyTorch pip wheels and Conda binaries ship with the CUDA runtime.
But CUDA does not normally come with NVCC, and requires to install separately from conda-forge/cudatoolkit-dev, which is very troublesome during the installation.

So, what I did was that I install NVCC from Nvidia CUDA toolkit.

```<code>$ wget https://developer.download.nvidia.com/compute/cuda/11.6.0/local_installers/cuda_11.6.0_510.39.01_linux.run
</code>```

And Conda Pytorch-GPU version

```<code>$ conda install pytorch torchvision torchaudio cudatoolkit=11.3 -c pytorch
</code>```

As it turns out both installations are not compatible with each other.

Therefore, the step I did to solve this issue:

remove any Conda environments in Ubuntu.

clean the pip list and Conda list until none of any PyTorch, torchvision,  Cuda etc works.

Install Nvidia CUDA toolkit cuda_11.3 first from Nvidia's official website.

Reinstall PyTorch only. $ pip3 install torch==1.10.1+cu113 -f https://download.pytorch.org/whl/cu113/torch_stable.html

Body:
Before this, I was able to connect to the GPU through CUDA runtime version 10.2. But then I ran into an error when setting up one of my projects.

Using torch 1.10.1+cu102 (NVIDIA GeForce RTX 3080)
UserWarning:
NVIDIA GeForce RTX 3080 with CUDA capability sm_86 is not compatible with the current PyTorch installation.
The current PyTorch install supports CUDA capabilities sm_37 sm_50 sm_60 sm_70.

After some readings, it seems that sm_86 is only available for CUDA version 11.0 and above. That's the reason why I upgraded to the latest CUDA version and can't connect to the GPU after this.
I have tried many ways, reinstalling cuda toolkit, PyTorch, torchvision and stuff but nothing works.

CUDA Toolkit I've used:

$ wget https://developer.download.nvidia.com/compute/cuda/11.6.0/local_installers/cuda_11.6.0_510.39.01_linux.run
$ sudo sh cuda_11.6.0_510.39.01_linux.run

PyTorch I've installed (tried both conda and pip):

$ conda install pytorch torchvision torchaudio cudatoolkit=11.3 -c pytorch

$ pip3 install torch==1.10.1+cu113 torchvision==0.11.2+cu113 torchaudio==0.10.1+cu113 -f https://download.pytorch.org/whl/cu113/torch_stable.html

These are some basic info:

(base) ubuntu@DESKTOP:~$ python
Python 3.9.5 (default, Jun  4 2021, 12:28:51)
[GCC 7.5.0] :: Anaconda, Inc. on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import torch
>>> torch.__version__
'1.10.1+cu113'
>>> x = torch.rand(6,6)
>>> print(x)
tensor([[0.0228, 0.3868, 0.9742, 0.2234, 0.5682, 0.7747],
        [0.2643, 0.3911, 0.3464, 0.5072, 0.4041, 0.4268],
        [0.2247, 0.0936, 0.4250, 0.1128, 0.0261, 0.5199],
        [0.0224, 0.7463, 0.1391, 0.8092, 0.3742, 0.2054],
        [0.3951, 0.4205, 0.6270, 0.4561, 0.4784, 0.5958],
        [0.8430, 0.5078, 0.7759, 0.5266, 0.4925, 0.7557]])
>>> torch.cuda.get_arch_list()
[]
>>> torch.cuda.is_available()
False
>>> torch.version.cuda
'11.3'
>>> torch.cuda.device_count()
0

Below are my configurations.

(base) ubuntu@DESKTOP:~$ ls -l /usr/local/ | grep cuda
lrwxrwxrwx  1 root root   21 Jan 24 13:47 cuda -> /usr/local/cuda-11.3/
lrwxrwxrwx  1 root root   25 Jan 17 10:52 cuda-11 -> /etc/alternatives/cuda-11
drwxr-xr-x 17 root root 4096 Jan 24 13:48 cuda-11.3
drwxr-xr-x 18 root root 4096 Jan 24 10:17 cuda-11.6

ubuntu version:

(base) ubuntu@DESKTOP:~$ lsb_release -a
No LSB modules are available.
Distributor ID: Ubuntu
Description:    Ubuntu 20.04.3 LTS
Release:        20.04
Codename:       focal

nvidia-smi:

(base) ubuntu@DESKTOP:~$ nvidia-smi
Mon Jan 24 17:22:42 2022
+-----------------------------------------------------------------------------+
| NVIDIA-SMI 510.39.01    Driver Version: 511.23       CUDA Version: 11.6     |
|-------------------------------+----------------------+----------------------+
| GPU  Name        Persistence-M| Bus-Id        Disp.A | Volatile Uncorr. ECC |
| Fan  Temp  Perf  Pwr:Usage/Cap|         Memory-Usage | GPU-Util  Compute M. |
|                               |                      |               MIG M. |
|===============================+======================+======================|
|   0  NVIDIA GeForce ...  On   | 00000000:02:00.0 Off |                  N/A |
|  0%   26C    P8     5W / 320W |    106MiB / 10240MiB |      0%      Default |
|                               |                      |                  N/A |
+-------------------------------+----------------------+----------------------+

+-----------------------------------------------------------------------------+
| Processes:                                                                  |
|  GPU   GI   CI        PID   Type   Process name                  GPU Memory |
|        ID   ID                                                   Usage      |
|=============================================================================|
|    0   N/A  N/A      4009      G   /Xorg                           N/A      |
|    0   N/A  N/A      4025      G   /xfce4-session                  N/A      |
|    0   N/A  N/A      4092      G   /xfwm4                          N/A      |
|    0   N/A  N/A     25903      G   /msedge                         N/A      |
+-----------------------------------------------------------------------------+

nvcc --version:

(base) ubuntu@DESKTOP:~$ nvcc -V
nvcc: NVIDIA (R) Cuda compiler driver
Copyright (c) 2005-2021 NVIDIA Corporation
Built on Sun_Mar_21_19:15:46_PDT_2021
Cuda compilation tools, release 11.3, V11.3.58
Build cuda_11.3.r11.3/compiler.29745058_0

Body:
I'm answering my own question.

PyTorch pip wheels and Conda binaries ship with the CUDA runtime.
But CUDA does not normally come with NVCC, and requires to install separately from conda-forge/cudatoolkit-dev, which is very troublesome during the installation.

So, what I did was that I install NVCC from Nvidia CUDA toolkit.

$ wget https://developer.download.nvidia.com/compute/cuda/11.6.0/local_installers/cuda_11.6.0_510.39.01_linux.run

And Conda Pytorch-GPU version

$ conda install pytorch torchvision torchaudio cudatoolkit=11.3 -c pytorch

As it turns out both installations are not compatible with each other.

Therefore, the step I did to solve this issue:

remove any Conda environments in Ubuntu.

clean the pip list and Conda list until none of any PyTorch, torchvision,  Cuda etc works.

Install Nvidia CUDA toolkit cuda_11.3 first from Nvidia's official website.

Reinstall PyTorch only. $ pip3 install torch==1.10.1+cu113 -f https://download.pytorch.org/whl/cu113/torch_stable.html