问:
React Big Calendar - Is it possible to click on a day and retrieve a list of events on that day?
I'm creating a calendar of sales appointments using React Big Calendar. When a user clicks on a day, I would like to create a map populated with all of the appointment locations for that day. But to do that, I need a list of events specific to that day. I know that I could write a function that filters the list of events supplied to the calendar component, but I'd rather not do that if React Big Calendar comes with that functionality already.

Here is my code for the Calendar component:

```<code><Calendar
    localizer={localizer}
    events={events}
    startAccessor='start'
    endAccessor='end'
    style={{ height: 500 }}
    onSelectSlot={(slotInfo) => {
        console.log(slotInfo)
    }}
    selectable
    popup={true}
    eventPropGetter={(eventStyleGetter)}
/>
</code>```

As you can see, I've tried using onSelectSlot prop, which console logs slotInfo. Here is the result in the console when I select a slot that has multiple events:

```<code>{
    "slots": [
        "2022-02-16T08:00:00.000Z"
    ],
    "start": "2022-02-16T08:00:00.000Z",
    "end": "2022-02-17T08:00:00.000Z",
    "action": "click",
    "box": {
        "x": 769,
        "y": 491,
        "clientX": 769,
        "clientY": 491
    }
}
</code>```

I'm confused why there is only one slot in the slot array if there are multiple events? Is there a way to get all of the events of that day without writing a function to filter the events array?

答:
Adding the selectable prop means that users can use the mouse to click and drag in order to select a range of times. The slots array will not give you all the events for the day, or for the selected range - rather, it'll give you just the selected range.

If you click on a day, the (only) value in the slots array will be the Date corresponding to the start of the day. You can use the start and end properties to see when the day starts and when it ends (exclusive).

If you click and drag, the slots array will contain all timeslots dragged over, where the duration of a timeslot is determined by the steps prop.

If you want to get a list of all elements for a particular day when the day is clicked, you can either filter out the events that don't match inside the onSelectSlot callback, or to pass down event objects that contain a reference to an array containing all events for that day. It does require a tiny bit of code on your part, but that's nothing to be afraid of.

```<code>const { start, end } = slotInfo;
const eventsForThisDay = events.filter(
  event => event.start >= start && event.start < end
);
</code>```

Body:
I'm creating a calendar of sales appointments using React Big Calendar. When a user clicks on a day, I would like to create a map populated with all of the appointment locations for that day. But to do that, I need a list of events specific to that day. I know that I could write a function that filters the list of events supplied to the calendar component, but I'd rather not do that if React Big Calendar comes with that functionality already.

Here is my code for the Calendar component:

<Calendar
    localizer={localizer}
    events={events}
    startAccessor='start'
    endAccessor='end'
    style={{ height: 500 }}
    onSelectSlot={(slotInfo) => {
        console.log(slotInfo)
    }}
    selectable
    popup={true}
    eventPropGetter={(eventStyleGetter)}
/>

As you can see, I've tried using onSelectSlot prop, which console logs slotInfo. Here is the result in the console when I select a slot that has multiple events:

{
    "slots": [
        "2022-02-16T08:00:00.000Z"
    ],
    "start": "2022-02-16T08:00:00.000Z",
    "end": "2022-02-17T08:00:00.000Z",
    "action": "click",
    "box": {
        "x": 769,
        "y": 491,
        "clientX": 769,
        "clientY": 491
    }
}

I'm confused why there is only one slot in the slot array if there are multiple events? Is there a way to get all of the events of that day without writing a function to filter the events array?

Body:
Adding the selectable prop means that users can use the mouse to click and drag in order to select a range of times. The slots array will not give you all the events for the day, or for the selected range - rather, it'll give you just the selected range.

If you click on a day, the (only) value in the slots array will be the Date corresponding to the start of the day. You can use the start and end properties to see when the day starts and when it ends (exclusive).

If you click and drag, the slots array will contain all timeslots dragged over, where the duration of a timeslot is determined by the steps prop.

If you want to get a list of all elements for a particular day when the day is clicked, you can either filter out the events that don't match inside the onSelectSlot callback, or to pass down event objects that contain a reference to an array containing all events for that day. It does require a tiny bit of code on your part, but that's nothing to be afraid of.

const { start, end } = slotInfo;
const eventsForThisDay = events.filter(
  event => event.start >= start && event.start < end
);


来源: stackexchange

问:
PHP cURL file returned as string, how to change to download?
I have a site that was working on my local host, but swapping to a production server has caused a headache of problems.  I can't really change the server at this point and trying to handle it.

I am attempting to download a file from a remote server.  It uses .net to return a Zip file with a bunch of files in it:

$url = 'https://myremoteserver.com/getFiles?model=12345&Files=1,2,3,4';

If I enter the URL into my browser, the file downloads perfectly.  But this server isn't accessible outside (my laptop can when on the VPN).

While hacked together from SO answers, my original code looks like this and works on my localhost:

```<code>ob_start();
$filepath= $url;    //your folder file path
header($_SERVER['SERVER_PROTOCOL'].' 200 OK');
header("Content-Type: application/zip");
header("Content-Transfer-Encoding: Binary");
header("Content-Disposition:attachment;filename=".$filename);

while (ob_get_level())
{
    ob_end_clean();
}
readfile($filepath);
exit;
</code>```

On the server, I get no response to this at all.   Chasing that tail, it looks like that security/SSL is stopping it from working.

I was able to get this code to work (but with CURLOPT_SSL_VERIFYHOST, false, and CURLOP_SSL_VERIFYPEER,false), but it returns the file as a string (basically a bunch of jibberish - the string shows some of the file path info in the jibberish).

The header is showing the file name, and now I need to :

Grab the filename from the header

Download the file to the client with the filename.

All of the files are .zip

THE PHP FILE:

```<code>$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_VERBOSE, 1);
curl_setopt($ch, CURLOPT_HEADER, 1);

//Need to figure out how to  fix this too!
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

$response = curl_exec($ch);

// Then, after your curl_exec call:
$header_size = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
$header = substr($response, 0, $header_size);
$body = substr($response, $header_size);

var_dump($header);
echo('</br></br>');
//File Name:
echo($body);
</code>```

The Response:

```<code>string(409) "HTTP/1.1 200 OK Cache-Control: private Content-Type: application/zip Server: Microsoft-IIS/8.5 Access-Control-Allow-Origin: * Set-Cookie: ASP.NET_SessionId=rx1zv2ihyhui4eaqp2jkwtv1; path=/; HttpOnly; SameSite=Lax Content-Disposition: attachment; filename = 2012-08-16-MORE-FILE-NAME.zip X-AspNet-Version: 4.0.30319 X-Powered-By: ASP.NET Date: Thu, 10 Feb 2022 22:17:30 GMT Content-Length: 868 "

PK-/�JT���������FolderName\FILE.txtL���n�0�Olbi��E�^�L[��M��f�]�Dm��H�yP)�!M�N��^ xނwA���m�Ŏ�o;�#'�O��縃�sX�x�}�6j�����!+�Z}[�ʯ�����;:`�)���s����$o�k��ˬw�of�e�ca#�-��3K��[��=@4�F��"�-4�����n��T��UGc��DC�bo���n1��U�·��%y��~�-�OmR��YZ��gn�A�#d�&u;��x��V�0�R�%�9����wny9V^~�B�f�����"Sm:)�)�j�ٱeq����n�P���ލ\@ٰ+�3����-�u�~`�y�b��b��}�o�έ� ��68�<�s�m����;B�F,7�{%��!�}�]�%=�&פ������[�s�U��n�m�;��`U��,��)�N� �N���~o�-��Ywcay!]�A��#p0�NI6�W�7�&bt%v��v�8�O��6�n,Ǘ~�/Kmtܓq,W�� /L�hC#4�C�U������D�mVK�"M�# k�Zrv��S�!���o�ܠ�w2H:�G�a[�Hc����K�㫷�/����ٮ�v{R��\-�j���5���vvW����c}@b����)�����o�����~-��u���$v�b��L�j��"���B��#�K`�.��K�� ���PK3-/�JT�����������FolderName\FILE.txL�PKS�
</code>```

So how do I get the $body to change to ZIP file (named in the Content Disposition)to a download?

Thank you for the help.

答:
As I understand you want your PHP script to serve the zip file as a download to the client.

So what you want to do is set a header to let the client know what it is being sent.

```<code>header("Content-Type: application/zip");
</code>```

That should cause most browsers to download the file, but it really depends on what the handlers are that the client has for that mime type.  To be anal you could use all these headers:

```<code>header("Content-Type: application/force-download");
header("Content-Type: application/download");
header("Content-Type: application/zip");
</code>```

Then you might want to specify a file name for the download so that it isn't named after your php script:

```<code>header("Content-Disposition: attachment;filename=".$file_name);
</code>```

Then you can output the body form your CURL request.

```<code>echo($body);
</code>```

You don't want to output anything else, so no var_dump($header); or echoing any html tags.

ContentLicense: CC BY-SA 4.0

Body:
I have a site that was working on my local host, but swapping to a production server has caused a headache of problems.  I can't really change the server at this point and trying to handle it.

I am attempting to download a file from a remote server.  It uses .net to return a Zip file with a bunch of files in it:

$url = 'https://myremoteserver.com/getFiles?model=12345&Files=1,2,3,4';

If I enter the URL into my browser, the file downloads perfectly.  But this server isn't accessible outside (my laptop can when on the VPN).

While hacked together from SO answers, my original code looks like this and works on my localhost:

ob_start();
$filepath= $url;    //your folder file path
header($_SERVER['SERVER_PROTOCOL'].' 200 OK');
header("Content-Type: application/zip");
header("Content-Transfer-Encoding: Binary");
header("Content-Disposition:attachment;filename=".$filename);

while (ob_get_level())
{
    ob_end_clean();
}
readfile($filepath);
exit;

On the server, I get no response to this at all.   Chasing that tail, it looks like that security/SSL is stopping it from working.

I was able to get this code to work (but with CURLOPT_SSL_VERIFYHOST, false, and CURLOP_SSL_VERIFYPEER,false), but it returns the file as a string (basically a bunch of jibberish - the string shows some of the file path info in the jibberish).

The header is showing the file name, and now I need to :

Grab the filename from the header

Download the file to the client with the filename.

All of the files are .zip

THE PHP FILE:

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_VERBOSE, 1);
curl_setopt($ch, CURLOPT_HEADER, 1);

//Need to figure out how to  fix this too!
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

$response = curl_exec($ch);

// Then, after your curl_exec call:
$header_size = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
$header = substr($response, 0, $header_size);
$body = substr($response, $header_size);

var_dump($header);
echo('

');
//File Name:
echo($body);

The Response:

string(409) "HTTP/1.1 200 OK Cache-Control: private Content-Type: application/zip Server: Microsoft-IIS/8.5 Access-Control-Allow-Origin: * Set-Cookie: ASP.NET_SessionId=rx1zv2ihyhui4eaqp2jkwtv1; path=/; HttpOnly; SameSite=Lax Content-Disposition: attachment; filename = 2012-08-16-MORE-FILE-NAME.zip X-AspNet-Version: 4.0.30319 X-Powered-By: ASP.NET Date: Thu, 10 Feb 2022 22:17:30 GMT Content-Length: 868 "

PK-/�JT���������FolderName\FILE.txtL���n�0�Olbi��E�^�L[��M��f�]�Dm��H�yP)�!M�N��^ xނwA���m�Ŏ�o;�#'�O��縃�sX�x�}�6j�����!+�Z}[�ʯ�����;:`�)���s����$o�k��ˬw�of�e�ca#�-��3K��[��=@4�F��"�-4�����n��T��UGc��DC�bo���n1��U�·��%y��~�-�OmR��YZ��gn�A�#d�&u;��x��V�0�R�%�9����wny9V^~�B�f�����"Sm:)�)�j�ٱeq����n�P���ލ\@ٰ+�3����-�u�~`�y�b��b��}�o�έ� ��68�<�s�m����;B�F,7�{%��!�}�]�%=�&פ������[�s�U��n�m�;��`U��,��)�N� �N���~o�-��Ywcay!]�A��#p0�NI6�W�7�&bt%v��v�8�O��6�n,Ǘ~�/Kmtܓq,W�� /L�hC#4�C�U������D�mVK�"M�# k�Zrv��S�!���o�ܠ�w2H:�G�a[�Hc����K�㫷�/����ٮ�v{R��\-�j���5���vvW����c}@b����)�����o�����~-��u���$v�b��L�j��"���B��#�K`�.��K�� ���PK3-/�JT�����������FolderName\FILE.txL�PKS�

