问:
How to get linux console $COLUMNS and $ROWS from PHP cli?
I'm currently creating a new neat CLI library for PHP, and i'd like to figure out the width/height of the console it's running in.

I've tried many things like digging through $_ENV, exec("echo $COLUMNS"), etc, but no result, while if i type echo $COLUMNS or $ROWS in bash commandline, it neatly displays the value.

What do i need to do to access this value from PHP?

I'm using .sh scripts like this:

```<code>#!/usr/bin/php -q
<?php

require_once('lib.commandline.php');

class HelloWorld extends CommandLineApp {

  public function main($args) {

       echo('O, Hai.');

    }

}
</code>```

Update
Final solution:

```<code>public function getScreenSize() {
      preg_match_all("/rows.([0-9]+);.columns.([0-9]+);/", strtolower(exec('stty -a |grep columns')), $output);
      if(sizeof($output) == 3) {
        $this->settings['screen']['width'] = $output[1][0];
        $this->settings['screen']['height'] = $output[2][0];
      }
    }
</code>```

答:
For the record, it is my function (PHP 7.2 and higher):

It works in Windows and Linux. In case of errors, it returns 80.

In the case of some wacky or too small value, it returns the minimum value (80)

ps: "mode con" does return the number of lines but it is based on the buffer than on the screen size.

ps2: Oddly but if I run it as a website, it returns 120 (Windows Host).

   function calculateColSize($min=80) {
       try {
            if (PHP_OS_FAMILY === 'Windows') {
                $a1 = shell_exec('mode con');
                /*
                 * Estado para dispositivo CON:
                 * ----------------------------
                 * Líneas:              9001
                 * Columnas:            85
                 * Ritmo del teclado:   31
                 * Retardo del teclado: 1
                 * Página de códigos:    65001
                 */
                $arr = explode("\n", $a1);
                $col = trim(explode(':', $arr[4])[1]);

            } else {
                $col = exec('tput cols');
                /*
                 * 184
                 */
            }
        } catch (Exception $ex) {
            $col = 80;
        }
    }
```

ContentLicense: CC BY-SA 2.5

Body:
I'm currently creating a new neat CLI library for PHP, and i'd like to figure out the width/height of the console it's running in.

I've tried many things like digging through $_ENV, exec("echo $COLUMNS"), etc, but no result, while if i type echo $COLUMNS or $ROWS in bash commandline, it neatly displays the value.

What do i need to do to access this value from PHP?

I'm using .sh scripts like this:

#!/usr/bin/php -q
<?php

require_once('lib.commandline.php');

class HelloWorld extends CommandLineApp {

  public function main($args) {

       echo('O, Hai.');

    }

}

Update
Final solution:

public function getScreenSize() {
      preg_match_all("/rows.([0-9]+);.columns.([0-9]+);/", strtolower(exec('stty -a |grep columns')), $output);
      if(sizeof($output) == 3) {
        $this->settings['screen']['width'] = $output[1][0];
        $this->settings['screen']['height'] = $output[2][0];
      }
    }


来源: stackexchange

问:
NoReverseMatch Django using pk
Reverse for 'update' with keyword arguments '{'pk': ''}' not found. 1 pattern(s) tried: ['basic_app/update/(?P[0-9]+)/\Z']

```<code>9     <p>Location: {{school_detail.location}} </p>
10    <h3>Students:</h3>
11    {% for student in school_detail.students.all %}
12    <p>{{student.name}} who is {{student.age}} years old</p>
13    {% endfor %}
14
15
16  </div>
17
18  <div class="container">
19  <p><a class='btn btn-warning' href="{% url 'basic_app:update' pk=school_details.pk %}">Update</a></p>
20
21  </div>
22  {% endblock %}
</code>```

Here is urls.py

```<code>from django.urls import path
from basic_app import views
app_name='basic_app'

urlpatterns = [
    path('',views.SchoolListView.as_view(),name='list'),
    path('<int:pk>/',views.SchoolDetailView.as_view(),name='detail'),
    path('create/',views.SchoolCreateView.as_view(),name='create'),
    path('update/<int:pk>/',views.SchoolUpdateView.as_view(),name='update'),
    ]
</code>```

答:
Try this:</p>
```<code>href="{% url 'basic_app:update' school_detail.pk %}"
</code>```

ContentLicense: CC BY-SA 4.0

Title: NoReverseMatch Django using pk

Body:
Reverse for 'update' with keyword arguments '{'pk': ''}' not found. 1 pattern(s) tried: ['basic_app/update/(?P[0-9]+)/\Z']

9
Location: {{school_detail.location}}

10
Students:

11    {% for student in school_detail.students.all %}
12
{{student.name}} who is {{student.age}} years old

13    {% endfor %}
14
15
16

17
18

19
Update

20
21

22  {% endblock %}

Here is urls.py

from django.urls import path
from basic_app import views
app_name='basic_app'

urlpatterns = [
    path('',views.SchoolListView.as_view(),name='list'),
    path('<int:pk>/',views.SchoolDetailView.as_view(),name='detail'),
    path('create/',views.SchoolCreateView.as_view(),name='create'),
    path('update/<int:pk>/',views.SchoolUpdateView.as_view(),name='update'),
    ]

Body:
Try this:

href="{% url 'basic_app:update' school_detail.pk %}"


问:
Get value of field from referenced model displayed in Django Admin site
I have two models - Contract and Supplier. Each supplier supplies a type of commodity. These are defined as follows:

```<code>class CommodityType(models.Model):
    name = models.CharField(max_length=64)

    def __unicode__(self):
        return self.name

class Supplier(models.Model):
    name = models.CharField(max_length=64)
    type = models.ForeignKey(CommodityType)

    def __unicode__(self):
        return self.name

    class Meta:
        ordering = ['type', 'name']

class Contract(models.Model):
    supplier = models.ForeignKey(Supplier)
    clientNumber = models.CharField(max_length=32)

    def __unicode__(self):
        return u'%s, %s' % (self.supplier, self.clientNumber)
</code>```

I want to have a listing of the Contracts in the Django Admin site. For each of the Contracts, I want to have the type from the referenced Supplier displayed. So, for example, if the associated supplier supplies Electricity, then I want to have that displayed in the listing of Contracts.

However, I cannot seem to find how this is done. I found this answer, but trying that gives me an ImproperlyConfigured error.

How can this be done?

答:
Recently, a library called django-related-admin released, which allows you to use foreign key attributes in Django admin change list list_display with '__'  so easily, Specifically for this question, how to use this library in admin.py module is as follows:

admin.py

from related_admin import RelatedFieldAdmin
from related_admin import getter_for_related_field

class ContractAdmin(RelatedFieldAdmin):
    # these fields will work automatically (and boolean fields will display an icon):
    list_display = ('clientNumber','supplier__type__name')

    # or you can also define them manually if you need to override short_description or boolean parameter:
    supplierType = getter_for_related_field('supplier__type__name', short_description='supplier type', boolean=False)
```

ContentLicense: CC BY-SA 3.0

Body:
I have two models - Contract and Supplier. Each supplier supplies a type of commodity. These are defined as follows:

class CommodityType(models.Model):
    name = models.CharField(max_length=64)

    def __unicode__(self):
        return self.name

class Supplier(models.Model):
    name = models.CharField(max_length=64)
    type = models.ForeignKey(CommodityType)

    def __unicode__(self):
        return self.name

    class Meta:
        ordering = ['type', 'name']

class Contract(models.Model):
    supplier = models.ForeignKey(Supplier)
    clientNumber = models.CharField(max_length=32)

    def __unicode__(self):
        return u'%s, %s' % (self.supplier, self.clientNumber)

I want to have a listing of the Contracts in the Django Admin site. For each of the Contracts, I want to have the type from the referenced Supplier displayed. So, for example, if the associated supplier supplies Electricity, then I want to have that displayed in the listing of Contracts.

However, I cannot seem to find how this is done. I found this answer, but trying that gives me an ImproperlyConfigured error.

How can this be done?


问:
Return random value for each row from different table
I'm trying to get random name for each row, but it just shows same random value for every row. What am I missing?

```<code>SELECT TOP (1000)  v.id,v.[Name], RandomName
FROM [V3_Priva].[dbo].[Vehicle] v
cross join
(Select top 1 ISNULL([Description_cs-CZ], [Description]) RandomName
from crm.Enumeration e
join crm.EnumerationType et on e.EnumerationType_FK = et.Id
where  EnumerationType_FK = 12
order by NEWID()) RandomName
</code>```

Result table

答:
Try using something like the following to drive your lookup.

```<code>DECLARE @Rows AS TABLE ( I INT NOT NULL )

DECLARE @Vals AS TABLE ( ID INT IDENTITY, Val NVARCHAR(255) NOT NULL )

INSERT INTO @Rows
VALUES ( 0 )
,      ( 1 )
,      ( 2 )
,      ( 3 )
,      ( 4 )
,      ( 5 )
,      ( 6 )
,      ( 7 )
,      ( 8 )
,      ( 9 )

INSERT INTO @Vals
VALUES ( 'Apple' )
,      ( 'Banana' )
,      ( 'Peach' )
,      ( 'Plum' )
,      ( 'Pear' )

WITH cte AS ( SELECT    *, ABS(CHECKSUM(NEWID())) % 5 ID FROM  @Rows )
SELECT  cte.I
,       cte.ID
,       V.ID
,       V.Val
  FROM  cte
  JOIN  @Vals V ON V.ID = cte.ID  + 1
 ORDER BY I
</code>```

This way new ID is generated for each row, rather than once for the lookup.

Body:
I'm trying to get random name for each row, but it just shows same random value for every row. What am I missing?

SELECT TOP (1000)  v.id,v.[Name], RandomName
FROM [V3_Priva].[dbo].[Vehicle] v
cross join
(Select top 1 ISNULL([Description_cs-CZ], [Description]) RandomName
from crm.Enumeration e
join crm.EnumerationType et on e.EnumerationType_FK = et.Id
where  EnumerationType_FK = 12
order by NEWID()) RandomName

Result table

Body:
Try using something like the following to drive your lookup.

DECLARE @Rows AS TABLE ( I INT NOT NULL )

DECLARE @Vals AS TABLE ( ID INT IDENTITY, Val NVARCHAR(255) NOT NULL )

INSERT INTO @Rows
VALUES ( 0 )
,      ( 1 )
,      ( 2 )
,      ( 3 )
,      ( 4 )
,      ( 5 )
,      ( 6 )
,      ( 7 )
,      ( 8 )
,      ( 9 )

INSERT INTO @Vals
VALUES ( 'Apple' )
,      ( 'Banana' )
,      ( 'Peach' )
,      ( 'Plum' )
,      ( 'Pear' )

WITH cte AS ( SELECT    *, ABS(CHECKSUM(NEWID())) % 5 ID FROM  @Rows )
SELECT  cte.I
,       cte.ID
,       V.ID
,       V.Val
  FROM  cte
  JOIN  @Vals V ON V.ID = cte.ID  + 1
 ORDER BY I

This way new ID is generated for each row, rather than once for the lookup.


问:
Visual Studio not installed; this is necessary for Windows development
My Flutter Doctor is saying:

Visual Studio - develop for Windows

X Visual Studio not installed; this is necessary for Windows development.
  Download at https://visualstudio.microsoft.com/downloads/.
  Please install the "Desktop development with C++" workload, including all
  of its default components.
```

How can I fix this problem?

答:
It's basically saying that if you want to develop your Flutter application for Windows you will need to install Visual Studio 2022 and while installing Visual Studio 2022 you will need to download this: Desktop development with C++

Also, you have to install the third link in this: Visual-studio

You could also get desktop development with the C++ tool after installing Visual Studio and then navigating to tool → Get tools and features → Desktop development with C++.

Body:
My Flutter Doctor is saying:

Visual Studio - develop for Windows

X Visual Studio not installed; this is necessary for Windows development.
  Download at https://visualstudio.microsoft.com/downloads/.
  Please install the "Desktop development with C++" workload, including all
  of its default components.

How can I fix this problem?


问:
How to create a deep insert structure using Olingo Client?
How to POST the following JSON structure using Apache OLINGO client? What is the best way to build up this structure? Are there any examples?</p>
```<code>{
"itemNumber": "ITEM1"

"lines": [

    {
        componentNumber":   "COMPONENT1"
    },
    {
        componentNumber":   "COMPONENT2"
    }
]
}
</code>```

答:
The following Java example using the Olingo Client works for me to post the following JSON structure:

```<code>{
"itemNumber": "ITEM1"

    "lines": [

        {
            componentNumber":   "COMPONENT1"
        },
        {
            componentNumber":   "COMPONENT2"
        }
    ]
    }
