问:
Django rest framework nest two or more viewsets instead of mapping custom actions with @action decorator
So, lets pretend im trying to build an API for a tiny Chat application. Imagine i have 2 models in my Django project, one is for Messages and the other is for Groups. Each group can have multiple messages, but a message belows to only one Group (resulting in an one to many relationship).

here are the models:

```<code>class Group(models.Model):
    title = models.CharField(max_length=250)

    def get_messages(self):
        return self.messages.all()

class Message(models.Model):
    body = models.TextField()
    group = models.ForeignKey(Group, on_delete=models.CASCADE, related_name="messages")

</code>```

And i have the following Django Rest Framework ViewSets:

```<code>class GroupViewset(viewsets.ModelViewSet):
    queryset = Group.objects.all()
    serializer_class = GroupSerializer

class MessageViewset(viewsets.ModelViewSet):
    queryset = Message.objects.all()
    serializer_class = MessageSerializer

</code>```

Viewsets are great! Only with those few lines i now have full CRUD operations for both Group and Message instances! I just need to access the following routes:

/groups/ -> To make GET, POST operations for Group instances

/groups/<group_pk>/ -> To make GET, PUT, PATCH, DELETE operations for Group instances

/messages/ -> To make GET, POST operations for Message instances

/messages/<message_pk>/ -> To make GET, PUT, PATCH, DELETE operations for Message instances

but since a message belows to a Group, and i can get all messages of a group by doing GroupObject.get_messages(), im looking for a better way to nest Viewsets.

Instead of the message routes i pointed early, i want to have the following routes:

/groups/ -> To make GET, POST operations for Group instances

/groups/<group_pk>/ -> To make GET, PUT, PATCH, DELETE operations for Group instances

/groups/<group_pk>/messages/ -> To make GET, POST operations for the Message instances that belows to the group with the <group_pk> informed.

/groups/<group_pk>/messages/<message_pk>/ -> For GET, PATCH, PUT and DELETE operations on a Message instance with the <message_pk> that belows to the Group instance with the <group_pk>

But heres the thing... i already managed to do it! The problem is that im feeling im not really "DRY" on my viewsets... theres too much code repeat, plus, for every new @action i made, i have to do all on my own, losing the power of a ModelViewset, and since i have a MessageViewset, im looking for a way to use it on top of my GroupViewset.

Heres how im doing it for now:

```<code>class GroupViewset(viewsets.ModelViewSet):

    queryset = Group.objects.all()
    serializer_class = GroupSerializer

    @action(detail=True, methods=["get"])
    def messages(self, request, pk=None):

        group = self.get_object()
        queryset = group.get_messages()

        message_serializer = MessageSerializer(queryset, many=True)
        return Response(message_serializer.data)

    @messages.mapping.post
    def messages_create(self, request, pk=None):
        ...

    @action(detail=True, methods=["get"], url_path=r"messages/(?P<message_pk>[^/.]+)")
    def messages_retrieve(self, request, pk=None, message_pk=None):
        ...

    @messages_retrieve.mapping.put
    def messages_update(self, request, pk=None, message_pk=None):
        ...

    @messages_retrieve.mapping.patch
    def messages_partial_update(self, request, pk=None, message_pk=None):
        ...

    @messages_retrieve.mapping.delete
    def messages_delete(self, request, pk=None, message_pk=None):
        ...

</code>```

Is there a way to nest my MessageViewset in top of my GroupViewset so that i don have to map all methods with @action like im doing it? mapping with @action works but its too much work and code repeat...

I am aware of the existence of the drf-nested-router library, i used it and liked it, but since im learning, i would like to do it on my own first and use it later, only after i figured out how to do it properly by myself.

Body:
So, lets pretend im trying to build an API for a tiny Chat application. Imagine i have 2 models in my Django project, one is for Messages and the other is for Groups. Each group can have multiple messages, but a message belows to only one Group (resulting in an one to many relationship).

here are the models:

class Group(models.Model):
    title = models.CharField(max_length=250)

    def get_messages(self):
        return self.messages.all()

class Message(models.Model):
    body = models.TextField()
    group = models.ForeignKey(Group, on_delete=models.CASCADE, related_name="messages")

And i have the following Django Rest Framework ViewSets:

class GroupViewset(viewsets.ModelViewSet):
    queryset = Group.objects.all()
    serializer_class = GroupSerializer

class MessageViewset(viewsets.ModelViewSet):
    queryset = Message.objects.all()
    serializer_class = MessageSerializer

Viewsets are great! Only with those few lines i now have full CRUD operations for both Group and Message instances! I just need to access the following routes:

/groups/ -> To make GET, POST operations for Group instances

/groups/<group_pk>/ -> To make GET, PUT, PATCH, DELETE operations for Group instances

/messages/ -> To make GET, POST operations for Message instances

/messages/<message_pk>/ -> To make GET, PUT, PATCH, DELETE operations for Message instances

but since a message belows to a Group, and i can get all messages of a group by doing GroupObject.get_messages(), im looking for a better way to nest Viewsets.

Instead of the message routes i pointed early, i want to have the following routes:

/groups/ -> To make GET, POST operations for Group instances

/groups/<group_pk>/ -> To make GET, PUT, PATCH, DELETE operations for Group instances

/groups/<group_pk>/messages/ -> To make GET, POST operations for the Message instances that belows to the group with the <group_pk> informed.

/groups/<group_pk>/messages/<message_pk>/ -> For GET, PATCH, PUT and DELETE operations on a Message instance with the <message_pk> that belows to the Group instance with the <group_pk>

But heres the thing... i already managed to do it! The problem is that im feeling im not really "DRY" on my viewsets... theres too much code repeat, plus, for every new @action i made, i have to do all on my own, losing the power of a ModelViewset, and since i have a MessageViewset, im looking for a way to use it on top of my GroupViewset.

Heres how im doing it for now:

class GroupViewset(viewsets.ModelViewSet):

    queryset = Group.objects.all()
    serializer_class = GroupSerializer

    @action(detail=True, methods=["get"])
    def messages(self, request, pk=None):

        group = self.get_object()
        queryset = group.get_messages()

        message_serializer = MessageSerializer(queryset, many=True)
        return Response(message_serializer.data)

    @messages.mapping.post
    def messages_create(self, request, pk=None):
        ...

    @action(detail=True, methods=["get"], url_path=r"messages/(?P<message_pk>[^/.]+)")
    def messages_retrieve(self, request, pk=None, message_pk=None):
        ...

    @messages_retrieve.mapping.put
    def messages_update(self, request, pk=None, message_pk=None):
        ...

    @messages_retrieve.mapping.patch
    def messages_partial_update(self, request, pk=None, message_pk=None):
        ...

    @messages_retrieve.mapping.delete
    def messages_delete(self, request, pk=None, message_pk=None):
        ...

Is there a way to nest my MessageViewset in top of my GroupViewset so that i don have to map all methods with @action like im doing it? mapping with @action works but its too much work and code repeat...

I am aware of the existence of the drf-nested-router library, i used it and liked it, but since im learning, i would like to do it on my own first and use it later, only after i figured out how to do it properly by myself.


来源: stackexchange

问:
PR curve is strange
I use tab transformer network to classify a binary imbalanced dataset, after getting the probabilities, I plot the ROC and PR curve using scikit-learn, and get the figure like this. The ROC looks normal, but the PR curve is strange

I'm using code like this:

def plot_roc(name, labels, predictions):
    fp, tp, _ = sklearn.metrics.roc_curve(labels, predictions)
    print(sklearn.metrics.auc(fp, tp))
    plt.figure()
    plt.plot(100*fp, 100*tp, label=name, linewidth=2)
    plt.xlabel('False positives [%]')
    plt.ylabel('True positives [%]')
    # plt.xlim([-0.5,20])
    # plt.ylim([80,100.5])
    plt.grid(True)
    ax = plt.gca()
    ax.set_aspect('equal')
    plt.show()

def plot_prc(name, labels, predictions,):
    precision, recall, _ = sklearn.metrics.precision_recall_curve(labels, predictions)
    print(sklearn.metrics.auc(recall, precision))
    plt.figure()
    plt.plot(recall, precision, label=name, linewidth=2)
    plt.ylabel('Precision')
    plt.xlabel('Recall')
    plt.grid(True)
    ax = plt.gca()
    ax.set_aspect('equal')
    plt.show()

