问:
Woocommerce codebase - how does the 'PAY FOR ORDER' button is mapped to the handler?
I am not able to understand from the code how does the 'PAY FOR ORDER' button is linked to the corresponding function handler.
When user goes to pay on the cart page (for an existing order), a button called 'PAY FOR ORDER' is displayed. This button is defined in the following file :
"woocommerce/templates/checkout/form-pay.php" --> 'woocommerce_pay_order_button_html'

When the button is clicked, the 'pay_action()' function is invoked. The function defined in the following file :
"woocommerce/includes/class-wc-form-handler.php"

However, I am not able to understand from the Woocommerce code how does the button 'PAY FOR ORDER' is linked to the function 'pay_action()' ?

Thanks !!!


来源: stackexchange

问:
Send images/files or low cost video streaming from Android to PC from a non LAN network using Java
I am new to video streaming but had been doing computer vision and have used an RTMP server to stream a video from Android to PC but it's costing too much data. I would like to create an app with a more condition-based transfer to lessen image transfer costs with a client-server program from Android to PC using Java.

And had thought of 2 different possible solutions:

Using file transfer: How to make a client-server program that would work from Android to PC connected to different networks (mobile data to PC) using Java

Pausing RTMP: How to pause RTMP?

Got any leads?

RTMP server connection (Costs too much data)

```<code>myrtmp_addr = "rtmp://myip:1935/myapp/mystream"
cap = cv2.VideoCapture(myrtmp_addr)
frame,err = cap.read()
</code>```

I was expecting to lessen the data costs by manipulating the RTMP server in Java in android (pause)
Or simply create a client-server file transfer for general purposes.

ContentLicense: CC BY-SA 4.0

Body:
I am new to video streaming but had been doing computer vision and have used an RTMP server to stream a video from Android to PC but it's costing too much data. I would like to create an app with a more condition-based transfer to lessen image transfer costs with a client-server program from Android to PC using Java.

And had thought of 2 different possible solutions:

Using file transfer: How to make a client-server program that would work from Android to PC connected to different networks (mobile data to PC) using Java

Pausing RTMP: How to pause RTMP?

Got any leads?

RTMP server connection (Costs too much data)

myrtmp_addr = "rtmp://myip:1935/myapp/mystream"
cap = cv2.VideoCapture(myrtmp_addr)
frame,err = cap.read()

I was expecting to lessen the data costs by manipulating the RTMP server in Java in android (pause)
Or simply create a client-server file transfer for general purposes.


问:
How to Specify two templates in the same index.html in the Angular Root's project
I'm working on an Angular project and I'm having two Module, each of them is using a different Template.
Now I'm trouble about how to specify it in the index.html file.  cause each template has specifics style.css and bootstrap.min.css files.

Thanks to shame with me your experience about this christmas braker .

I'v try to charge each part of the style.css in the each component.css, but first of all isn't a good approch and it remain the .boostrap.css files conflict.


问:
Getting "Value cannot be null. (Parameter 'source')" on mac m1 but not on windows
After updating dotnet from 2.1 to 6 in my project, I had to replace System.Data.SqlClient by Microsoft.Data.SqlClient.

When project was on dotnet 2.1 and System.Data.SqlClient was remaining, every thing was working well (on mac m1 and windows). but after updating project to dotnet 6 and Microsoft.Data.SqlClient, when run project on windows platform, every thing is ok, but on mac m1 I get the Value cannot be null. (Parameter 'source') error.

I get the error when trying to work with methods of EF Core and Linq such as SaveChanges or Where methods.

this is callstack:

```<code>at System.Linq.ThrowHelper.ThrowArgumentNullException(ExceptionArgument argument)
   at System.Linq.Enumerable.Where[TSource](IEnumerable`1 source, Func`2 predicate)
   at Microsoft.Data.SqlClient.SNI.SSRP.SendUDPRequest(String browserHostname, Int32 port, Byte[] requestPacket, Int64 timerExpire, Boolean allIPsInParallel, SqlConnectionIPAddressPreference ipPreference)
   at Microsoft.Data.SqlClient.SNI.SSRP.GetPortByInstanceName(String browserHostName, String instanceName, Int64 timerExpire, Boolean allIPsInParallel, SqlConnectionIPAddressPreference ipPreference)
   at Microsoft.Data.SqlClient.SNI.SNIProxy.CreateTcpHandle(DataSource details, Int64 timerExpire, Boolean parallel, SqlConnectionIPAddressPreference ipPreference, String cachedFQDN, SQLDNSInfo& pendingDNSInfo, Boolean tlsFirst, String hostNameInCertificate)
   at Microsoft.Data.SqlClient.SNI.SNIProxy.CreateConnectionHandle(String fullServerName, Boolean ignoreSniOpenTimeout, Int64 timerExpire, Byte[]& instanceName, Byte[][]& spnBuffer, String serverSPN, Boolean flushCache, Boolean async, Boolean parallel, Boolean isIntegratedSecurity, SqlConnectionIPAddressPreference ipPreference, String cachedFQDN, SQLDNSInfo& pendingDNSInfo, Boolean tlsFirst, String hostNameInCertificate)
   at Microsoft.Data.SqlClient.SNI.TdsParserStateObjectManaged.CreatePhysicalSNIHandle(String serverName, Boolean ignoreSniOpenTimeout, Int64 timerExpire, Byte[]& instanceName, Byte[][]& spnBuffer, Boolean flushCache, Boolean async, Boolean parallel, SqlConnectionIPAddressPreference iPAddressPreference, String cachedFQDN, SQLDNSInfo& pendingDNSInfo, String serverSPN, Boolean isIntegratedSecurity, Boolean tlsFirst, String hostNameInCertificate)
   at Microsoft.Data.SqlClient.TdsParser.Connect(ServerInfo serverInfo, SqlInternalConnectionTds connHandler, Boolean ignoreSniOpenTimeout, Int64 timerExpire, SqlConnectionString connectionOptions, Boolean withFailover)
   at Microsoft.Data.SqlClient.SqlInternalConnectionTds.AttemptOneLogin(ServerInfo serverInfo, String newPassword, SecureString newSecurePassword, Boolean ignoreSniOpenTimeout, TimeoutTimer timeout, Boolean withFailover)
   at Microsoft.Data.SqlClient.SqlInternalConnectionTds.LoginNoFailover(ServerInfo serverInfo, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance, SqlConnectionString connectionOptions, SqlCredential credential, TimeoutTimer timeout)
   at Microsoft.Data.SqlClient.SqlInternalConnectionTds.OpenLoginEnlist(TimeoutTimer timeout, SqlConnectionString connectionOptions, SqlCredential credential, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance)
   at Microsoft.Data.SqlClient.SqlInternalConnectionTds..ctor(DbConnectionPoolIdentity identity, SqlConnectionString connectionOptions, SqlCredential credential, Object providerInfo, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance, SqlConnectionString userConnectionOptions, SessionData reconnectSessionData, Boolean applyTransientFaultHandling, String accessToken, DbConnectionPool pool)
   at Microsoft.Data.SqlClient.SqlConnectionFactory.CreateConnection(DbConnectionOptions options, DbConnectionPoolKey poolKey, Object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningConnection, DbConnectionOptions userOptions)
   at Microsoft.Data.ProviderBase.DbConnectionFactory.CreatePooledConnection(DbConnectionPool pool, DbConnection owningObject, DbConnectionOptions options, DbConnectionPoolKey poolKey, DbConnectionOptions userOptions)
   at Microsoft.Data.ProviderBase.DbConnectionPool.CreateObject(DbConnection owningObject, DbConnectionOptions userOptions, DbConnectionInternal oldConnection)
   at Microsoft.Data.ProviderBase.DbConnectionPool.UserCreateRequest(DbConnection owningObject, DbConnectionOptions userOptions, DbConnectionInternal oldConnection)
   at Microsoft.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject, UInt32 waitForMultipleObjectsTimeout, Boolean allowCreate, Boolean onlyOneCheckConnection, DbConnectionOptions userOptions, DbConnectionInternal& connection)
   at Microsoft.Data.ProviderBase.DbConnectionPool.WaitForPendingOpen()
--- End of stack trace from previous location ---
   at Microsoft.EntityFrameworkCore.Storage.RelationalConnection.OpenInternalAsync(Boolean errorsExpected, CancellationToken cancellationToken)
   at Microsoft.EntityFrameworkCore.Storage.RelationalConnection.OpenInternalAsync(Boolean errorsExpected, CancellationToken cancellationToken)
   at Microsoft.EntityFrameworkCore.Storage.RelationalConnection.OpenAsync(CancellationToken cancellationToken, Boolean errorsExpected)
   at Microsoft.EntityFrameworkCore.Update.Internal.BatchExecutor.ExecuteAsync(IEnumerable`1 commandBatches, IRelationalConnection connection, CancellationToken cancellationToken)
   at Microsoft.EntityFrameworkCore.Update.Internal.BatchExecutor.ExecuteAsync(IEnumerable`1 commandBatches, IRelationalConnection connection, CancellationToken cancellationToken)
   at Microsoft.EntityFrameworkCore.Update.Internal.BatchExecutor.ExecuteAsync(IEnumerable`1 commandBatches, IRelationalConnection connection, CancellationToken cancellationToken)
   at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.StateManager.SaveChangesAsync(IList`1 entriesToSave, CancellationToken cancellationToken)
   at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.StateManager.SaveChangesAsync(StateManager stateManager, Boolean acceptAllChangesOnSuccess, CancellationToken cancellationToken)
   at Microsoft.EntityFrameworkCore.SqlServer.Storage.Internal.SqlServerExecutionStrategy.ExecuteAsync[TState,TResult](TState state, Func`4 operation, Func`4 verifySucceeded, CancellationToken cancellationToken)
   at Microsoft.EntityFrameworkCore.DbContext.SaveChangesAsync(Boolean acceptAllChangesOnSuccess, CancellationToken cancellationToken)
   at Microsoft.EntityFrameworkCore.DbContext.SaveChangesAsync(Boolean acceptAllChangesOnSuccess, CancellationToken cancellationToken)
   at ICD.Framework.Data.UnitOfWork.UnitOfWork.SaveChangesAsync(CancellationToken cancellationToken)
   at ICD.Base.BusinessService.ContactTypeService.InsertContactTypeAsync(InsertContactTypeRequest request) in /Users/hmd/Documents/icd/base/ICD.Base.BusinessService/ContactTypeService.cs:line 97
</code>```

and Connection string:

```<code>"BaseDbContext": "Data Source=172.18.176.74\\SANA;Initial Catalog=SANA;User Id=Sana;password=******;MultipleActiveResultSets=true;Persist Security Info=True;"
</code>```

Do you know what is the problem?

Body:
After updating dotnet from 2.1 to 6 in my project, I had to replace System.Data.SqlClient by Microsoft.Data.SqlClient.

When project was on dotnet 2.1 and System.Data.SqlClient was remaining, every thing was working well (on mac m1 and windows). but after updating project to dotnet 6 and Microsoft.Data.SqlClient, when run project on windows platform, every thing is ok, but on mac m1 I get the Value cannot be null. (Parameter 'source') error.

I get the error when trying to work with methods of EF Core and Linq such as SaveChanges or Where methods.

this is callstack:

at System.Linq.ThrowHelper.ThrowArgumentNullException(ExceptionArgument argument)
   at System.Linq.Enumerable.Where[TSource](IEnumerable`1 source, Func`2 predicate)
   at Microsoft.Data.SqlClient.SNI.SSRP.SendUDPRequest(String browserHostname, Int32 port, Byte[] requestPacket, Int64 timerExpire, Boolean allIPsInParallel, SqlConnectionIPAddressPreference ipPreference)
   at Microsoft.Data.SqlClient.SNI.SSRP.GetPortByInstanceName(String browserHostName, String instanceName, Int64 timerExpire, Boolean allIPsInParallel, SqlConnectionIPAddressPreference ipPreference)
   at Microsoft.Data.SqlClient.SNI.SNIProxy.CreateTcpHandle(DataSource details, Int64 timerExpire, Boolean parallel, SqlConnectionIPAddressPreference ipPreference, String cachedFQDN, SQLDNSInfo& pendingDNSInfo, Boolean tlsFirst, String hostNameInCertificate)
   at Microsoft.Data.SqlClient.SNI.SNIProxy.CreateConnectionHandle(String fullServerName, Boolean ignoreSniOpenTimeout, Int64 timerExpire, Byte[]& instanceName, Byte[][]& spnBuffer, String serverSPN, Boolean flushCache, Boolean async, Boolean parallel, Boolean isIntegratedSecurity, SqlConnectionIPAddressPreference ipPreference, String cachedFQDN, SQLDNSInfo& pendingDNSInfo, Boolean tlsFirst, String hostNameInCertificate)
   at Microsoft.Data.SqlClient.SNI.TdsParserStateObjectManaged.CreatePhysicalSNIHandle(String serverName, Boolean ignoreSniOpenTimeout, Int64 timerExpire, Byte[]& instanceName, Byte[][]& spnBuffer, Boolean flushCache, Boolean async, Boolean parallel, SqlConnectionIPAddressPreference iPAddressPreference, String cachedFQDN, SQLDNSInfo& pendingDNSInfo, String serverSPN, Boolean isIntegratedSecurity, Boolean tlsFirst, String hostNameInCertificate)
   at Microsoft.Data.SqlClient.TdsParser.Connect(ServerInfo serverInfo, SqlInternalConnectionTds connHandler, Boolean ignoreSniOpenTimeout, Int64 timerExpire, SqlConnectionString connectionOptions, Boolean withFailover)
   at Microsoft.Data.SqlClient.SqlInternalConnectionTds.AttemptOneLogin(ServerInfo serverInfo, String newPassword, SecureString newSecurePassword, Boolean ignoreSniOpenTimeout, TimeoutTimer timeout, Boolean withFailover)
   at Microsoft.Data.SqlClient.SqlInternalConnectionTds.LoginNoFailover(ServerInfo serverInfo, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance, SqlConnectionString connectionOptions, SqlCredential credential, TimeoutTimer timeout)
   at Microsoft.Data.SqlClient.SqlInternalConnectionTds.OpenLoginEnlist(TimeoutTimer timeout, SqlConnectionString connectionOptions, SqlCredential credential, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance)
   at Microsoft.Data.SqlClient.SqlInternalConnectionTds..ctor(DbConnectionPoolIdentity identity, SqlConnectionString connectionOptions, SqlCredential credential, Object providerInfo, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance, SqlConnectionString userConnectionOptions, SessionData reconnectSessionData, Boolean applyTransientFaultHandling, String accessToken, DbConnectionPool pool)
   at Microsoft.Data.SqlClient.SqlConnectionFactory.CreateConnection(DbConnectionOptions options, DbConnectionPoolKey poolKey, Object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningConnection, DbConnectionOptions userOptions)
   at Microsoft.Data.ProviderBase.DbConnectionFactory.CreatePooledConnection(DbConnectionPool pool, DbConnection owningObject, DbConnectionOptions options, DbConnectionPoolKey poolKey, DbConnectionOptions userOptions)
   at Microsoft.Data.ProviderBase.DbConnectionPool.CreateObject(DbConnection owningObject, DbConnectionOptions userOptions, DbConnectionInternal oldConnection)
   at Microsoft.Data.ProviderBase.DbConnectionPool.UserCreateRequest(DbConnection owningObject, DbConnectionOptions userOptions, DbConnectionInternal oldConnection)
   at Microsoft.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject, UInt32 waitForMultipleObjectsTimeout, Boolean allowCreate, Boolean onlyOneCheckConnection, DbConnectionOptions userOptions, DbConnectionInternal& connection)
   at Microsoft.Data.ProviderBase.DbConnectionPool.WaitForPendingOpen()