</code>```

Java code using OLINGO CLient

```<code>public void deepInsertExample(){
        //Initiate the ODATA client
    ODataClient client = ODataClientFactory.getClient();
        client.getConfiguration();
        getClient().getObjectFactory();
        //Initiate the Client Object Factory
        ClientObjectFactory factory = getClient().getObjectFactory();
        //Create Line Item 1
        ClientEntity lineItem1 = factory.newEntity(new FullQualifiedName("ODATA.LineItem"));
        lineItem1.getProperties()
                .add(factory.newPrimitiveProperty("componentNumber", factory.newPrimitiveValueBuilder().buildString("COMPONENT2")));
        //Create Line Item 2
    ClientEntity   lineItem2 = factory.newEntity(new FullQualifiedName("ODATA.LineItem"));
        lineItem2.getProperties()
                .add(factory.newPrimitiveProperty("componentNumber", factory.newPrimitiveValueBuilder().buildString("COMPONENT1")));
        //Initiate the entity set
        ClientEntitySet entitySet = factory.newEntitySet();
        //Add  Line Item 1 and Line Item 2 to the Enity
        entitySet.getEntities().add(lineItem1);
        entitySet.getEntities().add(lineItem2);
        //Create the Lines LInk
        ClientLink linesLink = factory.newDeepInsertEntitySet("Lines", entitySet);
        ClientComplexValue complexValueCreate = factory.newComplexValue("Lines");
        complexValueCreate.getNavigationLinks().add(linesLink);
        //Create the Item object
        ClientEntity item = factory.newEntity(new FullQualifiedName("ODATA.Item"));
    item.getProperties()
                .add(factory.newPrimitiveProperty("itemNumber", factory.newPrimitiveValueBuilder().buildString("ITEM1")));
        //Add the Lines(Entity Set) link to Item Object
        item.addLink(linesLink);
        //Post the Item
        URI absoluteUri = client.newURIBuilder("URL").build();
        ODataEntityCreateRequest<ClientEntity> request = client.getCUDRequestFactory()
                .getEntityCreateRequest(absoluteUri, item);
        request.setAccept("application/json;odata.metadata=minimal");
        request.execute();
 }

</code>```

Body:
How to POST the following JSON structure using Apache OLINGO client? What is the best way to build up this structure? Are there any examples?

{
"itemNumber": "ITEM1"

"lines": [

    {
        componentNumber":   "COMPONENT1"
    },
    {
        componentNumber":   "COMPONENT2"
    }
]
}

Body:
The following Java example using the Olingo Client works for me to post the following JSON structure:

{
"itemNumber": "ITEM1"

    "lines": [

        {
            componentNumber":   "COMPONENT1"
        },
        {
            componentNumber":   "COMPONENT2"
        }
    ]
    }

Java code using OLINGO CLient

public void deepInsertExample(){
        //Initiate the ODATA client
    ODataClient client = ODataClientFactory.getClient();
        client.getConfiguration();
        getClient().getObjectFactory();
        //Initiate the Client Object Factory
        ClientObjectFactory factory = getClient().getObjectFactory();
        //Create Line Item 1
        ClientEntity lineItem1 = factory.newEntity(new FullQualifiedName("ODATA.LineItem"));
        lineItem1.getProperties()
                .add(factory.newPrimitiveProperty("componentNumber", factory.newPrimitiveValueBuilder().buildString("COMPONENT2")));
        //Create Line Item 2
    ClientEntity   lineItem2 = factory.newEntity(new FullQualifiedName("ODATA.LineItem"));
        lineItem2.getProperties()
                .add(factory.newPrimitiveProperty("componentNumber", factory.newPrimitiveValueBuilder().buildString("COMPONENT1")));
        //Initiate the entity set
        ClientEntitySet entitySet = factory.newEntitySet();
        //Add  Line Item 1 and Line Item 2 to the Enity
        entitySet.getEntities().add(lineItem1);
        entitySet.getEntities().add(lineItem2);
        //Create the Lines LInk
        ClientLink linesLink = factory.newDeepInsertEntitySet("Lines", entitySet);
        ClientComplexValue complexValueCreate = factory.newComplexValue("Lines");
        complexValueCreate.getNavigationLinks().add(linesLink);
        //Create the Item object
        ClientEntity item = factory.newEntity(new FullQualifiedName("ODATA.Item"));
    item.getProperties()
                .add(factory.newPrimitiveProperty("itemNumber", factory.newPrimitiveValueBuilder().buildString("ITEM1")));
        //Add the Lines(Entity Set) link to Item Object
        item.addLink(linesLink);
        //Post the Item
        URI absoluteUri = client.newURIBuilder("URL").build();
        ODataEntityCreateRequest<ClientEntity> request = client.getCUDRequestFactory()
                .getEntityCreateRequest(absoluteUri, item);
        request.setAccept("application/json;odata.metadata=minimal");
        request.execute();
 }


问:
Apache shut down unexpectly xampp
I downloaded php 7.4 to replace with php7.3.
I move php 7.4 to xampp folder and rename old php folder with different name.
after that restart apache.

```<code>[Fri Feb 11 12:46:33.751685 2022] [mpm_winnt:notice] [pid 7948:tid 580] AH00418: Parent: Created child process 4032
[Fri Feb 11 12:46:34.268497 2022] [ssl:warn] [pid 4032:tid 580] AH01909: www.example.com:443:0 server certificate does NOT include an ID which matches the server name
[Fri Feb 11 12:46:34.346148 2022] [ssl:warn] [pid 4032:tid 580] AH01909: www.example.com:443:0 server certificate does NOT include an ID which matches the server name
[Fri Feb 11 12:46:34.377653 2022] [mpm_winnt:notice] [pid 4032:tid 580] AH00354: Child: Starting 150 worker threads.
[Fri Feb 11 13:12:35.902924 2022] [php7:error] [pid 4032:tid 1844] [client ::1:53129] PHP Fatal error:  Maximum execution time of 300 seconds exceeded in C:\\xampp\\phpMyAdmin\\libraries\\classes\\Dbal\\DbiMysqli.php on line 246
[Fri Feb 11 15:34:38.829295 2022] [ssl:warn] [pid 11328:tid 568] AH01909: www.example.com:443:0 server certificate does NOT include an ID which matches the server name
[Fri Feb 11 15:34:39.230678 2022] [core:warn] [pid 11328:tid 568] AH00098: pid file C:/xampp/apache/logs/httpd.pid overwritten -- Unclean shutdown of previous Apache run?
[Fri Feb 11 15:34:39.236676 2022] [ssl:warn] [pid 11328:tid 568] AH01909: www.example.com:443:0 server certificate does NOT include an ID which matches the server name
[Fri Feb 11 15:34:39.306825 2022] [mpm_winnt:notice] [pid 11328:tid 568] AH00455: Apache/2.4.51 (Win64) OpenSSL/1.1.1l PHP/7.3.31 configured -- resuming normal operations
[Fri Feb 11 15:34:39.307821 2022] [mpm_winnt:notice] [pid 11328:tid 568] AH00456: Apache Lounge VC15 Server built: Oct  8 2021 10:03:59
[Fri Feb 11 15:34:39.307821 2022] [core:notice] [pid 11328:tid 568] AH00094: Command line: 'c:\\xampp\\apache\\bin\\httpd.exe -d C:/xampp/apache'
[Fri Feb 11 15:34:39.312818 2022] [mpm_winnt:notice] [pid 11328:tid 568] AH00418: Parent: Created child process 8416
[Fri Feb 11 15:34:39.927399 2022] [ssl:warn] [pid 8416:tid 660] AH01909: www.example.com:443:0 server certificate does NOT include an ID which matches the server name
[Fri Feb 11 15:34:40.270899 2022] [ssl:warn] [pid 8416:tid 660] AH01909: www.example.com:443:0 server certificate does NOT include an ID which matches the server name
[Fri Feb 11 15:34:40.302876 2022] [mpm_winnt:notice] [pid 8416:tid 660] AH00354: Child: Starting 150 worker threads.

</code>```

Apache cannot run.
what wrong ?
How can fix

答:
I try help you.

Go in xampp control panel and go in apache->config-> apache(httpd-xampp.conf)
You need change path of "LoadFile" and "LoadModule" to new version of php and new directory. This is an example

LoadFile"D:/xampp/php/php7ts.dll"

LoadFile"D:/xampp/php/libpq.dll"

LoadModule php7_module"D:/xampp/php/php7apache2_4.dll"

I hope I was helpful.
Best regards,

Title: Apache shut down unexpectly xampp

Body:
I downloaded php 7.4 to replace with php7.3.
I move php 7.4 to xampp folder and rename old php folder with different name.
after that restart apache.

[Fri Feb 11 12:46:33.751685 2022] [mpm_winnt:notice] [pid 7948:tid 580] AH00418: Parent: Created child process 4032
[Fri Feb 11 12:46:34.268497 2022] [ssl:warn] [pid 4032:tid 580] AH01909: www.example.com:443:0 server certificate does NOT include an ID which matches the server name
[Fri Feb 11 12:46:34.346148 2022] [ssl:warn] [pid 4032:tid 580] AH01909: www.example.com:443:0 server certificate does NOT include an ID which matches the server name
[Fri Feb 11 12:46:34.377653 2022] [mpm_winnt:notice] [pid 4032:tid 580] AH00354: Child: Starting 150 worker threads.
[Fri Feb 11 13:12:35.902924 2022] [php7:error] [pid 4032:tid 1844] [client ::1:53129] PHP Fatal error:  Maximum execution time of 300 seconds exceeded in C:\\xampp\\phpMyAdmin\\libraries\\classes\\Dbal\\DbiMysqli.php on line 246
[Fri Feb 11 15:34:38.829295 2022] [ssl:warn] [pid 11328:tid 568] AH01909: www.example.com:443:0 server certificate does NOT include an ID which matches the server name
[Fri Feb 11 15:34:39.230678 2022] [core:warn] [pid 11328:tid 568] AH00098: pid file C:/xampp/apache/logs/httpd.pid overwritten -- Unclean shutdown of previous Apache run?
[Fri Feb 11 15:34:39.236676 2022] [ssl:warn] [pid 11328:tid 568] AH01909: www.example.com:443:0 server certificate does NOT include an ID which matches the server name
[Fri Feb 11 15:34:39.306825 2022] [mpm_winnt:notice] [pid 11328:tid 568] AH00455: Apache/2.4.51 (Win64) OpenSSL/1.1.1l PHP/7.3.31 configured -- resuming normal operations
[Fri Feb 11 15:34:39.307821 2022] [mpm_winnt:notice] [pid 11328:tid 568] AH00456: Apache Lounge VC15 Server built: Oct  8 2021 10:03:59
[Fri Feb 11 15:34:39.307821 2022] [core:notice] [pid 11328:tid 568] AH00094: Command line: 'c:\\xampp\\apache\\bin\\httpd.exe -d C:/xampp/apache'
[Fri Feb 11 15:34:39.312818 2022] [mpm_winnt:notice] [pid 11328:tid 568] AH00418: Parent: Created child process 8416
[Fri Feb 11 15:34:39.927399 2022] [ssl:warn] [pid 8416:tid 660] AH01909: www.example.com:443:0 server certificate does NOT include an ID which matches the server name
[Fri Feb 11 15:34:40.270899 2022] [ssl:warn] [pid 8416:tid 660] AH01909: www.example.com:443:0 server certificate does NOT include an ID which matches the server name
[Fri Feb 11 15:34:40.302876 2022] [mpm_winnt:notice] [pid 8416:tid 660] AH00354: Child: Starting 150 worker threads.

Apache cannot run.
what wrong ?
How can fix


问:
React Typescript - Types problem | One component that renders sub component
Parent Component: Font

Sub Component: FontHeading, FontText, FontSubTitle.

```<code>  return (
    <>
      {type === "title" && <FontTitle as={as} variant={variant as HeadingVariants}>{children}</FontTitle>}
      {type === "subtitle" && <FontSubtitle>{children}</FontSubtitle>}
      {type === "iperlink" && <FontIperLink>{children}</FontIperLink>}
    </>
  );