probabilies = np.concatenate(predictions)

plot_roc("Tab Transformer", y_val, probabilies)
plot_prc("Tab Transformer", y_val, probabilies)
```

where y_val is the ground truth and probabilies is the output of a network.

Is this result normal? If not, what is causing this?

ContentLicense: CC BY-SA 4.0

Title: PR curve is strange

Body:
I use tab transformer network to classify a binary imbalanced dataset, after getting the probabilities, I plot the ROC and PR curve using scikit-learn, and get the figure like this. The ROC looks normal, but the PR curve is strange

I'm using code like this:

def plot_roc(name, labels, predictions):
    fp, tp, _ = sklearn.metrics.roc_curve(labels, predictions)
    print(sklearn.metrics.auc(fp, tp))
    plt.figure()
    plt.plot(100*fp, 100*tp, label=name, linewidth=2)
    plt.xlabel('False positives [%]')
    plt.ylabel('True positives [%]')
    # plt.xlim([-0.5,20])
    # plt.ylim([80,100.5])
    plt.grid(True)
    ax = plt.gca()
    ax.set_aspect('equal')
    plt.show()

def plot_prc(name, labels, predictions,):
    precision, recall, _ = sklearn.metrics.precision_recall_curve(labels, predictions)
    print(sklearn.metrics.auc(recall, precision))
    plt.figure()
    plt.plot(recall, precision, label=name, linewidth=2)
    plt.ylabel('Precision')
    plt.xlabel('Recall')
    plt.grid(True)
    ax = plt.gca()
    ax.set_aspect('equal')
    plt.show()

probabilies = np.concatenate(predictions)

plot_roc("Tab Transformer", y_val, probabilies)
plot_prc("Tab Transformer", y_val, probabilies)

where y_val is the ground truth and probabilies is the output of a network.

Is this result normal? If not, what is causing this?


问:
Question regarding multiples of preferred work group size and work groups overall
I wanted to test out time comparisons between two platforms - my graphics card and CPU. I've wrote:

```<code>    clGetKernelWorkGroupInfo(kernel, devices_arr[j], CL_KERNEL_WORK_GROUP_SIZE, sizeof(local_work_size),
        &local_work_size, NULL);
</code>```

Global work size is calculated based on rows and columns number of matrix (it's 1D so global_work_size equals product of columns by rows multiplication):

```<code>global_work_size = height_first * width_first;
</code>```

Above clGetKernelWorkGroupInfo function basically dumps biggest work group size possible for calculated kernel in local_work_size variable. For my AMD GPU it is 256, for my Intel CPU it is 8192. Now my question is - whenever I enqueue kernel and specify local_work_size of 8192 and write anything else to global_work_size less than what is NOT a preferred multiple (CL_KERNEL_PREFFERED_WORK_GROUP_SIZE_MULTIPLE), which in Intel's example is equal to 128, then it returns an error code. For example, if my global_work_size is equal to 127*127, then it returns an error code.

If I use global_work_size equal to for example 7*7 = 49 work items (which is less than 8192 naturally) it still crashes, but if I reduce local_work_size to size equal 49 instead of using max work group size of 8192, then it works. Why is that? Fun fact - AMD for example doesn't require reducing the work group size. 7*7 works for local_work_size of 256 (for AMD).

That's the first question, and now for the second question - why someone would try to use local_work_size bigger than max work group size provided? Like in Intel's CPU example - someone could use local_work_size of 8192+128 (when 128 is the preferred multiple) which gives us 8320. But wouldn't that just divide that into another, big work group of 8192 work items, since 8320 won't fit in 1 work group, since as before it was specified - max work group size is 8192? So wouldn't it just be better to use 8192 instead since we won't have to care about adding preferred multiple to the max work group size?

Body:
I wanted to test out time comparisons between two platforms - my graphics card and CPU. I've wrote:

    clGetKernelWorkGroupInfo(kernel, devices_arr[j], CL_KERNEL_WORK_GROUP_SIZE, sizeof(local_work_size),
        &local_work_size, NULL);

Global work size is calculated based on rows and columns number of matrix (it's 1D so global_work_size equals product of columns by rows multiplication):

global_work_size = height_first * width_first;

Above clGetKernelWorkGroupInfo function basically dumps biggest work group size possible for calculated kernel in local_work_size variable. For my AMD GPU it is 256, for my Intel CPU it is 8192. Now my question is - whenever I enqueue kernel and specify local_work_size of 8192 and write anything else to global_work_size less than what is NOT a preferred multiple (CL_KERNEL_PREFFERED_WORK_GROUP_SIZE_MULTIPLE), which in Intel's example is equal to 128, then it returns an error code. For example, if my global_work_size is equal to 127*127, then it returns an error code.

If I use global_work_size equal to for example 7*7 = 49 work items (which is less than 8192 naturally) it still crashes, but if I reduce local_work_size to size equal 49 instead of using max work group size of 8192, then it works. Why is that? Fun fact - AMD for example doesn't require reducing the work group size. 7*7 works for local_work_size of 256 (for AMD).

That's the first question, and now for the second question - why someone would try to use local_work_size bigger than max work group size provided? Like in Intel's CPU example - someone could use local_work_size of 8192+128 (when 128 is the preferred multiple) which gives us 8320. But wouldn't that just divide that into another, big work group of 8192 work items, since 8320 won't fit in 1 work group, since as before it was specified - max work group size is 8192? So wouldn't it just be better to use 8192 instead since we won't have to care about adding preferred multiple to the max work group size?


问:
VBA: Exporting groups of multiple worksheets (each of different range) into a new workbook
I am using these sets of VBA codes to copy and paste multiple worksheets into a new workbook, i.e. exporting into a clean copy of Excel (without the linkage and formulas and PDF.

E.g., my workbook consists of following worksheets: ATP610, ATP610 Power, ATP620, ATP620 Power, ATP648, ATP648 Power, ATP648 KWTP, ATP648 SW, etc. As such, I will need to export three groups of worksheets:

ATP610 and ATP610 Power into a new workbook called ATP610. The worksheets are named as "ATP610 WP&B" and "ATP610 Electricity Profile".

ATP620 and ATP620 Power into a new workbook called ATP620. The worksheets are named as "ATP620 WP&B" and "ATP620 Electricity Profile".

ATP648, ATP648 Power, ATP648 KWTP and ATP648 SW into a new workbook called ATP648. The worksheets are named as "ATP648 WP&B", "ATP648 Electricity Profile", "ATP648 KWTP" and "ATP648 SW".

Note that each worksheet has a different range that I need to copy and paste in both values and format in their own worksheets in a new workbook. E.g. for ATP610, I need to copy D3:AU197 and ATP610 Power, D3:Q29.

When I used these sets of VBA codes for ATP610, the first worksheet ATP610 has been copied over to a new workbook. However, afterwards, I get the error message "Run-time error '424': Object required" and it stopped after the first sheet was copied over to the new workbook. The second worksheet "ATP610 Power" did not get copied over to the new workbook. What did I miss?

I plan to use these codes by copying them into the first sheet for each group of worksheets that I need to export: ATP610, ATP620 and ATP648.

```<code>Sub ExportDataTEST()

    Dim wb As Workbook: Set wb = ThisWorkbook: Dim ws As Worksheet: Set ws = wb.Sheets("ATP610"): ExportData ws, "D3:AU197", "ATP610": Set ws = wb.Sheets("ATP610 Power"): ExportData ws, "D3:Q29", "ATP610":

End Sub