--- End of stack trace from previous location ---
   at Microsoft.EntityFrameworkCore.Storage.RelationalConnection.OpenInternalAsync(Boolean errorsExpected, CancellationToken cancellationToken)
   at Microsoft.EntityFrameworkCore.Storage.RelationalConnection.OpenInternalAsync(Boolean errorsExpected, CancellationToken cancellationToken)
   at Microsoft.EntityFrameworkCore.Storage.RelationalConnection.OpenAsync(CancellationToken cancellationToken, Boolean errorsExpected)
   at Microsoft.EntityFrameworkCore.Update.Internal.BatchExecutor.ExecuteAsync(IEnumerable`1 commandBatches, IRelationalConnection connection, CancellationToken cancellationToken)
   at Microsoft.EntityFrameworkCore.Update.Internal.BatchExecutor.ExecuteAsync(IEnumerable`1 commandBatches, IRelationalConnection connection, CancellationToken cancellationToken)
   at Microsoft.EntityFrameworkCore.Update.Internal.BatchExecutor.ExecuteAsync(IEnumerable`1 commandBatches, IRelationalConnection connection, CancellationToken cancellationToken)
   at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.StateManager.SaveChangesAsync(IList`1 entriesToSave, CancellationToken cancellationToken)
   at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.StateManager.SaveChangesAsync(StateManager stateManager, Boolean acceptAllChangesOnSuccess, CancellationToken cancellationToken)
   at Microsoft.EntityFrameworkCore.SqlServer.Storage.Internal.SqlServerExecutionStrategy.ExecuteAsync[TState,TResult](TState state, Func`4 operation, Func`4 verifySucceeded, CancellationToken cancellationToken)
   at Microsoft.EntityFrameworkCore.DbContext.SaveChangesAsync(Boolean acceptAllChangesOnSuccess, CancellationToken cancellationToken)
   at Microsoft.EntityFrameworkCore.DbContext.SaveChangesAsync(Boolean acceptAllChangesOnSuccess, CancellationToken cancellationToken)
   at ICD.Framework.Data.UnitOfWork.UnitOfWork.SaveChangesAsync(CancellationToken cancellationToken)
   at ICD.Base.BusinessService.ContactTypeService.InsertContactTypeAsync(InsertContactTypeRequest request) in /Users/hmd/Documents/icd/base/ICD.Base.BusinessService/ContactTypeService.cs:line 97

and Connection string:

"BaseDbContext": "Data Source=172.18.176.74\\SANA;Initial Catalog=SANA;User Id=Sana;password=******;MultipleActiveResultSets=true;Persist Security Info=True;"

Do you know what is the problem?


问:
No Qt.UserRole in PyQt6
I'm trying to implement a basic progress bar using a delegate within a TreeView widget. I've double-checked the official documentation, and confirmed that the UserRole is supposed to be contained in PyQt6.QtCore.Qt. However, I always get the error upon trying to launch the code

AttributeError: type object 'Qt' has no attribute 'DisplayRole'

How can I solve this problem?

```<code>import sys
from PyQt6 import QtWidgets, QtGui
from PyQt6.QtCore import Qt

print(Qt.UserRole)

class ProgressBarDelegate(QtWidgets.QStyledItemDelegate):
    def paint(self, painter, option, index):
        # Get the data for the item
        progress = index.data(Qt.UserRole)

        # Draw the progress bar
        painter.save()
        rect = option.rect
        rect.setWidth(int(rect.width() * progress))
        painter.fillRect(rect, QtGui.QColor("#00c0ff"))
        painter.restore()

class MainWindow(QtWidgets.QMainWindow):
    def __init__(self):
        super().__init__()

        # Set up the tree view
        self.tree_view = QtWidgets.QTreeView(self)
        self.setCentralWidget(self.tree_view)

        # Set up the model
        self.model = QtGui.QStandardItemModel(self)
        self.tree_view.setModel(self.model)

        # Add some items to the model
        for i in range(10):
            item = QtGui.QStandardItem("Item {}".format(i))
            progress = i / 10
            item.setData(progress, Qt.UserRole)
            self.model.appendRow(item)

        # Set the delegate for the progress bar column
        self.tree_view.setItemDelegateForColumn(1, ProgressBarDelegate(self))

app = QtWidgets.QApplication(sys.argv)
window = MainWindow()
window.show()
sys.exit(app.exec())

</code>```

Update:
I've tried Qt.ItemDataRole.UserRole, it didn't give the error above, but the progress bar didn't show up.

Title: No Qt.UserRole in PyQt6

Body:
I'm trying to implement a basic progress bar using a delegate within a TreeView widget. I've double-checked the official documentation, and confirmed that the UserRole is supposed to be contained in PyQt6.QtCore.Qt. However, I always get the error upon trying to launch the code

AttributeError: type object 'Qt' has no attribute 'DisplayRole'

How can I solve this problem?

import sys
from PyQt6 import QtWidgets, QtGui
from PyQt6.QtCore import Qt

print(Qt.UserRole)

class ProgressBarDelegate(QtWidgets.QStyledItemDelegate):
    def paint(self, painter, option, index):
        # Get the data for the item
        progress = index.data(Qt.UserRole)

        # Draw the progress bar
        painter.save()
        rect = option.rect
        rect.setWidth(int(rect.width() * progress))
        painter.fillRect(rect, QtGui.QColor("#00c0ff"))
        painter.restore()

class MainWindow(QtWidgets.QMainWindow):
    def __init__(self):
        super().__init__()

        # Set up the tree view
        self.tree_view = QtWidgets.QTreeView(self)
        self.setCentralWidget(self.tree_view)

        # Set up the model
        self.model = QtGui.QStandardItemModel(self)
        self.tree_view.setModel(self.model)

        # Add some items to the model
        for i in range(10):
            item = QtGui.QStandardItem("Item {}".format(i))
            progress = i / 10
            item.setData(progress, Qt.UserRole)
            self.model.appendRow(item)

        # Set the delegate for the progress bar column
        self.tree_view.setItemDelegateForColumn(1, ProgressBarDelegate(self))

app = QtWidgets.QApplication(sys.argv)
window = MainWindow()
window.show()
sys.exit(app.exec())

Update:
I've tried Qt.ItemDataRole.UserRole, it didn't give the error above, but the progress bar didn't show up.


问:
Java, Code Folding using Coffee Bytes for Eclipse 2022 and higher versions
When I was using Eclipse 2018-12 (Java 8) I could use Coffee-Bytes plugin for Code Folding.
Coffee-Bytes plugin is rally awesome, but recently I have found that I can use Eclipse 2022 based on JDK 11 (It needs JDK-11 for installing), but I can config that in properties to JDK 8 (1.8) for writing Java 8 in the last version of Eclipse, How perfect, isn't it?!

Eclipse Code Folding using Coffee Bytes

enter image description here

However, Coffee-Bytes plugin, doesn't work with Eclipse 2022 or any version of Eclipse which compatible with JDK 11 (higher than 8) and just works on Eclipse until to 2018-12 version! Opss...

My problem is,
How can I use The Coffee-Bytes plugin in Eclipse 2022 for Code Folding?


问:
How to represent a non-Beneficial criterion in PROMETHEE II method?
I am trying to solve a Multi Criteria Decision Making problem using The PROMETHEE Method, and I have come across PyDecision Library for Python that contains all PROMETHEE Versions, Yet in their Colab demo they have used an abstract example that has only Beneficial Criterions.

Let's say I want to solve this problem:

Alternat
Cost (NB)
RAM (B)
Storage (B)

Phone1
500 $
16 GB
64 GB

Phone2
350 $
8 GB
32 GB

Cost: is a non-beneficial criterion because we want to minimize its value.
Ram & Storage: are Beneficial criterions because we want to maximize these values.