export type IFont = {
  type: 'title' | 'subtitle' | 'link',
  children: React.ReactNode,
  variant: HeadingVariants | TextVariants | LinkVariants;
  setRef?: React.Ref<HTMLDivElement>;
}

export type IFontTitle = {
  as?: "h1" | "h2" | "h3" | "h4" | "h5";
  variant: HeadingVariants
}

export type IFontSubTitle = {
  variant: TextVariants
}

export type IFontLink = {
  href: string;
  variant: LinkVariants;
}
</code>```

How can I tell that if <Field type="title" .... /> then it needs to accept props that are of IFontTitle ? Viceversa with type="variant" or type="link".
Also would be great if it's auto select the correct variant, any help is appreciated..

Thanks

答:
You can use union types for that:</p>
```<code>type SharedProps = {
  children: React.ReactNode,
  setRef?: React.Ref<HTMLDivElement>;
}
type TFontTitle = {
    type: 'title'
    as?: "h1" | "h2" | "h3" | "h4" | "h5";
    variant: HeadingVariants
}
type TFontSubTitle = {
    type: 'subtitle'
    variant: TextVariants
}
type TFontLink = {
    type: 'link'
    href: string;
    variant: LinkVariants;
}
type UnionProps = TFontTitle | TFontSubTitle | TFontLink
type Props = UnionProps & SharedProps
</code>```

Body:
Parent Component: Font

Sub Component: FontHeading, FontText, FontSubTitle.

  return (
    <>
      {type === "title" && <FontTitle as={as} variant={variant as HeadingVariants}>{children}</FontTitle>}
      {type === "subtitle" && <FontSubtitle>{children}</FontSubtitle>}
      {type === "iperlink" && <FontIperLink>{children}</FontIperLink>}
    </>
  );

export type IFont = {
  type: 'title' | 'subtitle' | 'link',
  children: React.ReactNode,
  variant: HeadingVariants | TextVariants | LinkVariants;
  setRef?: React.Ref<HTMLDivElement>;
}

export type IFontTitle = {
  as?: "h1" | "h2" | "h3" | "h4" | "h5";
  variant: HeadingVariants
}

export type IFontSubTitle = {
  variant: TextVariants
}

export type IFontLink = {
  href: string;
  variant: LinkVariants;
}

How can I tell that if <Field type="title" .... /> then it needs to accept props that are of IFontTitle ? Viceversa with type="variant" or type="link".
Also would be great if it's auto select the correct variant, any help is appreciated..

Thanks

Body:
You can use union types for that:

type SharedProps = {
  children: React.ReactNode,
  setRef?: React.Ref<HTMLDivElement>;
}
type TFontTitle = {
    type: 'title'
    as?: "h1" | "h2" | "h3" | "h4" | "h5";
    variant: HeadingVariants
}
type TFontSubTitle = {
    type: 'subtitle'
    variant: TextVariants
}
type TFontLink = {
    type: 'link'
    href: string;
    variant: LinkVariants;
}
type UnionProps = TFontTitle | TFontSubTitle | TFontLink
type Props = UnionProps & SharedProps


问:
How can I 'clean up' a virtualenv?
If I want to keep my venv as clean as possible how can I clean up the stuff I don't need? Let me lay out an example...

Say I try a bunch of new modules...

```<code>pip install foo
pip install bar
pip install foobar
pip install foobarfoo
</code>```

and these modules have some requirements of their own, etc. later I decide on which one I want to use, but then I have a huge list of stuff in my requirement.txt and I can't remember what I need and what I don't, what depends on what, etc.

How can I keep it clean and lean?

答:
Following the answers from @Steve Rossiter and @James Rocker
one could also do a trivial modification and avoid generating a temp file in a one-liner like:

```<code>pip uninstall -y -r <(pip freeze)
</code>```

(I wanted to post this as a comment on the answer, but I don't have enough reputation for that.)

Title: How can I 'clean up' a virtualenv?

Body:
If I want to keep my venv as clean as possible how can I clean up the stuff I don't need? Let me lay out an example...

Say I try a bunch of new modules...

pip install foo
pip install bar
pip install foobar
pip install foobarfoo

and these modules have some requirements of their own, etc. later I decide on which one I want to use, but then I have a huge list of stuff in my requirement.txt and I can't remember what I need and what I don't, what depends on what, etc.

How can I keep it clean and lean?

Body:
Following the answers from @Steve Rossiter and @James Rocker
one could also do a trivial modification and avoid generating a temp file in a one-liner like:

pip uninstall -y -r <(pip freeze)

(I wanted to post this as a comment on the answer, but I don't have enough reputation for that.)


问:
@IBDesignable view doesn't draw background color inside Interface Builder
I'm curious why doesn't this set the backgroundColor to red?

```<code>@IBDesignable class CustomLabel: UIView {

  let view = UIView()

  func setup() {
    backgroundColor = UIColor.red
    view.backgroundColor = UIColor.green
    view.frame = CGRect(x: 0, y: 0, width: 50, height: 50)
    addSubview(view)
  }

  override init(frame: CGRect) {
    super.init(frame: frame)
    setup()
  }
  required init?(coder aDecoder: NSCoder) {
    super.init(coder: aDecoder)
    setup()
  }
}
</code>```

This is the result.

And this is what I expect it to look like.

答:
The logic of init(frame:) and init?(coder:) results in two different renderings in InterfaceBuilder rendering mode because IBDesignablesAgent-iOS which is used to render IBDesignable classes calls init(frame:) and after that it uses "User Defined Run Time Attributes" default / custom values to configure the custom view. So, the backgroundColor set in init(frame:) will be changed by default/custom value of background color set in Interface builder.
In case of run time rendering when app runs on a device or simulator, the init?(coder:) method is used and "setup()" logic is applied after default / custom values from storyboard were applied. In case of creating a custom view from code then init(frame:) method is used but there is no decoding from "User Defined Run Time Attributes" of storyboard because this one does't exists.</p>

Body:
I'm curious why doesn't this set the backgroundColor to red?

@IBDesignable class CustomLabel: UIView {

  let view = UIView()

  func setup() {
    backgroundColor = UIColor.red
    view.backgroundColor = UIColor.green
    view.frame = CGRect(x: 0, y: 0, width: 50, height: 50)
    addSubview(view)
  }

  override init(frame: CGRect) {
    super.init(frame: frame)
    setup()
  }
  required init?(coder aDecoder: NSCoder) {
    super.init(coder: aDecoder)
    setup()
  }
}

This is the result.

And this is what I expect it to look like.


问:
It is necessary to go over an element at least once to execute JS code
I am doing a Connect Four in HTML CSS JS and I want to display a token at the top of the grid if you are hover the grid, align to the column so I put a listener to the grid. But to display this I need to go over all the elements at least one time and then after it will display as expected.

Here's the snippet, I'm sorry for the low quality code

quiJoue = 0;

$('#grille').on("mouseover", function(e) {
  let couleur = quiJoue % 2 === 0 ? "Jaune" : "Rouge";
  let classes = e.target.classList;
  if (classes.contains("top") && classes.contains("pion")) {
    let courant = e.target;
    $(courant).css("background", 'yellow').css("background-size", "contain");
  } else if (classes.contains('pion')) {
    let courant = (e.target);
    let colonne = (e.target.parentNode.classList[2]).split("-")[1];
    $('.cell.row-top.colonne-' + colonne).children().css("background", 'yellow').css("background-size", "contain")
    $(courant).hover(function() {
      $('.cell.row-top.colonne-' + colonne).children().addClass('top_hover');
    }, function() {
      $('.cell.row-top.colonne-' + colonne).children().removeClass('top_hover')
    });
  } else if (classes.contains('cell')) {
    let colonne = (e.target.classList[2]).split("-")[1];
    let courant = (e.target);
    $('.cell.row-top.colonne-' + colonne).children().css("background", 'yellow').css("background-size", "contain")
    $(courant).hover(function() {
      $('.cell.row-top.colonne-' + colonne).children().addClass('top_hover');
    }, function() {
      $('.cell.row-top.colonne-' + colonne).children().removeClass('top_hover')
    });

  }
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.game-board {
  display: grid;
  grid-template-columns: repeat(7, 1fr);
  height: 700px;
  margin: 10px 0 25px;
  width: 700px;
}

.cell {
  align-items: center;
  background: #4370F1;
  display: flex;
  height: 100px;
  justify-content: center;
  width: 100px;
}

.pion {
  background: white;
  background-size: contain;
  border-radius: 50%;
  border: 3px solid black;
  height: 75px;
  width: 75px;
}

.top {
  transition: opacity 50ms linear;
  opacity: 0;
  border: 0;
}

.top:hover {
  transition: opacity 50ms linear;
  background-size: contain;
  opacity: 1;
}

.top_hover {
  transition: opacity 50ms linear;
  background-size: contain;
  opacity: 1;
}

.cell:not(.row-top).red::after {
  background: red;
}

.cell:not(.row-top).yellow::after {
  background: yellow;
}

.cell:not(.row-top).red.win {
  background: red;
}

.cell:not(.row-top).yellow.win {
  background: yellow;
}

.cell.row-top {
  background: rgba(255, 255, 255, 0);
}

.cell.row-top::after {
  border: none;
}

.cell.row-top.red::after {
  background: red;
  border: 3px solid black;
}

.cell.row-top.yellow::after {
  background: yellow;
  border: 3px solid black;
}

.left-border {
  border-left: 3px solid black;
}

.top-border {
  border-top: 3px solid black;
}

.right-border {
  border-right: 3px solid black;
}

.bottom-border {
  border-bottom: 3px solid black;
}

.left-border.top-border {
  border-radius: 10px 0 0 0;
}

.right-border.top-border {
  border-radius: 0 10px 0 0;
}

.right-border.bottom-border {
  border-radius: 0 0 10px 0;
}

.left-border.bottom-border {
  border-radius: 0 0 0 10px;
}</code>```

```

答:
I will try to demonstrate the issue in some bullet points, so let me know if they are not clear enough.

After the compiling process ends and your page load, there are no listeners attached to the game elements.

In the first hover iteration, your code will initialize the event listener dynamically but will not execute it.

After that, you have a listener attached to your element and will fire its callback function from now on.

So, for every hover event after that, your code will work as expected

SOLUTION

We need to attach the event listener to all game elements statically not dynamically. so here is the JS code we need.

```<code>    $(".pion").hover(function(e) {
      const colonne = (e.target.parentNode.classList[2]).split("-")[1];
      $('.cell.row-top.colonne-' + colonne).children().toggleClass('top_hover');
    })
</code>```

It will select all elements with pion class and will attach them our hover event that toggles the class name of the related colonne number.

Note: I have hard-coded the background color of the token to yellow in the HTML snippet for all columns. you can remove it and handle the logic of Jaune and Rouge

```<code><div class="pion justify-content-center d-flex top" style="background: yellow url("../img/pionJaune.png") repeat scroll center center / contain;"></div>
</code>```

$(".pion").hover(function(e) {
  const colonne = (e.target.parentNode.classList[2]).split("-")[1];
  $('.cell.row-top.colonne-' + colonne).children().toggleClass('top_hover');
})```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.game-board {
  display: grid;
  grid-template-columns: repeat(7, 1fr);
  height: 700px;
  margin: 10px 0 25px;
  width: 700px;
}

.cell {
  align-items: center;
  background: #4370F1;
  display: flex;
  height: 100px;
  justify-content: center;
  width: 100px;
}