So how do I get the $body to change to ZIP file (named in the Content Disposition)to a download?

Thank you for the help.

Body:
As I understand you want your PHP script to serve the zip file as a download to the client.

So what you want to do is set a header to let the client know what it is being sent.

header("Content-Type: application/zip");

That should cause most browsers to download the file, but it really depends on what the handlers are that the client has for that mime type.  To be anal you could use all these headers:

header("Content-Type: application/force-download");
header("Content-Type: application/download");
header("Content-Type: application/zip");

Then you might want to specify a file name for the download so that it isn't named after your php script:

header("Content-Disposition: attachment;filename=".$file_name);

Then you can output the body form your CURL request.

echo($body);

You don't want to output anything else, so no var_dump($header); or echoing any html tags.


问:
Best way to smooth scrolling to an internal link
I've searched and see lots of examples about this subject but I couldn't best way for me.

I'm just a bit familiar with JS and jQuery and I want to ask about smooth scrolling.

```<code>    <a name="urunler"></a>
<ul>
    <li><a href="#ppanjur" class="uruna">Plastik Panjur</a></li>
    <li><a href="#ipanjur" class="uruna">Alüminyum (İthal / Yalıtımlı) Panjur</a></li>
    <li><a href="#opanjur" class="uruna">Otomatik Panjur</a></li>
    </ul>
</code>```

I've a navigation like this. This scrolls instatly. But I want to do it slowly. Which is the shortest & easiest way for this? I'm more familiar to JS and I don't want to download and use JS plugins.

I need to know full syntax with a click method for my links (they all have same class)

Should I remove href park from links?

Waiting for your help & still searching

EDIT!!!: In this situation, I need only one class. Is it possible to give this property for multiple classes?

```<code>    function scrollToElement (selector) {
  $('html, body').animate({
    scrollTop: $(selector).offset().top
  }, 2000);
};

$(document).on('click', 'a.uruna', function () {
    scrollToElement($(this).attr('href'));
});
</code>```

I've got ('click', 'a.uruna', function (), how can I insert another class here or should I just write:

```<code>$(document).on('click', 'a.uruna', function () {
    scrollToElement($(this).attr('href'));
});
$(document).on('click', 'a.new', function () {
    scrollToElement($(this).attr('href'));
});
</code>```

答:
It can also be done in pure CSS using the following in your Style Sheet.</p>
```<code>html{
   scroll-behavior: smooth
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I've searched and see lots of examples about this subject but I couldn't best way for me.

I'm just a bit familiar with JS and jQuery and I want to ask about smooth scrolling.

Plastik Panjur

Alüminyum (İthal / Yalıtımlı) Panjur

Otomatik Panjur

I've a navigation like this. This scrolls instatly. But I want to do it slowly. Which is the shortest & easiest way for this? I'm more familiar to JS and I don't want to download and use JS plugins.

I need to know full syntax with a click method for my links (they all have same class)

Should I remove href park from links?

Waiting for your help & still searching

EDIT!!!: In this situation, I need only one class. Is it possible to give this property for multiple classes?

    function scrollToElement (selector) {
  $('html, body').animate({
    scrollTop: $(selector).offset().top
  }, 2000);
};

$(document).on('click', 'a.uruna', function () {
    scrollToElement($(this).attr('href'));
});

I've got ('click', 'a.uruna', function (), how can I insert another class here or should I just write:

$(document).on('click', 'a.uruna', function () {
    scrollToElement($(this).attr('href'));
});
$(document).on('click', 'a.new', function () {
    scrollToElement($(this).attr('href'));
});

Body:
It can also be done in pure CSS using the following in your Style Sheet.

html{
   scroll-behavior: smooth
}


问:
Parenthesis for reshape in numpy

x = np.array([1, 2, 3])
print(x)

x.reshape((1, 3))
```
<p>My question is: why are there two parenthesis in <code>((1, 3))</code>? When I write it like this:</p>
<pre class="lang-py prettyprint-override"><code>x.reshape(1, 3)
</code>```

...the answer comes out the same. So why the two parenthesis?

答:
According to the docs:

Unlike the free function numpy.reshape, this method on ndarray allows the elements of the shape parameter to be passed in as separate arguments.

So it's just a convenience. Almost everywhere else in NumPy, e.g. np.ones((2,3)), it's more usual to pass shapes with the parentheses around the shape tuple. In fact, I can't think of anywhere else!

Title: Parenthesis for reshape in numpy

Body:
x = np.array([1, 2, 3])
print(x)

x.reshape((1, 3))

My question is: why are there two parenthesis in ((1, 3))? When I write it like this:

x.reshape(1, 3)

...the answer comes out the same. So why the two parenthesis?


问:
Non-nullable instance field must be initialized (data persistence)
I want to correct the error of the code.
My Problem is:

Non-nullable instance fields must be initialized.

答:
This is the normal way we do this in Dart/Flutter:

```<code>    class Course {
      final int id;
      final String name;
      final String content;
      final int hours;

      const Course({
        this.id = 0;
        this.name = '';
        this.content = '';
        this.hours = 0;
      });

      factory Course.fromMap<String, dynamic> data) {
        return Course(
          id: data['id'] as int ?? 0,
          name: data['name'] as String ?? '',
          content: data['content'] as String ?? '',
          hours: data['hours'] as int ?? 0,
        );
      }
    }

    ...

    final course = Course.fromMap(data);

</code>```

We don't usually use underscore (private) variables for data classes because Dart will automatically provide getters to access the fields via the dot notation.

```<code>final name = course.name;
</code>```

Body:
This is the normal way we do this in Dart/Flutter:

    class Course {
      final int id;
      final String name;
      final String content;
      final int hours;

      const Course({
        this.id = 0;
        this.name = '';
        this.content = '';
        this.hours = 0;
      });

      factory Course.fromMap<String, dynamic> data) {
        return Course(
          id: data['id'] as int ?? 0,
          name: data['name'] as String ?? '',
          content: data['content'] as String ?? '',
          hours: data['hours'] as int ?? 0,
        );
      }
    }

    ...

    final course = Course.fromMap(data);

We don't usually use underscore (private) variables for data classes because Dart will automatically provide getters to access the fields via the dot notation.

final name = course.name;


问:
How to separate entity's primary key from base class?
I want to accomplish clean architecture with EF Core.
I trid to separate primary key from base class, but it failed with below exception.

System.InvalidOperationException: 'A key cannot be configured on 'ManagerEntity' because it is a derived type. The key must be configured on the root type 'Manager'. If you did not intend for 'Manager' to be included in the model, ensure that it is not referenced by a DbSet property on your context, referenced in a configuration call to ModelBuilder, or referenced from a navigation on a type that is included in the model.'

Core

public class Manager
{
    public Manager(Guid identifier, string email)
    {
        Identifier = identifier;
        Email = email;
    }

    public Guid Identifier { get; }
    public string Email { get; }

    public void FixPrinter(Printer printer)
    {
        printer.IsOutOfControl = true;
    }
}
```
<pre class="lang-cs prettyprint-override"><code>public class Printer
{
    public Printer(Guid token)
    {
        Token = token;
        Manager = null;
        IsOutOfControl = false;
    }

    public Guid Token { get; }

    public Manager? Manager { get; set; }

    public bool IsOutOfControl { get; set; }
}
</code>```

Infrastructure

public class ApplicationContext
    : DbContext
{
    // ...

    public DbSet<ManagerEntity> ManagerSet { get; set; }
    public DbSet<PrinterEntity> PrinterSet { get; set; }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);
        modelBuilder.ApplyConfiguration(new ManagerEntityConfiguration(Database));
        modelBuilder.ApplyConfiguration(new PrinterEntityConfiguration(Database));
    }
}
```
<h4>Configure <code>Manager</code></h4>
<pre class="lang-cs prettyprint-override"><code>public sealed class ManagerEntity
    : Manager
{
    public ManagerEntity(string email)
        : base(Guid.Empty, email)
    {
    }

    // Primary key for database.
    public long Id { get; }
}
</code>```

internal sealed class ManagerEntityConfiguration
    : IEntityTypeConfiguration<ManagerEntity>
{
    private readonly DatabaseFacade _database;

    public ManagerEntityConfiguration(DatabaseFacade database)
    {
        _database = database;
    }

    public void Configure(EntityTypeBuilder<ManagerEntity> builder)
    {
        builder
            .Property(e => e.Id)
            .ValueGeneratedOnAdd();

        // The exception occurs here.
        builder
            .HasKey(e => e.Id);

        // ...
    }
}
```
<h4>Configure <code>Printer</code></h4>
<pre class="lang-cs prettyprint-override"><code>public sealed class PrinterEntity
    : Printer
{
    public PrinterEntity()
        : base(Guid.Empty)
    {
    }

    // Primary key for database.
    public long Id { get; }
}
</code>```

internal sealed class PrinterEntityConfiguration
    : IEntityTypeConfiguration<PrinterEntity>
{
    private readonly DatabaseFacade _database;

    public PrinterEntityConfiguration(DatabaseFacade database)
    {
        _database = database;
    }

    public void Configure(EntityTypeBuilder<PrinterEntity> builder)
    {
        builder
            .Property(e => e.Id)
            .ValueGeneratedOnAdd();

        builder
            .HasKey(e => e.Id);

        // ...
    }
}
```
<h3>Web API</h3>
<pre class="lang-cs prettyprint-override"><code>app.MapPost("/printer", async (ApplicationContext context) =>
{
    PrinterEntity printer = new()
    {
        Manager = new ManagerEntity("master@google.com"),
    };

    await context.PrinterSet.AddAsync(printer);
    await context.SaveChangesAsync();

    return printer;
});
</code>```

Should I architect it by using interface, not inheritance?

At Core,

public interface IPrinter
{
    public Manager? Manager { get; set; }
}
```
<p>At <strong>Infrastructure</strong>,</p>
<pre class="lang-cs prettyprint-override"><code>public sealed class PrinterEntity : IPrinter
{
    // ...
}
</code>```

Github source code

答:
Thanks, @roji!

https://github.com/dotnet/efcore/issues/27421#issuecomment-1034762908

This is likely happening because you're mapping both Manager and ManagerEntity in your model, which means you're configuring inheritance mapping (i.e. EF thinks you intend to store both Manager and ManagerEntity instances in the database). With inheritance mapping, the key must be specified at the root.

However, it seems like you only want the class separation on the .NET side, without needing any actual hierarchy, so make sure you are not mapping the base class (Manager in the above). See the minimal code sample below.

await using var ctx = new BlogContext();
await ctx.Database.EnsureDeletedAsync();
await ctx.Database.EnsureCreatedAsync();

public class BlogContext : DbContext
{
    // Uncomment the below to make the exception appear
    // public DbSet<Manager> Managers { get; set; }
    public DbSet<ManagerEntity> ManagerEntities { get; set; }

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        => optionsBuilder
            .UseSqlServer(@"Server=localhost;Database=test;User=SA;Password=Abcd5678;Connect Timeout=60;ConnectRetryCount=0")
            .LogTo(Console.WriteLine, LogLevel.Information)
            .EnableSensitiveDataLogging();

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<ManagerEntity>().HasKey(b => b.Id);
    }
}

public class Manager
{
    public string Name { get; set; }
}

public class ManagerEntity : Manager
{
    public int Id { get; set; }
}
```