So, is there a way to present the type of criterion to PROMETHEE?


问:
How to speed up animation created using matplotlib?
I am trying to visualize water interference by matplotlib and numpy. But after the caculation is finished, the animation fps is too slow. I have found several ways to solve it but they do not work. I think the caculation process may not be that time costing and I have no idea why the fps is so low.

```<code>import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import make_axes_locatable
import matplotlib.animation as animation

"""
 1.parameter setup
"""
L, sep, N, k, cut = 6, 2, 500, 5*2, 0.8 # 0.5倍寬度, 波源與原點距離, 每邊分割數量, 角波數, z軸範圍
fps, frn = 24, 50         # 每秒影格數量, 影格總數
x = np.linspace(-2*L, 2*L, N)   # x axis
y = np.linspace(-L, L, N)   # y axis
X, Y = np.meshgrid(x, y)    # 2D  matrix
j = complex(0, 1)        # 根號 -1

"""
 2.設定計算振幅的函數, 計算每個位置的振幅並存入陣列
"""
# 自訂函式, 計算每個位置對應的振幅
"""
def func(x, y, t):
    r1 = np.sqrt(x**2 + y**2)    # 點波源1
    for i in range(250):
        r1[i] = y[i]+L
    r2 = np.sqrt((x+sep)**2 + y**2)    # 點波源2
    z = np.exp(j*k*r1)/k*3
    for i in range(250, 499):
        z[i] = np.exp(j*k*(r1[249]+r1[i]))/k*3

    z_real = np.real(z*np.exp(-j*t))

    return  z_real  # 回傳實部
"""

def func(x, y, t, n, a, b):
    """
    r0 = np.sqrt((x-6)**2 + y**2)
    r1 = np.sqrt((x-5)**2 + y**2)
    ...
    r11 = np.sqrt((x+5)**2 + y**2)
    r12 = np.sqrt((x+6)**2 + y**2)
    """
    for i in range(n):
        r = np.sqrt((x-a[i])**2 + (y-b[i])**2)
        if(i == 0):
            z = np.exp(j*k*r)/r
        else:
            z += np.exp(j*k*r)/r

    return np.real(z*np.exp(-j*t))    # 回傳實部

Z = np.zeros((N, N, frn))   # 儲存振幅用的2維陣列
T = np.linspace(0, 2*np.pi, frn)   # 儲存時間用的1維陣列

# user input
n=int(input("輸入波源數量:"))
print('點波源位置輸入格式: x , y')
a=[]
b=[]
for i in range(n):
  temp=input(f"位置{i}:").split(',')
  a.append(int(temp[0]))
  b.append(int(temp[1]))

# 計算每個時刻每個位置對應的振幅, 有加cut效果較佳
for i in range(frn):
    Z[:, :, i] = func(X, Y, T[i], n,a,b).clip(-cut, cut)

"""
 3.繪圖
"""
fig = plt.figure(figsize=(7, 6), dpi=100)   # 開啟繪圖視窗
ax = fig.gca()
ax.set_aspect(1.0)   # 使圖片長寬變成1:1

# 以某個預設的colormap為基底, 修改成對應到 -cut ~ +cut 的colormap
mappable = plt.cm.ScalarMappable(cmap=plt.cm.jet)
mappable.set_array(np.arange(-cut, cut, 0.1))

# 在圖片右側加上color bar, 高度與圖片相同
divider = make_axes_locatable(ax)
cax = divider.append_axes("right", size="5%", pad=0.05)
plt.colorbar(mappable, cax=cax)

# 自訂函式, 先移除前一張圖, 再畫出下一張圖
def update(frame_number):
    plot[0] = ax.contourf(X, Y, Z[:, :, frame_number], cmap=mappable.cmap, norm=mappable.norm)

# t = 0 的圖片
plot = [ax.contourf(X, Y, Z[:, :, 0], cmap=mappable.cmap, norm=mappable.norm)]

# 產生動畫, 目標為繪圖物件fig, 使用自訂函式update更新圖片, 圖片總數為frn, 時間間隔為interal, 單位為ms
ani = animation.FuncAnimation(fig, update, frn, interval=1000/fps)

plt.show()   # 顯示圖片

# ani.save('TwoSourcesInterference2D.gif', writer='imagemagick', fps=fps)   # 儲存圖片
</code>```

I am expected to speed up the animation to about 12fps.

Body:
I am trying to visualize water interference by matplotlib and numpy. But after the caculation is finished, the animation fps is too slow. I have found several ways to solve it but they do not work. I think the caculation process may not be that time costing and I have no idea why the fps is so low.

import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import make_axes_locatable
import matplotlib.animation as animation

"""
 1.parameter setup
"""
L, sep, N, k, cut = 6, 2, 500, 5*2, 0.8 # 0.5倍寬度, 波源與原點距離, 每邊分割數量, 角波數, z軸範圍
fps, frn = 24, 50         # 每秒影格數量, 影格總數
x = np.linspace(-2*L, 2*L, N)   # x axis
y = np.linspace(-L, L, N)   # y axis
X, Y = np.meshgrid(x, y)    # 2D  matrix
j = complex(0, 1)        # 根號 -1

"""
 2.設定計算振幅的函數, 計算每個位置的振幅並存入陣列
"""
# 自訂函式, 計算每個位置對應的振幅
"""
def func(x, y, t):
    r1 = np.sqrt(x**2 + y**2)    # 點波源1
    for i in range(250):
        r1[i] = y[i]+L
    r2 = np.sqrt((x+sep)**2 + y**2)    # 點波源2
    z = np.exp(j*k*r1)/k*3
    for i in range(250, 499):
        z[i] = np.exp(j*k*(r1[249]+r1[i]))/k*3

    z_real = np.real(z*np.exp(-j*t))

    return  z_real  # 回傳實部
"""

def func(x, y, t, n, a, b):
    """
    r0 = np.sqrt((x-6)**2 + y**2)
    r1 = np.sqrt((x-5)**2 + y**2)
    ...
    r11 = np.sqrt((x+5)**2 + y**2)
    r12 = np.sqrt((x+6)**2 + y**2)
    """
    for i in range(n):
        r = np.sqrt((x-a[i])**2 + (y-b[i])**2)
        if(i == 0):
            z = np.exp(j*k*r)/r
        else:
            z += np.exp(j*k*r)/r

    return np.real(z*np.exp(-j*t))    # 回傳實部

Z = np.zeros((N, N, frn))   # 儲存振幅用的2維陣列
T = np.linspace(0, 2*np.pi, frn)   # 儲存時間用的1維陣列

# user input
n=int(input("輸入波源數量:"))
print('點波源位置輸入格式: x , y')
a=[]
b=[]
for i in range(n):
  temp=input(f"位置{i}:").split(',')
  a.append(int(temp[0]))
  b.append(int(temp[1]))

# 計算每個時刻每個位置對應的振幅, 有加cut效果較佳
for i in range(frn):
    Z[:, :, i] = func(X, Y, T[i], n,a,b).clip(-cut, cut)

"""
 3.繪圖
"""
fig = plt.figure(figsize=(7, 6), dpi=100)   # 開啟繪圖視窗
ax = fig.gca()
ax.set_aspect(1.0)   # 使圖片長寬變成1:1

# 以某個預設的colormap為基底, 修改成對應到 -cut ~ +cut 的colormap
mappable = plt.cm.ScalarMappable(cmap=plt.cm.jet)
mappable.set_array(np.arange(-cut, cut, 0.1))

# 在圖片右側加上color bar, 高度與圖片相同
divider = make_axes_locatable(ax)
cax = divider.append_axes("right", size="5%", pad=0.05)
plt.colorbar(mappable, cax=cax)

# 自訂函式, 先移除前一張圖, 再畫出下一張圖
def update(frame_number):
    plot[0] = ax.contourf(X, Y, Z[:, :, frame_number], cmap=mappable.cmap, norm=mappable.norm)

# t = 0 的圖片
plot = [ax.contourf(X, Y, Z[:, :, 0], cmap=mappable.cmap, norm=mappable.norm)]

# 產生動畫, 目標為繪圖物件fig, 使用自訂函式update更新圖片, 圖片總數為frn, 時間間隔為interal, 單位為ms
ani = animation.FuncAnimation(fig, update, frn, interval=1000/fps)

plt.show()   # 顯示圖片

# ani.save('TwoSourcesInterference2D.gif', writer='imagemagick', fps=fps)   # 儲存圖片

I am expected to speed up the animation to about 12fps.


问:
How to get resultSet SYS_REFCURSOR from PL/SQL in executeMany Nodejs?
I'm trying to use the executeMany method to insert some data in my oracle DB.

I have a procedure that looks like:

and node js looks like:

```<code>const connection = async (sql,params,rows) => {
await oracledb.createPool({
    user: USER,
    password: PASSWORD,
    connectString:connectString,
    poolMin: 1,
    poolMax: 100,
    poolIncrement: 1,
    poolTimeOut: 60
});

const conn = await oracledb.getConnection();

try {

    //EXAMPLE
    sql = `BEGIN PROCEDURE_NAME(:param1, :param2, :param3, :param4, :param5, :cursor); END;`;
    params = { param1: '1', param2: '2', param3: '3', param4: '4', param5: '5', cursor: { dir: oracledb.BIND_OUT, type: oracledb.CURSOR } };
    row = { prefetchRows: 1, fetchArraySize: 1 };

    const result = await conn.execute(
        sql,
        params,
        rows
    );

    const resultSet = await result.outBinds.cursor;
    const records = await resultSet.getRows();

    await conn.commit();
    await conn.close();

    return records;
} catch(err){
    return err;
}};
</code>```

Using execute method perfectly works. It inserts the record and return the expected message from the procedure but when using executeMany I am getting an error message related with the cursor

Error: NJS-012: encountered invalid bind data type in parameter 2

This is what I have:

```<code>const connectionMany = async (sql,params) => {
await oracledb.createPool({
    user: USER,
    password: PASSWORD,
    connectString:connectString,
    poolMin: 1,
    poolMax: 100,
    poolIncrement: 1,
    poolTimeOut: 60
});

const conn = await oracledb.getConnection();

try {

    //EXAMPLE

    sql = `BEGIN PROCEDURE_NAME(:param1, :param2, :param3, :param4, :param5, :cursor); END;`;

    params = [
        {
        param1: '1',
        param2: '2',
        param3: '3',
        param4: '4',
        param5: '5',
        cursor: { dir: oracledb.BIND_OUT, type: oracledb.CURSOR }
        },
        {
        param1: '6',
        param2: '7',
        param3: '8',
        param4: '9',
        param5: '10',
        cursor: { dir: oracledb.BIND_OUT, type: oracledb.CURSOR }
        },
        {
        param1: '11',
        param2: '12',
        param3: '13',
        param4: '14',
        param5: '15',
        cursor: { dir: oracledb.BIND_OUT, type: oracledb.CURSOR }
        }
    ];

    const result = await conn.executeMany(
        sql,
        params
    );

    const resultSet = await result.outBinds.cursor;
    const records = await resultSet.getRows();

    await conn.commit();
    await conn.close();

    return records;
} catch(err){
    return err;
}};
</code>```

I am don't know if I am doing something wrong here. If I don't bind the cursor the procedure doesn't work. I tried to delete the cursor from the procedure, rearrange the sql, params without the cursor and it works. It inserts the data but I don't get any result from it. Just an empty object so I don't know whether it was a success or failure.

Body:
I'm trying to use the executeMany method to insert some data in my oracle DB.

I have a procedure that looks like:

and node js looks like:

const connection = async (sql,params,rows) => {
await oracledb.createPool({
    user: USER,
    password: PASSWORD,
    connectString:connectString,
    poolMin: 1,
    poolMax: 100,
    poolIncrement: 1,
    poolTimeOut: 60
});

const conn = await oracledb.getConnection();

try {

    //EXAMPLE
    sql = `BEGIN PROCEDURE_NAME(:param1, :param2, :param3, :param4, :param5, :cursor); END;`;
    params = { param1: '1', param2: '2', param3: '3', param4: '4', param5: '5', cursor: { dir: oracledb.BIND_OUT, type: oracledb.CURSOR } };
    row = { prefetchRows: 1, fetchArraySize: 1 };

    const result = await conn.execute(
        sql,
        params,
        rows
    );

    const resultSet = await result.outBinds.cursor;
    const records = await resultSet.getRows();

    await conn.commit();
    await conn.close();

    return records;
} catch(err){
    return err;
}};

Using execute method perfectly works. It inserts the record and return the expected message from the procedure but when using executeMany I am getting an error message related with the cursor

Error: NJS-012: encountered invalid bind data type in parameter 2

This is what I have:

const connectionMany = async (sql,params) => {
await oracledb.createPool({
    user: USER,
    password: PASSWORD,
    connectString:connectString,
    poolMin: 1,
    poolMax: 100,
    poolIncrement: 1,
    poolTimeOut: 60
});

const conn = await oracledb.getConnection();

try {

    //EXAMPLE

    sql = `BEGIN PROCEDURE_NAME(:param1, :param2, :param3, :param4, :param5, :cursor); END;`;

    params = [
        {
        param1: '1',
        param2: '2',
        param3: '3',
        param4: '4',
        param5: '5',
        cursor: { dir: oracledb.BIND_OUT, type: oracledb.CURSOR }
        },
        {
        param1: '6',
        param2: '7',
        param3: '8',
        param4: '9',
        param5: '10',
        cursor: { dir: oracledb.BIND_OUT, type: oracledb.CURSOR }
        },
        {
        param1: '11',
        param2: '12',
        param3: '13',
        param4: '14',
        param5: '15',
        cursor: { dir: oracledb.BIND_OUT, type: oracledb.CURSOR }
        }
    ];

    const result = await conn.executeMany(
        sql,
        params
    );

    const resultSet = await result.outBinds.cursor;
    const records = await resultSet.getRows();

    await conn.commit();
    await conn.close();

    return records;
} catch(err){
    return err;
}};

I am don't know if I am doing something wrong here. If I don't bind the cursor the procedure doesn't work. I tried to delete the cursor from the procedure, rearrange the sql, params without the cursor and it works. It inserts the data but I don't get any result from it. Just an empty object so I don't know whether it was a success or failure.


问:
Pentaho Workbench Return mdx Query Result in A Tabular Format
I am using Pentaho Version 3.14.0.0-12 on Mac.
When making mdx queries, the results are returned for each axis. Here is an example:

```<code>Axis #0:
{[OrderDate.Days].[2021]}
Axis #1:
{[Measures].[Profit]}
Axis #2:
{[Product.ProductCategory].[Bikes]}
{[Product.ProductCategory].[Accessories]}
{[Product.ProductCategory].[Clothing]}
{[Product.ProductCategory].[Components]}
Row #0: £3,183,670.33
Row #1: £217,753.85
Row #2: £69,062.19
Row #3:
</code>```

Is it possible to enforce a tabular format for the mdx query results?

Body:
I am using Pentaho Version 3.14.0.0-12 on Mac.
When making mdx queries, the results are returned for each axis. Here is an example:

Axis #0:
{[OrderDate.Days].[2021]}
Axis #1:
{[Measures].[Profit]}
Axis #2:
{[Product.ProductCategory].[Bikes]}
{[Product.ProductCategory].[Accessories]}
{[Product.ProductCategory].[Clothing]}
{[Product.ProductCategory].[Components]}
Row #0: £3,183,670.33
Row #1: £217,753.85
Row #2: £69,062.19
Row #3:

Is it possible to enforce a tabular format for the mdx query results?


问:
Intuition behind action predicted by Contextual Bandit on Training dataset
Doing the Contextual Bandit tutorial https://vowpalwabbit.org/docs/vowpal_wabbit/python/latest/tutorials/python_Contextual_bandits_and_Vowpal_Wabbit.html I wanted to try what would the predicted choice/action be when the training dataset was passed to get predictions from the model. I got the following results and I don't understand why the model predicted a different action and not the exact same action as in the training dataset.

I get the predictions like mentioned in the tutorial for the Test DataFrame.

From an expectation point of view, I think the model should have given the same actions as the actions in the training dataset when asked to predict on it.

Code reference

# Prepare the training dataset.
train_data = [
    {
        'action': 1,
        'cost': 2,
        'probability': 0.4,
        'feature1': 'a',
        'feature2': 'c',
        'feature3': '',
    },
    {
        'action': 3,
        'cost': 0,
        'probability': 0.2,
        'feature1': 'b',
        'feature2': 'd',
        'feature3': '',
    },
    {
        'action': 4,
        'cost': 1,
        'probability': 0.5,
        'feature1': 'a',
        'feature2': 'b',
        'feature3': '',
    },
    {
        'action': 2,
        'cost': 1,
        'probability': 0.3,
        'feature1': 'a',
        'feature2': 'b',
        'feature3': 'c',
    },
    {
        'action': 3,
        'cost': 1,
        'probability': 0.7,
        'feature1': 'a',
        'feature2': 'd',
        'feature3': '',
    },
]
train_df = pd.DataFrame(train_data)

train_df['index'] = range(1, len(train_df) + 1)
train_df = train_df.set_index('index')

# Prepare the test dataset.
test_data = [
    {'feature1': 'a', 'feature2': 'c', 'feature3': ''},
    {'feature1': 'b', 'feature2': 'c', 'feature3': ''},
    {'feature1': 'a', 'feature2': '', 'feature3': 'b'},
    {'feature1': 'b', 'feature2': 'b', 'feature3': ''},
    {'feature1': 'a', 'feature2': '', 'feature3': 'b'},
]
test_df = pd.DataFrame(test_data)

test_df['index'] = range(1, len(test_df) + 1)
test_df = test_df.set_index('index')

# Initialize a contextual bandit with four possible actions.
model = vowpalwabbit.Workspace('--cb 4', quiet=True)

# Train the model on each of the training samples.
for i, row in train_df.iterrows():

    # Construct the example in the required Vowpal Wabbit format.
    row_vw = ('{}:{}:{} | {} {} {}'.format(
        str(row['action']),
        str(row['cost']),
        str(row['probability']),
        str(row['feature1']),
        str(row['feature2']),
        str(row['feature3']),
    ))
    model.learn(row_vw)

# Get prediction from the model on both the training and test dataset.
def calculate_prediction(row, model):

    # Construct the example in the required Vowpal Wabbit format.
    row_vw = '| {} {} {}'.format(row['feature1'], row['feature2'], row['feature3'])

    # Get prediction from the model.
    predicted_action = model.predict(row_vw)
    return predicted_action

train_df['predicted_action'] = train_df.apply(calculate_prediction, axis=1, model=model)
test_df['predicted_action'] = test_df.apply(calculate_prediction, axis=1, model=model)

# Predicted actions on the train dataset.
train_df
```


问:
Connect a discord bot with sqlite database?
Could u please help me in:
how to connect a discord bot created in javascript with sqlite Database using those informations:
-host:
-port:
-name:
-user:
-pass:
And Also how to get the database prefix??
Please make in consideration that i'm creating the bot in replit.( Windows )
Thanks a lot waiting for ur responses.

This the code i have to complet...

```<code>DB_ENCRYPTION_KEY=
DB_TYPE=sqlite
DB_HOST=
DB_PORT=
DB_NAME=
DB_USER=
DB_PASS=
DB_TABLE_PREFIX=dsctickets_
</code>```

i tried Nothing coz im new in using sqlite databases; i need help with this please..

Body:
Could u please help me in:
how to connect a discord bot created in javascript with sqlite Database using those informations:
-host:
-port:
-name:
-user:
-pass:
And Also how to get the database prefix??
Please make in consideration that i'm creating the bot in replit.( Windows )
Thanks a lot waiting for ur responses.

This the code i have to complet...

DB_ENCRYPTION_KEY=
DB_TYPE=sqlite
DB_HOST=
DB_PORT=
DB_NAME=
DB_USER=
DB_PASS=
DB_TABLE_PREFIX=dsctickets_

i tried Nothing coz im new in using sqlite databases; i need help with this please..


问:
How to change the plot x axis in time series in graph objects plotly
I want them to go from 0 to 24 h to export those images and create a gif.


问:
Playwright - Cookies not set from storageState file from different domains in Chromium

Concept

I'm using the concept of reusing the authentication state via storageState file in Playwright.

Following is my code snippet spread across different files:

Code

playwright.config.json

import type { PlaywrightTestConfig } from '@playwright/test';
import { devices } from '@playwright/test';

const config: PlaywrightTestConfig = {
    testDir: './e2e',
    reporter: 'html',
    globalSetup: require.resolve('./e2e/global-setup.ts'),
    use: {
        storageState: './e2e/authStorageState.json',
    },

    projects: [
        {
            name: 'firefox',
            use: {
                ...devices['Desktop Firefox'],
            },
        },

        {
            name: 'webkit',
            use: {
                ...devices['Desktop Safari'],
            },
        },

        {
            name: 'chromium',
            use: {
                ...devices['Desktop Chrome'],
            },
        },
    ],
};

export default config;
```
<p><strong>global-setup.ts</strong></p>
<pre class="lang-js prettyprint-override"><code>require('dotenv').config();

import { firefox, FullConfig } from '@playwright/test';
import E2EConstants from './e2e.constants';

const authenticateUser = async () => {
    const browser = await firefox.launch();
    const page = await browser.newPage();

    await page.goto(`${process.env.BASE_URL}/${E2EConstants.LoginPage.URL}`);
    await page
        .getByLabel(E2EConstants.LoginPage.LABEL.EMAIL)
        .fill(process.env.TEST_ADMIN_USERNAME as string);
    await page
        .getByLabel(E2EConstants.LoginPage.LABEL.PASSWORD)
        .fill(process.env.TEST_ADMIN_PASSWORD as string);
    await page.getByText(E2EConstants.LoginPage.BUTTON).click();

    await page.waitForLoadState('networkidle');

    await page.context().storageState({ path: './e2e/authStorageState.json' });

    await browser.close();
};

async function globalSetup(_: FullConfig) {
    await authenticateUser();
}

export default globalSetup;
</code>```

This sets all the cookies in the authStorageState.json file. However, some cookies have domain as .b.com and some of them have the domain as a.b.com.

example.spec.ts

require('dotenv').config();
import { test, expect } from '@playwright/test';

test('homepage has same link', async ({ page }) => {
    await page.goto(process.env.TEST_URL as string);

    await expect(page).toHaveURL(process.env.TEST_URL as string);
});
```

The TEST_URL is the URL with domain a.b.com that is behind authentication and is accessible only when the user is signed in.

Problem

When I run the tests, I see that the Chromium test fails but the Firefox and Webkit tests pass. The test is unable to sign the user in on Chromium, unlike on other browsers. This is because the auth-related cookies (belonging to a.b.com domain) are not set on Chromium but they are set on other browsers. However, the non-auth-related cookies (belonging to .b.com domain) are set properly on all browsers.

What I tried

I tried manually setting the url of the cookies saved in authStorageState.json file to https://a.b.com after deleting the domain and path keys for the auth-related cookies and then when I run the tests, the Chromium test also passes.

The secure key for all cookies, which were not set, had the value as false. I tried manually changing the "secure": true for all cookies which were not set. Note that the sameSite property is set to "None". This change made the Chromium test cases to pass.