.pion {
  background: white;
  background-size: contain;
  border-radius: 50%;
  border: 3px solid black;
  height: 75px;
  width: 75px;
}

.top {
  transition: opacity 50ms linear;
  opacity: 0;
  border: 0;
}

.top:hover {
  transition: opacity 50ms linear;
  background-size: contain;
  opacity: 1;
}

.top_hover {
  transition: opacity 50ms linear;
  background-size: contain;
  opacity: 1;
}

.cell:not(.row-top).red::after {
  background: red;
}

.cell:not(.row-top).yellow::after {
  background: yellow;
}

.cell:not(.row-top).red.win {
  background: red;
}

.cell:not(.row-top).yellow.win {
  background: yellow;
}

.cell.row-top {
  background: rgba(255, 255, 255, 0);
}

.cell.row-top::after {
  border: none;
}

.cell.row-top.red::after {
  background: red;
  border: 3px solid black;
}

.cell.row-top.yellow::after {
  background: yellow;
  border: 3px solid black;
}

.left-border {
  border-left: 3px solid black;
}

.top-border {
  border-top: 3px solid black;
}

.right-border {
  border-right: 3px solid black;
}

.bottom-border {
  border-bottom: 3px solid black;
}

.left-border.top-border {
  border-radius: 10px 0 0 0;
}

.right-border.top-border {
  border-radius: 0 10px 0 0;
}

.right-border.bottom-border {
  border-radius: 0 0 10px 0;
}

.left-border.bottom-border {
  border-radius: 0 0 0 10px;
}</code>```

```

Body:
I am doing a Connect Four in HTML CSS JS and I want to display a token at the top of the grid if you are hover the grid, align to the column so I put a listener to the grid. But to display this I need to go over all the elements at least one time and then after it will display as expected.

Here's the snippet, I'm sorry for the low quality code

quiJoue = 0;

$('#grille').on("mouseover", function(e) {
  let couleur = quiJoue % 2 === 0 ? "Jaune" : "Rouge";
  let classes = e.target.classList;
  if (classes.contains("top") && classes.contains("pion")) {
    let courant = e.target;
    $(courant).css("background", 'yellow').css("background-size", "contain");
  } else if (classes.contains('pion')) {
    let courant = (e.target);
    let colonne = (e.target.parentNode.classList[2]).split("-")[1];
    $('.cell.row-top.colonne-' + colonne).children().css("background", 'yellow').css("background-size", "contain")
    $(courant).hover(function() {
      $('.cell.row-top.colonne-' + colonne).children().addClass('top_hover');
    }, function() {
      $('.cell.row-top.colonne-' + colonne).children().removeClass('top_hover')
    });
  } else if (classes.contains('cell')) {
    let colonne = (e.target.classList[2]).split("-")[1];
    let courant = (e.target);
    $('.cell.row-top.colonne-' + colonne).children().css("background", 'yellow').css("background-size", "contain")
    $(courant).hover(function() {
      $('.cell.row-top.colonne-' + colonne).children().addClass('top_hover');
    }, function() {
      $('.cell.row-top.colonne-' + colonne).children().removeClass('top_hover')
    });

  }
});

.game-board {
  display: grid;
  grid-template-columns: repeat(7, 1fr);
  height: 700px;
  margin: 10px 0 25px;
  width: 700px;
}

.cell {
  align-items: center;
  background: #4370F1;
  display: flex;
  height: 100px;
  justify-content: center;
  width: 100px;
}

.pion {
  background: white;
  background-size: contain;
  border-radius: 50%;
  border: 3px solid black;
  height: 75px;
  width: 75px;
}

.top {
  transition: opacity 50ms linear;
  opacity: 0;
  border: 0;
}

.top:hover {
  transition: opacity 50ms linear;
  background-size: contain;
  opacity: 1;
}

.top_hover {
  transition: opacity 50ms linear;
  background-size: contain;
  opacity: 1;
}

.cell:not(.row-top).red::after {
  background: red;
}

.cell:not(.row-top).yellow::after {
  background: yellow;
}

.cell:not(.row-top).red.win {
  background: red;
}

.cell:not(.row-top).yellow.win {
  background: yellow;
}

.cell.row-top {
  background: rgba(255, 255, 255, 0);
}

.cell.row-top::after {
  border: none;
}

.cell.row-top.red::after {
  background: red;
  border: 3px solid black;
}

.cell.row-top.yellow::after {
  background: yellow;
  border: 3px solid black;
}

.left-border {
  border-left: 3px solid black;
}

.top-border {
  border-top: 3px solid black;
}

.right-border {
  border-right: 3px solid black;
}

.bottom-border {
  border-bottom: 3px solid black;
}

.left-border.top-border {
  border-radius: 10px 0 0 0;
}

.right-border.top-border {
  border-radius: 0 10px 0 0;
}

.right-border.bottom-border {
  border-radius: 0 0 10px 0;
}

.left-border.bottom-border {
  border-radius: 0 0 0 10px;
}

Body:
I will try to demonstrate the issue in some bullet points, so let me know if they are not clear enough.

After the compiling process ends and your page load, there are no listeners attached to the game elements.

In the first hover iteration, your code will initialize the event listener dynamically but will not execute it.

After that, you have a listener attached to your element and will fire its callback function from now on.

So, for every hover event after that, your code will work as expected

SOLUTION

We need to attach the event listener to all game elements statically not dynamically. so here is the JS code we need.

    $(".pion").hover(function(e) {
      const colonne = (e.target.parentNode.classList[2]).split("-")[1];
      $('.cell.row-top.colonne-' + colonne).children().toggleClass('top_hover');
    })

It will select all elements with pion class and will attach them our hover event that toggles the class name of the related colonne number.

Note: I have hard-coded the background color of the token to yellow in the HTML snippet for all columns. you can remove it and handle the logic of Jaune and Rouge

<div class="pion justify-content-center d-flex top" style="background: yellow url(&quot;../img/pionJaune.png&quot;) repeat scroll center center / contain;"></div>

$(".pion").hover(function(e) {
  const colonne = (e.target.parentNode.classList[2]).split("-")[1];
  $('.cell.row-top.colonne-' + colonne).children().toggleClass('top_hover');
})

.game-board {
  display: grid;
  grid-template-columns: repeat(7, 1fr);
  height: 700px;
  margin: 10px 0 25px;
  width: 700px;
}

.cell {
  align-items: center;
  background: #4370F1;
  display: flex;
  height: 100px;
  justify-content: center;
  width: 100px;
}

.pion {
  background: white;
  background-size: contain;
  border-radius: 50%;
  border: 3px solid black;
  height: 75px;
  width: 75px;
}

.top {
  transition: opacity 50ms linear;
  opacity: 0;
  border: 0;
}

.top:hover {
  transition: opacity 50ms linear;
  background-size: contain;
  opacity: 1;
}

.top_hover {
  transition: opacity 50ms linear;
  background-size: contain;
  opacity: 1;
}

.cell:not(.row-top).red::after {
  background: red;
}

.cell:not(.row-top).yellow::after {
  background: yellow;
}

.cell:not(.row-top).red.win {
  background: red;
}

.cell:not(.row-top).yellow.win {
  background: yellow;
}

.cell.row-top {
  background: rgba(255, 255, 255, 0);
}

.cell.row-top::after {
  border: none;
}

.cell.row-top.red::after {
  background: red;
  border: 3px solid black;
}

.cell.row-top.yellow::after {
  background: yellow;
  border: 3px solid black;
}

.left-border {
  border-left: 3px solid black;
}

.top-border {
  border-top: 3px solid black;
}

.right-border {
  border-right: 3px solid black;
}

.bottom-border {
  border-bottom: 3px solid black;
}

.left-border.top-border {
  border-radius: 10px 0 0 0;
}

.right-border.top-border {
  border-radius: 0 10px 0 0;
}

.right-border.bottom-border {
  border-radius: 0 0 10px 0;
}