Sub ExportData( _
        ByVal SourceWorksheet As Worksheet, _
        ByVal SourceRangeAddress As String, _
        ByVal TargetNameSuffix As String)
    Const PROC_TITLE As String = "Export Data"

    ' Reference the Source range.
    Dim srg As Range: Set srg = SourceWorksheet.Range(SourceRangeAddress)

    ' Create and reference a new single-worksheet workbook, the Target workbook.
    Dim twb As Workbook: Set twb = Application.Workbooks.Add(xlWBATWorksheet)

    ' Reference the Target worksheet.
    Dim tws As Worksheet: Set tws = twb.Sheets(1) ' the one and only

    ' Copy/paste.

    srg.Copy

    With tws.Range("A1")
        .PasteSpecial Paste:=xlPasteValues
        .PasteSpecial Paste:=xlPasteFormats
        .PasteSpecial Paste:=xlPasteColumnWidths
    End With

    ' Adjust the row heights.

    Dim sCell As Range, r As Long

    For Each sCell In srg.Columns(1).Cells
        r = r + 1
        tws.Rows(1).RowHeight = sCell.RowHeight
    Next sCell

    ' Get the path of the new workbook.

    Dim tBaseName As String: tBaseName = ws.Name & TargetNameSuffix

    Dim tPath As Variant: tPath = Application.GetSaveAsFilename( _
        InitialFileName:=tBaseName, _
        FileFilter:="Excel Workbooks (*.xlsx),*.xlsx")

    If VarType(tPath) = vbBoolean Then
        MsgBox "Saving operation canceled", vbExclamation, PROC_TITLE
        twb.Close SaveChanges:=False
        Application.CutCopyMode = False
        Exit Sub
    End If

    ' Save the new workbook.

    Dim ErrNum As Long
    Dim ErrDescription As String

    Application.DisplayAlerts = False ' overwrite without confirmation
        On Error Resume Next ' e.g. workbook with same name is already open
           twb.SaveAs Filename:=tPath
           ErrNum = Err.Number
           ErrDescription = Err.Description
        On Error GoTo 0
    Application.DisplayAlerts = True

    If ErrNum <> 0 Then
        MsgBox "Run-time error '" & ErrNum & vbLf & vbLf & ErrDescription, _
            vbCritical, PROC_TITLE
        Exit Sub
    End If

    twb.Close SaveChanges:=False ' just got saved

    ' Export to PDF.

    srg.ExportAsFixedFormat Type:=xlTypePDF, Filename:=tBaseName, _
        Quality:=xlQualityStandard, IncludeDocProperties:=True, _
        IgnorePrintAreas:=False, OpenAfterPublish:=False

End Sub
</code>```

Body:
I am using these sets of VBA codes to copy and paste multiple worksheets into a new workbook, i.e. exporting into a clean copy of Excel (without the linkage and formulas and PDF.

E.g., my workbook consists of following worksheets: ATP610, ATP610 Power, ATP620, ATP620 Power, ATP648, ATP648 Power, ATP648 KWTP, ATP648 SW, etc. As such, I will need to export three groups of worksheets:

ATP610 and ATP610 Power into a new workbook called ATP610. The worksheets are named as "ATP610 WP&B" and "ATP610 Electricity Profile".

ATP620 and ATP620 Power into a new workbook called ATP620. The worksheets are named as "ATP620 WP&B" and "ATP620 Electricity Profile".

ATP648, ATP648 Power, ATP648 KWTP and ATP648 SW into a new workbook called ATP648. The worksheets are named as "ATP648 WP&B", "ATP648 Electricity Profile", "ATP648 KWTP" and "ATP648 SW".

Note that each worksheet has a different range that I need to copy and paste in both values and format in their own worksheets in a new workbook. E.g. for ATP610, I need to copy D3:AU197 and ATP610 Power, D3:Q29.

When I used these sets of VBA codes for ATP610, the first worksheet ATP610 has been copied over to a new workbook. However, afterwards, I get the error message "Run-time error '424': Object required" and it stopped after the first sheet was copied over to the new workbook. The second worksheet "ATP610 Power" did not get copied over to the new workbook. What did I miss?

I plan to use these codes by copying them into the first sheet for each group of worksheets that I need to export: ATP610, ATP620 and ATP648.

Sub ExportDataTEST()

    Dim wb As Workbook: Set wb = ThisWorkbook: Dim ws As Worksheet: Set ws = wb.Sheets("ATP610"): ExportData ws, "D3:AU197", "ATP610": Set ws = wb.Sheets("ATP610 Power"): ExportData ws, "D3:Q29", "ATP610":

End Sub

Sub ExportData( _
        ByVal SourceWorksheet As Worksheet, _
        ByVal SourceRangeAddress As String, _
        ByVal TargetNameSuffix As String)
    Const PROC_TITLE As String = "Export Data"

    ' Reference the Source range.
    Dim srg As Range: Set srg = SourceWorksheet.Range(SourceRangeAddress)

    ' Create and reference a new single-worksheet workbook, the Target workbook.
    Dim twb As Workbook: Set twb = Application.Workbooks.Add(xlWBATWorksheet)

    ' Reference the Target worksheet.
    Dim tws As Worksheet: Set tws = twb.Sheets(1) ' the one and only

    ' Copy/paste.

    srg.Copy

    With tws.Range("A1")
        .PasteSpecial Paste:=xlPasteValues
        .PasteSpecial Paste:=xlPasteFormats
        .PasteSpecial Paste:=xlPasteColumnWidths
    End With

    ' Adjust the row heights.

    Dim sCell As Range, r As Long

    For Each sCell In srg.Columns(1).Cells
        r = r + 1
        tws.Rows(1).RowHeight = sCell.RowHeight
    Next sCell

    ' Get the path of the new workbook.

    Dim tBaseName As String: tBaseName = ws.Name & TargetNameSuffix

    Dim tPath As Variant: tPath = Application.GetSaveAsFilename( _
        InitialFileName:=tBaseName, _
        FileFilter:="Excel Workbooks (*.xlsx),*.xlsx")

    If VarType(tPath) = vbBoolean Then
        MsgBox "Saving operation canceled", vbExclamation, PROC_TITLE
        twb.Close SaveChanges:=False
        Application.CutCopyMode = False
        Exit Sub
    End If

    ' Save the new workbook.

    Dim ErrNum As Long
    Dim ErrDescription As String

    Application.DisplayAlerts = False ' overwrite without confirmation
        On Error Resume Next ' e.g. workbook with same name is already open
           twb.SaveAs Filename:=tPath
           ErrNum = Err.Number
           ErrDescription = Err.Description
        On Error GoTo 0
    Application.DisplayAlerts = True

    If ErrNum <> 0 Then
        MsgBox "Run-time error '" & ErrNum & vbLf & vbLf & ErrDescription, _
            vbCritical, PROC_TITLE
        Exit Sub
    End If

    twb.Close SaveChanges:=False ' just got saved

    ' Export to PDF.

    srg.ExportAsFixedFormat Type:=xlTypePDF, Filename:=tBaseName, _
        Quality:=xlQualityStandard, IncludeDocProperties:=True, _
        IgnorePrintAreas:=False, OpenAfterPublish:=False

End Sub


问:
VBA Writing to Array Using Userform Results in 'Subscript Out of Range' at Array Size of 10
I am using a VBA user form to audit the part numbers put onto a roller cart and the corresponding slot number. I want the users to be able to use a bar code scanner to scan parts and slot numbers in any order, so I just need to determine the maximum slot number that they scan, no matter which order they scan the parts and slots in. That means being able to search an array for a maximum slot value, which I have done, and redimension the part number array to it. This code works perfectly until the part number array size hits ten, then the if statement that I used to determine the maximum slot number is no longer triggered, meaning my part number array cannot be redimensioned to the new maximum value and I get a 'Subscript out of Range' error. Any ideas why this might be happening? I'm at a loss. Any help is greatly appreciated!

P.S. Some public variables shown below are not used in this section of the code. Also, this is the code for the entire continue button, but focus is really only on the code before the first unload statement.

`

```<code>Public Item As Variant
Public SlotNum(), clicked, I, max, c, p, z, ECounter As Integer
Public PartNum(), TSN, Beacon As String
Private Sub BTNNextSlot_Click()

If TBSlotNum.Value <> 0 And TBPartNum.Value <> "" Then
        p = 0
        z = 0
        Do While p = 0
            clicked = clicked + 1
            ReDim Preserve SlotNum(clicked)
            SlotNum(clicked) = TBSlotNum.Value
            For Each Item In SlotNum
                If SlotNum(Item) > max Then
                    max = SlotNum(Item)
                End If

            Next Item

        ReDim Preserve PartNum(max)
        PartNum(TBSlotNum.Value) = TBPartNum.Value**
        Unload Step2

        For Each Item In PartNum
            If IsEmpty(Item) Then
                ECounter = ECounter + 1
            End If
        Next Item

        If c = UBound(PartNum) And ECounter = 0 Then
            p = 1
        Else: p = 0
        Load Step2
        Step2.Show
        End If
        Loop
    Else: MsgBox "Complete the above fields"
    End If

    End Sub
</code>```