The sameSite key for all cookies, which were not set, had the value "None" while having "secure": false property. I tried manually removing the "sameSite": "None" property for all cookies which were not set. Note that I did not change the secure property. This change made the Chromium test cases to pass.

[Note that all the above points were independently implemented as workarounds and were not done together.]

Requirement

However, because the authStorageState.json file is to be created by default on first sign-in, I want to persist the same cookies that appear on browser instead of manually manipulating them. How can I get my Chromium test cases to pass?

Doubts

What is the difference between providing url instead of domain + path for Chromium?

Why do the cookies with subdomain a.b.com require secure property to be set to true and the Chromium-based test cases pass after this change?

Is removing the "sameSite": "None" for all the cookies with subdomain a.b.com right and why do the Chromium-based test cases pass after this change?

Body:
Concept

I'm using the concept of reusing the authentication state via storageState file in Playwright.

Following is my code snippet spread across different files:

Code

playwright.config.json

import type { PlaywrightTestConfig } from '@playwright/test';
import { devices } from '@playwright/test';

const config: PlaywrightTestConfig = {
    testDir: './e2e',
    reporter: 'html',
    globalSetup: require.resolve('./e2e/global-setup.ts'),
    use: {
        storageState: './e2e/authStorageState.json',
    },

    projects: [
        {
            name: 'firefox',
            use: {
                ...devices['Desktop Firefox'],
            },
        },

        {
            name: 'webkit',
            use: {
                ...devices['Desktop Safari'],
            },
        },

        {
            name: 'chromium',
            use: {
                ...devices['Desktop Chrome'],
            },
        },
    ],
};

export default config;

global-setup.ts

require('dotenv').config();

import { firefox, FullConfig } from '@playwright/test';
import E2EConstants from './e2e.constants';

const authenticateUser = async () => {
    const browser = await firefox.launch();
    const page = await browser.newPage();

    await page.goto(`${process.env.BASE_URL}/${E2EConstants.LoginPage.URL}`);
    await page
        .getByLabel(E2EConstants.LoginPage.LABEL.EMAIL)
        .fill(process.env.TEST_ADMIN_USERNAME as string);
    await page
        .getByLabel(E2EConstants.LoginPage.LABEL.PASSWORD)
        .fill(process.env.TEST_ADMIN_PASSWORD as string);
    await page.getByText(E2EConstants.LoginPage.BUTTON).click();

    await page.waitForLoadState('networkidle');

    await page.context().storageState({ path: './e2e/authStorageState.json' });

    await browser.close();
};

async function globalSetup(_: FullConfig) {
    await authenticateUser();
}

export default globalSetup;

This sets all the cookies in the authStorageState.json file. However, some cookies have domain as .b.com and some of them have the domain as a.b.com.

example.spec.ts

require('dotenv').config();
import { test, expect } from '@playwright/test';

test('homepage has same link', async ({ page }) => {
    await page.goto(process.env.TEST_URL as string);

    await expect(page).toHaveURL(process.env.TEST_URL as string);
});

The TEST_URL is the URL with domain a.b.com that is behind authentication and is accessible only when the user is signed in.

Problem

When I run the tests, I see that the Chromium test fails but the Firefox and Webkit tests pass. The test is unable to sign the user in on Chromium, unlike on other browsers. This is because the auth-related cookies (belonging to a.b.com domain) are not set on Chromium but they are set on other browsers. However, the non-auth-related cookies (belonging to .b.com domain) are set properly on all browsers.

What I tried

I tried manually setting the url of the cookies saved in authStorageState.json file to https://a.b.com after deleting the domain and path keys for the auth-related cookies and then when I run the tests, the Chromium test also passes.

The secure key for all cookies, which were not set, had the value as false. I tried manually changing the "secure": true for all cookies which were not set. Note that the sameSite property is set to "None". This change made the Chromium test cases to pass.

The sameSite key for all cookies, which were not set, had the value "None" while having "secure": false property. I tried manually removing the "sameSite": "None" property for all cookies which were not set. Note that I did not change the secure property. This change made the Chromium test cases to pass.

[Note that all the above points were independently implemented as workarounds and were not done together.]

Requirement

However, because the authStorageState.json file is to be created by default on first sign-in, I want to persist the same cookies that appear on browser instead of manually manipulating them. How can I get my Chromium test cases to pass?

Doubts

What is the difference between providing url instead of domain + path for Chromium?

Why do the cookies with subdomain a.b.com require secure property to be set to true and the Chromium-based test cases pass after this change?

Is removing the "sameSite": "None" for all the cookies with subdomain a.b.com right and why do the Chromium-based test cases pass after this change?


问:
Not able to access model attributes in view through thymeleaf and spring boot
I'm having hardtime to access model attribute values in the view using thymeleaf.

```<code>            <h4>Employees per Project</h4>
            <table class="table table-bordered table-striped">
                <thead class="thead-dark">
                    <tr>
                        <th> FirstName<span></span></th>
                        <th> LastName</th>
                        <th>Projects Count</th>
                    </tr>
                </thead>
                <tbody>
                    <tr th:each=" EmpPrjCnt : ${employeeProjectCount} ">
                        <td th:text="${EmpPrjCnt.fName}"></td>
                        <td th:text="${EmpPrjCnt.lname}"></td>
                        <td th:text="${EmpPrjCnt.Pc}"></td>
                    </tr>
                </tbody>
            </table>
        </div>
</code>```

Controller Code:

```<code>List<projectEmployee> employeeProjectCount= empRep.employeeProjects();  //.employeeProjects();
    System.out.println("FROM Home Controller :::::::::: "+employeeProjectCount);
    System.out.println("FROM Home Controller :::::::::: "+employeeProjectCount.get(1).getfName());
    System.out.println("FROM Home Controller :::::::::: "+employeeProjectCount.get(1).getlName());
    System.out.println("FROM Home Controller :::::::::: "+employeeProjectCount.get(1).getPc());

    model.addAttribute("employeeProjectCount", employeeProjectCount);
</code>```

I can access all the attributes in the controller through but not in the view. Let me know where im going wrong.

Error:

```<code>There was an unexpected error (type=Internal Server Error, status=500).
An error happened during template parsing (template: "class path resource [templates/main/Home.html]")
org.thymeleaf.exceptions.TemplateInputException: An error happened during template parsing (template: "class path resource [templates/main/Home.html]")
    at org.thymeleaf.templateparser.markup.AbstractMarkupTemplateParser.parse(AbstractMarkupTemplateParser.java:241)
    at org.thymeleaf.templateparser.markup.AbstractMarkupTemplateParser.parseStandalone(AbstractMarkupTemplateParser.java:100)
    at org.thymeleaf.engine.TemplateManager.parseAndProcess(TemplateManager.java:666)
    at org.thymeleaf.TemplateEngine.process(TemplateEngine.java:1103)
    at org.thymeleaf.TemplateEngine.process(TemplateEngine.java:1077)
    at org.thymeleaf.spring6.view.ThymeleafView.renderFragment(ThymeleafView.java:372)
    at org.thymeleaf.spring6.view.ThymeleafView.render(ThymeleafView.java:192)
    at org.springframework.web.servlet.DispatcherServlet.render(DispatcherServlet.java:1414)
    at org.springframework.web.servlet.DispatcherServlet.processDispatchResult(DispatcherServlet.java:1158)
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1097)
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:973)
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1003)
    at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:895)
    at jakarta.servlet.http.HttpServlet.service(HttpServlet.java:705)
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:880)
    at jakarta.servlet.http.HttpServlet.service(HttpServlet.java:814)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:223)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:158)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:185)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:158)
    at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:100)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:116)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:185)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:158)
    at org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:93)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:116)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:185)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:158)
    at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:201)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:116)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:185)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:158)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:197)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:97)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:542)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:119)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:78)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:357)
    at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:400)
    at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65)
    at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:861)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1739)
    at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:52)
    at org.apache.tomcat.util.threads.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1191)
    at org.apache.tomcat.util.threads.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:659)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.base/java.lang.Thread.run(Thread.java:833)

Caused by: org.attoparser.ParseException: Exception evaluating SpringEL expression: "EmpPrjCnt.fName" (template: "main/Home" - line 70, col 12)
    at org.attoparser.MarkupParser.parseDocument(MarkupParser.java:393)
    at org.attoparser.MarkupParser.parse(MarkupParser.java:257)
    at org.thymeleaf.templateparser.markup.AbstractMarkupTemplateParser.parse(AbstractMarkupTemplateParser.java:230)
    ... 48 more

Caused by: org.thymeleaf.exceptions.TemplateProcessingException: Exception evaluating SpringEL expression: "EmpPrjCnt.fName" (template: "main/Home" - line 70, col 12)
    at org.thymeleaf.spring6.expression.SPELVariableExpressionEvaluator.evaluate(SPELVariableExpressionEvaluator.java:292)
    at org.thymeleaf.standard.expression.VariableExpression.executeVariableExpression(VariableExpression.java:166)
    at org.thymeleaf.standard.expression.SimpleExpression.executeSimple(SimpleExpression.java:66)
    at org.thymeleaf.standard.expression.Expression.execute(Expression.java:109)
    at org.thymeleaf.standard.expression.Expression.execute(Expression.java:138)
    at org.thymeleaf.standard.processor.AbstractStandardExpressionAttributeTagProcessor.doProcess(AbstractStandardExpressionAttributeTagProcessor.java:144)
    at org.thymeleaf.processor.element.AbstractAttributeTagProcessor.doProcess(AbstractAttributeTagProcessor.java:74)
    at org.thymeleaf.processor.element.AbstractElementTagProcessor.process(AbstractElementTagProcessor.java:95)
    at org.thymeleaf.util.ProcessorConfigurationUtils$ElementTagProcessorWrapper.process(ProcessorConfigurationUtils.java:633)
    at org.thymeleaf.engine.ProcessorTemplateHandler.handleOpenElement(ProcessorTemplateHandler.java:1314)
    at org.thymeleaf.engine.OpenElementTag.beHandled(OpenElementTag.java:205)
    at org.thymeleaf.engine.Model.process(Model.java:282)
    at org.thymeleaf.engine.Model.process(Model.java:290)
    at org.thymeleaf.engine.IteratedGatheringModelProcessable.processIterationModel(IteratedGatheringModelProcessable.java:368)
    at org.thymeleaf.engine.IteratedGatheringModelProcessable.process(IteratedGatheringModelProcessable.java:222)
    at org.thymeleaf.engine.ProcessorTemplateHandler.handleCloseElement(ProcessorTemplateHandler.java:1640)
    at org.thymeleaf.engine.TemplateHandlerAdapterMarkupHandler.handleCloseElementEnd(TemplateHandlerAdapterMarkupHandler.java:388)
    at org.thymeleaf.templateparser.markup.InlinedOutputExpressionMarkupHandler$InlineMarkupAdapterPreProcessorHandler.handleCloseElementEnd(InlinedOutputExpressionMarkupHandler.java:322)
    at org.thymeleaf.standard.inline.OutputExpressionInlinePreProcessorHandler.handleCloseElementEnd(OutputExpressionInlinePreProcessorHandler.java:220)
    at org.thymeleaf.templateparser.markup.InlinedOutputExpressionMarkupHandler.handleCloseElementEnd(InlinedOutputExpressionMarkupHandler.java:164)
    at org.attoparser.HtmlElement.handleCloseElementEnd(HtmlElement.java:169)
    at org.attoparser.HtmlMarkupHandler.handleCloseElementEnd(HtmlMarkupHandler.java:412)
    at org.attoparser.MarkupEventProcessorHandler.handleCloseElementEnd(MarkupEventProcessorHandler.java:473)
    at org.attoparser.ParsingElementMarkupUtil.parseCloseElement(ParsingElementMarkupUtil.java:201)
    at org.attoparser.MarkupParser.parseBuffer(MarkupParser.java:725)
    at org.attoparser.MarkupParser.parseDocument(MarkupParser.java:301)
    ... 50 more

Caused by: org.springframework.expression.spel.SpelEvaluationException: EL1021E: A problem occurred whilst attempting to access the property 'fName': 'Accessing member 'fName' is forbidden for type 'class jdk.proxy5.$Proxy124' in Thymeleaf expressions. Blocked classes are: [com.sun.*, jakarta.*, java.*, javax.*, jdk.*, org.ietf.jgss.*, org.omg.*, org.w3c.dom.*, org.xml.sax.*, sun.*]. Allowed classes are: [java.lang.Boolean, java.lang.Byte, java.lang.Character, java.lang.Double, java.lang.Enum, java.lang.Float, java.lang.Integer, java.lang.Iterable, java.lang.Long, java.lang.Math, java.lang.Number, java.lang.Short, java.lang.String, java.math.BigDecimal, java.math.BigInteger, java.math.RoundingMode, java.time.*, java.util.ArrayList, java.util.Calendar, java.util.Calendar, java.util.Collection, java.util.Date, java.util.Enumeration, java.util.HashMap, java.util.HashSet, java.util.Iterator, java.util.LinkedHashMap, java.util.LinkedHashSet, java.util.LinkedList, java.util.List, java.util.Locale, java.util.Map, java.util.Map$Entry, java.util.Optional, java.util.Properties, java.util.Set, java.util.stream.Stream].'
    at org.springframework.expression.spel.ast.PropertyOrFieldReference.readProperty(PropertyOrFieldReference.java:209)
    at org.springframework.expression.spel.ast.PropertyOrFieldReference.getValueInternal(PropertyOrFieldReference.java:104)
    at org.springframework.expression.spel.ast.PropertyOrFieldReference$AccessorLValue.getValue(PropertyOrFieldReference.java:405)
    at org.springframework.expression.spel.ast.CompoundExpression.getValueInternal(CompoundExpression.java:92)
    at org.springframework.expression.spel.ast.SpelNodeImpl.getValue(SpelNodeImpl.java:112)
    at org.springframework.expression.spel.standard.SpelExpression.getValue(SpelExpression.java:338)
    at org.thymeleaf.spring6.expression.SPELVariableExpressionEvaluator.evaluate(SPELVariableExpressionEvaluator.java:265)
    ... 75 more

Caused by: org.springframework.expression.EvaluationException: Accessing member 'fName' is forbidden for type 'class jdk.proxy5.$Proxy124' in Thymeleaf expressions. Blocked classes are: [com.sun.*, jakarta.*, java.*, javax.*, jdk.*, org.ietf.jgss.*, org.omg.*, org.w3c.dom.*, org.xml.sax.*, sun.*]. Allowed classes are: [java.lang.Boolean, java.lang.Byte, java.lang.Character, java.lang.Double, java.lang.Enum, java.lang.Float, java.lang.Integer, java.lang.Iterable, java.lang.Long, java.lang.Math, java.lang.Number, java.lang.Short, java.lang.String, java.math.BigDecimal, java.math.BigInteger, java.math.RoundingMode, java.time.*, java.util.ArrayList, java.util.Calendar, java.util.Calendar, java.util.Collection, java.util.Date, java.util.Enumeration, java.util.HashMap, java.util.HashSet, java.util.Iterator, java.util.LinkedHashMap, java.util.LinkedHashSet, java.util.LinkedList, java.util.List, java.util.Locale, java.util.Map, java.util.Map$Entry, java.util.Optional, java.util.Properties, java.util.Set, java.util.stream.Stream].
    at org.thymeleaf.spring6.expression.ThymeleafEvaluationContext$ThymeleafEvaluationContextACLPropertyAccessor.canRead(ThymeleafEvaluationContext.java:237)
    at org.springframework.expression.spel.ast.PropertyOrFieldReference.readProperty(PropertyOrFieldReference.java:198)
    ... 81 more
</code>```