.left-border.bottom-border {
  border-radius: 0 0 0 10px;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="text-center justify-content-center d-flex">
  <div class="game-board justify-content-center" id="grille" style="grid-template-columns: repeat(7, 1fr);">
    <div class="cell row-top colonne-0">
      <div class="pion justify-content-center d-flex top" style="background: yellow url(&quot;../img/pionJaune.png&quot;) repeat scroll center center / contain;"></div>
    </div>
    <div class="cell row-top colonne-1">
      <div class="pion justify-content-center d-flex top" style="background: yellow url(&quot;../img/pionJaune.png&quot;) repeat scroll center center / contain;"></div>
    </div>
    <div class="cell row-top colonne-2">
      <div class="pion justify-content-center d-flex top" style="background: yellow url(&quot;../img/pionJaune.png&quot;) repeat scroll center center / contain;"></div>
    </div>
    <div class="cell row-top colonne-3">
      <div class="pion justify-content-center d-flex top" style="background: yellow url(&quot;../img/pionJaune.png&quot;) repeat scroll center center / contain;"></div>
    </div>
    <div class="cell row-top colonne-4">
      <div class="pion justify-content-center d-flex top" style="background: yellow url(&quot;../img/pionJaune.png&quot;) repeat scroll center center / contain;"></div>
    </div>
    <div class="cell row-top colonne-5">
      <div class="pion justify-content-center d-flex top" style="background: yellow url(&quot;../img/pionJaune.png&quot;) repeat scroll center center / contain;"></div>
    </div>
    <div class="cell row-top colonne-6">
      <div class="pion justify-content-center d-flex top" style="background: yellow url(&quot;../img/pionJaune.png&quot;) repeat scroll center center / contain;"></div>
    </div>
    <div class="cell row-0 colonne-0 left-border top-border" data-couleur="">
      <div class="pion justify-content-center d-flex"></div>
    </div>
    <div class="cell row-0 colonne-1 top-border" data-couleur="">
      <div class="pion justify-content-center d-flex"></div>
    </div>
    <div class="cell row-0 colonne-2 top-border" data-couleur="">
      <div class="pion justify-content-center d-flex"></div>
    </div>
    <div class="cell row-0 colonne-3 top-border" data-couleur="">
      <div class="pion justify-content-center d-flex"></div>
    </div>
    <div class="cell row-0 colonne-4 top-border" data-couleur="">
      <div class="pion justify-content-center d-flex"></div>
    </div>
    <div class="cell row-0 colonne-5 top-border" data-couleur="">
      <div class="pion justify-content-center d-flex"></div>
    </div>
    <div class="cell row-0 colonne-6 right-border top-border" data-couleur="">
      <div class="pion justify-content-center d-flex"></div>
    </div>
    <div class="cell row-1 colonne-0 left-border" data-couleur="">
      <div class="pion justify-content-center d-flex"></div>
    </div>
    <div class="cell row-1 colonne-1 " data-couleur="">
      <div class="pion justify-content-center d-flex"></div>
    </div>
    <div class="cell row-1 colonne-2 " data-couleur="">
      <div class="pion justify-content-center d-flex"></div>
    </div>
    <div class="cell row-1 colonne-3 " data-couleur="">
      <div class="pion justify-content-center d-flex"></div>
    </div>
    <div class="cell row-1 colonne-4 " data-couleur="">
      <div class="pion justify-content-center d-flex"></div>
    </div>
    <div class="cell row-1 colonne-5 " data-couleur="">
      <div class="pion justify-content-center d-flex"></div>
    </div>
    <div class="cell row-1 colonne-6 right-border" data-couleur="">
      <div class="pion justify-content-center d-flex"></div>
    </div>
    <div class="cell row-2 colonne-0 left-border" data-couleur="">
      <div class="pion justify-content-center d-flex"></div>
    </div>
    <div class="cell row-2 colonne-1 " data-couleur="">
      <div class="pion justify-content-center d-flex"></div>
    </div>
    <div class="cell row-2 colonne-2 " data-couleur="">
      <div class="pion justify-content-center d-flex"></div>
    </div>
    <div class="cell row-2 colonne-3 " data-couleur="">
      <div class="pion justify-content-center d-flex"></div>
    </div>
    <div class="cell row-2 colonne-4 " data-couleur="">
      <div class="pion justify-content-center d-flex"></div>
    </div>
    <div class="cell row-2 colonne-5 " data-couleur="">
      <div class="pion justify-content-center d-flex"></div>
    </div>
    <div class="cell row-2 colonne-6 right-border" data-couleur="">
      <div class="pion justify-content-center d-flex"></div>
    </div>
    <div class="cell row-3 colonne-0 left-border" data-couleur="">
      <div class="pion justify-content-center d-flex"></div>
    </div>
    <div class="cell row-3 colonne-1 " data-couleur="">
      <div class="pion justify-content-center d-flex"></div>
    </div>
    <div class="cell row-3 colonne-2 " data-couleur="">
      <div class="pion justify-content-center d-flex"></div>
    </div>
    <div class="cell row-3 colonne-3 " data-couleur="">
      <div class="pion justify-content-center d-flex"></div>
    </div>
    <div class="cell row-3 colonne-4 " data-couleur="">
      <div class="pion justify-content-center d-flex"></div>
    </div>
    <div class="cell row-3 colonne-5 " data-couleur="">
      <div class="pion justify-content-center d-flex"></div>
    </div>
    <div class="cell row-3 colonne-6 right-border" data-couleur="">
      <div class="pion justify-content-center d-flex"></div>
    </div>
    <div class="cell row-4 colonne-0 left-border" data-couleur="">
      <div class="pion justify-content-center d-flex"></div>
    </div>
    <div class="cell row-4 colonne-1 " data-couleur="">
      <div class="pion justify-content-center d-flex"></div>
    </div>
    <div class="cell row-4 colonne-2 " data-couleur="">
      <div class="pion justify-content-center d-flex"></div>
    </div>
    <div class="cell row-4 colonne-3 " data-couleur="">
      <div class="pion justify-content-center d-flex"></div>
    </div>
    <div class="cell row-4 colonne-4 " data-couleur="">
      <div class="pion justify-content-center d-flex"></div>
    </div>
    <div class="cell row-4 colonne-5 " data-couleur="">
      <div class="pion justify-content-center d-flex"></div>
    </div>
    <div class="cell row-4 colonne-6 right-border" data-couleur="">
      <div class="pion justify-content-center d-flex"></div>
    </div>
    <div class="cell row-5 colonne-0 left-border bottom-border" data-couleur="">
      <div class="pion justify-content-center d-flex"></div>
    </div>
    <div class="cell row-5 colonne-1 bottom-border" data-couleur="">
      <div class="pion justify-content-center d-flex"></div>
    </div>
    <div class="cell row-5 colonne-2 bottom-border" data-couleur="">
      <div class="pion justify-content-center d-flex"></div>
    </div>
    <div class="cell row-5 colonne-3 bottom-border" data-couleur="">
      <div class="pion justify-content-center d-flex"></div>
    </div>
    <div class="cell row-5 colonne-4 bottom-border" data-couleur="">
      <div class="pion justify-content-center d-flex"></div>
    </div>
    <div class="cell row-5 colonne-5 bottom-border" data-couleur="">
      <div class="pion justify-content-center d-flex"></div>
    </div>
    <div class="cell row-5 colonne-6 right-border bottom-border" data-couleur="">
      <div class="pion justify-content-center d-flex"></div>
    </div>
  </div>
</div>


问:
Use RobustScaler in a LSTM with Keras
I want to scale time series data with outliers and use it in a LSTM model with Keras.

My code for the scaling is:

```<code># Train Data
scaler = RobustScaler().fit(train)
train = pd.DataFrame(scaler.fit_transform(train))
train = train.values
# Test Data
test = pd.DataFrame(scaler.transform(test))
test = test.values
</code>```

Afterwards, I put the data into 3D format for Keras:

```<code># split a multivariate sequence into samples
def split_sequences(sequences, n_steps):
  X, y = list(), list()
  for i in range(len(sequences)):
    # find the end of this pattern
    end_ix = i + n_steps
    # check if we are beyond the dataset
    if end_ix > len(sequences)-1:
      break
    # gather input and output parts of the pattern
    seq_x, seq_y = sequences[i:end_ix, :], sequences[end_ix, :12]
    X.append(seq_x)
    y.append(seq_y)
  return np.array(X), np.array(y)

# choose a number of time steps
n_steps = 30

# convert into train input/output
X_trai, y_trai = split_sequences(train, n_steps)
print(X_trai.shape, y_trai.shape)

# convert into test input/output
X_test, y_test = split_sequences(test, n_steps)
print(X_test.shape, y_test.shape)
</code>```

The training and prediction works well, however, I am not able to inverse transform the predicted y data of the test dataset.

My questions:

Is the above scaling method correct?

If yes, How can I regain the original scale of my y_hat predictions to compare it with the original y test dataset?

Thank you!

答:
I am pretty new to this, but this is the way I've been able to do it successfully:

Create a transformer for the various features

Create a transformer for the target (i.e., the thing you are predicting)

Transform the data

Create the dataset

Create and run the model

Use the "inverse_transform" function to bring the data back to its original form

Here is an example of what I am trying to describe, below.

Note: This does cause a "setting with copy warning" that I need to resolve as in "See the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy
iloc._setitem_with_indexer(indexer, value, self.name)"

```<code>from sklearn.preprocessing import RobustScaler
f_columns = ['A',
             'B',
             'C',
             'D'
             ]

f_transformer = RobustScaler()
target_transformer = RobustScaler()

f_transformer = f_transformer.fit(train[f_columns].to_numpy())
target_transformer = target_transformer.fit(train[['target']])

train.loc[:, f_columns] = f_transformer.transform(train[f_columns].to_numpy()).copy()
train['target'] = DA_transformer.transform(train[['target']]).copy()
</code>```

#Steps 4 and 5

```<code>y_trai_inv = target_transformer.inverse_transform(y_trai.reshape(1, -1))
y_test_inv = target_transformer.inverse_transform(y_test.reshape(1, -1))
y_pred_inv = target_transformer.inverse_transform(y_pred)
</code>```

Title: Use RobustScaler in a LSTM with Keras

Body:
I want to scale time series data with outliers and use it in a LSTM model with Keras.

My code for the scaling is:

# Train Data
scaler = RobustScaler().fit(train)
train = pd.DataFrame(scaler.fit_transform(train))
train = train.values
# Test Data
test = pd.DataFrame(scaler.transform(test))
test = test.values

Afterwards, I put the data into 3D format for Keras:

# split a multivariate sequence into samples
def split_sequences(sequences, n_steps):
  X, y = list(), list()
  for i in range(len(sequences)):
    # find the end of this pattern
    end_ix = i + n_steps
    # check if we are beyond the dataset
    if end_ix > len(sequences)-1:
      break
    # gather input and output parts of the pattern
    seq_x, seq_y = sequences[i:end_ix, :], sequences[end_ix, :12]
    X.append(seq_x)
    y.append(seq_y)
  return np.array(X), np.array(y)

# choose a number of time steps
n_steps = 30

# convert into train input/output
X_trai, y_trai = split_sequences(train, n_steps)
print(X_trai.shape, y_trai.shape)

# convert into test input/output
X_test, y_test = split_sequences(test, n_steps)
print(X_test.shape, y_test.shape)

The training and prediction works well, however, I am not able to inverse transform the predicted y data of the test dataset.

My questions:

Is the above scaling method correct?

If yes, How can I regain the original scale of my y_hat predictions to compare it with the original y test dataset?

Thank you!

Body:
I am pretty new to this, but this is the way I've been able to do it successfully:

Create a transformer for the various features

Create a transformer for the target (i.e., the thing you are predicting)

Transform the data

Create the dataset

Create and run the model

Use the "inverse_transform" function to bring the data back to its original form

Here is an example of what I am trying to describe, below.

Note: This does cause a "setting with copy warning" that I need to resolve as in "See the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy
iloc._setitem_with_indexer(indexer, value, self.name)"

from sklearn.preprocessing import RobustScaler
f_columns = ['A',
             'B',
             'C',
             'D'
             ]

f_transformer = RobustScaler()
target_transformer = RobustScaler()

f_transformer = f_transformer.fit(train[f_columns].to_numpy())
target_transformer = target_transformer.fit(train[['target']])

train.loc[:, f_columns] = f_transformer.transform(train[f_columns].to_numpy()).copy()
train['target'] = DA_transformer.transform(train[['target']]).copy()

#Steps 4 and 5

y_trai_inv = target_transformer.inverse_transform(y_trai.reshape(1, -1))
y_test_inv = target_transformer.inverse_transform(y_test.reshape(1, -1))
y_pred_inv = target_transformer.inverse_transform(y_pred)


问:
Error: React Hook "useDocumentOnce" is called conditionally. React Hooks must be called in the exact same order in every component render
I was making an app using NextJS, TailwindCSS, Firebase and It is working 100% correctly on local host but on deploying on Vercel, I get the following error :

15:18  Error: React Hook "useRouter" is called conditionally. React Hooks must be called in the exact same order in every component render.  react-hooks/rules-of-hooks
17:39  Error: React Hook "useDocumentOnce" is called conditionally. React Hooks must be called in the exact same order in every component render.  react-hooks/rules-of-hooks

I am not able to understand why I get this error when deploying my app to Vercel.Maybe it's something related to redirect link in google API console

Here's my [id].js file :

```<code>import TextEditor from "../../components/TextEditor";
import Button from "@material-tailwind/react/Button";
import Icon from "@material-tailwind/react/Icon";
import { useRouter } from "next/dist/client/router";
import { db } from "../../firebase";
import { useDocumentOnce } from "react-firebase-hooks/firestore";
import { getSession, signOut, useSession } from "next-auth/client";
import Login from "../../components/Login";

function Doc() {
  const [session, loading] = useSession();
  console.log(session);
  if (!session) return <Login />;

  const router = useRouter();
  const { id } = router.query;
  const [snapshot, loadingSnapshot] = useDocumentOnce(
    db.collection("userDocs").doc(session.user.email).collection("docs").doc(id)
  );

  // Redirect if user tries to access a URL they do not have access to...
  if (!loadingSnapshot && !snapshot?.data()?.fileName) {
    // Filename will not be present if the user doesnt have access...
    router.replace("/");
  }

  return (
    <div>
      <header className="flex justify-between items-center p-3 pb-1">
        <span onClick={() => router.push("/")} className="cursor-pointer">
          <Icon name="description" size="5xl" color="blue" />
        </span>
        <div className="flex-grow px-2">
          <h2 className="text-lg text-left">{snapshot?.data()?.fileName}</h2>
          <div className="flex items-center text-sm -ml-1 h-8 text-gray-600 space-x-1">
            <p className="option">File</p>
            <p className="option">Edit</p>
            <p className="option">View</p>
            <p className="option">Insert</p>
            <p className="option">Format</p>
            <p className="option">Tools</p>
          </div>
        </div>

        <Button
          color="lightBlue"
          buttonType="filled"
          size="regular"
          className="hidden md:!inline-flex h-10"
          rounded={false}
          block={false}
          iconOnly={false}
          ripple="light"
        >
          <Icon name="people" size="md" /> SHARE
        </Button>

        <img
          onClick={signOut}
          className="cursor-pointer h-10 w-10 rounded-full ml-2"
          src={session.user.image}
          alt=""
        />
      </header>
      <TextEditor />
    </div>
  );
}

export default Doc;

export async function getServerSideProps(context) {
  const session = await getSession(context);

  return {
    props: {
      session,
    },
  };
}
</code>```

答:
You have early return before calling useDocumentOnce on line

```<code>if (!session) return <Login />
</code>```

Which is not good as the error says. You should make sure that you always render the same amount of hooks on each render. In your case you are calling 3 hooks. But if session is not defined you only render 1 hook. That is the problem you have to resolve.

Body:
I was making an app using NextJS, TailwindCSS, Firebase and It is working 100% correctly on local host but on deploying on Vercel, I get the following error :

15:18  Error: React Hook "useRouter" is called conditionally. React Hooks must be called in the exact same order in every component render.  react-hooks/rules-of-hooks
17:39  Error: React Hook "useDocumentOnce" is called conditionally. React Hooks must be called in the exact same order in every component render.  react-hooks/rules-of-hooks

I am not able to understand why I get this error when deploying my app to Vercel.Maybe it's something related to redirect link in google API console

Here's my [id].js file :

import TextEditor from "../../components/TextEditor";
import Button from "@material-tailwind/react/Button";
import Icon from "@material-tailwind/react/Icon";
import { useRouter } from "next/dist/client/router";
import { db } from "../../firebase";
import { useDocumentOnce } from "react-firebase-hooks/firestore";
import { getSession, signOut, useSession } from "next-auth/client";
import Login from "../../components/Login";

function Doc() {
  const [session, loading] = useSession();
  console.log(session);
  if (!session) return <Login />;

  const router = useRouter();
  const { id } = router.query;
  const [snapshot, loadingSnapshot] = useDocumentOnce(
    db.collection("userDocs").doc(session.user.email).collection("docs").doc(id)
  );

  // Redirect if user tries to access a URL they do not have access to...
  if (!loadingSnapshot && !snapshot?.data()?.fileName) {
    // Filename will not be present if the user doesnt have access...
    router.replace("/");
  }

  return (

         router.push("/")} className="cursor-pointer">
          <Icon name="description" size="5xl" color="blue" />

{snapshot?.data()?.fileName}

File

Edit

View

Insert

Format

Tools

        <Button
          color="lightBlue"
          buttonType="filled"
          size="regular"
          className="hidden md:!inline-flex h-10"
          rounded={false}
          block={false}
          iconOnly={false}
          ripple="light"
        >
          <Icon name="people" size="md" /> SHARE
        </Button>

      <TextEditor />

  );
}