`

Body:
I am using a VBA user form to audit the part numbers put onto a roller cart and the corresponding slot number. I want the users to be able to use a bar code scanner to scan parts and slot numbers in any order, so I just need to determine the maximum slot number that they scan, no matter which order they scan the parts and slots in. That means being able to search an array for a maximum slot value, which I have done, and redimension the part number array to it. This code works perfectly until the part number array size hits ten, then the if statement that I used to determine the maximum slot number is no longer triggered, meaning my part number array cannot be redimensioned to the new maximum value and I get a 'Subscript out of Range' error. Any ideas why this might be happening? I'm at a loss. Any help is greatly appreciated!

P.S. Some public variables shown below are not used in this section of the code. Also, this is the code for the entire continue button, but focus is really only on the code before the first unload statement.

`

Public Item As Variant
Public SlotNum(), clicked, I, max, c, p, z, ECounter As Integer
Public PartNum(), TSN, Beacon As String
Private Sub BTNNextSlot_Click()

If TBSlotNum.Value <> 0 And TBPartNum.Value <> "" Then
        p = 0
        z = 0
        Do While p = 0
            clicked = clicked + 1
            ReDim Preserve SlotNum(clicked)
            SlotNum(clicked) = TBSlotNum.Value
            For Each Item In SlotNum
                If SlotNum(Item) > max Then
                    max = SlotNum(Item)
                End If

            Next Item

        ReDim Preserve PartNum(max)
        PartNum(TBSlotNum.Value) = TBPartNum.Value**
        Unload Step2

        For Each Item In PartNum
            If IsEmpty(Item) Then
                ECounter = ECounter + 1
            End If
        Next Item

        If c = UBound(PartNum) And ECounter = 0 Then
            p = 1
        Else: p = 0
        Load Step2
        Step2.Show
        End If
        Loop
    Else: MsgBox "Complete the above fields"
    End If

    End Sub

`


问:
RuntimeError: CUDA runtime implicit initialization on GPU:0 failed. Status: out of memory
I predicted it using 2 models and ended the model.
And when I try to restart, the process is not running due to out of memory problem.

```<code>logger.debug(device_lib.list_local_devices())
</code>```

This error occurred while checking the available gpu.

```<code> File "/home/kgtmx/anaconda3/envs/ai-engine/lib/python3.6/site-packages/tensorflow/python/client/device_lib.py", line 43, in list_local_devices
    _convert(s) for s in _pywrap_device_lib.list_devices(serialized_config)
RuntimeError: CUDA runtime implicit initialization on GPU:0 failed. Status: out of memory
</code>```

enter image description here

enter image description here

I checked the gpu status with nvidia-smi, but there was no problem.
I tried looking for solutions to this problem but none of them solved it.

```<code>os.environ['TF_FORCE_GPU_ALLOW_GROWTH'] = 'true'
</code>```

I tried to limit memory usage, but it has not already been applied.

```<code>tf.keras.backend.clear_session()
</code>```

session_clear() does not work.

```<code>from numba import cuda
enter code here`cuda.current_context().trashing.clear()
</code>```

Unable to access numba due to OOM phenomenon.

i am currently using tensorflow 2.5.0 and python 2.8.2

Body:
I predicted it using 2 models and ended the model.
And when I try to restart, the process is not running due to out of memory problem.

logger.debug(device_lib.list_local_devices())

This error occurred while checking the available gpu.

 File "/home/kgtmx/anaconda3/envs/ai-engine/lib/python3.6/site-packages/tensorflow/python/client/device_lib.py", line 43, in list_local_devices
    _convert(s) for s in _pywrap_device_lib.list_devices(serialized_config)
RuntimeError: CUDA runtime implicit initialization on GPU:0 failed. Status: out of memory

enter image description here

enter image description here

I checked the gpu status with nvidia-smi, but there was no problem.
I tried looking for solutions to this problem but none of them solved it.

os.environ['TF_FORCE_GPU_ALLOW_GROWTH'] = 'true'

I tried to limit memory usage, but it has not already been applied.

tf.keras.backend.clear_session()

session_clear() does not work.

from numba import cuda
enter code here`cuda.current_context().trashing.clear()

Unable to access numba due to OOM phenomenon.

i am currently using tensorflow 2.5.0 and python 2.8.2


问:
how to count in django templates
Hi I am trying to count infringement inside templates. The results I am getting for 'a' the counter is 1 1 (two separate values) instead of total count of 2 or 1 1 1 instead of a total of 3. Please help as I am new to programming.

html

```<code> {% for infringer in page_obj %}
  <tr>
  <td>{{infringer.id}}</td>
  <td>{{infringer.created|date:"d M, Y"}}</td>
  <td>{{infringer.name}}</td>
  <td>{{infringer.brand_name}}</td>
  <td>{{infringer.status}}</td>
  <td>
  {% with a=0 %}

  {% for i in inc %}
  {% if infringer.id == i.infringer.id %}

  {{ a|add:"1" }}

    {% endif %}
    {% endfor %}
   {% endwith %}
</code>```

views.py

```<code>@login_required(login_url='login')
def infringerlist(request):
    q = request.GET.get('q') if request.GET.get('q') != None else ''
    ings= Infringer.objects.filter(Q(created__icontains=q) | Q(id__icontains=q) | Q(status__name__icontains=q) | Q(brand_name__icontains=q) | Q(name__icontains=q), customer=request.user.customer,)
    paginator = Paginator(ings, 10)
    page_number = request.GET.get('page')
    page_obj = paginator.get_page(page_number)
    inc = Infringement.objects.filter(customer=request.user.customer)
    context= {'page_obj': page_obj, 'inc': inc}
    return render(request,'base/infringers_list.html', context)