Body:
I'm having hardtime to access model attribute values in the view using thymeleaf.

Employees per Project

                         FirstName
                         LastName
                        Projects Count

Controller Code:

List<projectEmployee> employeeProjectCount= empRep.employeeProjects();  //.employeeProjects();
    System.out.println("FROM Home Controller :::::::::: "+employeeProjectCount);
    System.out.println("FROM Home Controller :::::::::: "+employeeProjectCount.get(1).getfName());
    System.out.println("FROM Home Controller :::::::::: "+employeeProjectCount.get(1).getlName());
    System.out.println("FROM Home Controller :::::::::: "+employeeProjectCount.get(1).getPc());

    model.addAttribute("employeeProjectCount", employeeProjectCount);

I can access all the attributes in the controller through but not in the view. Let me know where im going wrong.

Error:

There was an unexpected error (type=Internal Server Error, status=500).
An error happened during template parsing (template: "class path resource [templates/main/Home.html]")
org.thymeleaf.exceptions.TemplateInputException: An error happened during template parsing (template: "class path resource [templates/main/Home.html]")
    at org.thymeleaf.templateparser.markup.AbstractMarkupTemplateParser.parse(AbstractMarkupTemplateParser.java:241)
    at org.thymeleaf.templateparser.markup.AbstractMarkupTemplateParser.parseStandalone(AbstractMarkupTemplateParser.java:100)
    at org.thymeleaf.engine.TemplateManager.parseAndProcess(TemplateManager.java:666)
    at org.thymeleaf.TemplateEngine.process(TemplateEngine.java:1103)
    at org.thymeleaf.TemplateEngine.process(TemplateEngine.java:1077)
    at org.thymeleaf.spring6.view.ThymeleafView.renderFragment(ThymeleafView.java:372)
    at org.thymeleaf.spring6.view.ThymeleafView.render(ThymeleafView.java:192)
    at org.springframework.web.servlet.DispatcherServlet.render(DispatcherServlet.java:1414)
    at org.springframework.web.servlet.DispatcherServlet.processDispatchResult(DispatcherServlet.java:1158)
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1097)
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:973)
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1003)
    at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:895)
    at jakarta.servlet.http.HttpServlet.service(HttpServlet.java:705)
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:880)
    at jakarta.servlet.http.HttpServlet.service(HttpServlet.java:814)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:223)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:158)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:185)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:158)
    at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:100)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:116)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:185)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:158)
    at org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:93)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:116)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:185)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:158)
    at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:201)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:116)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:185)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:158)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:197)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:97)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:542)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:119)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:78)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:357)
    at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:400)
    at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65)
    at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:861)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1739)
    at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:52)
    at org.apache.tomcat.util.threads.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1191)
    at org.apache.tomcat.util.threads.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:659)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.base/java.lang.Thread.run(Thread.java:833)

Caused by: org.attoparser.ParseException: Exception evaluating SpringEL expression: "EmpPrjCnt.fName" (template: "main/Home" - line 70, col 12)
    at org.attoparser.MarkupParser.parseDocument(MarkupParser.java:393)
    at org.attoparser.MarkupParser.parse(MarkupParser.java:257)
    at org.thymeleaf.templateparser.markup.AbstractMarkupTemplateParser.parse(AbstractMarkupTemplateParser.java:230)
    ... 48 more

Caused by: org.thymeleaf.exceptions.TemplateProcessingException: Exception evaluating SpringEL expression: "EmpPrjCnt.fName" (template: "main/Home" - line 70, col 12)
    at org.thymeleaf.spring6.expression.SPELVariableExpressionEvaluator.evaluate(SPELVariableExpressionEvaluator.java:292)
    at org.thymeleaf.standard.expression.VariableExpression.executeVariableExpression(VariableExpression.java:166)
    at org.thymeleaf.standard.expression.SimpleExpression.executeSimple(SimpleExpression.java:66)
    at org.thymeleaf.standard.expression.Expression.execute(Expression.java:109)
    at org.thymeleaf.standard.expression.Expression.execute(Expression.java:138)
    at org.thymeleaf.standard.processor.AbstractStandardExpressionAttributeTagProcessor.doProcess(AbstractStandardExpressionAttributeTagProcessor.java:144)
    at org.thymeleaf.processor.element.AbstractAttributeTagProcessor.doProcess(AbstractAttributeTagProcessor.java:74)
    at org.thymeleaf.processor.element.AbstractElementTagProcessor.process(AbstractElementTagProcessor.java:95)
    at org.thymeleaf.util.ProcessorConfigurationUtils$ElementTagProcessorWrapper.process(ProcessorConfigurationUtils.java:633)
    at org.thymeleaf.engine.ProcessorTemplateHandler.handleOpenElement(ProcessorTemplateHandler.java:1314)
    at org.thymeleaf.engine.OpenElementTag.beHandled(OpenElementTag.java:205)
    at org.thymeleaf.engine.Model.process(Model.java:282)
    at org.thymeleaf.engine.Model.process(Model.java:290)
    at org.thymeleaf.engine.IteratedGatheringModelProcessable.processIterationModel(IteratedGatheringModelProcessable.java:368)
    at org.thymeleaf.engine.IteratedGatheringModelProcessable.process(IteratedGatheringModelProcessable.java:222)
    at org.thymeleaf.engine.ProcessorTemplateHandler.handleCloseElement(ProcessorTemplateHandler.java:1640)
    at org.thymeleaf.engine.TemplateHandlerAdapterMarkupHandler.handleCloseElementEnd(TemplateHandlerAdapterMarkupHandler.java:388)
    at org.thymeleaf.templateparser.markup.InlinedOutputExpressionMarkupHandler$InlineMarkupAdapterPreProcessorHandler.handleCloseElementEnd(InlinedOutputExpressionMarkupHandler.java:322)
    at org.thymeleaf.standard.inline.OutputExpressionInlinePreProcessorHandler.handleCloseElementEnd(OutputExpressionInlinePreProcessorHandler.java:220)
    at org.thymeleaf.templateparser.markup.InlinedOutputExpressionMarkupHandler.handleCloseElementEnd(InlinedOutputExpressionMarkupHandler.java:164)
    at org.attoparser.HtmlElement.handleCloseElementEnd(HtmlElement.java:169)
    at org.attoparser.HtmlMarkupHandler.handleCloseElementEnd(HtmlMarkupHandler.java:412)
    at org.attoparser.MarkupEventProcessorHandler.handleCloseElementEnd(MarkupEventProcessorHandler.java:473)
    at org.attoparser.ParsingElementMarkupUtil.parseCloseElement(ParsingElementMarkupUtil.java:201)
    at org.attoparser.MarkupParser.parseBuffer(MarkupParser.java:725)
    at org.attoparser.MarkupParser.parseDocument(MarkupParser.java:301)
    ... 50 more