export default Doc;

export async function getServerSideProps(context) {
  const session = await getSession(context);

  return {
    props: {
      session,
    },
  };
}

Body:
You have early return before calling useDocumentOnce on line

if (!session) return <Login />

Which is not good as the error says. You should make sure that you always render the same amount of hooks on each render. In your case you are calling 3 hooks. But if session is not defined you only render 1 hook. That is the problem you have to resolve.


问:
How to disable the length limitation of pasted text in VScode when word wrap is disabled?
When I paste a very long text, it will limit the end of the string with three dots, like so:

```<code>verylongtextverylongtextvxtverylongtextverylongtextverylongtext…
</code>```

This does not happen if I enable word wrap, which I don't prefer to have enabled, especially when I am pasting huge content into the editor.

答:
I got around this by pasting the raw data into notepad, saving as whatever.txt in my target directory, and then changing the filename to whatever.json in VSC. Worked like a charm.

Of course, this is fine for a one time solution, I'm not recommending it for routine practice.

Body:
When I paste a very long text, it will limit the end of the string with three dots, like so:

verylongtextverylongtextvxtverylongtextverylongtextverylongtext…

This does not happen if I enable word wrap, which I don't prefer to have enabled, especially when I am pasting huge content into the editor.


问:
How I could append a variable in a list after converted in variable
I have this:

```<code>listVar=[]
listSel={'one':'x','two':'code'}
for row in listSel:
    exec("%s = '%s'" % (row,listSel[row]))
    listVar.append("%s" %row)
print(one,two)
print(listVar)
</code>```

I convert the row in a variable with exec(), but i don't know how could i append the new  variables in the listVar; next to this i'm looking for inside the variable in a list with listVar.append("%s" %row), my expected answer with print would be:

```<code>['x','code']
</code>```

(Because I'm printing the variables one and two)

But when I print listVar Python answered me:

```<code>['one','two']
</code>```

I don't want to use something like:

```<code>listVar.append(one)
</code>```

Because I'll make a function and I'll not know the rows.

Edit: I need listVar to be [one,two] not ['one','two'].

答:
Edit: Maybe, this is what you needed:</p>
```<code>listSel={'one':'x','two':'code'}
one, two = listSel.values()
listVar= [one, two]
print(listVar)
</code>```

Body:
I have this:

listVar=[]
listSel={'one':'x','two':'code'}
for row in listSel:
    exec("%s = '%s'" % (row,listSel[row]))
    listVar.append("%s" %row)
print(one,two)
print(listVar)

I convert the row in a variable with exec(), but i don't know how could i append the new  variables in the listVar; next to this i'm looking for inside the variable in a list with listVar.append("%s" %row), my expected answer with print would be:

['x','code']

(Because I'm printing the variables one and two)

But when I print listVar Python answered me:

['one','two']

I don't want to use something like:

listVar.append(one)

Because I'll make a function and I'll not know the rows.

Edit: I need listVar to be [one,two] not ['one','two'].

Body:
Edit: Maybe, this is what you needed:

listSel={'one':'x','two':'code'}
one, two = listSel.values()
listVar= [one, two]
print(listVar)


问:
Referring to columns by name in for loop
I have a loop in R that loops over columns in a dataframe las_ref for those columns where the name matches a value in a vector las_names.
As the original las_ref dataframe has rows with duplicated incidentid values, I am aiming to extract the most common value in each of the columns in las_names for each incidentid, produce a new column and use a join to produce a dataframe las_ref3 with the most common values in every row.

Structure of las_ref

```<code>incidentid incident var1
001             abc   45
002             abc   NA
002              NA   78
003             def   12
004             xyz   NA
004             xyz   10
004             abc   10
</code>```

Intended structure of las_ref3

```<code>incidentid incident var1 incident-new var1-new
001             abc   45          abc       45
002             abc   NA          abc       78
002              NA   78          abc       78
003             def   12          def       12
004             xyz   NA          xyz       10
004             xyz   10          xyz       10
004             abs   10          xyz       10
</code>```

Below is the loop I am trying to use.

```<code>las_names <- c("incident","var1")
for(i in las_names) {
  las_ref2 <- las_ref %>%
    group_by(across(c(incidentid, paste(i)))) %>%
    tally() %>%
    filter(!is.na(paste(i))) %>%
    arrange(incidentid, desc(n)) %>%
    summarize(paste(i,"-new") = first(paste(i)))
  las_ref3 <- las_ref %>%
    left_join(select(las_ref2, incidentid, paste(i,"-new")), by = c("incidentid"))
}
</code>```

Currently there seem to be two issues that I think revolve around the use of i to refer to the columns incident and var in the examples above.

The first is that the !is.na() function is not removing the NA values in the columns referred to by i, although this does not produce an error.
The second, which does produce an error, is the summarise line. I get an  unexpected '=' in error when this line is run.

Neither issue occurs when I run the code outside of the loop, specifying column names individually - the result comes out as expected. As the dataset is fairly large, I was hoping to use the loop to avoid doing each column individually.

答:
A version that avoids manual loops:</p>
```<code>library(tidyverse)

las_ref <- tribble(~incidentid , ~incident, ~var1,
                   "001",             "abc",   45,
                   "002",             "abc",   NA,
                   "002",              NA,     78,
                   "003",             "def",   12,
                   "004",             "xyz",   NA,
                   "004",             "xyz",   10,
                   "004",             "abc",   10
)

las_ref3 <- las_ref %>%
  group_by(incidentid) %>%
  mutate(
    across(c(incident, var1), ~names(sort(table(.x, useNA = 'no'), decreasing = T))[1], .names = '{.col}-new' )
  )

  incidentid incident  var1 incident-new var1-new
  <chr>      <chr>    <dbl> <chr>        <chr>
1 001        abc         45 abc          45
2 002        abc         NA abc          78
3 002        NA          78 abc          78
4 003        def         12 def          12
5 004        xyz         NA xyz          10
6 004        xyz         10 xyz          10
7 004        abc         10 xyz          10
</code>```

Body:
I have a loop in R that loops over columns in a dataframe las_ref for those columns where the name matches a value in a vector las_names.
As the original las_ref dataframe has rows with duplicated incidentid values, I am aiming to extract the most common value in each of the columns in las_names for each incidentid, produce a new column and use a join to produce a dataframe las_ref3 with the most common values in every row.

Structure of las_ref

incidentid incident var1
001             abc   45
002             abc   NA
002              NA   78
003             def   12
004             xyz   NA
004             xyz   10
004             abc   10

Intended structure of las_ref3

incidentid incident var1 incident-new var1-new
001             abc   45          abc       45
002             abc   NA          abc       78
002              NA   78          abc       78
003             def   12          def       12
004             xyz   NA          xyz       10
004             xyz   10          xyz       10
004             abs   10          xyz       10

Below is the loop I am trying to use.

las_names <- c("incident","var1")
for(i in las_names) {
  las_ref2 <- las_ref %>%
    group_by(across(c(incidentid, paste(i)))) %>%
    tally() %>%
    filter(!is.na(paste(i))) %>%
    arrange(incidentid, desc(n)) %>%
    summarize(paste(i,"-new") = first(paste(i)))
  las_ref3 <- las_ref %>%
    left_join(select(las_ref2, incidentid, paste(i,"-new")), by = c("incidentid"))
}

Currently there seem to be two issues that I think revolve around the use of i to refer to the columns incident and var in the examples above.

The first is that the !is.na() function is not removing the NA values in the columns referred to by i, although this does not produce an error.
The second, which does produce an error, is the summarise line. I get an  unexpected '=' in error when this line is run.

Neither issue occurs when I run the code outside of the loop, specifying column names individually - the result comes out as expected. As the dataset is fairly large, I was hoping to use the loop to avoid doing each column individually.

Body:
A version that avoids manual loops:

library(tidyverse)

las_ref <- tribble(~incidentid , ~incident, ~var1,
                   "001",             "abc",   45,
                   "002",             "abc",   NA,
                   "002",              NA,     78,
                   "003",             "def",   12,
                   "004",             "xyz",   NA,
                   "004",             "xyz",   10,
                   "004",             "abc",   10
)

las_ref3 <- las_ref %>%
  group_by(incidentid) %>%
  mutate(
    across(c(incident, var1), ~names(sort(table(.x, useNA = 'no'), decreasing = T))[1], .names = '{.col}-new' )
  )

  incidentid incident  var1 incident-new var1-new
  <chr>      <chr>    <dbl> <chr>        <chr>
1 001        abc         45 abc          45
2 002        abc         NA abc          78
3 002        NA          78 abc          78
4 003        def         12 def          12
5 004        xyz         NA xyz          10
6 004        xyz         10 xyz          10
7 004        abc         10 xyz          10


问:
Are System.Generics.Collections TList<record> subject to memory fragmentation in Delphi?
In Delphi 10.4, I have a record that I use like this in a TList (System.Generics.Collections):

```<code>uses
    System.Generics.Collections;

type
    TSomething = record
        Name: String;
        Foo: String;
        Bar: String;
        Group: String;
        Flag1: Boolean;
        Flag2: Boolean;
        Flag3: Boolean;
        Flag4: Boolean;
        Flag5: Boolean;
    end;

    PTSomething = ^TSomething;

//Simplified code for readability...

var
    Something: TSomething;
    MyList := TList<TSomething>;
    lRecP: PTSomething;

MyList := TList<TSomething>.Create;

while ACondition do
begin
    Something.Name := 'Something';
    //Fill the rest of the record
    MyList.Add(Something); //Add is done in a while loop which result around 1000 items in MyList
end;

//Later...
for i := 0 to MyList.Count - 1 do
begin
    if ACondition then
    begin
        lRecP := @MyList.List[i];
        lRecP.Name := 'Modified'; //Items can be modified but never deleted
    end;
end;

//Later...
MyList.Free;
</code>```

Is my code prone to memory fragmentation? I have about 1000 records in my list that I will iterate through and maybe modify a string off the record once per record.

Would there be a better way to do what I want to do?

答:
This is not an Answer to your Code. I don´t know if Fragmentation happens. In my experience it is dependent on other things happening in parallel or over time. If your Application has Issues like "E Out Of Memory" after running several days, then its time to look at it.

I Would suggest having a look at FastMM. Using its FastMMUsageTracker
Memory Fragmentation Map over FastMM

For me it was a big help. I had Problems in a Service, but i cant remember where i read about Memory Exhaustion. In FastMM or Mad Except? Sorry i can´t remember. It was a Article explaining why Fragmention happens over time.

Body:
In Delphi 10.4, I have a record that I use like this in a TList (System.Generics.Collections):

uses
    System.Generics.Collections;

type
    TSomething = record
        Name: String;
        Foo: String;
        Bar: String;
        Group: String;
        Flag1: Boolean;
        Flag2: Boolean;
        Flag3: Boolean;
        Flag4: Boolean;
        Flag5: Boolean;
    end;

    PTSomething = ^TSomething;

//Simplified code for readability...

var
    Something: TSomething;
    MyList := TList<TSomething>;
    lRecP: PTSomething;

MyList := TList<TSomething>.Create;

while ACondition do
begin
    Something.Name := 'Something';
    //Fill the rest of the record
    MyList.Add(Something); //Add is done in a while loop which result around 1000 items in MyList
end;

//Later...
for i := 0 to MyList.Count - 1 do
begin
    if ACondition then
    begin
        lRecP := @MyList.List[i];
        lRecP.Name := 'Modified'; //Items can be modified but never deleted
    end;
end;

//Later...
MyList.Free;

Is my code prone to memory fragmentation? I have about 1000 records in my list that I will iterate through and maybe modify a string off the record once per record.

Would there be a better way to do what I want to do?


问:
How to input date and time in a Vuetify text input field
I am attempting to build a Vuetify form that enables inputting of a date format that includes both the date and specific time of the event, for both starting and ending. So far, I have the following:

```<code>            <v-form @submit.prevent="addEvent">
              <v-text-field v-model="eventName" type="text" label="event name (required)"></v-text-field>
              <v-text-field v-model="start" type="date" label="start (required)"></v-text-field>
              <v-text-field v-model="end" type="date" label="end (required)"></v-text-field>
              <v-btn type="submit" color="primary" class="mr-4" @click.stop="dialog = false">
                Add Event
              </v-btn>
            </v-form>
</code>```

Is there an input type that allows both date and time to be inputted into the same input field? If so, how can I implement such a field? Thanks!

答:
Is there an input type that allows both date and time to be inputted into the same input field?

The v-text-field component in Vuetify lets you select date and time together if you set type="datetime-local" instead of "date".

Explanation of datetime-local: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/datetime-local

Body:
I am attempting to build a Vuetify form that enables inputting of a date format that includes both the date and specific time of the event, for both starting and ending. So far, I have the following:

            <v-form @submit.prevent="addEvent">
              <v-text-field v-model="eventName" type="text" label="event name (required)"></v-text-field>
              <v-text-field v-model="start" type="date" label="start (required)"></v-text-field>
              <v-text-field v-model="end" type="date" label="end (required)"></v-text-field>
              <v-btn type="submit" color="primary" class="mr-4" @click.stop="dialog = false">
                Add Event
              </v-btn>
            </v-form>

Is there an input type that allows both date and time to be inputted into the same input field? If so, how can I implement such a field? Thanks!


问:
Binary Heap and Priority Queues
I am new to Heaps, Binary Heap and I am trying to understand why do we need to implement Priority Queue using a Binary Heap. I also understand that the underlying data structure of Binary Heap is again an array.

So my question is why can we not use an array, sorted in either descending (for max heap) or ascending (for min heap) order to represent a priority queue ? I might be wrong here, but I think the time complexity of the operations like, findMax, findMin, insert and delete will remain almost the same if implemented this way. So can we not not a use a sorted array to represent the priority queue ?

I have already read this answer: Heap vs Binary Search Tree (BST)

答:
Both has its own advantages and disadvantages:

Trees are more flexible and, if they are balanced, have better performance, with worst-case logarithmic search, insertion, and delete. All these benefits have a price. In trees, lists, and graphs every node requires extra space
for the pointers and each node is placed in random places, which causes memory overhead

All the elements in the array are contiguous in memory, and this means lower latency when reading them. Use a sorted array if deletions and insertions are not going to happen often

Title: Binary Heap and Priority Queues


问:
Connection could not be established with host smtp.sendgrid.net :stream_socket_client(): unable to connect to tcp://smtp.sendgrid.net:465
I am trying to send mail using sendgrid in Laravel but it is working on localserver but as i hosted it on server it is giving me following error message:

my mail settings in .env file:

```<code>MAIL_DRIVER=smtp
MAIL_HOST=smtp.sendgrid.net
MAIL_PORT=587
MAIL_USERNAME=myusername
MAIL_PASSWORD=XXX
MAIL_ENCRYPTION=tls
MAIL_FROM_ADDRESS=info@xyz.com
MAIL_FROM_NAME=xyz
</code>```

答:
when I migrated to laravel 9, sending with sendgrid didn't work anymore.
The problem was because the new symfony mailer was trying to send with ssl beside tls was set in the config file.
So in the config file, I changed the port from 587 to 465 and it worked again.</p>

Body:
I am trying to send mail using sendgrid in Laravel but it is working on localserver but as i hosted it on server it is giving me following error message:

my mail settings in .env file:

MAIL_DRIVER=smtp
MAIL_HOST=smtp.sendgrid.net
MAIL_PORT=587
MAIL_USERNAME=myusername
MAIL_PASSWORD=XXX
MAIL_ENCRYPTION=tls
MAIL_FROM_ADDRESS=info@xyz.com
MAIL_FROM_NAME=xyz


问:
Convert Dask Bag of Pandas DataFrames to a single Dask DataFrame
Summary of Problem

Short Version

How do I go from a Dask Bag of Pandas DataFrames, to a single Dask DataFrame?

Long Version

I have a number of files that are not readable by any of dask.dataframe's various read functions (e.g. dd.read_csv or dd.read_parquet). I do have my own function that will read them in as Pandas DataFrames (function only works on one file at a time, akin to pd.read_csv). I would like to have all of these single Pandas DataFrames in one large Dask DataFrame.

Minimum Working Example

Here's some example CSV data (my data isn't actually in CSVs, but using it here for ease of example). To create a minimum working example, you can save this as a CSV and make a few copies, then use the code below

```<code>"gender","race/ethnicity","parental level of education","lunch","test preparation course","math score","reading score","writing score"
"female","group B","bachelor's degree","standard","none","72","72","74"
"female","group C","some college","standard","completed","69","90","88"
"female","group B","master's degree","standard","none","90","95","93"
"male","group A","associate's degree","free/reduced","none","47","57","44"
"male","group C","some college","standard","none","76","78","75"
</code>```

from glob import glob
import pandas as pd
import dask.bag as db

files = glob('/path/to/your/csvs/*.csv')
bag = db.from_sequence(files).map(pd.read_csv)
```

<p><strong>What I've tried so far</strong></p>

<pre class="lang-py prettyprint-override"><code>import pandas as pd
import dask.bag as db
import dask.dataframe as dd

# Create a Dask bag of pandas dataframes
bag = db.from_sequence(list_of_files).map(my_reader_function)

df = bag.map(lambda x: x.to_records()).to_dataframe() # this doesn't work
df = bag.map(lambda x: x.to_dict(orient = <any option>)).to_dataframe() # neither does this

# This gets me really close. It's a bag of Dask DataFrames.
# But I can't figure out how to concatenate them together
df = bag.map(dd.from_pandas, npartitions = 1)

df = dd.from_delayed(bag) # returns an error
</code>```

答:
Here are two additional possible solutions:

1. Convert the bag to a list of dataframes then use dd.multi.concat:

```<code>bag #a dask bag of dataframes
list_of_dfs = bag.compute()
df = dd.multi.concat(list_of_dfs).compute()
</code>```

2. Convert to a bag of dictionaries and use bag.to_dataframe:

```<code>bag_of_dicts = bag.map(lambda df: df.to_dict(orient='records')).flatten()
df = bag_of_dicts.to_dataframe().compute()
</code>```

In my own specific use case, option #2 had better performance than option #1.

Body:
Summary of Problem

Short Version

How do I go from a Dask Bag of Pandas DataFrames, to a single Dask DataFrame?

Long Version

I have a number of files that are not readable by any of dask.dataframe's various read functions (e.g. dd.read_csv or dd.read_parquet). I do have my own function that will read them in as Pandas DataFrames (function only works on one file at a time, akin to pd.read_csv). I would like to have all of these single Pandas DataFrames in one large Dask DataFrame.

Minimum Working Example

Here's some example CSV data (my data isn't actually in CSVs, but using it here for ease of example). To create a minimum working example, you can save this as a CSV and make a few copies, then use the code below