</code>```

Title: how to count in django templates

Body:
Hi I am trying to count infringement inside templates. The results I am getting for 'a' the counter is 1 1 (two separate values) instead of total count of 2 or 1 1 1 instead of a total of 3. Please help as I am new to programming.

html

 {% for infringer in page_obj %}

  {{infringer.id}}
  {{infringer.created|date:"d M, Y"}}
  {{infringer.name}}
  {{infringer.brand_name}}
  {{infringer.status}}

  {% with a=0 %}

  {% for i in inc %}
  {% if infringer.id == i.infringer.id %}

  {{ a|add:"1" }}

    {% endif %}
    {% endfor %}
   {% endwith %}

views.py

@login_required(login_url='login')
def infringerlist(request):
    q = request.GET.get('q') if request.GET.get('q') != None else ''
    ings= Infringer.objects.filter(Q(created__icontains=q) | Q(id__icontains=q) | Q(status__name__icontains=q) | Q(brand_name__icontains=q) | Q(name__icontains=q), customer=request.user.customer,)
    paginator = Paginator(ings, 10)
    page_number = request.GET.get('page')
    page_obj = paginator.get_page(page_number)
    inc = Infringement.objects.filter(customer=request.user.customer)
    context= {'page_obj': page_obj, 'inc': inc}
    return render(request,'base/infringers_list.html', context)


问:
Android studio error "java.io.FileNotFoundException" even file is exist
Error:
java.io.FileNotFoundException: /storage/emulated/0/Android/data/com.lemniscate.dc/files/DC_data/randomforest.model

file randomforest.model is exist and i can see it in my android phone.

But still not able to access it.

It's weka model which i want to use for my Machine Learning project.

Code Where I am using file.

```<code>ref = (Classifier) read(getAssets().open(String.valueOf(file)));
</code>```

Thank you!

Body:
Error:
java.io.FileNotFoundException: /storage/emulated/0/Android/data/com.lemniscate.dc/files/DC_data/randomforest.model

file randomforest.model is exist and i can see it in my android phone.

But still not able to access it.

It's weka model which i want to use for my Machine Learning project.

Code Where I am using file.

ref = (Classifier) read(getAssets().open(String.valueOf(file)));

Thank you!


问:
How can I convert 5 cube group by in Teradata to BQ?
Trying to convert the following Teradata code to BQ, since BQ doesnt support cube group by how do we rewrite this to ensure the cube functionality remains in the output ? There is 8 expressions so i would suspect we will need to enter multiple union statements to get it to convert, but that is not efficient, is there any other way ?</p>
```<code>sel
        cal_dt
        ,month_id
        ,f_dt
        ,coalesce(Product,'_Overall') Product
        ,coalesce(Partner,'_Overall') Partner
        ,coalesce(cntry,'_Overall') cntry
        ,coalesce(Channel,'_Overall') Channel
        ,coalesce(Model,'_Overall') Model
        ,sum(prod_vol           ) Prod
        ,sum(prod_vol_EUR       ) prod_vol_EUR
        ,sum(prod_vol_AUD       ) prod_vol_AUD
        ,sum(prod_vol_CAD       ) prod_vol_CAD
        ,sum(prod_vol_GBP       ) prod_vol_GBP
        ,sum(Revenue        ) Revenue
        ,sum(Revenue_EUR       ) Revenue_EUR
        ,sum(Revenue_AUD       ) Revenue_AUD
        ,sum(Revenue_CAD       ) Revenue_CAD
        ,sum(Revenue_GBP       ) Revenue_GBP
        ,sum(Txns) Txns
        ,sum( actv_sndrs) actv_sndrs
        ,sum( actv_rcvrs) actv_rcvrs
        ,sum(actvns) actvns
            from (sel
                    a.cal_dt
                    ,a.month_id
                    ,f_dt
                    ,cast(Product as varchar(40)) Product
                    ,cast(Partner as varchar(40)) Partner
                    ,cast(cntry as varchar(40)) cntry
                    ,cast(Channel as varchar(40)) Channel
                    ,cast(Model as varchar(40)) Model
                    ,sum(prod_vol           ) prod_vol
                    ,sum(prod_vol_EUR       ) prod_vol_EUR
                    ,sum(prod_vol_AUD       ) prod_vol_AUD
                    ,sum(prod_vol_CAD       ) prod_vol_CAD
                    ,sum(prod_vol_GBP       ) prod_vol_GBP
                    ,sum(Revenue        ) Revenue
                    ,sum(Revenue_EUR       ) Revenue_EUR
                    ,sum(Revenue_AUD       ) Revenue_AUD
                    ,sum(Revenue_CAD       ) Revenue_CAD
                    ,sum(Revenue_GBP       ) Revenue_GBP
                    ,sum(Txns           ) Txns
                    ,count(distinct case when Txns>0 then sndr_id end) actv_sndrs
                    ,count(distinct case when Txns>0 then rcvr_id end) actv_rcvrs
                    ,sum(actvn) actvns
                from base.table a
                join
                    (sel month_id, min(calendar_dt) f_dt from calender.table group by 1) cal on a.month_id=cal.month_id

            group by 1,2,3,cube(4,5,6,7,8)
    ) x
    group by 1,2,3,4,5,6,7,8
</code>```
```<code>

im Trying to rewrite this in an efficient way with BQ
</code>```

Body:
Trying to convert the following Teradata code to BQ, since BQ doesnt support cube group by how do we rewrite this to ensure the cube functionality remains in the output ? There is 8 expressions so i would suspect we will need to enter multiple union statements to get it to convert, but that is not efficient, is there any other way ?

sel
        cal_dt
        ,month_id
        ,f_dt
        ,coalesce(Product,'_Overall') Product
        ,coalesce(Partner,'_Overall') Partner
        ,coalesce(cntry,'_Overall') cntry
        ,coalesce(Channel,'_Overall') Channel
        ,coalesce(Model,'_Overall') Model
        ,sum(prod_vol           ) Prod
        ,sum(prod_vol_EUR       ) prod_vol_EUR
        ,sum(prod_vol_AUD       ) prod_vol_AUD
        ,sum(prod_vol_CAD       ) prod_vol_CAD
        ,sum(prod_vol_GBP       ) prod_vol_GBP
        ,sum(Revenue        ) Revenue
        ,sum(Revenue_EUR       ) Revenue_EUR
        ,sum(Revenue_AUD       ) Revenue_AUD
        ,sum(Revenue_CAD       ) Revenue_CAD
        ,sum(Revenue_GBP       ) Revenue_GBP
        ,sum(Txns) Txns
        ,sum( actv_sndrs) actv_sndrs
        ,sum( actv_rcvrs) actv_rcvrs
        ,sum(actvns) actvns
            from (sel
                    a.cal_dt
                    ,a.month_id
                    ,f_dt
                    ,cast(Product as varchar(40)) Product
                    ,cast(Partner as varchar(40)) Partner
                    ,cast(cntry as varchar(40)) cntry
                    ,cast(Channel as varchar(40)) Channel
                    ,cast(Model as varchar(40)) Model
                    ,sum(prod_vol           ) prod_vol
                    ,sum(prod_vol_EUR       ) prod_vol_EUR
                    ,sum(prod_vol_AUD       ) prod_vol_AUD
                    ,sum(prod_vol_CAD       ) prod_vol_CAD
                    ,sum(prod_vol_GBP       ) prod_vol_GBP
                    ,sum(Revenue        ) Revenue
                    ,sum(Revenue_EUR       ) Revenue_EUR
                    ,sum(Revenue_AUD       ) Revenue_AUD
                    ,sum(Revenue_CAD       ) Revenue_CAD
                    ,sum(Revenue_GBP       ) Revenue_GBP
                    ,sum(Txns           ) Txns
                    ,count(distinct case when Txns>0 then sndr_id end) actv_sndrs
                    ,count(distinct case when Txns>0 then rcvr_id end) actv_rcvrs
                    ,sum(actvn) actvns
                from base.table a
                join
                    (sel month_id, min(calendar_dt) f_dt from calender.table group by 1) cal on a.month_id=cal.month_id

            group by 1,2,3,cube(4,5,6,7,8)
    ) x
    group by 1,2,3,4,5,6,7,8

im Trying to rewrite this in an efficient way with BQ


问:
rn keyboard aware scroll view when press input then it scrolls a little bit up
if I scroll down and press on input then my scroll position scrolls a little bit up. Every time when I press a button my scroll position goes up. How can I prevent this when I press that the scroll position remains the same?</p>
```<code><KeyboardAwareScrollView
  keyboardShouldPersistTaps='handled'
  contentContainerStyle={{flexGrow: 1}}
  alwaysBounceVertical={false}