However... if the goal is simply not to expose an Id property on Manager, there are simpler ways to do that rather than introducing a .NET hierarchy. You can have a private _id field instead, which would be used by EF Core but not otherwise exposed in your application, keeping your data model clean (see docs). Alternatively, you can have an Id shadow property, removing the field/property from your CLR type altogether.

Body:
I want to accomplish clean architecture with EF Core.
I trid to separate primary key from base class, but it failed with below exception.

System.InvalidOperationException: 'A key cannot be configured on 'ManagerEntity' because it is a derived type. The key must be configured on the root type 'Manager'. If you did not intend for 'Manager' to be included in the model, ensure that it is not referenced by a DbSet property on your context, referenced in a configuration call to ModelBuilder, or referenced from a navigation on a type that is included in the model.'

Core

public class Manager
{
    public Manager(Guid identifier, string email)
    {
        Identifier = identifier;
        Email = email;
    }

    public Guid Identifier { get; }
    public string Email { get; }

    public void FixPrinter(Printer printer)
    {
        printer.IsOutOfControl = true;
    }
}

public class Printer
{
    public Printer(Guid token)
    {
        Token = token;
        Manager = null;
        IsOutOfControl = false;
    }

    public Guid Token { get; }

    public Manager? Manager { get; set; }

    public bool IsOutOfControl { get; set; }
}

Infrastructure

public class ApplicationContext
    : DbContext
{
    // ...

    public DbSet<ManagerEntity> ManagerSet { get; set; }
    public DbSet<PrinterEntity> PrinterSet { get; set; }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);
        modelBuilder.ApplyConfiguration(new ManagerEntityConfiguration(Database));
        modelBuilder.ApplyConfiguration(new PrinterEntityConfiguration(Database));
    }
}

Configure Manager

public sealed class ManagerEntity
    : Manager
{
    public ManagerEntity(string email)
        : base(Guid.Empty, email)
    {
    }

    // Primary key for database.
    public long Id { get; }
}

internal sealed class ManagerEntityConfiguration
    : IEntityTypeConfiguration<ManagerEntity>
{
    private readonly DatabaseFacade _database;

    public ManagerEntityConfiguration(DatabaseFacade database)
    {
        _database = database;
    }

    public void Configure(EntityTypeBuilder<ManagerEntity> builder)
    {
        builder
            .Property(e => e.Id)
            .ValueGeneratedOnAdd();

        // The exception occurs here.
        builder
            .HasKey(e => e.Id);

        // ...
    }
}

Configure Printer

public sealed class PrinterEntity
    : Printer
{
    public PrinterEntity()
        : base(Guid.Empty)
    {
    }

    // Primary key for database.
    public long Id { get; }
}

internal sealed class PrinterEntityConfiguration
    : IEntityTypeConfiguration<PrinterEntity>
{
    private readonly DatabaseFacade _database;

    public PrinterEntityConfiguration(DatabaseFacade database)
    {
        _database = database;
    }

    public void Configure(EntityTypeBuilder<PrinterEntity> builder)
    {
        builder
            .Property(e => e.Id)
            .ValueGeneratedOnAdd();

        builder
            .HasKey(e => e.Id);

        // ...
    }
}

Web API

app.MapPost("/printer", async (ApplicationContext context) =>
{
    PrinterEntity printer = new()
    {
        Manager = new ManagerEntity("master@google.com"),
    };

    await context.PrinterSet.AddAsync(printer);
    await context.SaveChangesAsync();

    return printer;
});

Should I architect it by using interface, not inheritance?

At Core,

public interface IPrinter
{
    public Manager? Manager { get; set; }
}

At Infrastructure,

public sealed class PrinterEntity : IPrinter
{
    // ...
}

Github source code

Body:
Thanks, @roji!

https://github.com/dotnet/efcore/issues/27421#issuecomment-1034762908

This is likely happening because you're mapping both Manager and ManagerEntity in your model, which means you're configuring inheritance mapping (i.e. EF thinks you intend to store both Manager and ManagerEntity instances in the database). With inheritance mapping, the key must be specified at the root.

However, it seems like you only want the class separation on the .NET side, without needing any actual hierarchy, so make sure you are not mapping the base class (Manager in the above). See the minimal code sample below.

await using var ctx = new BlogContext();
await ctx.Database.EnsureDeletedAsync();
await ctx.Database.EnsureCreatedAsync();

public class BlogContext : DbContext
{
    // Uncomment the below to make the exception appear
    // public DbSet<Manager> Managers { get; set; }
    public DbSet<ManagerEntity> ManagerEntities { get; set; }

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        => optionsBuilder
            .UseSqlServer(@"Server=localhost;Database=test;User=SA;Password=Abcd5678;Connect Timeout=60;ConnectRetryCount=0")
            .LogTo(Console.WriteLine, LogLevel.Information)
            .EnableSensitiveDataLogging();

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<ManagerEntity>().HasKey(b => b.Id);
    }
}

public class Manager
{
    public string Name { get; set; }
}

public class ManagerEntity : Manager
{
    public int Id { get; set; }
}

However... if the goal is simply not to expose an Id property on Manager, there are simpler ways to do that rather than introducing a .NET hierarchy. You can have a private _id field instead, which would be used by EF Core but not otherwise exposed in your application, keeping your data model clean (see docs). Alternatively, you can have an Id shadow property, removing the field/property from your CLR type altogether.


问:
HTML new line starts to early
I am working on my 404 page and I am struggling to figure out what is causing my text to automatically go into a new line.
This is what it currently looks like:

body {
  background: #081421;
  color: #d3d7de;
  font-family: "Courier new";
  font-size: 18px;
  line-height: 1.5em;
  cursor: default;
}

a {
  color: #fff;
  text-decoration: none;
  background-image: linear-gradient(currentColor, currentColor);
  background-position: 0% 100%;
  background-repeat: no-repeat;
  background-size: 0% 2px;
  transition: background-size cubic-bezier(0, 0.5, 0, 1) 0.3s;
}

a:hover,
a:focus {
  text-decoration: none;
  background-size: 100% 2px;
}

.code {
  position: absolute;
  width: 320px;
  min-width: 320px;
  top: 50%;
  left: 50%;
  -webkit-transform: translate(-50%, -50%);
  transform: translate(-50%, -50%);
}

.code>span {
  display: block;
}