"gender","race/ethnicity","parental level of education","lunch","test preparation course","math score","reading score","writing score"
"female","group B","bachelor's degree","standard","none","72","72","74"
"female","group C","some college","standard","completed","69","90","88"
"female","group B","master's degree","standard","none","90","95","93"
"male","group A","associate's degree","free/reduced","none","47","57","44"
"male","group C","some college","standard","none","76","78","75"

from glob import glob
import pandas as pd
import dask.bag as db

files = glob('/path/to/your/csvs/*.csv')
bag = db.from_sequence(files).map(pd.read_csv)

What I've tried so far

import pandas as pd
import dask.bag as db
import dask.dataframe as dd

# Create a Dask bag of pandas dataframes
bag = db.from_sequence(list_of_files).map(my_reader_function)

df = bag.map(lambda x: x.to_records()).to_dataframe() # this doesn't work
df = bag.map(lambda x: x.to_dict(orient = <any option>)).to_dataframe() # neither does this

# This gets me really close. It's a bag of Dask DataFrames.
# But I can't figure out how to concatenate them together
df = bag.map(dd.from_pandas, npartitions = 1)

df = dd.from_delayed(bag) # returns an error

Body:
Here are two additional possible solutions:

1. Convert the bag to a list of dataframes then use dd.multi.concat:

bag #a dask bag of dataframes
list_of_dfs = bag.compute()
df = dd.multi.concat(list_of_dfs).compute()

2. Convert to a bag of dictionaries and use bag.to_dataframe:

bag_of_dicts = bag.map(lambda df: df.to_dict(orient='records')).flatten()
df = bag_of_dicts.to_dataframe().compute()

In my own specific use case, option #2 had better performance than option #1.


问:
My function returns same data without do the jobs
I have made function like below to remove html tags and special characters from the string.

```<code>function input_filter_data($data) {
        $data= trim($data);
        $data= stripslashes($data);
        $data= htmlspecialchars($data);
        $data= strip_tags($data);
        return $data;
}
</code>```

and I am trying to use it like below

```<code>$affiliate_id =input_filter_data("Hello <b><i>world!</i></b>","<i>");

echo $affiliate_id;
</code>```

But its giving me same result like

```<code>Hello <b><i>world!</i></b>","<i>
</code>```

But if I use simple like

```<code>echo strip_tags("Hello <b><i>world!</i></b>","<i>");
</code>```

then its removing all html tags from string.

I am not getting idea why its happening like this, let me know if anyone here can help me for solve the puzzle.

Thanks!

答: It could help to debug what each step of input_filter_data does: after calling htmlspecialchars, the string does not contain any markup, but solely escaped markup. strip_tags won't perform any change on such a input

Body:
I have made function like below to remove html tags and special characters from the string.

function input_filter_data($data) {
        $data= trim($data);
        $data= stripslashes($data);
        $data= htmlspecialchars($data);
        $data= strip_tags($data);
        return $data;
}

and I am trying to use it like below

$affiliate_id =input_filter_data("Hello world!","");

echo $affiliate_id;

But its giving me same result like

Hello world!","

But if I use simple like

echo strip_tags("Hello world!","");

then its removing all html tags from string.

I am not getting idea why its happening like this, let me know if anyone here can help me for solve the puzzle.

Thanks!


问:
How to Add Api Permissions to an Azure App Registration using PowerShell
I am figure out the commands in Azure PowerShell to add an the User.Read Ape Permission to my App Registration in Azure.

I can find some examples using *Azure, but would prefer one that uses the *Az commands, e.g. https://learn.microsoft.com/en-us/powershell/azure/?view=azps-2.8.0.