>
</code>```

Body:
if I scroll down and press on input then my scroll position scrolls a little bit up. Every time when I press a button my scroll position goes up. How can I prevent this when I press that the scroll position remains the same?

<KeyboardAwareScrollView
  keyboardShouldPersistTaps='handled'
  contentContainerStyle={{flexGrow: 1}}
  alwaysBounceVertical={false}
>


问:
Amplify.DataStore.query returns AnyPublisher instead of data
Update: The docs show no additional configurations for "Reading from the database": https://docs.amplify.aws/lib/datastore/getting-started/q/platform/ios/#writing-to-the-database

So I am using AWS Amplify and for some reason, I am unable to get my data to return properly, it keeps coming back with a AnyPublisher return which means that no data was returned.

I have my function setup as the following in the ViewModel:

```<code>func fetchPlaces() async {
    do {
        let items = try await Amplify.DataStore.query(MGLocation.self)
        log.info("\n : (MapGlider) - Locations retrieved successfully: \(items)")
    } catch let error as DataStoreError {
        log.info("\n : (MapGlider) - Error retrieving locations: \(error)")
    } catch {
        log.info("\n : (MapGlider) - Unexpected Error: \(error)")
    }
}
</code>```

I'm then calling it using the following script:

```<code>WindowGroup {
    ContentView()
        .onAppear() {
            Task {
                await model.fetchPlaces()
            }
        }
}
</code>```

I keep getting the following return : (MapGlider) - Locations retrieved successfully: AnyPublisher

I have my API configured properly:

I also have the MGLocation table setup with some data:

Would anyone know what might be the issue? The DataStore Plugin is configured and called inside the ViewModels init:

```<code>func configureAmplifyDataStore() {
    do {
        // AmplifyModels is generated in the previous step
        let dataStorePlugin = AWSDataStorePlugin(modelRegistration: AmplifyModels())
        try Amplify.add(plugin: dataStorePlugin)
        try Amplify.configure()
        log.info("\n : (MapGlider) - Amplify has been configured with DataStore plugin.")
        print("")
    } catch {
        log.info("\n : (MapGlider) - Failed to initialize Amplify with \(error)")
        print("")
    }
}
</code>```

Also the Models are all setup properly:

Body:
Update: The docs show no additional configurations for "Reading from the database": https://docs.amplify.aws/lib/datastore/getting-started/q/platform/ios/#writing-to-the-database

So I am using AWS Amplify and for some reason, I am unable to get my data to return properly, it keeps coming back with a AnyPublisher return which means that no data was returned.

I have my function setup as the following in the ViewModel:

func fetchPlaces() async {
    do {
        let items = try await Amplify.DataStore.query(MGLocation.self)
        log.info("\n : (MapGlider) - Locations retrieved successfully: \(items)")
    } catch let error as DataStoreError {
        log.info("\n : (MapGlider) - Error retrieving locations: \(error)")
    } catch {
        log.info("\n : (MapGlider) - Unexpected Error: \(error)")
    }
}

I'm then calling it using the following script:

WindowGroup {
    ContentView()
        .onAppear() {
            Task {
                await model.fetchPlaces()
            }
        }
}

I keep getting the following return : (MapGlider) - Locations retrieved successfully: AnyPublisher

I have my API configured properly:

I also have the MGLocation table setup with some data:

Would anyone know what might be the issue? The DataStore Plugin is configured and called inside the ViewModels init:

func configureAmplifyDataStore() {
    do {
        // AmplifyModels is generated in the previous step
        let dataStorePlugin = AWSDataStorePlugin(modelRegistration: AmplifyModels())
        try Amplify.add(plugin: dataStorePlugin)
        try Amplify.configure()
        log.info("\n : (MapGlider) - Amplify has been configured with DataStore plugin.")
        print("")
    } catch {
        log.info("\n : (MapGlider) - Failed to initialize Amplify with \(error)")
        print("")
    }
}

Also the Models are all setup properly:


问:
Button filter address border radius error in flutter
Firstly I just want to say thank everyone for everything. I've learned much through reading the threads.

I can change button-search for city in form-address and then change his button search engine radius , but it doesn't work.

I tried giving radius from the parent and still nothing work ,

I tried to make a value to call the function and I call it in the parent section.
Please help me thank you

Here is the code that causes the trouble


问:
Mediapipe installation on Raspberry pi 4b+
During the installation I followed the https://github.com/superuser789/MediaPipe-on-RaspberryPi guide on my Raspberry Pi 4b+ 4gb and running Raspberry Pi OS 32bit. All my packages are up to date.

I ran python3 setup.py gen_protos && python3 setup.py bdist_wheel and got this result:

```<code>ERROR: Traceback (most recent call last):
    File "/home/diegos-pi/.cache/bazel/_bazel_diegos-pi/7f3a9a61ae329ba025208f264fd9a815/external/rules_cc/cc/private/rules_impl/compiler_flag.bzl", line 17, column 76, in <toplevel>
        load("@bazel_tools//tools/cpp:toolchain_utils.bzl", "find_cpp_toolchain", "use_cpp_toolchain")
Error: file '@bazel_tools//tools/cpp:toolchain_utils.bzl' does not contain symbol 'use_cpp_toolchain' (did you mean 'find_cpp_toolchain'?)
ERROR: While resolving toolchains for target //mediapipe/modules/face_detection:face_detection_short_range_cpu: com.google.devtools.build.lib.packages.BuildFileContainsErrorsException: error loading package '@bazel_tools//tools/cpp': in /home/diegos-pi/.cache/bazel/_bazel_diegos-pi/7f3a9a61ae329ba025208f264fd9a815/external/rules_cc/cc/defs.bzl: Extension file 'cc/private/rules_impl/compiler_flag.bzl' has errors
ERROR: Analysis of target '//mediapipe/modules/face_detection:face_detection_short_range_cpu' failed; build aborted: com.google.devtools.build.lib.packages.BuildFileContainsErrorsException: error loading package '@bazel_tools//tools/cpp': in /home/diegos-pi/.cache/bazel/_bazel_diegos-pi/7f3a9a61ae329ba025208f264fd9a815/external/rules_cc/cc/defs.bzl: Extension file 'cc/private/rules_impl/compiler_flag.bzl' has errors
INFO: Elapsed time: 16.113s
INFO: 0 processes.
FAILED: Build did NOT complete successfully (2 packages loaded, 0 targets conf\
igured)

</code>```

Body:
During the installation I followed the https://github.com/superuser789/MediaPipe-on-RaspberryPi guide on my Raspberry Pi 4b+ 4gb and running Raspberry Pi OS 32bit. All my packages are up to date.

I ran python3 setup.py gen_protos && python3 setup.py bdist_wheel and got this result:

ERROR: Traceback (most recent call last):
    File "/home/diegos-pi/.cache/bazel/_bazel_diegos-pi/7f3a9a61ae329ba025208f264fd9a815/external/rules_cc/cc/private/rules_impl/compiler_flag.bzl", line 17, column 76, in <toplevel>
        load("@bazel_tools//tools/cpp:toolchain_utils.bzl", "find_cpp_toolchain", "use_cpp_toolchain")
Error: file '@bazel_tools//tools/cpp:toolchain_utils.bzl' does not contain symbol 'use_cpp_toolchain' (did you mean 'find_cpp_toolchain'?)
ERROR: While resolving toolchains for target //mediapipe/modules/face_detection:face_detection_short_range_cpu: com.google.devtools.build.lib.packages.BuildFileContainsErrorsException: error loading package '@bazel_tools//tools/cpp': in /home/diegos-pi/.cache/bazel/_bazel_diegos-pi/7f3a9a61ae329ba025208f264fd9a815/external/rules_cc/cc/defs.bzl: Extension file 'cc/private/rules_impl/compiler_flag.bzl' has errors
ERROR: Analysis of target '//mediapipe/modules/face_detection:face_detection_short_range_cpu' failed; build aborted: com.google.devtools.build.lib.packages.BuildFileContainsErrorsException: error loading package '@bazel_tools//tools/cpp': in /home/diegos-pi/.cache/bazel/_bazel_diegos-pi/7f3a9a61ae329ba025208f264fd9a815/external/rules_cc/cc/defs.bzl: Extension file 'cc/private/rules_impl/compiler_flag.bzl' has errors
INFO: Elapsed time: 16.113s
INFO: 0 processes.
FAILED: Build did NOT complete successfully (2 packages loaded, 0 targets conf\
igured)


问:
GORM Fetch native query results into a slice of uints
I have a raw query to be used with gorm and I would like to store the results in a slice of uints.

```<code>    taskIds := make([]uint64, 0)
    tx := tx.WithContext(ctx).Debug()
    if err := tx.Raw("select task_id from group_tasks where group_id in ?", intIds).Scan(&taskIds).Error; err != nil {...}