@media screen and (max-width: 320px) {
  .code {
    font-size: 5vw;
    min-width: auto;
    width: 95%;
    margin: auto;
    padding: 5px;
    padding-left: 10px;
    line-height: 6.5vw;
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="code">
  <span>
    <span style="color: #c46dd4"> if </span>(<span style="font-style: italic; color: #d65562">error</span>
     <span style="color: #4ca8ef"> === </span
    ><span style="color: #d8955c">404</span>) {
  </span>

  <span>
    <span style="padding-left: 15px; color: #ebbd70"
      ><i style="width: 10px; display: inline-block"></i>console</span
    >.<span style="font-style: italic; color: #3fb0f3">error</span>(<span style="color: #88c06e">"Page not found!"</span
    >);
  </span>

  <span>
    <span style="display: block">}</span>
  <span style="color: #7e848f; font-style: italic">
      // Go Back or
      Home!
    </span>
  </span>
</div></code>```

And here is my reference / what I would like my final product to look like:

I'm pretty lost on how I can force the console.error... into only one line while keeping the code block in the center of the website.

Thank you

答:
Your  width is too short at 320px.

    body {
      background: #081421;
      color: #d3d7de;
      font-family: "Courier new";
      font-size: 18px;
      line-height: 1.5em;
      cursor: default;
    }

    a {
      color: #fff;
      text-decoration: none;
      background-image: linear-gradient(currentColor, currentColor);
      background-position: 0% 100%;
      background-repeat: no-repeat;
      background-size: 0% 2px;
      transition: background-size cubic-bezier(0, 0.5, 0, 1) 0.3s;
    }

    a:hover,
    a:focus {
      text-decoration: none;
      background-size: 100% 2px;
    }

    .code {
      position: absolute;
      width: 390px;
      min-width: 320px;
      top: 50%;
      left: 50%;
      -webkit-transform: translate(-50%, -50%);
      transform: translate(-50%, -50%);
      border: 1px solid red;
    }

    .code>span {
      display: block;
    }

    @media screen and (max-width: 320px) {
      .code {
        font-size: 5vw;
        min-width: auto;
        width: 95%;
        margin: auto;
        padding: 5px;
        padding-left: 10px;
        line-height: 6.5vw;
      }
    }```
<pre class="snippet-code-html lang-html prettyprint-override"><code>    <div class="code">
      <span>
        <span style="color: #c46dd4"> if </span>(<span style="font-style: italic; color: #d65562">error</span>
         <span style="color: #4ca8ef"> === </span
        ><span style="color: #d8955c">404</span>) {
      </span>

      <span>
        <span style="padding-left: 15px; color: #ebbd70"
          ><i style="width: 10px; display: inline-block"></i>console</span
        >.<span style="font-style: italic; color: #3fb0f3">error</span>(<span style="color: #88c06e">"Page not found!"</span
        >);
      </span>

      <span>
        <span style="display: block">}</span>
      <span style="color: #7e848f; font-style: italic">
          // Go Back or
          Home!
        </span>
      </span>
    </div></code>```

Title: HTML new line starts to early

Body:
I am working on my 404 page and I am struggling to figure out what is causing my text to automatically go into a new line.
This is what it currently looks like:

body {
  background: #081421;
  color: #d3d7de;
  font-family: "Courier new";
  font-size: 18px;
  line-height: 1.5em;
  cursor: default;
}

a {
  color: #fff;
  text-decoration: none;
  background-image: linear-gradient(currentColor, currentColor);
  background-position: 0% 100%;
  background-repeat: no-repeat;
  background-size: 0% 2px;
  transition: background-size cubic-bezier(0, 0.5, 0, 1) 0.3s;
}

a:hover,
a:focus {
  text-decoration: none;
  background-size: 100% 2px;
}

.code {
  position: absolute;
  width: 320px;
  min-width: 320px;
  top: 50%;
  left: 50%;
  -webkit-transform: translate(-50%, -50%);
  transform: translate(-50%, -50%);
}

.code>span {
  display: block;
}

@media screen and (max-width: 320px) {
  .code {
    font-size: 5vw;
    min-width: auto;
    width: 95%;
    margin: auto;
    padding: 5px;
    padding-left: 10px;
    line-height: 6.5vw;
  }
}

     if (error
      === 404) {

    console.error("Page not found!");

    }

      // Go Back or
      Home!

And here is my reference / what I would like my final product to look like:

I'm pretty lost on how I can force the console.error... into only one line while keeping the code block in the center of the website.

Thank you

Body:
Your  width is too short at 320px.

    body {
      background: #081421;
      color: #d3d7de;
      font-family: "Courier new";
      font-size: 18px;
      line-height: 1.5em;
      cursor: default;
    }

    a {
      color: #fff;
      text-decoration: none;
      background-image: linear-gradient(currentColor, currentColor);
      background-position: 0% 100%;
      background-repeat: no-repeat;
      background-size: 0% 2px;
      transition: background-size cubic-bezier(0, 0.5, 0, 1) 0.3s;
    }

    a:hover,
    a:focus {
      text-decoration: none;
      background-size: 100% 2px;
    }

    .code {
      position: absolute;
      width: 390px;
      min-width: 320px;
      top: 50%;
      left: 50%;
      -webkit-transform: translate(-50%, -50%);
      transform: translate(-50%, -50%);
      border: 1px solid red;
    }

    .code>span {
      display: block;
    }

    @media screen and (max-width: 320px) {
      .code {
        font-size: 5vw;
        min-width: auto;
        width: 95%;
        margin: auto;
        padding: 5px;
        padding-left: 10px;
        line-height: 6.5vw;
      }
    }

    <div class="code">
      <span>
        <span style="color: #c46dd4"> if </span>(<span style="font-style: italic; color: #d65562">error</span>
         <span style="color: #4ca8ef"> === </span
        ><span style="color: #d8955c">404</span>) {
      </span>

      <span>
        <span style="padding-left: 15px; color: #ebbd70"
          ><i style="width: 10px; display: inline-block"></i>console</span
        >.<span style="font-style: italic; color: #3fb0f3">error</span>(<span style="color: #88c06e">"Page not found!"</span
        >);
      </span>

      <span>
        <span style="display: block">}</span>
      <span style="color: #7e848f; font-style: italic">
          // Go <a href="javascript:history.back()">Back</a> or
          <a href="/">Home!</a>
        </span>
      </span>
    </div>


问:
Running Jekyll from Java program under eclipse on OSX
I have a java program that does some preparation and then invokes Jekyll on the content it's prepared. Jekyll is a Ruby program installed on the local PC as a gem. On windows and linux, no problem, but when running on OSX, under the eclipse debugger, Jekyll doesn't run. Presumably this is because of interactive shell issues (Jekyll runs fine from the terminal).

Here's my java code:

  DefaultExecutor exec = new DefaultExecutor(); // from org.apache.commons.exec
  exec.setExitValue(0);
  MyFilterHandler pumpHandler = new MyFilterHandler();
  exec.setWorkingDirectory(new File("/Users/grahamegrieve/temp/igs/swissnoso/temp/pages"));

  ProcessBuilder processBuilder = new ProcessBuilder(new String("bash -c jekyll build --destination /Users/grahamegrieve/temp/igs/swissnoso/output"));
  Map<String, String> env = processBuilder.environment();
  Map<String, String> vars = new HashMap<>();
  vars.putAll(env);
  String path = "/Users/grahamegrieve/.gem/ruby/3.1.0/bin:/Users/grahamegrieve/.gem/ruby/3.1.0/bin:/opt/homebrew/opt/ruby/bin:/Users/grahamegrieve/.nvm/versions/node/v17.4.0/bin:/opt/homebrew/bin:/opt/homebrew/sbin:"+env.get("PATH");
  vars.put("PATH", path);
  exec.execute(org.apache.commons.exec.CommandLine.parse("bash -c -i jekyll build --destination /Users/grahamegrieve/temp/igs/swissnoso/output"), vars);
```
<p>this results in the following output from the process:</p>
```A subcommand is required.
```
<p>followed by Jekyll's standard documentation - so Jekyll is running but not getting the parameters. The same thing happens in terminal:</p>
```➜  ~ bash -c jekyll build --destination /Users/grahamegrieve/temp/igs/swissnoso/output
A subcommand is required.
jekyll 4.2.1 -- Jekyll is a blog-aware, static site generator in Ruby

Usage:

  jekyll <subcommand> [options]

```
<p>In the terminal, I can do this:</p>
```➜  ~ bash -c 'jekyll build --destination /Users/grahamegrieve/temp/igs/swissnoso/output'
Configuration file: none
            Source: /Users/grahamegrieve
       Destination: /Users/grahamegrieve/temp/igs/swissnoso/output
 Incremental build: disabled. Enable with --incremental
      Generating...

```
<p>so the parameters work fine when the entire command is wrapped in ''. But putting '' (or "") in the java code results in</p>
```Jekyll: bash: jekyll build --destination /Users/grahamegrieve/temp/igs/swissnoso/output: No such file or directory
```

As far as I can tell, that means there is no file with the name 'Jekyll build ...'.

So I don't know how to invoke Jekyll from my java code on OSX. Is it possible?

答:
The answer is over here: execute shell command with org.apache.commons.exec.DefaultExecutor

It's to do with the way CommandLine works, and interacts with Bash.

DefaultExecutor exec = new DefaultExecutor(); // from org.apache.commons.exec
  exec.setExitValue(0);
  MyFilterHandler pumpHandler = new MyFilterHandler();
  exec.setWorkingDirectory(new File("/Users/grahamegrieve/temp/igs/swissnoso/temp/pages"));

  ProcessBuilder processBuilder = new ProcessBuilder(new String("bash -c jekyll build --destination /Users/grahamegrieve/temp/igs/swissnoso/output"));
  Map<String, String> env = processBuilder.environment();
  Map<String, String> vars = new HashMap<>();
  vars.putAll(env);
  String path = "/Users/grahamegrieve/.gem/ruby/3.1.0/bin:/Users/grahamegrieve/.gem/ruby/3.1.0/bin:/opt/homebrew/opt/ruby/bin:/Users/grahamegrieve/.nvm/versions/node/v17.4.0/bin:/opt/homebrew/bin:/opt/homebrew/sbin:"+env.get("PATH");
  vars.put("PATH", path);
  CommandLine cmd = new CommandLine("bash").addArgument("-c").addArgument("Jekyll build --destination /Users/grahamegrieve/temp/igs/swissnoso/output", false);
  exec.execute(cmd, vars);

```

Body:
I have a java program that does some preparation and then invokes Jekyll on the content it's prepared. Jekyll is a Ruby program installed on the local PC as a gem. On windows and linux, no problem, but when running on OSX, under the eclipse debugger, Jekyll doesn't run. Presumably this is because of interactive shell issues (Jekyll runs fine from the terminal).

Here's my java code:

  DefaultExecutor exec = new DefaultExecutor(); // from org.apache.commons.exec
  exec.setExitValue(0);
  MyFilterHandler pumpHandler = new MyFilterHandler();
  exec.setWorkingDirectory(new File("/Users/grahamegrieve/temp/igs/swissnoso/temp/pages"));

  ProcessBuilder processBuilder = new ProcessBuilder(new String("bash -c jekyll build --destination /Users/grahamegrieve/temp/igs/swissnoso/output"));
  Map<String, String> env = processBuilder.environment();
  Map<String, String> vars = new HashMap<>();
  vars.putAll(env);
  String path = "/Users/grahamegrieve/.gem/ruby/3.1.0/bin:/Users/grahamegrieve/.gem/ruby/3.1.0/bin:/opt/homebrew/opt/ruby/bin:/Users/grahamegrieve/.nvm/versions/node/v17.4.0/bin:/opt/homebrew/bin:/opt/homebrew/sbin:"+env.get("PATH");
  vars.put("PATH", path);
  exec.execute(org.apache.commons.exec.CommandLine.parse("bash -c -i jekyll build --destination /Users/grahamegrieve/temp/igs/swissnoso/output"), vars);

this results in the following output from the process:

A subcommand is required.

followed by Jekyll's standard documentation - so Jekyll is running but not getting the parameters. The same thing happens in terminal:

➜  ~ bash -c jekyll build --destination /Users/grahamegrieve/temp/igs/swissnoso/output
A subcommand is required.
jekyll 4.2.1 -- Jekyll is a blog-aware, static site generator in Ruby

Usage:

  jekyll <subcommand> [options]

In the terminal, I can do this:

➜  ~ bash -c 'jekyll build --destination /Users/grahamegrieve/temp/igs/swissnoso/output'
Configuration file: none
            Source: /Users/grahamegrieve
       Destination: /Users/grahamegrieve/temp/igs/swissnoso/output
 Incremental build: disabled. Enable with --incremental
      Generating...

so the parameters work fine when the entire command is wrapped in ''. But putting '' (or "") in the java code results in

Jekyll: bash: jekyll build --destination /Users/grahamegrieve/temp/igs/swissnoso/output: No such file or directory

As far as I can tell, that means there is no file with the name 'Jekyll build ...'.

So I don't know how to invoke Jekyll from my java code on OSX. Is it possible?


问:
html <select> event handler onfocus
Tested with Internet explorer 7 (for backwards compatibility) and Firefox 4.
I am getting strange behaviour from select event handler.

http://www.w3schools.com/tags/tag_select.asp states that event handlers supported.

```<code><select id="selection" onfocus="window.status='here';"
  onblur="window.status='there';">
 <option value="1">1</option>
 <option value="2">2</option>
 <option value="3">3</option>
 </select>
</code>```

I cannot get any event handler to respond through the select tag. Am I doing something wrong? is the select event handler not firing or?
any ideas anyone?

答:
The issue is with window.status.

The status property does not work in the default configuration of IE,
  Firefox, Chrome, or Safari. To allow scripts to change the text of the
  status, the user must set the dom.disable_window_status_change
  preference to false in the about:config screen. (or in Firefox: "Tools
  - Options - Content -Enable JavaScript / Advanced - Allow scripts to
  change status bar text").

Source.

Title: html <select> event handler onfocus

Body:
Tested with Internet explorer 7 (for backwards compatibility) and Firefox 4.
I am getting strange behaviour from select event handler.

http://www.w3schools.com/tags/tag_select.asp states that event handlers supported.

<select id="selection" onfocus="window.status='here';"
  onblur="window.status='there';">
 <option value="1">1</option>
 <option value="2">2</option>
 <option value="3">3</option>
 </select>

I cannot get any event handler to respond through the select tag. Am I doing something wrong? is the select event handler not firing or?
any ideas anyone?


问:
How to take snapshot when every document is added/ deleted/ updated in index in elastic search cluster?
We have a s3 bucket and repository is registered.

We want to take snapshot whenever documents are added/deleted/updated in index in elastic search cluster.

Do we have any option to do this in elastic search or any other way to do this. Pls suggest ?

答:
tldr there's nothing native to Elasticsearch that will take a snapshot "whenever documents are added/deleted/updated". if you had a high rate of change in your docs, that'd be unrealistic anyway

you can create snapshots on a schedule using SLM - https://www.elastic.co/guide/en/elasticsearch/reference/8.0/snapshots-take-snapshot.html#automate-snapshots-slm, which would be the next best thing


问:
send excel file as base64 via using WhatsApp api with Ultramsg
I am trying to convert excel file to base64 to send WhatsApp API with Ultramsg  :

```<code><?php

require_once ('vendor/autoload.php'); // if you use Composer
//require_once('ultramsg.class.php'); // if you download ultramsg.class.php
$token=""; // Ultramsg.com token
$instance_id=""; // Ultramsg.com instance id
$client = new UltraMsg\WhatsAppApi($token,$instance_id);
$to="";
$filename="test.xlsx";
$document = base64_encode(file_get_contents("test.xlsx"));
$api=$client->sendDocumentMessage($to,$filename,$document);
print_r($api);
</code>```

But I see this error :

```<code>Array
(
    [error] => Array
        (
            [0] => Array
                (
                    [document] => file extension not supported
                )

        )

)
</code>```

答:
You need add MIME types for Microsoft Excel
.xls=application/vnd.ms-excel
or
.xlsx=application/vnd.openxmlformats-officedocument.spreadsheetml.sheet

```<code>$document ="data:application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;base64,".$document;
</code>```

So , Try this code block and enjoy (: :

```<code><?php
require_once ('vendor/autoload.php'); // if you use Composer
//require_once('ultramsg.class.php'); // if you download ultramsg.class.php
$token=""; // Ultramsg.com token
$instance_id=""; // Ultramsg.com instance id
$client = new UltraMsg\WhatsAppApi($token,$instance_id);
$to="";
$filename="test.xlsx";
$document = base64_encode(file_get_contents("test.xlsx"));
$document ="data:application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;base64,".$document;
$api=$client->sendDocumentMessage($to,$filename,$document);
print_r($api);
</code>```

Body:
I am trying to convert excel file to base64 to send WhatsApp API with Ultramsg  :

<?php

require_once ('vendor/autoload.php'); // if you use Composer
//require_once('ultramsg.class.php'); // if you download ultramsg.class.php
$token=""; // Ultramsg.com token
$instance_id=""; // Ultramsg.com instance id
$client = new UltraMsg\WhatsAppApi($token,$instance_id);
$to="";
$filename="test.xlsx";
$document = base64_encode(file_get_contents("test.xlsx"));
$api=$client->sendDocumentMessage($to,$filename,$document);
print_r($api);

But I see this error :

Array
(
    [error] => Array
        (
            [0] => Array
                (
                    [document] => file extension not supported
                )

        )

)

Body:
You need add MIME types for Microsoft Excel
.xls=application/vnd.ms-excel
or
.xlsx=application/vnd.openxmlformats-officedocument.spreadsheetml.sheet

$document ="data:application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;base64,".$document;

So , Try this code block and enjoy (: :

<?php
require_once ('vendor/autoload.php'); // if you use Composer
//require_once('ultramsg.class.php'); // if you download ultramsg.class.php
$token=""; // Ultramsg.com token
$instance_id=""; // Ultramsg.com instance id
$client = new UltraMsg\WhatsAppApi($token,$instance_id);
$to="";
$filename="test.xlsx";
$document = base64_encode(file_get_contents("test.xlsx"));
$document ="data:application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;base64,".$document;
$api=$client->sendDocumentMessage($to,$filename,$document);
print_r($api);


问:
ImageMagick .net c# mp4/webm video getting N frame without artifacts?
Trying to make some manipulation with frames using ImageMagick lib on .net (resizing + composing with other image), but faced with incorrect "re-assembling" video, output video coming with some artifacts.

So, as a sample of mp4 short file we have :
mp4 (130kb) : https://c2n.me/4eU1Twz.mp4

first frame is :
second frame is :

and all next frames with similar artifacts.

Code to get frames and save them to disk :

```<code>string incomingFilePath = AppContext.BaseDirectory + "test.mp4";

using (var videoFrames = new MagickImageCollection(incomingFilePath, MagickFormat.Mp4))
{
        for (var i = 0; i < _incomingImageFrames.Count; i++)
        {
            _incomingImageFrames[i].Write(AppContext.BaseDirectory + Guid.NewGuid() + ".png");
        }
}
</code>```

In case i am trying to "re-assemble" images to mp4 (with some modifications, using composing() method and etc), i am getting video with artifacts. Sample from output .mp4 :

So need to fix it somehow, but not sure why. Can anyone help me with it?

答:
The reason is in "nature" of mp4/h.264 codec. First frame is always "full" and all others - are the difference between current and previous frame, so as i understand, when mp4 is trying "assemble" not original images (modified) - ffmpeg trying to do the best and glue them all to video.

So as a workaround - we can just remove this frame difference at runtime before forwarding them to ffmpeg engine.

In case of ImageMagick, we need to compose current frame with previous to obtain "full drew frame" as a result before assembling.

Sample code :

```<code>string incomingFilePath = AppContext.BaseDirectory + "test.mp4";

    using (var videoFrames = new MagickImageCollection(incomingFilePath, MagickFormat.Mp4))
    {
            var _resultImageCollection = new MagickImageCollection(); //temp collection
            var prevFullFrame = _incomingImageFrames.First(); //save last full frame, as initial it will be first in collection
            for (var i = 0; i < _incomingImageFrames.Count; i++)
            {
                prevFullFrame.Composite(_incomingImageFrames[i],_incomingImageFrames[i].Page.X, _incomingImageFrames[i].Page.Y, CompositeOperator.Over); //combining previous (full frame) with current (with partial filled pixels)
                _resultImageCollection.add(prevFullFrame); //adding to result collection
            }
            _resultImageCollection.Write(AppContext.BaseDirectory + "result.mp4"); //assembling mp4
    }
</code>```

Maybe not the best from performance side, but it works fine. Also, it will some increase size, but not dramatically. In my case it was about +10%, so acceptable. (36Kb vs 40Kb)

Update : it will have the same size if you will call Optimize() for collection before save.

```<code>_resultImageCollection.Optimize();
</code>```

Maybe anyone know better solution?

Body:
Trying to make some manipulation with frames using ImageMagick lib on .net (resizing + composing with other image), but faced with incorrect "re-assembling" video, output video coming with some artifacts.

So, as a sample of mp4 short file we have :
mp4 (130kb) : https://c2n.me/4eU1Twz.mp4

first frame is :
second frame is :

and all next frames with similar artifacts.

Code to get frames and save them to disk :

string incomingFilePath = AppContext.BaseDirectory + "test.mp4";

using (var videoFrames = new MagickImageCollection(incomingFilePath, MagickFormat.Mp4))
{
        for (var i = 0; i < _incomingImageFrames.Count; i++)
        {
            _incomingImageFrames[i].Write(AppContext.BaseDirectory + Guid.NewGuid() + ".png");
        }
}

In case i am trying to "re-assemble" images to mp4 (with some modifications, using composing() method and etc), i am getting video with artifacts. Sample from output .mp4 :

So need to fix it somehow, but not sure why. Can anyone help me with it?

Body:
The reason is in "nature" of mp4/h.264 codec. First frame is always "full" and all others - are the difference between current and previous frame, so as i understand, when mp4 is trying "assemble" not original images (modified) - ffmpeg trying to do the best and glue them all to video.

So as a workaround - we can just remove this frame difference at runtime before forwarding them to ffmpeg engine.

In case of ImageMagick, we need to compose current frame with previous to obtain "full drew frame" as a result before assembling.

Sample code :

string incomingFilePath = AppContext.BaseDirectory + "test.mp4";

    using (var videoFrames = new MagickImageCollection(incomingFilePath, MagickFormat.Mp4))
    {
            var _resultImageCollection = new MagickImageCollection(); //temp collection
            var prevFullFrame = _incomingImageFrames.First(); //save last full frame, as initial it will be first in collection
            for (var i = 0; i < _incomingImageFrames.Count; i++)
            {
                prevFullFrame.Composite(_incomingImageFrames[i],_incomingImageFrames[i].Page.X, _incomingImageFrames[i].Page.Y, CompositeOperator.Over); //combining previous (full frame) with current (with partial filled pixels)
                _resultImageCollection.add(prevFullFrame); //adding to result collection
            }
            _resultImageCollection.Write(AppContext.BaseDirectory + "result.mp4"); //assembling mp4
    }

Maybe not the best from performance side, but it works fine. Also, it will some increase size, but not dramatically. In my case it was about +10%, so acceptable. (36Kb vs 40Kb)

Update : it will have the same size if you will call Optimize() for collection before save.

_resultImageCollection.Optimize();

Maybe anyone know better solution?


问:
How to determine step size for this program
So the basis of this assignment is to make a python program that generates a logarithmic table.
We're given steps of functions we need to make in order to execute the program. I haven't gotten very far and I would would appreciate some help.

A function that prompts the user for the step size and returns it to
the calling statement. Function also deals with range checking to make
sure that step size provided is greater than 0.

Here's my code so far

```<code>  def min():
          return int(input("What's your minimum value"))
  def check():
          if min >= 0
             return print("ERROR. Minimum should be greater than 0"
          else:
             return min

    def max():
            return int(input("What's your maximum value? ")

    def max_Check():
            if max <= min
                return print(f"ERROR. Maximum should be greater than {min})
</code>```

答:
A function that prompts the user for the step size and returns it to the calling statement. Function also deals with range checking to make sure that step size provided is greater than 0

Your assignment wants you to write a function that'll ask the user for the step size. If it's < 0, it should complain (and possibly ask again, see Asking the user for input until they give a valid response).

Note: You shouldn't use min and max as function names because they are already defined in python.

```<code>def get_step():
    while True:
        try:
            x = float(input("Enter a step size: "))
            if x <= 0:
                print("Must enter a value greater than 0.")
                continue
            return x
        except ValueError:
            print("Invalid number. Please try again.")
</code>```

To use it, you'd do something like this:

```<code>step_size = get_step()
</code>```

Now, step_size contains the value that the user entered.

Similarly, they want a function that asks the user for a min value.

```<code>min_value = get_min()
</code>```

And also a max value. Remember that the max value function takes an argument (the previously entered minimum value), and checks that the entered number is greater than that minimum value. This function would look something like this:

```<code>def get_max(min_val):
    # The function body is an exercise for you
    # Hint: Use min_val when checking if the given number is greater

max_value = get_max(min_value)
</code>```

You could probably generalize all these three functions as a single function if it takes the message and the lower bound as an argument:

```<code>def get_number(msg, min_val):
    # How would you adapt the function to use msg and min_val?
</code>```

And use it like so:

```<code>min_value = get_number("Enter a min value: ", 0)
max_value = get_number("Enter a max value: ", min_value)
step_value = get_number("Enter a step size: ", 0)
</code>```

Body:
So the basis of this assignment is to make a python program that generates a logarithmic table.
We're given steps of functions we need to make in order to execute the program. I haven't gotten very far and I would would appreciate some help.

A function that prompts the user for the step size and returns it to
the calling statement. Function also deals with range checking to make
sure that step size provided is greater than 0.

Here's my code so far

  def min():
          return int(input("What's your minimum value"))
  def check():
          if min >= 0
             return print("ERROR. Minimum should be greater than 0"
          else:
             return min

    def max():
            return int(input("What's your maximum value? ")

    def max_Check():
            if max <= min
                return print(f"ERROR. Maximum should be greater than {min})

Body:
A function that prompts the user for the step size and returns it to the calling statement. Function also deals with range checking to make sure that step size provided is greater than 0

Your assignment wants you to write a function that'll ask the user for the step size. If it's < 0, it should complain (and possibly ask again, see Asking the user for input until they give a valid response).

Note: You shouldn't use min and max as function names because they are already defined in python.

def get_step():
    while True:
        try:
            x = float(input("Enter a step size: "))
            if x <= 0:
                print("Must enter a value greater than 0.")
                continue
            return x
        except ValueError:
            print("Invalid number. Please try again.")

To use it, you'd do something like this:

step_size = get_step()

Now, step_size contains the value that the user entered.

Similarly, they want a function that asks the user for a min value.

min_value = get_min()

And also a max value. Remember that the max value function takes an argument (the previously entered minimum value), and checks that the entered number is greater than that minimum value. This function would look something like this:

def get_max(min_val):
    # The function body is an exercise for you
    # Hint: Use min_val when checking if the given number is greater

max_value = get_max(min_value)

You could probably generalize all these three functions as a single function if it takes the message and the lower bound as an argument:

def get_number(msg, min_val):
    # How would you adapt the function to use msg and min_val?

And use it like so:

min_value = get_number("Enter a min value: ", 0)
max_value = get_number("Enter a max value: ", min_value)
step_value = get_number("Enter a step size: ", 0)


问:
Does Google Dialogflow's phone integration gateway has the DTMF cabability?
I have integrated dialogflow's Phone Gateway with my agent. I want to know if dialogflow's phone integration gateway has DTMF capability? Example, I want something like, press 1 for this and press 2 for this? and then that bot should work on numbers entered by user? So, is there a way to get the numbers input from the user and get the value entered by the user in dialoglow response?
Thanks</p>

答:
DTMF capability is available in the Dialogflow CX Phone Gateway integration, but not available out-of-the-box in Dialogflow ES Phone Gateway.

Check the DTMF for telephony integrations documentation for instructions on how to implement DTMF in the Dialogflow CX edition.


问:
Pandas Group By, Aggregate, Then Return A Different Column
I have a pandas DataFrame containing baseball fielding statistics. Each row shows how many games a player has appeared at a given position over the course of his career.

Player
Position
Games

Brock Holt
2B
20

Brock Holt
3B
70

Ben Zobrist
OF
100

Ben Zobrist
2B
15

I want to be able to return one row per player containing the position they played the most over the years. In the example above the resulting DataFrame would be:

Player
Position

Brock Holt
3B

Ben Zobrist
OF

I've been attempting to group by Player and aggregate by Games like so

```<code>df.groupby('Player').agg({'Games':['max']})
</code>```

which simply provides the name of the player and the maximum number of games played at a position and

```<code>df.groupby('Player')['Position'].agg({'Games':['max']})
</code>```

which returns the error "nested renamer is not supported."

答:
You could transform max and use eq to create a boolean mask where True corresponds to the most played Games row for each player. Then filter df:

```<code>msk = df.groupby('Player')['Games'].transform('max').eq(df['Games'])
out = df[msk].drop(columns='Games')
</code>```

Output:

```<code>        Player Position
1   Brock Holt       3B
2  Ben Zobrist       OF
</code>```

Body:
I have a pandas DataFrame containing baseball fielding statistics. Each row shows how many games a player has appeared at a given position over the course of his career.

Player
Position
Games

Brock Holt
2B
20

Brock Holt
3B
70

Ben Zobrist
OF
100

Ben Zobrist
2B
15

I want to be able to return one row per player containing the position they played the most over the years. In the example above the resulting DataFrame would be:

Player
Position

Brock Holt
3B

Ben Zobrist
OF

I've been attempting to group by Player and aggregate by Games like so

df.groupby('Player').agg({'Games':['max']})

which simply provides the name of the player and the maximum number of games played at a position and

df.groupby('Player')['Position'].agg({'Games':['max']})

which returns the error "nested renamer is not supported."

Body:
You could transform max and use eq to create a boolean mask where True corresponds to the most played Games row for each player. Then filter df:

msk = df.groupby('Player')['Games'].transform('max').eq(df['Games'])
out = df[msk].drop(columns='Games')

Output:

        Player Position
1   Brock Holt       3B
2  Ben Zobrist       OF


问:
error: failed to import to kibana dashhboards
```<code>Exiting: Error importing Kibana dashboards: fail to import the dashboards in Kibana: Error importing directory /usr/share/metricbeat/kibana: failed to import Kibana index pattern: 1 error: error loading index pattern: returned 200 to import file: 1 error: error: unknown, asset ID=metricbeat-*; asset type=index-pattern; references=[]. Response: {"successCount":0,"success":false,"warnings":[],"errors":[{"id":"metricbeat-*","type":"index-pattern","title":"metricbeat-*","meta":{"title":"metricbeat-*","icon":"indexPatternApp"},"error":{"error":"Internal Server Error","message":"Unexpected bulk response [429] cluster_block_exception: index [.kibana_7.15.2_001] blocked by: [TOO_MANY_REQUESTS/12/disk usage exceeded flood-stage watermark, index has read-only-allow-delete block];","statusCode":500,"type":"unknown"},"overwrite":true}]}
</code>```

Exiting: Error importing Kibana dashboards: fail to import the dashboards in Kibana: Error importing directory /usr/share/metricbeat/kibana: failed to import Kibana index pattern: 1 error: error loading index pattern: returned 200 to import file: 1 error: error: unknown, asset ID=metricbeat-; asset type=index-pattern; references=[]. Response: {"successCount":0,"success":false,"warnings":[],"errors":[{"id":"metricbeat-","type":"index-pattern","title":"metricbeat-","meta":{"title":"metricbeat-","icon":"indexPatternApp"},"error":{"error":"Internal Server Error","message":"Unexpected bulk response [429] cluster_block_exception: index [.kibana_7.15.2_001] blocked by: [TOO_MANY_REQUESTS/12/disk usage exceeded flood-stage watermark, index has read-only-allow-delete block];","statusCode":500,"type":"unknown"},"overwrite":true}]}

答:
your Elasticsearch node is out of disk space, which is what disk usage exceeded flood-stage watermark, index has read-only-allow-delete block is telling you

you will need to figure out what's happened there, either add more space for it or delete data you don't need (using the Elasticsearch API). once you have that sorted, you will need to change the index from read only

https://www.elastic.co/guide/en/elasticsearch/reference/8.0/fix-common-cluster-issues.html#_error_disk_usage_exceeded_flood_stage_watermark_index_has_read_only_allow_delete_block has some good tips here as well

Body:
Exiting: Error importing Kibana dashboards: fail to import the dashboards in Kibana: Error importing directory /usr/share/metricbeat/kibana: failed to import Kibana index pattern: 1 error: error loading index pattern: returned 200 to import file: 1 error: error: unknown, asset ID=metricbeat-*; asset type=index-pattern; references=[]. Response: {"successCount":0,"success":false,"warnings":[],"errors":[{"id":"metricbeat-*","type":"index-pattern","title":"metricbeat-*","meta":{"title":"metricbeat-*","icon":"indexPatternApp"},"error":{"error":"Internal Server Error","message":"Unexpected bulk response [429] cluster_block_exception: index [.kibana_7.15.2_001] blocked by: [TOO_MANY_REQUESTS/12/disk usage exceeded flood-stage watermark, index has read-only-allow-delete block];","statusCode":500,"type":"unknown"},"overwrite":true}]}

Exiting: Error importing Kibana dashboards: fail to import the dashboards in Kibana: Error importing directory /usr/share/metricbeat/kibana: failed to import Kibana index pattern: 1 error: error loading index pattern: returned 200 to import file: 1 error: error: unknown, asset ID=metricbeat-; asset type=index-pattern; references=[]. Response: {"successCount":0,"success":false,"warnings":[],"errors":[{"id":"metricbeat-","type":"index-pattern","title":"metricbeat-","meta":{"title":"metricbeat-","icon":"indexPatternApp"},"error":{"error":"Internal Server Error","message":"Unexpected bulk response [429] cluster_block_exception: index [.kibana_7.15.2_001] blocked by: [TOO_MANY_REQUESTS/12/disk usage exceeded flood-stage watermark, index has read-only-allow-delete block];","statusCode":500,"type":"unknown"},"overwrite":true}]}


问:
Matching files using python program
I have to two files as follows

```<code>File1
ids
CID5265
CID7263
CID9289
....

File 2
ids
CID7363  3.5e-06 -3837
CID5265  4.5      -938
CID9289  8.9      -9873
....
</code>```

I want  compare file1 with file2  to match any ids in file1 is present in file2 if yes  i should print whole line as follows

```<code>CIDS9289  8.9  -9873
....
</code>```

to acheive this wrote python script as follows

```<code>infile = open("file1","r")

searchtxt = open("file2.txt","r")

for line in infile.readlines():

    if searchtxt in line:

       print line
</code>```

but i gives following error

```<code>Traceback (most recent call last):
  File "finding_words.py", line 7, in <module>
    if searchtxt in line:
TypeError: 'in <string>' requires string as left operand, not file
</code>```

I know im doing very simple mistake but not able to figure it out can anybody tell how to solve this..

THanks in advance

NI

答:
The problem is you have your search backwards -- instead of looking to see if your line from the first file is in the second, you are asking if the entire second file is in the line from the first file.  You need to loop over the second file, checking to see if the key that starts each line is in the first file data.  Change your code as follows:</p>

```<code>infile = open("file1","r")

keys = set()
for line in infile:
    break   # skip first line
for line in infile:
    keys.add(line.strip())   # get rid of trailing newline

searchtxt = open("file2.txt","r")

for line in searchtxt:
    break   # skip first line
for line in searchtxt:
    key, rest = line.split(' ', 1)
    if key in keys:
        print line
</code>```

Title: Matching files using python program

Body:
I have to two files as follows

File1
ids
CID5265
CID7263
CID9289
....

File 2
ids
CID7363  3.5e-06 -3837
CID5265  4.5      -938
CID9289  8.9      -9873
....

I want  compare file1 with file2  to match any ids in file1 is present in file2 if yes  i should print whole line as follows

CIDS9289  8.9  -9873
....

to acheive this wrote python script as follows

infile = open("file1","r")

searchtxt = open("file2.txt","r")

for line in infile.readlines():

    if searchtxt in line:

       print line

but i gives following error

Traceback (most recent call last):
  File "finding_words.py", line 7, in <module>
    if searchtxt in line:
TypeError: 'in <string>' requires string as left operand, not file

I know im doing very simple mistake but not able to figure it out can anybody tell how to solve this..

THanks in advance

NI

Body:
The problem is you have your search backwards -- instead of looking to see if your line from the first file is in the second, you are asking if the entire second file is in the line from the first file.  You need to loop over the second file, checking to see if the key that starts each line is in the first file data.  Change your code as follows:

infile = open("file1","r")

keys = set()
for line in infile:
    break   # skip first line
for line in infile:
    keys.add(line.strip())   # get rid of trailing newline

searchtxt = open("file2.txt","r")

for line in searchtxt:
    break   # skip first line
for line in searchtxt:
    key, rest = line.split(' ', 1)
    if key in keys:
        print line


问:
Do `overflow-wrap: break-word` and `word-break: break-word` ever behave differently?
My question:

Is there any difference between overflow-wrap: break-word and word-break: break-word?

Non-duplicates:

Here are some existing questions that may appear to be duplicates at first sight but aren't.

What is the difference between "word-break: break-all" versus "word-wrap: break-word" in CSS (That question is about word-break: break-all but my question here is about word-break: break-word)

Difference between overflow-wrap and word-break? (That question asks about overflow-wrap and word-break attributes but my question here is about the break-word value for this attributes in particular. Also, that question is mysteriously marked as a duplicate of the previous question even though it is unrelated.)

Code:

I wrote this code snippet that appears to show that both overflow-wrap: break-word and word-break: break-word behave the same way. But I don't know for sure if I have accounted for all cases. Maybe there is a case in which they behave differently?

.ow {
  overflow-wrap: break-word;
  background: lightgreen;
}

.wb {
  word-break: break-word;
  background: lightblue;
}

div {
  width: 5em;
  display: inline-block;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="ow">
Honorificabilitudinitatibus califragilisticexpialidocious Taumatawhakatangihangakoauauotamateaturipukakapikimaungahoronukupokaiwhenuakitanatahu
</div>

<div class="wb">
Honorificabilitudinitatibus califragilisticexpialidocious Taumatawhakatangihangakoauauotamateaturipukakapikimaungahoronukupokaiwhenuakitanatahu
</div>

<div class="ow">
Most words are short and don't need to break. But Antidisestablishmentarianism is long.
</div>

<div class="wb">
Most words are short and don't need to break. But Antidisestablishmentarianism is long.
</div></code>```

Browser support:

https://developer.mozilla.org/en-US/docs/Web/CSS/overflow-wrap#Browser_compatibility shows that overflow-wrap: break-word is supported since Chrome 23, Edge 18, Firefox 49, Safari 6.1. It isn't supported in IE. (I am ignoring the non-standard name word-wrap here. I care only about the standard name.)

https://developer.mozilla.org/en-US/docs/Web/CSS/word-break#Browser_compatibility shows that word-break: break-word is supported since Chrome 1, Firefox 67, Safari 3. It isn't supported in IE and Edge.

Considering the browser support matrix, it looks like overflow-wrap: break-word works with all modern browsers.

What I want to know if you can imagine any type of text or HTML that would make overflow-wrap: break-word and word-break: break-word behave differently?

答:
As written in documentation, word-break: break-word behaves as word-break: normal combined with overflow-wrap: anywhere, but overwrites actual overflow-wrap value.

Documentation for overflow-wrap states that anywhere allows soft wraps (for example, on spaces), introduced by hard wraps, while word-break doesn't.

This means, that if the container has with depending on content size, anywhere will calculate width as if there are no overflowing words and then cut them to fit the container, while word-break will consider overflowing words as a reason to make the container as wide as possible.

In the example, the width is set as the longest word in the first sentence for word-break: break-word and overflow-wrap: anywhere, while overflow-wrap: break-word forces width to reach the limit, as there is a long word in the second sentence.

.owbw {
  overflow-wrap: break-word;
}

.owaw {
  overflow-wrap: anywhere;
}

.wbbw {
  word-break: break-word;
}

div {
  width: min-content;
  max-width: 150px;
  display: inline-block;
  background: lightgreen;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><h3>overflow-wrap: break-word</h3>
<div>
This text has no reason to take the max width. <b  class="owbw">The word AVeryLongWordWithoutAnyPlacesToBreakIt might cause it in some cases.</b>
</div><br>

<h3>overflow-wrap: anywhere</h3>
<div>
This text has no reason to take the max width. <b  class="owaw">The word AVeryLongWordWithoutAnyPlacesToBreakIt might cause it in some cases.</b>
</div><br>

<h3>word-break: break-word</h3>
<div>
This text has no reason to take the max width. <b  class="wbbw">The word AVeryLongWordWithoutAnyPlacesToBreakIt might cause it in some cases.</b>
</div></code>```

Body:
My question:

Is there any difference between overflow-wrap: break-word and word-break: break-word?

Non-duplicates:

Here are some existing questions that may appear to be duplicates at first sight but aren't.

What is the difference between "word-break: break-all" versus "word-wrap: break-word" in CSS (That question is about word-break: break-all but my question here is about word-break: break-word)

Difference between overflow-wrap and word-break? (That question asks about overflow-wrap and word-break attributes but my question here is about the break-word value for this attributes in particular. Also, that question is mysteriously marked as a duplicate of the previous question even though it is unrelated.)

Code:

I wrote this code snippet that appears to show that both overflow-wrap: break-word and word-break: break-word behave the same way. But I don't know for sure if I have accounted for all cases. Maybe there is a case in which they behave differently?

.ow {
  overflow-wrap: break-word;
  background: lightgreen;
}

.wb {
  word-break: break-word;
  background: lightblue;
}

div {
  width: 5em;
  display: inline-block;
}

Honorificabilitudinitatibus califragilisticexpialidocious Taumatawhakatangihangakoauauotamateaturipukakapikimaungahoronukupokaiwhenuakitanatahu

Honorificabilitudinitatibus califragilisticexpialidocious Taumatawhakatangihangakoauauotamateaturipukakapikimaungahoronukupokaiwhenuakitanatahu

Most words are short and don't need to break. But Antidisestablishmentarianism is long.

Most words are short and don't need to break. But Antidisestablishmentarianism is long.

Browser support:

https://developer.mozilla.org/en-US/docs/Web/CSS/overflow-wrap#Browser_compatibility shows that overflow-wrap: break-word is supported since Chrome 23, Edge 18, Firefox 49, Safari 6.1. It isn't supported in IE. (I am ignoring the non-standard name word-wrap here. I care only about the standard name.)

https://developer.mozilla.org/en-US/docs/Web/CSS/word-break#Browser_compatibility shows that word-break: break-word is supported since Chrome 1, Firefox 67, Safari 3. It isn't supported in IE and Edge.

Considering the browser support matrix, it looks like overflow-wrap: break-word works with all modern browsers.

What I want to know if you can imagine any type of text or HTML that would make overflow-wrap: break-word and word-break: break-word behave differently?

Body:
As written in documentation, word-break: break-word behaves as word-break: normal combined with overflow-wrap: anywhere, but overwrites actual overflow-wrap value.

Documentation for overflow-wrap states that anywhere allows soft wraps (for example, on spaces), introduced by hard wraps, while word-break doesn't.

This means, that if the container has with depending on content size, anywhere will calculate width as if there are no overflowing words and then cut them to fit the container, while word-break will consider overflowing words as a reason to make the container as wide as possible.

In the example, the width is set as the longest word in the first sentence for word-break: break-word and overflow-wrap: anywhere, while overflow-wrap: break-word forces width to reach the limit, as there is a long word in the second sentence.

.owbw {
  overflow-wrap: break-word;
}

.owaw {
  overflow-wrap: anywhere;
}

.wbbw {
  word-break: break-word;
}

div {
  width: min-content;
  max-width: 150px;
  display: inline-block;
  background: lightgreen;
}

<h3>overflow-wrap: break-word</h3>
<div>
This text has no reason to take the max width. <b  class="owbw">The word AVeryLongWordWithoutAnyPlacesToBreakIt might cause it in some cases.</b>
</div><br>

<h3>overflow-wrap: anywhere</h3>
<div>
This text has no reason to take the max width. <b  class="owaw">The word AVeryLongWordWithoutAnyPlacesToBreakIt might cause it in some cases.</b>
</div><br>

<h3>word-break: break-word</h3>
<div>
This text has no reason to take the max width. <b  class="wbbw">The word AVeryLongWordWithoutAnyPlacesToBreakIt might cause it in some cases.</b>
</div>


问:
The FastCGI process exited unexpectedly - (Django iis hosting)
I am following this tutorial to hosting my django application on windows IIS Manager.
After following all steps from the tutorial I have got the following HTTP Error 500.0 - Internal Server Error

Is there any way to solve the issue?? I didn't find any solution for this...

I am using,

```<code>Python==3.10.0
Django==3.2.8
wfastcgi==3.0.0
IIS 10.0.17763.1
</code>```

答:
I had this same issue (Error code 0x00000067) and have been beating my head against a wall for 24 hours. I am new to Windows servers, but have been deploying Django Apps on Linux servers for over a decade.

In my case, I had deviated from the Johnnyboycurtis tutorial you referenced in a few ways:

I tried to install every python package in a virtual environment

I did not install Python at C:\, but rather hidden under my user's AppData\local\Programs\Python dir (the default)

I am assuming that your app works when running the Django Development server (py manage.py runserver -> http://localhost:8000 ) your app looks as expected (when DEBUG = True in settings.py)

Fixing my code install meant taking the following steps:

Navigating to C:\Users\MyUserName\AppData\local\Programs\Python, and following Johnnyboycurtis' instructions (but on Python310 instead of Python37) I added permissions for my AppPool to run Python.

I had to install wfastcgi OUTSIDE of my virtual environment:

deactivate (if you have a python virtual environment activated)

py -m pip install wfastcgi

Note that I did NOT have to change any other settings that were assuming my virtual environment:

web.config: 'scriptProcessor' still points to a python.exe and wfastcgi.py inside my virtual environment

IIS FastCGI Settings 'Full Path' and 'Arguments' both refer to files in my virtual environment

Body:
I am following this tutorial to hosting my django application on windows IIS Manager.
After following all steps from the tutorial I have got the following HTTP Error 500.0 - Internal Server Error

Is there any way to solve the issue?? I didn't find any solution for this...

I am using,

Python==3.10.0
Django==3.2.8
wfastcgi==3.0.0
IIS 10.0.17763.1


问:
How to make a list using strings from another list?
So, in this code, I'm trying to make list_1 a list of 8 strings from alp_list where no strings are the same, and to delete the items in list_1 from alp_list for more codes. I'm not sure what's the best way to do this.

```<code>import random

alp_list = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']
a = 0
list_1 = []
while a < 9:
    random_alp = random.choices(alp_list)
    list_1.append(random_alp)
    alp_list.remove(random_alp)
    a += 1
print (list_1)
</code>```

答:
You may use a preexisting function:

```<code>list_1 = random.sample(alp_list, 8)
</code>```

To delete the items from the original list, you may go with:

```<code>for item in list_1:
    alp_list.remove(item)
</code>```

Body:
So, in this code, I'm trying to make list_1 a list of 8 strings from alp_list where no strings are the same, and to delete the items in list_1 from alp_list for more codes. I'm not sure what's the best way to do this.

import random

alp_list = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']
a = 0
list_1 = []
while a < 9:
    random_alp = random.choices(alp_list)
    list_1.append(random_alp)
    alp_list.remove(random_alp)
    a += 1
print (list_1)

Body:
You may use a preexisting function:

list_1 = random.sample(alp_list, 8)

To delete the items from the original list, you may go with:

for item in list_1:
    alp_list.remove(item)


问:
Python byte array to bit array
I want to parse some data with Python and scapy.
Therefor I have to analyse single bits. But at the moment I have for example UDP packets with some payload like:

```<code>bytes = b'\x18\x00\x03\x61\xFF\xFF\x00\x05\x42\xFF\xFF\xFF\xFF'
</code>```

Is there any elegant way to convert the bytes so that I can access single bits like:

```<code>bytes_as_bits = convert(bytes)
bit_at_index_42 = bytes_as_bits[42]
</code>```

答:
I would just use a simple lambda expression to convert the bytes to a string:

```<code>>>> bytes = b'\x18\x00\x03\x61\xFF\xFF\x00\x05\x42\xFF\xFF\xFF\xFF'
>>> convert = lambda x: f"{int.from_bytes(x, 'big'):b}"
>>> bytes_as_bits = convert(bytes)
>>> bytes_as_bits[42]
'1'
>>> _
</code>```

'big' is the byteorder to be used. The official python documentation describes it as follows:

The byteorder argument determines the byte order used to represent the integer. If byteorder is "big", the most significant byte is at the beginning of the byte array. If byteorder is "little", the most significant byte is at the end of the byte array. To request the native byte order of the host system, use sys.byteorder as the byte order value.

Title: Python byte array to bit array

Body:
I want to parse some data with Python and scapy.
Therefor I have to analyse single bits. But at the moment I have for example UDP packets with some payload like:

bytes = b'\x18\x00\x03\x61\xFF\xFF\x00\x05\x42\xFF\xFF\xFF\xFF'

Is there any elegant way to convert the bytes so that I can access single bits like:

bytes_as_bits = convert(bytes)
bit_at_index_42 = bytes_as_bits[42]

Body:
I would just use a simple lambda expression to convert the bytes to a string:

>>> bytes = b'\x18\x00\x03\x61\xFF\xFF\x00\x05\x42\xFF\xFF\xFF\xFF'
>>> convert = lambda x: f"{int.from_bytes(x, 'big'):b}"
>>> bytes_as_bits = convert(bytes)
>>> bytes_as_bits[42]
'1'
>>> _

'big' is the byteorder to be used. The official python documentation describes it as follows:

The byteorder argument determines the byte order used to represent the integer. If byteorder is "big", the most significant byte is at the beginning of the byte array. If byteorder is "little", the most significant byte is at the end of the byte array. To request the native byte order of the host system, use sys.byteorder as the byte order value.


问:
Iterating over list creates endless loop and extends list even though it should not
I iterate over a Sublist (A). A has a defined lenght. Then, i extend another list (B) with the values of (A). For some reason, the first sublist (A) gets extended by the value i extend the other list (B) by.

I have absolutly no idea why this would happen and I'd be very thankfull for help regarding this issue.

```<code>combinations_list = [[[[1, 0], [], -3], [[0, 2], [], -3], [[2, 1], [], -3], [[0, 3], [], -3]]]

for A in combinations_list:
    B = []

    for i in range(len(A)):
        for element in A[i][0]:

            if B == []:
                B.extend(A[i])

            else:
                if element in B[0]:
                    for e in A[i][0]: #Endless loop, A[i][0] gets extended by value of e
                        B[0].extend([e])

</code>```

答:
You were appending a shallow copy of A's sublists into B. This means that when you were changing B in the last loop, you were actually also changing elements of A.. so A just kept growing and the loop kept iterating.

To avoid it, use deepcopy from the copy module - it creates an actual, independent copy of As lists so now when you change them through B, only B will have them,

```<code>import copy

combinations_list = [[[[1, 0], [], -3], [[0, 2], [], -3], [[2, 1], [], -3], [[0, 3], [], -3]]]

for A in combinations_list:
    B = []
    for i in range(len(A)):
        for element in A[i][0]:
            print(B)
            if B == []:
                B.extend(copy.deepcopy(A[i]))
            else:
                if element in B[0]:
                    for e in A[i][0]:
                        B[0].append([e])
</code>```

Body:
I iterate over a Sublist (A). A has a defined lenght. Then, i extend another list (B) with the values of (A). For some reason, the first sublist (A) gets extended by the value i extend the other list (B) by.

I have absolutly no idea why this would happen and I'd be very thankfull for help regarding this issue.

combinations_list = [[[[1, 0], [], -3], [[0, 2], [], -3], [[2, 1], [], -3], [[0, 3], [], -3]]]

for A in combinations_list:
    B = []

    for i in range(len(A)):
        for element in A[i][0]:

            if B == []:
                B.extend(A[i])

            else:
                if element in B[0]:
                    for e in A[i][0]: #Endless loop, A[i][0] gets extended by value of e
                        B[0].extend([e])

Body:
You were appending a shallow copy of A's sublists into B. This means that when you were changing B in the last loop, you were actually also changing elements of A.. so A just kept growing and the loop kept iterating.

To avoid it, use deepcopy from the copy module - it creates an actual, independent copy of As lists so now when you change them through B, only B will have them,

import copy

combinations_list = [[[[1, 0], [], -3], [[0, 2], [], -3], [[2, 1], [], -3], [[0, 3], [], -3]]]

for A in combinations_list:
    B = []
    for i in range(len(A)):
        for element in A[i][0]:
            print(B)
            if B == []:
                B.extend(copy.deepcopy(A[i]))
            else:
                if element in B[0]:
                    for e in A[i][0]:
                        B[0].append([e])


问:
What return this function in typescript?
When I hover on the keyword 'function' the description says:

"(local function)(this: any, next: (err?: mongoose.CallbackError | undefined) => void): Promise<void>"

So does It return a Promise<void> or a simple <void>? I can't even understand what does this function returns? And to be honest I don't understand really well the concept of Promise<void>...

userSchema.pre('save', async function (next) {

    let user = this as UserDocument;
    if(!user.isModified('password')){
        return next();
    }

    const salt = await bcrypt.genSalt(config.get<number>('saltWorkFactor'));
    const hash = await bcrypt.hash(user.password, salt);

    user.password = hash;
    return next();

})
```

答:
This question is really interesting. Your function returns a Promise<void>, which is compatible with the void return type that pre is expecting, but Mongoose is quietly smart enough to know what to do with your Promise so you don't even have to call next at all.

First some background:

void has a special meaning in TypeScript to mean that the return value could be any value; the value is frequently undefined (because that's what a function returns without a return statement) but it doesn't have to be. As in the TypeScript FAQ, this makes it convenient to accept or pass functions that return a value by indicating the return value is unused. If you need to supply a function with return type void, you could pass back a function that returns a string, Promise<void>, Promise<SomeObject>, null, undefined, or anything else.

All async functions return Promises, and this is no exception. A Promise<number> is a Promise that says that its then function will receive a number; a Promise<void> is a Promise that doesn't tell you anything about what its then function receives. The then function will still be called, unless it has an error to catch; you just don't know much about its argument.

In Mongoose's types, pre takes a PreSaveMiddlewareFunction<T> function, which is the type of the function you wrote. It accepts a function called next and returns void: Mongoose claims not to care what you return. Your middleware function is allowed to be asynchronous; when you're done you're expected to call next (with an error object, if you have one), and that call to next also returns void.

Your function passed to pre returns type Promise<void>: The function is async so it absolutely returns a promise, and your return next(); means that the Promise resolves to whatever next returns, which is defined as void. You don't know what next returns and shouldn't care about it. You don't even need to return next(), you just need to call it: It's just a callback so you can tell Mongoose your middleware is done and report any errors.

So your async function returns Promise<void>, but that works with the definition of pre: pre doesn't care what kind of return value your function has (void) as long as you call next to indicate you're done.

But wait! Reporting that your asynchronous function is done and whether or not there were errors is exactly the problem that Promises were designed to solve, and the next callback pattern is exactly the kind of pattern that Promises were designed to replace. If you're returning a Promise, why would you need to call next at all when Mongoose can just watch the promise you return?

In fact, in Mongoose 5.x or later, that's exactly what happens: If the function you pass into pre returns a Promise, then you can use that instead of calling next. You can still call next manually for compatibility's sake, but in your case you could delete return next() and everything would keep working. See the middleware docs:

In mongoose 5.x, instead of calling next() manually, you can use a function that returns a promise. In particular, you can use async/await.

```<code>schema.pre('save', function() {
  return doStuff().
    then(() => doMoreStuff());
});

// Or, in Node.js >= 7.6.0:
schema.pre('save', async function() {
  await doStuff();
  await doMoreStuff();
});
</code>```

The docs further explain why return next() is a pattern at all:

If you use next(), the next() call does not stop the rest of the code in your middleware function from executing. Use the early return pattern to prevent the rest of your middleware function from running when you call next().

```<code>const schema = new Schema(..);
schema.pre('save', function(next) {
  if (foo()) {
    console.log('calling next!');
    // `return next();` will make sure the rest of this function doesn't run
    /*return*/ next();
  }
  // Unless you comment out the `return` above, 'after next' will print
  console.log('after next');
});
</code>```

In summary, the expected return type of void is compatible with the fact that you're returning a Promise<void>, but it hides the fact that recent versions of Mongoose are smart enough to check whether you're returning a Promise and do the right thing without needing a call to next. They're two different styles that both work.

Body:
This question is really interesting. Your function returns a Promise<void>, which is compatible with the void return type that pre is expecting, but Mongoose is quietly smart enough to know what to do with your Promise so you don't even have to call next at all.

First some background:

void has a special meaning in TypeScript to mean that the return value could be any value; the value is frequently undefined (because that's what a function returns without a return statement) but it doesn't have to be. As in the TypeScript FAQ, this makes it convenient to accept or pass functions that return a value by indicating the return value is unused. If you need to supply a function with return type void, you could pass back a function that returns a string, Promise<void>, Promise<SomeObject>, null, undefined, or anything else.

All async functions return Promises, and this is no exception. A Promise<number> is a Promise that says that its then function will receive a number; a Promise<void> is a Promise that doesn't tell you anything about what its then function receives. The then function will still be called, unless it has an error to catch; you just don't know much about its argument.

In Mongoose's types, pre takes a PreSaveMiddlewareFunction<T> function, which is the type of the function you wrote. It accepts a function called next and returns void: Mongoose claims not to care what you return. Your middleware function is allowed to be asynchronous; when you're done you're expected to call next (with an error object, if you have one), and that call to next also returns void.

Your function passed to pre returns type Promise<void>: The function is async so it absolutely returns a promise, and your return next(); means that the Promise resolves to whatever next returns, which is defined as void. You don't know what next returns and shouldn't care about it. You don't even need to return next(), you just need to call it: It's just a callback so you can tell Mongoose your middleware is done and report any errors.

So your async function returns Promise<void>, but that works with the definition of pre: pre doesn't care what kind of return value your function has (void) as long as you call next to indicate you're done.

But wait! Reporting that your asynchronous function is done and whether or not there were errors is exactly the problem that Promises were designed to solve, and the next callback pattern is exactly the kind of pattern that Promises were designed to replace. If you're returning a Promise, why would you need to call next at all when Mongoose can just watch the promise you return?

In fact, in Mongoose 5.x or later, that's exactly what happens: If the function you pass into pre returns a Promise, then you can use that instead of calling next. You can still call next manually for compatibility's sake, but in your case you could delete return next() and everything would keep working. See the middleware docs:

In mongoose 5.x, instead of calling next() manually, you can use a function that returns a promise. In particular, you can use async/await.

schema.pre('save', function() {
  return doStuff().
    then(() => doMoreStuff());
});

// Or, in Node.js >= 7.6.0:
schema.pre('save', async function() {
  await doStuff();
  await doMoreStuff();
});

The docs further explain why return next() is a pattern at all:

If you use next(), the next() call does not stop the rest of the code in your middleware function from executing. Use the early return pattern to prevent the rest of your middleware function from running when you call next().

const schema = new Schema(..);
schema.pre('save', function(next) {
  if (foo()) {
    console.log('calling next!');
    // `return next();` will make sure the rest of this function doesn't run
    /*return*/ next();
  }
  // Unless you comment out the `return` above, 'after next' will print
  console.log('after next');
});

In summary, the expected return type of void is compatible with the fact that you're returning a Promise<void>, but it hides the fact that recent versions of Mongoose are smart enough to check whether you're returning a Promise and do the right thing without needing a call to next. They're two different styles that both work.