Wonder if anybody knows how to do this? Thanks!

答:
UPDATE

With the new Graph API we can use the following command to add API permissions to an App Registration/Service Principal using PowerShell. It's much simpler than the old process.

```<code>Add-AzADAppPermission -ApplicationId "$spId" -ApiId "00000009-0000-0000-c000-000000000000" -PermissionId "7504609f-c495-4c64-8542-686125a5a36f"
</code>```

(This is the case for the PowerBI API)

If deploying via an Azure Devops Pipeline I often recommend using the following script to authenticate into AAD:

```<code>  echo "Install Azure AD module..."
  Install-Module -Name "AzureAD" -Force
  Import-Module AzureAD -Force

  echo "Connect Azure AD..."
  $context = [Microsoft.Azure.Commands.Common.Authentication.Abstractions.AzureRmProfileProvider]::Instance.Profile.DefaultContext
  echo $context
  $graphToken = [Microsoft.Azure.Commands.Common.Authentication.AzureSession]::Instance.AuthenticationFactory.Authenticate($context.Account, $context.Environment, $context.Tenant.Id.ToString(), $null, [Microsoft.Azure.Commands.Common.Authentication.ShowDialog]::Never, $null, "https://graph.microsoft.com").AccessToken
  echo $graphToken
  $aadToken = [Microsoft.Azure.Commands.Common.Authentication.AzureSession]::Instance.AuthenticationFactory.Authenticate($context.Account, $context.Environment, $context.Tenant.Id.ToString(), $null, [Microsoft.Azure.Commands.Common.Authentication.ShowDialog]::Never, $null, "https://graph.windows.net").AccessToken
  Write-Output "Hi I'm $($context.Account.Id)"
  Connect-AzureAD -AadAccessToken $aadToken -AccountId $context.Account.Id -TenantId $context.tenant.id -MsAccessToken $graphToken
  echo "Connection ends"
</code>```

Body:
UPDATE

With the new Graph API we can use the following command to add API permissions to an App Registration/Service Principal using PowerShell. It's much simpler than the old process.

Add-AzADAppPermission -ApplicationId "$spId" -ApiId "00000009-0000-0000-c000-000000000000" -PermissionId "7504609f-c495-4c64-8542-686125a5a36f"

(This is the case for the PowerBI API)

If deploying via an Azure Devops Pipeline I often recommend using the following script to authenticate into AAD:

  echo "Install Azure AD module..."
  Install-Module -Name "AzureAD" -Force
  Import-Module AzureAD -Force

  echo "Connect Azure AD..."
  $context = [Microsoft.Azure.Commands.Common.Authentication.Abstractions.AzureRmProfileProvider]::Instance.Profile.DefaultContext
  echo $context
  $graphToken = [Microsoft.Azure.Commands.Common.Authentication.AzureSession]::Instance.AuthenticationFactory.Authenticate($context.Account, $context.Environment, $context.Tenant.Id.ToString(), $null, [Microsoft.Azure.Commands.Common.Authentication.ShowDialog]::Never, $null, "https://graph.microsoft.com").AccessToken
  echo $graphToken
  $aadToken = [Microsoft.Azure.Commands.Common.Authentication.AzureSession]::Instance.AuthenticationFactory.Authenticate($context.Account, $context.Environment, $context.Tenant.Id.ToString(), $null, [Microsoft.Azure.Commands.Common.Authentication.ShowDialog]::Never, $null, "https://graph.windows.net").AccessToken
  Write-Output "Hi I'm $($context.Account.Id)"
  Connect-AzureAD -AadAccessToken $aadToken -AccountId $context.Account.Id -TenantId $context.tenant.id -MsAccessToken $graphToken
  echo "Connection ends"


问:
Add a character to a specific part of a string?
I have a list of file names as such:

```<code>"A/B/file.jpeg"

"A/C/file2.jpeg"

"B/C/file3.jpeg"
</code>```

and a couple of variations of such.

My question is how would I be able to add a "new" or any characters into each of these file names after the second "/" such that the length of the string/name doesn't matter just that it is placed after the second "/"

Results would ideally be:

```<code>"A/B/newfile.jpeg"

"A/B/newfile2.jpeg" etc.
</code>```

Thanks!

答:
Another possible solution, based on stringr::str_replace:

library(stringr)

l <- c("A/B/file.jpeg", "A/B/file2.jpeg", "A/B/file3.jpeg")

str_replace(l, "\\/(?=file)", "\\/new")

#> [1] "A/B/newfile.jpeg"  "A/B/newfile2.jpeg" "A/B/newfile3.jpeg"
```

Body:
I have a list of file names as such:

"A/B/file.jpeg"

"A/C/file2.jpeg"

"B/C/file3.jpeg"

and a couple of variations of such.

My question is how would I be able to add a "new" or any characters into each of these file names after the second "/" such that the length of the string/name doesn't matter just that it is placed after the second "/"

Results would ideally be:

"A/B/newfile.jpeg"

"A/B/newfile2.jpeg" etc.

Thanks!


问:
ActiveStorage::FileNotFoundError (ActiveStorage::FileNotFoundError) in server log, but not reproducable in console
I have the following model:

```<code>class Section < ApplicationRecord
  has_many_attached :files
  def to_dir
    [client.to_dir, operation.to_dir, self.name.parameterize].join('/')
  end
  after_save :transload_files

  def transload_files
    TransloadService.sync( self.to_dir, self.files )
  end
end
</code>```

The transload_files method is the issue.  Here is the transload service:

```<code>class TransloadService

    class << self

        def sync(check_dir, files)
            # First we have to check the transload dir for files that have been deleted on the app
            transloaded_files = Request.list(check_dir)
            cull_list = transloaded_files.reject{ |e| files.map{|t| t.filename }.include? Request.filename(e)}
            if cull_list.count > 0
                Request.trim(cull_list)
                p "#{cull_list.count} files trimed from #{check_dir}."
            end

            # Next we have to upload files which arent present in the transload dir

            send_list = files.reject{ |e| transloaded_files.map{|t| Request.filename(t) }.include? e.filename.to_s }
            if send_list.count > 0
                Request.upload_to(check_dir, send_list)
                p "#{send_list.map{|r| r.filename.to_s}.join(', ')} uploaded to #{check_dir}"
            end
        end

    end

end
</code>```

and here is the relevant code in request.rb

```<code>class Request
    class << self
        def upload_to(destination, files)
            files.each do |file|
                send_to = connection.object("#{destination}/#{file.filename}")
                file.open{ |tmp| send_to.upload_file(tmp) }
            end
        end
    end
end
</code>```

The issue I'm facing is this: When the after_save callback runs the transload_files method it returns
ActiveStorage::FileNotFoundError (ActiveStorage::FileNotFoundError)

When I run the Section.last.transload_files in the console, it performs exactly as intended.  What am I missing here?

答: In my case, what I noticed is that attaching attachments with ActiveStorage is not working properly when doing it inside a transaction. This applies to migrations or callbacks.</p>

Body:
I have the following model:

class Section < ApplicationRecord
  has_many_attached :files
  def to_dir
    [client.to_dir, operation.to_dir, self.name.parameterize].join('/')
  end
  after_save :transload_files

  def transload_files
    TransloadService.sync( self.to_dir, self.files )
  end
end

The transload_files method is the issue.  Here is the transload service:

class TransloadService

    class << self

        def sync(check_dir, files)
            # First we have to check the transload dir for files that have been deleted on the app
            transloaded_files = Request.list(check_dir)
            cull_list = transloaded_files.reject{ |e| files.map{|t| t.filename }.include? Request.filename(e)}
            if cull_list.count > 0
                Request.trim(cull_list)
                p "#{cull_list.count} files trimed from #{check_dir}."
            end

            # Next we have to upload files which arent present in the transload dir

            send_list = files.reject{ |e| transloaded_files.map{|t| Request.filename(t) }.include? e.filename.to_s }
            if send_list.count > 0
                Request.upload_to(check_dir, send_list)
                p "#{send_list.map{|r| r.filename.to_s}.join(', ')} uploaded to #{check_dir}"
            end
        end

    end

end

and here is the relevant code in request.rb

class Request
    class << self
        def upload_to(destination, files)
            files.each do |file|
                send_to = connection.object("#{destination}/#{file.filename}")
                file.open{ |tmp| send_to.upload_file(tmp) }
            end
        end
    end
end

The issue I'm facing is this: When the after_save callback runs the transload_files method it returns
ActiveStorage::FileNotFoundError (ActiveStorage::FileNotFoundError)

When I run the Section.last.transload_files in the console, it performs exactly as intended.  What am I missing here?


问:
Mongoose find by reference field
I have a channel schema like this:

```<code>const channelSchema = new mongoose.Schema(
  {
    name: {
      type: String,
      unique: true
    }
  }
);
</code>```

And this is the feedback schema:

```<code>const feedbackSchema = new mongoose.Schema({
  channelId: {
    type: mongoose.Schema.Types.ObjectId,
    ref: "channel",
    require: true
  }
});
</code>```

How can I find the feedback by channel name?

```<code>Feedback.find({channelId.name : 'something'})
</code>```

Thanks

答:
You can use plugin mongoose-find-by-reference.

Step.1 install

```<code>npm i -S mongoose-find-by-reference
</code>```

npm link
Github link

Step.2 plugin() the plugin

const mongoose = require("mongoose");

// Require mongoose-find-by-reference
const { MongooseFindByReference } = require('mongoose-find-by-reference');

await mongoose.connect("mongodb://localhost:27017/test")

const channelSchema = new mongoose.Schema(
  {
    name: {
      type: String,
      unique: true
    }
  }
);

const feedbackSchema = new mongoose.Schema({
  channelId: {
    type: mongoose.Schema.Types.ObjectId,
    ref: "channel",
    require: true
  }
});

// Execute function plugin() on schema with Reference paths
feedbackSchema.plugin(MongooseFindByReference);

const Channel= mongoose.model('channel', channelSchema );
const Feedback= mongoose.model('feedback', feedbackSchema );
```
<h1>Step.3 just use it!</h1>
```const { _id } = await Channel.create({ name: "C" })

await Feedback.create({channelId : _id})

/** Its conditions will be auto automatically replaced with :
{
  channelId: {
    $in: [
      /* ObjectIDs for Eligible channels */
    ],
  },
}
 */
const findResult = await Feedback.find({channelId.name : 'C'})

```

Title: Mongoose find by reference field

Body:
I have a channel schema like this:

const channelSchema = new mongoose.Schema(
  {
    name: {
      type: String,
      unique: true
    }
  }
);

And this is the feedback schema:

const feedbackSchema = new mongoose.Schema({
  channelId: {
    type: mongoose.Schema.Types.ObjectId,
    ref: "channel",
    require: true
  }
});

How can I find the feedback by channel name?

Feedback.find({channelId.name : 'something'})

Thanks

Body:
You can use plugin mongoose-find-by-reference.

Step.1 install

npm i -S mongoose-find-by-reference

npm link
Github link

Step.2 plugin() the plugin

const mongoose = require("mongoose");

// Require mongoose-find-by-reference
const { MongooseFindByReference } = require('mongoose-find-by-reference');

await mongoose.connect("mongodb://localhost:27017/test")

const channelSchema = new mongoose.Schema(
  {
    name: {
      type: String,
      unique: true
    }
  }
);

const feedbackSchema = new mongoose.Schema({
  channelId: {
    type: mongoose.Schema.Types.ObjectId,
    ref: "channel",
    require: true
  }
});

// Execute function plugin() on schema with Reference paths
feedbackSchema.plugin(MongooseFindByReference);

const Channel= mongoose.model('channel', channelSchema );
const Feedback= mongoose.model('feedback', feedbackSchema );

Step.3 just use it!

const { _id } = await Channel.create({ name: "C" })

await Feedback.create({channelId : _id})

/** Its conditions will be auto automatically replaced with :
{
  channelId: {
    $in: [
      /* ObjectIDs for Eligible channels */
    ],
  },
}
 */
const findResult = await Feedback.find({channelId.name : 'C'})