</code>```

Gorm seems to be having a problem doing that. What's the cause and is there a workaround?

Body:
I have a raw query to be used with gorm and I would like to store the results in a slice of uints.

    taskIds := make([]uint64, 0)
    tx := tx.WithContext(ctx).Debug()
    if err := tx.Raw("select task_id from group_tasks where group_id in ?", intIds).Scan(&taskIds).Error; err != nil {...}

Gorm seems to be having a problem doing that. What's the cause and is there a workaround?


问:
how to remove all yup validations for fields for one particular field select?
i am using Formik with yup and I want to remove all fields validation when a particular value form particular field having dropdown is selected.

I cant be able to find any solution yet. Kindly help me about this


问:
question marks (???) when connect to excel file with ODBC driver , FDConnection component
With FDConnection component I read Excel files(xls or xlsx), using ODBC driver, but non-English symbols (for example, Russians, Georgians) are replaced with "???" marks.
In FDComponent I choose only Driver_id "odbc". In Driver combobox I select or not "Microsoft Excel Driver(*.xls)" nothing changed. FDConnection component hasn't parameter like 'character set' to set it to Unicode or utf-8 or utf-16 value.

How and which properties of FDConnection I have to set to read non-English symbols?

Delphi 10.4.2, Office Professional Plus 2021.

in OnCreate procedure I write this code but nothing has been changed:

```<code>FDConnection1.Connected          := false;
FDConnection1.Params.Values['Database']:= ....
FDConnection1.Params.Values['OpenMode']     := 'CreateUTF16';
FDConnection1.Params.Values['StringFormat'] := 'Unicode';
FDConnection1.Connected:=true;
fdQuery1.open;
</code>```

Connection Info of FDConnection component:

```<code>Connection definition parameters
    ================================
    Database=D:\Delphi Projects\Excel\DB\myData.xls
    DriverID=ODBC
    ================================
    FireDAC info
    ================================
    Tool = RAD Studio 10.4
    FireDAC = 27.0.0 (Build 99682)
    Platform = Windows 32 bit
    Defines = FireDAC_NOLOCALE_META;FireDAC_MONITOR
    ================================
    Client info
    ================================
    Loading driver ODBC ...
      Loading odbc32.dll driver manager
      Creating ODBC environment handle
      Variable [ODBCDriver]: [Microsoft Excel Driver (*.xls)]
    Driver Manager version = 03.81.19041.0000
    ================================
    Session info
    ================================
    Current catalog =
    Current schema =
    Driver name = odbcjt32.dll
    Driver version = 10.00.19041
    Driver conformance = 3
    DBMS name = EXCEL
    DBMS version = 08.00.0000
</code>```

Body:
With FDConnection component I read Excel files(xls or xlsx), using ODBC driver, but non-English symbols (for example, Russians, Georgians) are replaced with "???" marks.
In FDComponent I choose only Driver_id "odbc". In Driver combobox I select or not "Microsoft Excel Driver(*.xls)" nothing changed. FDConnection component hasn't parameter like 'character set' to set it to Unicode or utf-8 or utf-16 value.

How and which properties of FDConnection I have to set to read non-English symbols?

Delphi 10.4.2, Office Professional Plus 2021.

in OnCreate procedure I write this code but nothing has been changed:

FDConnection1.Connected          := false;
FDConnection1.Params.Values['Database']:= ....
FDConnection1.Params.Values['OpenMode']     := 'CreateUTF16';
FDConnection1.Params.Values['StringFormat'] := 'Unicode';
FDConnection1.Connected:=true;
fdQuery1.open;

Connection Info of FDConnection component:

Connection definition parameters
    ================================
    Database=D:\Delphi Projects\Excel\DB\myData.xls
    DriverID=ODBC
    ================================
    FireDAC info
    ================================
    Tool = RAD Studio 10.4
    FireDAC = 27.0.0 (Build 99682)
    Platform = Windows 32 bit
    Defines = FireDAC_NOLOCALE_META;FireDAC_MONITOR
    ================================
    Client info
    ================================
    Loading driver ODBC ...
      Loading odbc32.dll driver manager
      Creating ODBC environment handle
      Variable [ODBCDriver]: [Microsoft Excel Driver (*.xls)]
    Driver Manager version = 03.81.19041.0000
    ================================
    Session info
    ================================
    Current catalog =
    Current schema =
    Driver name = odbcjt32.dll
    Driver version = 10.00.19041
    Driver conformance = 3
    DBMS name = EXCEL
    DBMS version = 08.00.0000


问:
How to export a table as pdf in blazor wasm
I am new to Blazor.

I want to generate a PDF of a table. I am using Mudblazor for UI.

I search and find this How can I create a pdf for download in blazor wasm

But this answer gave an error.

Is there any way to export pdf in Mudblazor table? https://dev.mudblazor.com/components/table#api

Can anyone share any example for export pdf in blazor?


问:
How can I fix the Error in `chr_as_locations()`: I keep getting?
I am doing a personal project to learn R , The goal is to make a table that outputs the most costly and least costly hospital. I translated this from Python and I keep getting errors when I go to run the code.

R code below:

```<code>knitr::opts_chunk$set(echo = TRUE)
library(tidyverse)

costs <- read.csv("Inpatient_Prospective_Payment_System__IPPS__Provider_Summary_for_the_Top_100_Diagnosis-Related_Groups__DRG__-_FY2011.csv")

costs <- rename(costs, DRG = 'DRG Definition',
                Total_Cost = ' Average Total Payments ',
                Count_Discharges = ' Total Discharges ')
costs[['DRG_Code', 'DRG_Description']] <- strsplit(costs$DRG, ' - ', fixed = TRUE)
costs <- costs[, -which(names(costs) == 'DRG')]
costs$Avg_DRG_Cost <- ave(costs$Total_Cost, costs$DRG_Code, FUN = mean)
costs$Cost_Diff <- costs$Total_Cost - costs$Avg_DRG_Cost
top_drgs <- costs %>%
  group_by(DRG_Code) %>%
  summarise(Count_Discharges = sum(Count_Discharges)) %>%
  arrange(desc(Count_Discharges))
top_drgs[1,1]

costs %>%
  filter(DRG_Code == '470' & Provider.State == 'CA') %>%
  write.csv("Hip_Replacement_Costs_by_Hosp.csv", row.names = FALSE)
</code>```

And this is the error I am getting:

```<code>Error in rename(costs, DRG = "DRG Definition", Total_Cost = " Average Total Payments ",  :
  unused arguments (DRG = "DRG Definition", Total_Cost = " Average Total Payments ", Count_Discharges = " Total Discharges ")
</code>```

I have been trying to reformat the code and not sure what I am missing to fix the error in 'rename'. I have to keep the name of the variable 'costs'. I attempted even changing the name or even reconfiguring the code. Am I missing data.frame? I am still so new to R personally

Body:
I am doing a personal project to learn R , The goal is to make a table that outputs the most costly and least costly hospital. I translated this from Python and I keep getting errors when I go to run the code.

R code below:

knitr::opts_chunk$set(echo = TRUE)
library(tidyverse)

costs <- read.csv("Inpatient_Prospective_Payment_System__IPPS__Provider_Summary_for_the_Top_100_Diagnosis-Related_Groups__DRG__-_FY2011.csv")

costs <- rename(costs, DRG = 'DRG Definition',
                Total_Cost = ' Average Total Payments ',
                Count_Discharges = ' Total Discharges ')
costs[['DRG_Code', 'DRG_Description']] <- strsplit(costs$DRG, ' - ', fixed = TRUE)
costs <- costs[, -which(names(costs) == 'DRG')]
costs$Avg_DRG_Cost <- ave(costs$Total_Cost, costs$DRG_Code, FUN = mean)
costs$Cost_Diff <- costs$Total_Cost - costs$Avg_DRG_Cost
top_drgs <- costs %>%
  group_by(DRG_Code) %>%
  summarise(Count_Discharges = sum(Count_Discharges)) %>%
  arrange(desc(Count_Discharges))
top_drgs[1,1]

costs %>%
  filter(DRG_Code == '470' & Provider.State == 'CA') %>%
  write.csv("Hip_Replacement_Costs_by_Hosp.csv", row.names = FALSE)

And this is the error I am getting:

Error in rename(costs, DRG = "DRG Definition", Total_Cost = " Average Total Payments ",  :
  unused arguments (DRG = "DRG Definition", Total_Cost = " Average Total Payments ", Count_Discharges = " Total Discharges ")

I have been trying to reformat the code and not sure what I am missing to fix the error in 'rename'. I have to keep the name of the variable 'costs'. I attempted even changing the name or even reconfiguring the code. Am I missing data.frame? I am still so new to R personally


问:
this.afAuth.signInWithRedirect(new firebase.) the rest is not suggesting
I am new to anguler however in this commandthis.afAuth.signInWithRedirect(new firebase.auth.GoogleAuthProvider());
firebase.auth is showing an error can not be fixed</p>
```<code>import { Component, OnInit } from '@angular/core';
import {AngularFireAuth} from '@angular/fire/compat/auth';
import 'firebase/compat/auth';
import 'firebase/compat/firestore';
import * as firebase from 'firebase/compat';
import "firebase/firestore";
import "firebase/auth";
import "firebase/storage";

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.scss']
})
export class LoginComponent{