Caused by: org.springframework.expression.spel.SpelEvaluationException: EL1021E: A problem occurred whilst attempting to access the property 'fName': 'Accessing member 'fName' is forbidden for type 'class jdk.proxy5.$Proxy124' in Thymeleaf expressions. Blocked classes are: [com.sun.*, jakarta.*, java.*, javax.*, jdk.*, org.ietf.jgss.*, org.omg.*, org.w3c.dom.*, org.xml.sax.*, sun.*]. Allowed classes are: [java.lang.Boolean, java.lang.Byte, java.lang.Character, java.lang.Double, java.lang.Enum, java.lang.Float, java.lang.Integer, java.lang.Iterable, java.lang.Long, java.lang.Math, java.lang.Number, java.lang.Short, java.lang.String, java.math.BigDecimal, java.math.BigInteger, java.math.RoundingMode, java.time.*, java.util.ArrayList, java.util.Calendar, java.util.Calendar, java.util.Collection, java.util.Date, java.util.Enumeration, java.util.HashMap, java.util.HashSet, java.util.Iterator, java.util.LinkedHashMap, java.util.LinkedHashSet, java.util.LinkedList, java.util.List, java.util.Locale, java.util.Map, java.util.Map$Entry, java.util.Optional, java.util.Properties, java.util.Set, java.util.stream.Stream].'
    at org.springframework.expression.spel.ast.PropertyOrFieldReference.readProperty(PropertyOrFieldReference.java:209)
    at org.springframework.expression.spel.ast.PropertyOrFieldReference.getValueInternal(PropertyOrFieldReference.java:104)
    at org.springframework.expression.spel.ast.PropertyOrFieldReference$AccessorLValue.getValue(PropertyOrFieldReference.java:405)
    at org.springframework.expression.spel.ast.CompoundExpression.getValueInternal(CompoundExpression.java:92)
    at org.springframework.expression.spel.ast.SpelNodeImpl.getValue(SpelNodeImpl.java:112)
    at org.springframework.expression.spel.standard.SpelExpression.getValue(SpelExpression.java:338)
    at org.thymeleaf.spring6.expression.SPELVariableExpressionEvaluator.evaluate(SPELVariableExpressionEvaluator.java:265)
    ... 75 more

Caused by: org.springframework.expression.EvaluationException: Accessing member 'fName' is forbidden for type 'class jdk.proxy5.$Proxy124' in Thymeleaf expressions. Blocked classes are: [com.sun.*, jakarta.*, java.*, javax.*, jdk.*, org.ietf.jgss.*, org.omg.*, org.w3c.dom.*, org.xml.sax.*, sun.*]. Allowed classes are: [java.lang.Boolean, java.lang.Byte, java.lang.Character, java.lang.Double, java.lang.Enum, java.lang.Float, java.lang.Integer, java.lang.Iterable, java.lang.Long, java.lang.Math, java.lang.Number, java.lang.Short, java.lang.String, java.math.BigDecimal, java.math.BigInteger, java.math.RoundingMode, java.time.*, java.util.ArrayList, java.util.Calendar, java.util.Calendar, java.util.Collection, java.util.Date, java.util.Enumeration, java.util.HashMap, java.util.HashSet, java.util.Iterator, java.util.LinkedHashMap, java.util.LinkedHashSet, java.util.LinkedList, java.util.List, java.util.Locale, java.util.Map, java.util.Map$Entry, java.util.Optional, java.util.Properties, java.util.Set, java.util.stream.Stream].
    at org.thymeleaf.spring6.expression.ThymeleafEvaluationContext$ThymeleafEvaluationContextACLPropertyAccessor.canRead(ThymeleafEvaluationContext.java:237)
    at org.springframework.expression.spel.ast.PropertyOrFieldReference.readProperty(PropertyOrFieldReference.java:198)
    ... 81 more


问:
Why is the voltage rising when I expect a voltage drop in my model?
Part of model

matlab model pdf

In the model, I have 4 blocks each existing with 3 homes and I am feeding homes with a 3-phase Voltage source, on the ways to homes there are resistors and inductors so I  expect voltage drops on lines. 1. and 3. phase as expected I have a voltage drop but in the 2. phase I am seeing a voltage rise which is not normal while I am having those resistors on the line.


问:
how to switch direction (ltr to rtl) dinamiclly while changing language?
I bought a dashboard ui template for my react project,
i read the documentation and implemented the RTL version but it's a one way,
my goal is to set the direction of the HTML side by side with the language,
i want each language will transfer the direction by the language default direction,
arabic - rtl
hebrew - rtl
english - ltr etc...

https://gist.github.com/carmelodevuz/9ee0d92db7bd15c3612e25356139c4f9

thanks.

I tried implementing the "how-to.md" from the docs (linked it here..)


问:
Pelican not rendering rst title and subtitle from imported rst file
I want to import an rst file to my Pelican index page like here:
Pelican: include file's contents on main page

```<code>*****
Title
*****

subtitle
########

subsubtitle
***********

Here is some content in the document.
**ReStructuredText** (rst): plain text markup

.. image:: images/22204100065.png
   :alt: exhale
   :width: 512px
</code>```

only from subsubtitle gets the page rendered as html.
The source of the index.html looks like this

```<code><div class="bg-white dark:bg-zinc-800 p-4 md:p-6 mb-4 rounded-lg"><div class="section" id="subsubtitle"> <h2>subsubtitle</h2>
</code>```

Here is some content in the document. ReStructuredText (rst): plain text markup

The start of the index.html template looks like this:

```<code>{% extends "base.html" %}

{% block content %}

{% block content_title %}
<div class="bg-white dark:bg-zinc-800 p-4 md:p-6 mb-4 rounded-lg">{{ INTRO }}</div>
{% if not category and not tag %}
<div class="my-12 md:my-24 text-zinc-800 dark:text-zinc-300">

  {% if SOCIAL or FEED_ALL_ATOM or FEED_ALL_RSS %}
</code>```

The part of my settings file looks like this (from the answer of above link):

```<code>from pelican.settings import DEFAULT_CONFIG
from pelican.readers import RstReader
config = DEFAULT_CONFIG.copy()
INTRO, _ = RstReader(config).read("content/incls/sample.rst")
</code>```

I expect the Title be rendered in h1 and the Subtitle in h2.

I am using the Papyrus theme. Update: I also tried with notmyidea but have the same problem.

I tried to ask the question in a comment of the above link but I am not allowed.

Body:
I want to import an rst file to my Pelican index page like here:
Pelican: include file's contents on main page

*****
Title
*****

subtitle
########

subsubtitle
***********

Here is some content in the document.
**ReStructuredText** (rst): plain text markup

.. image:: images/22204100065.png
   :alt: exhale
   :width: 512px

only from subsubtitle gets the page rendered as html.
The source of the index.html looks like this

subsubtitle

Here is some content in the document. ReStructuredText (rst): plain text markup

The start of the index.html template looks like this:

{% extends "base.html" %}

{% block content %}

{% block content_title %}

{{ INTRO }}

{% if not category and not tag %}

  {% if SOCIAL or FEED_ALL_ATOM or FEED_ALL_RSS %}

The part of my settings file looks like this (from the answer of above link):

from pelican.settings import DEFAULT_CONFIG
from pelican.readers import RstReader
config = DEFAULT_CONFIG.copy()
INTRO, _ = RstReader(config).read("content/incls/sample.rst")

I expect the Title be rendered in h1 and the Subtitle in h2.

I am using the Papyrus theme. Update: I also tried with notmyidea but have the same problem.

I tried to ask the question in a comment of the above link but I am not allowed.


问:
How is NumPy working with a null OpenBLAS installation?
I've been fiddling around, trying to find my way to a maximally performant installation of NumPy on my new Apple MacBook Air M2 and have arrived at this NumPy configuration:

```<code>(env) dbanas@Davids-Air prj % python3 -c "import numpy as np; np.show_config()"
openblas64__info:
    libraries = ['openblas64_', 'openblas64_']
    library_dirs = ['/usr/local/lib']
    language = c
    define_macros = [('HAVE_CBLAS', None), ('BLAS_SYMBOL_SUFFIX', '64_'), ('HAVE_BLAS_ILP64', None)]
    runtime_library_dirs = ['/usr/local/lib']
blas_ilp64_opt_info:
    libraries = ['openblas64_', 'openblas64_']
    library_dirs = ['/usr/local/lib']
    language = c
    define_macros = [('HAVE_CBLAS', None), ('BLAS_SYMBOL_SUFFIX', '64_'), ('HAVE_BLAS_ILP64', None)]
    runtime_library_dirs = ['/usr/local/lib']
openblas64__lapack_info:
    libraries = ['openblas64_', 'openblas64_']
    library_dirs = ['/usr/local/lib']
    language = c
    define_macros = [('HAVE_CBLAS', None), ('BLAS_SYMBOL_SUFFIX', '64_'), ('HAVE_BLAS_ILP64', None), ('HAVE_LAPACKE', None)]
    runtime_library_dirs = ['/usr/local/lib']
lapack_ilp64_opt_info:
    libraries = ['openblas64_', 'openblas64_']
    library_dirs = ['/usr/local/lib']
    language = c
    define_macros = [('HAVE_CBLAS', None), ('BLAS_SYMBOL_SUFFIX', '64_'), ('HAVE_BLAS_ILP64', None), ('HAVE_LAPACKE', None)]
    runtime_library_dirs = ['/usr/local/lib']
Supported SIMD extensions in this NumPy install:
    baseline = NEON,NEON_FP16,NEON_VFPV4,ASIMD
    found = ASIMDHP
    not found = ASIMDDP,ASIMDFHM
</code>```

I was curious as to whether the installed OpenBLAS runtime libraries were native.
So, I started to probe, but...

```<code>(env) dbanas@Davids-Air prj % ls /usr/local/lib/
    ls: /usr/local/lib/: No such file or directory
    (env) dbanas@Davids-Air prj % ls /usr/local/
    bin
    (env) dbanas@Davids-Air prj % ls /usr/local/bin
    2to3            idle3.11        pydoc3          python3-config      python3.11-config
    2to3-3.11       pip3            pydoc3.11       python3-intel64     python3.11-intel64
    idle3           pip3.11         python3         python3.11      stack
</code>```

So, how did I get through a successful installation of NumPy pointing it at non-existent OpenBLAS libraries?!

Body:
I've been fiddling around, trying to find my way to a maximally performant installation of NumPy on my new Apple MacBook Air M2 and have arrived at this NumPy configuration:

(env) dbanas@Davids-Air prj % python3 -c "import numpy as np; np.show_config()"
openblas64__info:
    libraries = ['openblas64_', 'openblas64_']
    library_dirs = ['/usr/local/lib']
    language = c
    define_macros = [('HAVE_CBLAS', None), ('BLAS_SYMBOL_SUFFIX', '64_'), ('HAVE_BLAS_ILP64', None)]
    runtime_library_dirs = ['/usr/local/lib']
blas_ilp64_opt_info:
    libraries = ['openblas64_', 'openblas64_']
    library_dirs = ['/usr/local/lib']
    language = c
    define_macros = [('HAVE_CBLAS', None), ('BLAS_SYMBOL_SUFFIX', '64_'), ('HAVE_BLAS_ILP64', None)]
    runtime_library_dirs = ['/usr/local/lib']
openblas64__lapack_info:
    libraries = ['openblas64_', 'openblas64_']
    library_dirs = ['/usr/local/lib']
    language = c
    define_macros = [('HAVE_CBLAS', None), ('BLAS_SYMBOL_SUFFIX', '64_'), ('HAVE_BLAS_ILP64', None), ('HAVE_LAPACKE', None)]
    runtime_library_dirs = ['/usr/local/lib']
lapack_ilp64_opt_info:
    libraries = ['openblas64_', 'openblas64_']
    library_dirs = ['/usr/local/lib']
    language = c
    define_macros = [('HAVE_CBLAS', None), ('BLAS_SYMBOL_SUFFIX', '64_'), ('HAVE_BLAS_ILP64', None), ('HAVE_LAPACKE', None)]
    runtime_library_dirs = ['/usr/local/lib']
Supported SIMD extensions in this NumPy install:
    baseline = NEON,NEON_FP16,NEON_VFPV4,ASIMD
    found = ASIMDHP
    not found = ASIMDDP,ASIMDFHM

I was curious as to whether the installed OpenBLAS runtime libraries were native.
So, I started to probe, but...

(env) dbanas@Davids-Air prj % ls /usr/local/lib/
    ls: /usr/local/lib/: No such file or directory
    (env) dbanas@Davids-Air prj % ls /usr/local/
    bin
    (env) dbanas@Davids-Air prj % ls /usr/local/bin
    2to3            idle3.11        pydoc3          python3-config      python3.11-config
    2to3-3.11       pip3            pydoc3.11       python3-intel64     python3.11-intel64
    idle3           pip3.11         python3         python3.11      stack

So, how did I get through a successful installation of NumPy pointing it at non-existent OpenBLAS libraries?!


问:
How to seperate google signed-in user and native mail user in flutter?
I am creating an application where I am implementing both Google Sign-In as well as Native mail. Firstly I implemented google sign-in to my application and it works properly.Then I created a Firebase Firestore to store data for registration. The registration also works properly but when I try to sign-in, I cannot seem to find the conditional logic to seperate which one is from Firestore/Native Mail and which one is from Google Sign-In.I am new to flutter so I might have some problem in my regular code too.

I also found similar questions here asked but when I implemented those, it still didn't work for me. This is why I have put this question again to solve for this particular situation.

Here's my initial code for the page that must be shown when a user logs in.

```<code>class LoggedInWidget extends StatefulWidget{
  const LoggedInWidget({super.key});

  @override
    LoggedInWidgetState createState() => LoggedInWidgetState();
}
class LoggedInWidgetState extends State<LoggedInWidget> {
  final ref = FirebaseDatabase.instance.ref('users'); // Firestore Database
  final user = FirebaseAuth.instance.currentUser;  // FirebaseAuth to get the current user.

  UserModel loggedInUser = UserModel();  //  Created a model in another page called UserModel
  var name;
  var email;
  var photo;

  @override
  Widget build(BuildContext context) {
    FirebaseFirestore.instance     // Gets data from the current logged in user data and
        .collection("users")       // saves it in a model called loggedInUser.
        .doc(user?.uid)
        .get()
        .then((value){
      loggedInUser = UserModel.fromMap(value.data());
      // setState(() {});
    });

    // This is the logic I implemented for seperating native mail and google sign-in as
    // the loggedInUser will have no name there and will be directly associated to the User variable

    if(loggedInUser.name == null){  /
      name = user?.displayName;
      email = user?.email;
      photo = user?.photoURL;
    }
    else{
      name = loggedInUser.name!;
      email = loggedInUser.email;
    }
</code>```

When running this code, I am able to get my google sign-in data successfully whereas when using Native mail to sign-in. I get the email (probably due to it being saved on the FirebaseAuth), but not the name and other details that is saved in the Firestore.

Body:
I am creating an application where I am implementing both Google Sign-In as well as Native mail. Firstly I implemented google sign-in to my application and it works properly.Then I created a Firebase Firestore to store data for registration. The registration also works properly but when I try to sign-in, I cannot seem to find the conditional logic to seperate which one is from Firestore/Native Mail and which one is from Google Sign-In.I am new to flutter so I might have some problem in my regular code too.

I also found similar questions here asked but when I implemented those, it still didn't work for me. This is why I have put this question again to solve for this particular situation.

Here's my initial code for the page that must be shown when a user logs in.

class LoggedInWidget extends StatefulWidget{
  const LoggedInWidget({super.key});

  @override
    LoggedInWidgetState createState() => LoggedInWidgetState();
}
class LoggedInWidgetState extends State<LoggedInWidget> {
  final ref = FirebaseDatabase.instance.ref('users'); // Firestore Database
  final user = FirebaseAuth.instance.currentUser;  // FirebaseAuth to get the current user.

  UserModel loggedInUser = UserModel();  //  Created a model in another page called UserModel
  var name;
  var email;
  var photo;

  @override
  Widget build(BuildContext context) {
    FirebaseFirestore.instance     // Gets data from the current logged in user data and
        .collection("users")       // saves it in a model called loggedInUser.
        .doc(user?.uid)
        .get()
        .then((value){
      loggedInUser = UserModel.fromMap(value.data());
      // setState(() {});
    });

    // This is the logic I implemented for seperating native mail and google sign-in as
    // the loggedInUser will have no name there and will be directly associated to the User variable

    if(loggedInUser.name == null){  /
      name = user?.displayName;
      email = user?.email;
      photo = user?.photoURL;
    }
    else{
      name = loggedInUser.name!;
      email = loggedInUser.email;
    }

When running this code, I am able to get my google sign-in data successfully whereas when using Native mail to sign-in. I get the email (probably due to it being saved on the FirebaseAuth), but not the name and other details that is saved in the Firestore.


问:
scikit-learn is not working and gives an error "module compiled against API version 0xf but this version of numpy is 0xe"
The error I am getting is as follows:

```<code>RuntimeError                              Traceback (most recent call last)
RuntimeError: module compiled against API version 0xf but this version of numpy is 0xe
</code>```

What is causing this error?

Body:
The error I am getting is as follows:

RuntimeError                              Traceback (most recent call last)
RuntimeError: module compiled against API version 0xf but this version of numpy is 0xe

What is causing this error?


问:
Sveltekit 2.0.1 - Async request "Cannot read properties of undefined (reading 'length')"
I'm a beginner at web development and sveltekit. I'm trying to do a async request in the following way:

```<code><script context="module">
    export async function load({ fetch }) {
      const res = await fetch('https://jsonplaceholder.typicode.com/posts');
      const posts = await res.json();

      return {
        props: { posts }
      };
    }
</script>

<script>
    export let posts
</script>

<div class="guides">
    <ul>
        {#each posts as guide}
            <a href="/">{guide.title}</a>
        {/each}
    </ul>
</div>
</code>```

The file is located in src/about/+page.svelte

I keep getting the same error whatever I do. I tried to use the docs for sveltekit - load but it does not help me, I keep getting the same error (https://kit.svelte.dev/docs/load)

Error:

```<code>Cannot read properties of undefined (reading 'length')
TypeError: Cannot read properties of undefined (reading 'length')
    at Module.each (/node_modules/svelte/internal/index.mjs:1841:31)
    at eval (/src/routes/about/+page.svelte:23:106)
    at Object.$$render (/node_modules/svelte/internal/index.mjs:1876:22)
    at Object.default (root.svelte:44:40)
    at eval (/src/routes/about/+layout.svelte:26:36)
    at Object.$$render (/node_modules/svelte/internal/index.mjs:1876:22)
    at Object.default (root.svelte:43:39)
    at eval (/node_modules/@sveltejs/kit/src/runtime/components/layout.svelte:8:41)
    at Object.$$render (/node_modules/svelte/internal/index.mjs:1876:22)
    at root.svelte:41:37
</code>```
```<code>Creating the svelte app:
✔ Which Svelte app template? › Skeleton project
✔ Add type checking with TypeScript? › No
✔ Add ESLint for code linting? … No
✔ Add Prettier for code formatting? … No
✔ Add Playwright for browser testing? … No
✔ Add Vitest for unit testing? … No
</code>```

Sveltekit version 2.0.1

Body:
I'm a beginner at web development and sveltekit. I'm trying to do a async request in the following way:

        {#each posts as guide}
            {guide.title}
        {/each}

The file is located in src/about/+page.svelte

I keep getting the same error whatever I do. I tried to use the docs for sveltekit - load but it does not help me, I keep getting the same error (https://kit.svelte.dev/docs/load)

Error:

Cannot read properties of undefined (reading 'length')
TypeError: Cannot read properties of undefined (reading 'length')
    at Module.each (/node_modules/svelte/internal/index.mjs:1841:31)
    at eval (/src/routes/about/+page.svelte:23:106)
    at Object.$$render (/node_modules/svelte/internal/index.mjs:1876:22)
    at Object.default (root.svelte:44:40)
    at eval (/src/routes/about/+layout.svelte:26:36)
    at Object.$$render (/node_modules/svelte/internal/index.mjs:1876:22)
    at Object.default (root.svelte:43:39)
    at eval (/node_modules/@sveltejs/kit/src/runtime/components/layout.svelte:8:41)
    at Object.$$render (/node_modules/svelte/internal/index.mjs:1876:22)
    at root.svelte:41:37

Creating the svelte app:
✔ Which Svelte app template? › Skeleton project
✔ Add type checking with TypeScript? › No
✔ Add ESLint for code linting? … No
✔ Add Prettier for code formatting? … No
✔ Add Playwright for browser testing? … No
✔ Add Vitest for unit testing? … No

Sveltekit version 2.0.1


问:
Python: Problem with print result variable in pdf.cell or pdf.write (fpdf)
I have problem with printing result from some simple example in pdf file?
pdf.cell(200, 10, "c= " + c_string, 1, 0)

It's problem create pdf file with results.

This is complete code without ui file.

There are no errors, but there is no pdf file either.

```<code>import sys
import fpdf

from PyQt6 import QtWidgets, uic
from fpdf import FPDF

qtcreator_file  = "testna_forma.ui" # Enter file here.
Ui_Prozor, QtBaseClass = uic.loadUiType(qtcreator_file)

class MyApp(QtWidgets.QDialog, Ui_Prozor):
    def __init__(self):
        QtWidgets.QMainWindow.__init__(self)
        Ui_Prozor.__init__(self)
        self.setupUi(self)

        self.Calculate_button.clicked.connect(self.Calculate_all)
        self.Print_pdf.clicked.connect(self.Print_result)

    def Calculate_all(self):

           a = float(self.input_a.text())
           b = float(self.input_b.text())

           c = a + b
           d = a - b
           e = a * b
           f = a / b

           self.show_c.setText(format(c))
           self.show_d.setText(format(d))
           self.show_e.setText(format(e))
           self.show_f.setText(format(f))
           print(c)
           print(d)
           print(e)
           print(f)

    def Print_result(self):
           c_string = str(c)
           d_string = str(d)
           e_string = str(e)
           f_string = str(f)
           pdf = FPDF('P', 'mm', 'A4')
           pdf.add_page()
           pdf.set_font('Arial', 'B', 12)
           pdf.cell(200, 10, "c= " + c_string, 1, 0)
           #pdf.write(5,'str(c)')
           pdf.output("Report.pdf", 'F')

if __name__ == "__main__":
    app = QtWidgets.QApplication(sys.argv)
    window = MyApp()
    window.show()
    sys.exit(app.exec())
</code>```

I have problem when try print result data as a string?!

Body:
I have problem with printing result from some simple example in pdf file?
pdf.cell(200, 10, "c= " + c_string, 1, 0)

It's problem create pdf file with results.

This is complete code without ui file.

There are no errors, but there is no pdf file either.

import sys
import fpdf

from PyQt6 import QtWidgets, uic
from fpdf import FPDF

qtcreator_file  = "testna_forma.ui" # Enter file here.
Ui_Prozor, QtBaseClass = uic.loadUiType(qtcreator_file)

class MyApp(QtWidgets.QDialog, Ui_Prozor):
    def __init__(self):
        QtWidgets.QMainWindow.__init__(self)
        Ui_Prozor.__init__(self)
        self.setupUi(self)

        self.Calculate_button.clicked.connect(self.Calculate_all)
        self.Print_pdf.clicked.connect(self.Print_result)

    def Calculate_all(self):

           a = float(self.input_a.text())
           b = float(self.input_b.text())

           c = a + b
           d = a - b
           e = a * b
           f = a / b

           self.show_c.setText(format(c))
           self.show_d.setText(format(d))
           self.show_e.setText(format(e))
           self.show_f.setText(format(f))
           print(c)
           print(d)
           print(e)
           print(f)

    def Print_result(self):
           c_string = str(c)
           d_string = str(d)
           e_string = str(e)
           f_string = str(f)
           pdf = FPDF('P', 'mm', 'A4')
           pdf.add_page()
           pdf.set_font('Arial', 'B', 12)
           pdf.cell(200, 10, "c= " + c_string, 1, 0)
           #pdf.write(5,'str(c)')
           pdf.output("Report.pdf", 'F')

if __name__ == "__main__":
    app = QtWidgets.QApplication(sys.argv)
    window = MyApp()
    window.show()
    sys.exit(app.exec())

I have problem when try print result data as a string?!