  constructor(private afAuth:AngularFireAuth) {

  }
  login(){
    this.afAuth.signInWithRedirect(new firebase.auth.GoogleAuthProvider());
  }
  Logout(){
    this.afAuth.signOut();
  }

}
basicall this code is not working I am missing some thing.
</code>```

Body:
I am new to anguler however in this commandthis.afAuth.signInWithRedirect(new firebase.auth.GoogleAuthProvider());
firebase.auth is showing an error can not be fixed

import { Component, OnInit } from '@angular/core';
import {AngularFireAuth} from '@angular/fire/compat/auth';
import 'firebase/compat/auth';
import 'firebase/compat/firestore';
import * as firebase from 'firebase/compat';
import "firebase/firestore";
import "firebase/auth";
import "firebase/storage";

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.scss']
})
export class LoginComponent{

  constructor(private afAuth:AngularFireAuth) {

  }
  login(){
    this.afAuth.signInWithRedirect(new firebase.auth.GoogleAuthProvider());
  }
  Logout(){
    this.afAuth.signOut();
  }

}
basicall this code is not working I am missing some thing.


问:
Python excel formula file saving issues with openpyxl
I'm running into a weird issue when saving changes to an .xlsx file. For testing purposes, the file I'm trying to modify has 10 lines with the last one being formulas. I'm trying to add two names only to the first column and then append that to the file. What's happening is that the once the code is executed the appended file is half the size of the original (adding the two names manually) and when comparing it to the original using Spreadsheet Compare it shows that the new appended file is missing all the formulas in the last row. What's weird though is if I open this new file, it actually has all the formulas and functions identical to the original. The only way to actually have this file updated is if I open and manually save the appended file in excel and then file size gets updated accordingly.

Not sure why this is happening, here the code

```<code>import pandas as pd
import pandas.io.formats.excel

pandas.io.formats.excel.ExcelFormatter.header_style = None

file = r'C:\Users\ABC\Desktop\Test\Project\AutoTracker\tracker.xlsx'

df = pd.read_excel(file,skipfooter=1)

firstNames = {'ABC': "John", 'DEF': "Tom"}

df[1] = df['Name'].map(firstNames)

with pd.ExcelWriter(file, engine="openpyxl", mode="a", if_sheet_exists="overlay") as writer:
    df[1].to_excel(writer, sheet_name='Sheet1', index=False, startrow=1,startcol=1, header=None)
</code>```

I created a copy of the original and made the same changes of adding the two names to compare it to the Python generated version and here are the results:

Note the file size differences in the new file being 6KB while the original with the manually added changes are 11KB.

This is what the excel file actually looks like with the two names added to it:

The excel file looks the same for both versions just for some reason it's not being saved correctly when generated in Python.

Body:
I'm running into a weird issue when saving changes to an .xlsx file. For testing purposes, the file I'm trying to modify has 10 lines with the last one being formulas. I'm trying to add two names only to the first column and then append that to the file. What's happening is that the once the code is executed the appended file is half the size of the original (adding the two names manually) and when comparing it to the original using Spreadsheet Compare it shows that the new appended file is missing all the formulas in the last row. What's weird though is if I open this new file, it actually has all the formulas and functions identical to the original. The only way to actually have this file updated is if I open and manually save the appended file in excel and then file size gets updated accordingly.

Not sure why this is happening, here the code

import pandas as pd
import pandas.io.formats.excel

pandas.io.formats.excel.ExcelFormatter.header_style = None

file = r'C:\Users\ABC\Desktop\Test\Project\AutoTracker\tracker.xlsx'

df = pd.read_excel(file,skipfooter=1)

firstNames = {'ABC': "John", 'DEF': "Tom"}

df[1] = df['Name'].map(firstNames)

with pd.ExcelWriter(file, engine="openpyxl", mode="a", if_sheet_exists="overlay") as writer:
    df[1].to_excel(writer, sheet_name='Sheet1', index=False, startrow=1,startcol=1, header=None)

I created a copy of the original and made the same changes of adding the two names to compare it to the Python generated version and here are the results:

Note the file size differences in the new file being 6KB while the original with the manually added changes are 11KB.

This is what the excel file actually looks like with the two names added to it:

The excel file looks the same for both versions just for some reason it's not being saved correctly when generated in Python.


问:
OPENCV-Python: cv2.matchTemplate (-215:Assertion failed) *Solved
I was trying to use cv2.matchTemplate.

My code :

!pip install opencv-Python

```<code>import cv2
import numpy as np

imgpath = ('E:\\nenv\\venv\\Images')

farm_img = cv2.imread(imgpath+'\\ImageFarm.PNG', cv2.IMREAD_COLOR)
mushray_img = cv2.imread(imgpath+'\\Mushray.PNG', cv2.IMREAD_COLOR)

# (farm_img and mushray_img both open and I see an image)
cv2.imshow('Farm', farm_img)
cv2.waitKey()
cv2.destroyAllWindows()

cv2.imshow('mush', mushray_img)
cv2.waitKey()
cv2.destroyAllWindows()

result = cv2.matchTemplate(farm_img, mushray_img, cv2.TM_CCOEFF_NORMED)

# (This doesn't work because I can't define 'result')
cv2.imshow ('Result', result)
cv2.waitKey()
cv2.destroyAllWindows()
</code>```

I tried to change in my code :

```<code>farm_img = cv2.imread(imgpath+'\\ImageFarm.PNG', cv2.IMREAD_UNCHANGED)
mushray_img = cv2.imread(imgpath+'\\Mushray.PNG', cv2.IMREAD_UNCHANGED)
</code>```

for

```<code>farm_img = cv2.imread(imgpath+'\\ImageFarm.PNG', cv2.IMREAD_COLOR)
mushray_img = cv2.imread(imgpath+'\\Mushray.PNG', cv2.IMREAD_COLOR)
</code>```

Which didn't work

I have found the error:
My template was bigger than the original image so it didn't work.
Also, after some testing maybe the size of the template wasnt in the same aspect ratio. I tried to use a template1 (which was smaller and from the image1) with 1000x1000 image1 which worked. I also tried to use template1 with image2 which was bigger 2000x2000 and also maybe was less zoomed in(I was playing on wakfu) and it didn<T work.

Found it on this post :
python cv2.matchTemplate stops working when I switch from image to video frame
From the first comment by fmw42

Body:
I was trying to use cv2.matchTemplate.

My code :

!pip install opencv-Python

import cv2
import numpy as np

imgpath = ('E:\\nenv\\venv\\Images')

farm_img = cv2.imread(imgpath+'\\ImageFarm.PNG', cv2.IMREAD_COLOR)
mushray_img = cv2.imread(imgpath+'\\Mushray.PNG', cv2.IMREAD_COLOR)

# (farm_img and mushray_img both open and I see an image)
cv2.imshow('Farm', farm_img)
cv2.waitKey()
cv2.destroyAllWindows()

cv2.imshow('mush', mushray_img)
cv2.waitKey()
cv2.destroyAllWindows()

result = cv2.matchTemplate(farm_img, mushray_img, cv2.TM_CCOEFF_NORMED)

# (This doesn't work because I can't define 'result')
cv2.imshow ('Result', result)
cv2.waitKey()
cv2.destroyAllWindows()

I tried to change in my code :

farm_img = cv2.imread(imgpath+'\\ImageFarm.PNG', cv2.IMREAD_UNCHANGED)
mushray_img = cv2.imread(imgpath+'\\Mushray.PNG', cv2.IMREAD_UNCHANGED)

for

farm_img = cv2.imread(imgpath+'\\ImageFarm.PNG', cv2.IMREAD_COLOR)
mushray_img = cv2.imread(imgpath+'\\Mushray.PNG', cv2.IMREAD_COLOR)

Which didn't work

I have found the error:
My template was bigger than the original image so it didn't work.
Also, after some testing maybe the size of the template wasnt in the same aspect ratio. I tried to use a template1 (which was smaller and from the image1) with 1000x1000 image1 which worked. I also tried to use template1 with image2 which was bigger 2000x2000 and also maybe was less zoomed in(I was playing on wakfu) and it didn<T work.

Found it on this post :
python cv2.matchTemplate stops working when I switch from image to video frame
From the first comment by fmw42