RError.com

RError.com Logo RError.com Logo

RError.com Navigation

  • 主页

Mobile menu

Close
  • 主页
  • 系统&网络
    • 热门问题
    • 最新问题
    • 标签
  • Ubuntu
    • 热门问题
    • 最新问题
    • 标签
  • 帮助
主页 / user-400114

Alexey's questions

Martin Hope
Alexey
Asked: 2024-08-20 19:41:27 +0000 UTC

如果是自动生成的JS实现如何实现

  • 6

挑战是将 JavaScript 嵌入到页面中。但问题是,就我而言,它不是静态的,而是自动生成的。那些。一个最低限度可重现的例子看起来像这样:

<script type="text/javascript" src="https://.../?key=sYdQHpBYyXiRyUNZtNcZkP1yAE15u4AQ"></script>

http://.../?key=sYdQHpBYyXiRyUNZtNcZkP1yAE15u4AQ 产生以下内容...

alert("Hurra!");

...但由于某种原因没有任何效果。

我想到的是通过 AJAX 动态加载和后续验证,但任务的具体情况是我可以用最小的代码大小(最好是一行)完成......如果您提供一个优雅的解决方案,我很高兴。

javascript
  • 1 个回答
  • 46 Views
Martin Hope
Alexey
Asked: 2024-03-28 05:52:15 +0000 UTC

设置 WebSocket Secure 时出现问题

  • 5

我正在使用 WebSocket 制作类似聊天机器人的东西。客户端使用原生 JavaScript,服务器使用 Python。以下是最低限度可重复的示例:

服务器.py

import asyncio
import websockets

async def echo(websocket, path):
    async for message in websocket:
        await websocket.send("Сообщение получено: " + message)
        await websocket.send("Здесь должен быть ответ на сообщение...")

async def main():
    async with websockets.serve(echo, "мой_хост", 1234):
        await asyncio.Future()

asyncio.run(main())

客户端.js

<script>
const socket = new WebSocket('ws://мой_хост:1234');
</script>

所以一切都很好。下一步是使用 WSS 而不仅仅是 WS 来完成所有操作。相应地对代码进行了以下更改:

服务器.py

import asyncio
import websockets
import ssl

async def echo(websocket, path):
    async for message in websocket:
        await websocket.send("Сообщение получено: " + message)
        await websocket.send("Здесь должен быть ответ на сообщение...")

async def main():
    ssl_context = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH)
    ssl_context.load_cert_chain(certfile="прописал_путь_к,сертификату", keyfile="прописал_путь_к_ключу")
    async with websockets.server.serve(echo, "мой_хост", 443, ssl=ssl_context):
        await asyncio.Future()

asyncio.run(main())

客户端.js

<script>
const socket = new WebSocket('wss://мой_хост:443');
</script>

我正在启动服务器nohup python3 -m server.py &。

问题是客户端在浏览器控制台中显示以下错误:

与“wss://my_host/”的 WebSocket 连接失败:

我究竟做错了什么?

我使用 Plesk 网络托管平台。Apache 版本 2.4.52,nginx 版本 1.24.0。我认为 Apache 是主要的。操作系统 Ubuntu 22.04.4 LTS。

UPD 我尝试将其添加到/var/www/vhosts/system/мой_хост/conf/httpd.conf行中......

ProxyPass /wss/ wss://мой_хост:443/
ProxyPassReverse /wss/ wss://мой_хост:443/

...用于代理并重新启动服务器。没有帮助...

UPD 添加了额外的 nginx 指令:

location /wss/ {
    proxy_pass https://мой_хост:443;
    proxy_http_version 1.1;
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection "upgrade";
    proxy_set_header Host $host;
}

...也没有任何作用。

UPD 让我提出一个问题:如何为 Ubuntu 配置 WSS?

UPD 当然,您可以在没有代理的情况下执行所有操作,以便客户端和服务器直接交互。但即使这样也不起作用...我在客户端和服务器中将端口从 443 更改为 8080...它仍然写相同的“连接到 'wss://my_host/' 失败”

UPD 我像这样启动服务器python3 -m server.py并收到以下错误:

  File "/usr/lib/python3.10/runpy.py", line 187, in _run_module_as_main
    mod_name, mod_spec, code = _get_module_details(mod_name, _Error)
  File "/usr/lib/python3.10/runpy.py", line 110, in _get_module_details
    __import__(pkg_name)
  File "/var/www/vhosts/мой_хост/httpdocs/chatbot/server.py", line 21, in <module>
    asyncio.run(main())
  File "/usr/lib/python3.10/asyncio/runners.py", line 44, in run
    return loop.run_until_complete(main)
  File "/usr/lib/python3.10/asyncio/base_events.py", line 649, in run_until_complete
    return future.result()
  File "/var/www/vhosts/мой_хост/httpdocs/chatbot/server.py", line 18, in main
    async with websockets.server.server(echo, "мой_хост", 8080, ssl=ssl_context):
  File "/usr/local/lib/python3.10/dist-packages/websockets/imports.py", line 92, in __getattr__
    raise AttributeError(f"module {package!r} has no attribute {name!r}")
AttributeError: module 'websockets' has no attribute 'server'. Did you mean: 'serve'?

javascript
  • 1 个回答
  • 164 Views
Martin Hope
Alexey
Asked: 2024-03-19 01:45:26 +0000 UTC

QScrollArea 中缩放小部件的问题

  • 6

有以下最低限度可重现的示例:

主要.py:

import sys
from PyQt5.QtWidgets import QApplication, QDialog, QPushButton
from PyQt5.uic import loadUi


class MyWindow(QDialog):
    def __init__(self):
        super().__init__()
        loadUi('main.ui', self)

        for i in range(15):
            button = QPushButton(f'Button {i}')
            self.verticalLayout.addWidget(button)

        self.scrollArea.setWidgetResizable(False)


if __name__ == '__main__':
    app = QApplication(sys.argv)
    window = MyWindow()
    window.show()
    sys.exit(app.exec_())

主.ui:

<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
 <class>Dialog</class>
 <widget class="QDialog" name="Dialog">
  <property name="geometry">
   <rect>
    <x>0</x>
    <y>0</y>
    <width>400</width>
    <height>300</height>
   </rect>
  </property>
  <property name="windowTitle">
   <string>Dialog</string>
  </property>
  <widget class="QScrollArea" name="scrollArea">
   <property name="geometry">
    <rect>
     <x>0</x>
     <y>0</y>
     <width>401</width>
     <height>301</height>
    </rect>
   </property>
   <property name="widgetResizable">
    <bool>true</bool>
   </property>
   <widget class="QWidget" name="scrollAreaWidgetContents">
    <property name="enabled">
     <bool>true</bool>
    </property>
    <property name="geometry">
     <rect>
      <x>0</x>
      <y>0</y>
      <width>399</width>
      <height>299</height>
     </rect>
    </property>
    <widget class="QWidget" name="verticalLayoutWidget">
     <property name="geometry">
      <rect>
       <x>0</x>
       <y>0</y>
       <width>401</width>
       <height>301</height>
      </rect>
     </property>
     <layout class="QVBoxLayout" name="verticalLayout"/>
    </widget>
   </widget>
  </widget>
 </widget>
 <resources/>
 <connections/>
</ui>

需要注意的是,当用按钮QVBoxLayout( ) 填充 -a ( ) 时,它们(按钮)不会缩放,而是为( ) 添加滚动。那些。就像左边一样,而不是右边。verticalLayoutQPushButtonQScrollAreascrollArea

文本


我找到了这个选项:

import sys
from PyQt5.QtWidgets import QApplication, QMainWindow, QVBoxLayout, QPushButton, QWidget, QScrollArea


class MyWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        self.initUI()

    def initUI(self):
        self.setWindowTitle('Пример QScrollArea без масштабирования виджетов')
        self.setGeometry(100, 100, 300, 300)

        # Создаем QScrollArea
        self.scrollArea = QScrollArea(self)
        self.scrollArea.setGeometry(10, 10, 280, 280)

        # Создаем содержимое для QScrollArea
        scroll_content_widget = QWidget()
        scroll_content_layout = QVBoxLayout(scroll_content_widget)

        # Добавляем кнопки в QVBoxLayout
        for i in range(20):
            button = QPushButton(f'Button {i}')
            scroll_content_layout.addWidget(button)

        # Устанавливаем содержимое для QScrollArea
        self.scrollArea.setWidget(scroll_content_widget)

        # Отключаем автоматическое масштабирование
        self.scrollArea.setWidgetResizable(False)


if __name__ == '__main__':
    app = QApplication(sys.argv)
    window = MyWindow()
    window.show()
    sys.exit(app.exec_())

...它有效,但逻辑并没有与图形界面分离,我试图将第二个选项变成第一个,但在某个地方出现了障碍,没有任何效果。main.ui是在Qt Designer中制作的。

问题是什么?

python
  • 1 个回答
  • 30 Views
Martin Hope
Alexey
Asked: 2024-03-18 17:47:14 +0000 UTC

PyQt5。QDialog 窗口未关闭

  • 6

我有以下代码(最小可重现的示例):

关闭.py

import sys
from PyQt5.QtWidgets import QApplication, QDialog
from PyQt5 import uic


class DialogWindow(QDialog):
    def __init__(self):
        super().__init__()
        uic.loadUi('close.ui', self)

        self.buttonBox.accepted.connect(self.accept)
        self.buttonBox.rejected.connect(self.reject)

    def accept(self):
        print("accept...")
        self.close()

    def reject(self):
        print("reject...")
        self.close()


if __name__ == '__main__':
    app = QApplication(sys.argv)
    main_window = DialogWindow()
    main_window.show()
    sys.exit(app.exec_())

关闭.ui

<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
 <class>Dialog</class>
 <widget class="QDialog" name="Dialog">
  <property name="geometry">
   <rect>
    <x>0</x>
    <y>0</y>
    <width>400</width>
    <height>300</height>
   </rect>
  </property>
  <property name="windowTitle">
   <string>New Experiment</string>
  </property>
  <widget class="QDialogButtonBox" name="buttonBox">
   <property name="geometry">
    <rect>
     <x>100</x>
     <y>250</y>
     <width>193</width>
     <height>28</height>
    </rect>
   </property>
   <property name="standardButtons">
    <set>QDialogButtonBox::Cancel|QDialogButtonBox::Ok</set>
   </property>
  </widget>
 </widget>
 <resources/>
 <connections/>
</ui>

尽管事实上,当您单击QDialogButtonBox相应的方法(accept()和reject())时,它们会起作用,但窗口仍然不想关闭。可能是什么问题呢?

UPD:我更改了方法和信号的名称(分别将accept 更改为accept2 并将reject 更改为reject2),一切正常。难道是父类?我将这些方法设为accept()私有reject(),它也有效......

python
  • 1 个回答
  • 25 Views
Martin Hope
Alexey
Asked: 2024-03-11 04:39:13 +0000 UTC

SQL。请求显示最新值

  • 5

有两个表(服务器版本:10.6.16-MariaDB-0ubuntu0.22.04.1 - Ubuntu 22.04),内容如下:

传感器表

传感器 ID 传感器地址
1 03173311a0ff
2 xxxxxxxxxxxx

...以及测量表

测量ID 传感器 ID 温度值 测量时间
1 1 18.567 2024-03-10 19:00:30
2 2 19.123 2024-03-10 19:00:40
3 1 20.0 2024-03-10 20:00:30
4 2 22.5 2024-03-10 20:00:40

任务: 显示所有传感器的最新温度(Temperature_value)和传感器地址(sensor_adress),即 像这样的东西:

传感器地址 温度值
03173311a0ff 20.0
xxxxxxxxxxxx 22.5

我尝试创建一个 SQL 查询,这就是我得到的结果:

SELECT `sensors`.`sensor_adress`, `measurements`.`temperature_value`
FROM `measurements` INNER JOIN `sensors`
ON `sensors`.`sensor_id` = `measurements`.`sensor_id`
WHERE `measurements`.`measurement_time` = (SELECT MAX(`measurement_time`) FROM `measurements`)
ORDER BY `sensors`.`sensor_id` ASC;

如何改进子查询?

SELECT MAX(`measurement_time`) FROM `measurements`

这样就不是根据最大时间戳进行选择,而是根据每个传感器最相关的时间戳进行选择?

sql
  • 1 个回答
  • 38 Views
Martin Hope
Alexey
Asked: 2023-09-27 15:03:20 +0000 UTC

为什么表单提交事件没有触发?

  • 6

有以下最低限度可重现的示例:

<form id="upload-form" enctype="multipart/form-data">
    <input type="file" id="file-input" style="display: none;" />
    <label for="file-input" id="file-label">Выберите файл</label>
</form>

<script>
    const fileInput = document.getElementById('file-input');
    const fileLabel = document.getElementById('file-label');
        
    fileInput.addEventListener('change', (event) => {
        alert("File selected!");
        document.getElementById('upload-form').submit();
    });

    document.getElementById('upload-form').addEventListener('submit', (event) => {
        event.preventDefault();
        alert("Form send!");
    });
</script>

为什么在这种情况下,表单未发送/无法addEventListener与参数一起使用submit?那些。alert("File selected!"); 它有效,但alert("Form send");它不...

先感谢您!

javascript
  • 1 个回答
  • 42 Views
Martin Hope
Alexey
Asked: 2023-02-24 23:25:29 +0000 UTC

流和信号

  • 7

有以下代码:

import time
import sys

#from PyQt6.QtWidgets import (
from PyQt5.QtWidgets import (
    QApplication,
    QPushButton,
    QTextEdit, 
    QVBoxLayout,
    QWidget
)

from threading import Thread


class Window(QWidget):

    def __init__(self):
        super().__init__()
   
        mainLayout = QVBoxLayout()
        self.output = QTextEdit()
        self.output.setReadOnly(True)
        mainLayout.addWidget(self.output)

        self.startButton = QPushButton("Start")
        self.startButton.clicked.connect(self.start)
        mainLayout.addWidget(self.startButton)
        self.setLayout(mainLayout)

    def task(self):
        while True:
            obj = Actions()
            obj.do()
            time.sleep(3)
            
    def start(self):
        t1 = Thread(target=self.task)
        t1.start()



class Actions():
    
    def do(self):
        window.output.append("...")   


if __name__ == "__main__":
    app = QApplication([])
    window = Window()
    window.show()
    sys.exit(app.exec()) 

执行此示例时(针对PyQt5)我收到以下计划的警告:

QObject::connect:无法对类型为“QTextCursor”的参数进行排队(确保使用 qRegisterMetaType() 注册了“QTextCursor”。)

在这里和这里它说:

  • 您无法与其他线程中的小部件交互,因此会显示此警告
  • 当一个线程需要改变窗口中的某些东西时,它向主线程发送一个信号,主线程中的处理程序执行必要的改变

如何落实第二点?有没有关于这个主题的例子的好教程?

先感谢您!

python
  • 1 个回答
  • 29 Views
Martin Hope
Alexey
Asked: 2023-02-24 19:57:38 +0000 UTC

多线程。事件和标志之间有区别吗?

  • 5

问候!

我想知道这两个可重现性最低的示例之间是否存在根本区别。在第一种情况下,我使用标志self.flagClose = True来指示流关闭,而在第二种情况下,我将它用于asyncio.Event相同的目的。

from threading import Thread
import time

class Main():

    def __init__(self):
        self.flagClose = True
        t1 = Thread(target=self.task)
        t1.start()

    def task(self):
        while True:
            if self.flagClose:
                print("Close")
                return
            else:
                print("Not close")
            print("...")
            time.sleep(3)  


    
obj = Main()

和

from asyncio import Event
from threading import Thread
import time

class Main():

    def __init__(self):
        
        t1 = Thread(target=self.task)
        t1.start()

    def task(self):
        while True:
            if event.is_set():
                print("Close")
                return
            else:
                print("Not close")
            print("...")
            time.sleep(3)  

    
event = Event()
event.set()
#event.clear()

obj = Main()

提前致谢!

python
  • 1 个回答
  • 29 Views
Martin Hope
Alexey
Asked: 2023-02-16 22:10:09 +0000 UTC

使用 PyQt6 确定屏幕分辨率

  • 6

是否可以使用 PyQt6 确定屏幕分辨率?

事实上,我需要将应用程序窗口放在屏幕中央,我想出了如何获取它的大小并将它移动到适当的位置。但问题是获取屏幕分辨率,我就是找不到可行的选项。

做了一些像空白的东西:

from PyQt6.QtWidgets import QApplication, QWidget
import sys

app = QApplication([])
window = QWidget()
window.resize(300, 100)

print(window.frameSize().width())
print(window.frameSize().height())

...

#window.move(x, y)

window.show()
sys.exit(app.exec())

这是PyQt5 上的一个版本,但即使您对其进行更改并尝试使其与 PyQt 版本 6 兼容,它仍然拒绝工作并说 QApplication 对象没有桌面属性。

提前致谢!

python
  • 1 个回答
  • 27 Views
Martin Hope
Alexey
Asked: 2020-08-13 23:17:49 +0000 UTC

php。字符串是整数吗?

  • 0

问题是这样的:您需要确定字符串是否为整数。我已经尝试了很多东西,但没有一个能正常工作。这里:

if(is_int($value)) { ...

如果您将参数作为字符串传递,即 在引号中,例如“123”,那么即使在这种情况下也会返回 false。

if((int)($value)) { ...

如果您进行类型转换,那么在这种情况下,如果参数是浮点数,则返回 true ......也不适合:(

if(ctype_digit($value)) { ...

在同一个变体中,即使参数从零开始,也会返回 true,即 '0123' 这不是一个真正的整数。

有人有工作版吗?

先感谢您!

php
  • 2 个回答
  • 10 Views
Martin Hope
Alexey
Asked: 2020-08-08 00:53:41 +0000 UTC

PHP中的日期验证。如何最好地实施?

  • 0

有一个 YYYY-MM-DD 格式的日期。面临检查其可靠性的问题。首先想到的是正则表达式,像这样......

if (preg_match("/([12]\d{3}-(0[1-9]|1[0-2])-(0[1-9]|[12]\d|3[01]))/", $date)) {
...

...但是据我所知,这里没有考虑到月份的天数不同,而且他们也忘记了高年这一事实。

实现这一点的最佳方法是什么?

php
  • 1 个回答
  • 10 Views
Martin Hope
Alexey
Asked: 2020-07-31 06:38:23 +0000 UTC

方法是否属于特定的类

  • 0

再会!

我有一个问题,还没有具体的解决方案。我想检查该方法是否属于特定类。method_exists() 适用于所有可用的方法,但它应该在类上。那些。这是关于其中存在一种或另一种方法...

class firstClass {

    public function firstMethod() {}
    private function secondMethod() {}

}

class secondClass extends firstClass {

    public function thirdMethod() {}
    private function fourthMethod() {}

}

$obj = new secondClass;

$methodName = 'firstMethod';

if(method_exists($obj,$methodName)) {

}

更准确地说,我想在子类继承的情况下定义它。

先感谢您!

php
  • 2 个回答
  • 10 Views

Sidebar

Stats

  • 问题 10021
  • Answers 30001
  • 最佳答案 8000
  • 用户 6900
  • 常问
  • 回答
  • Marko Smith

    我看不懂措辞

    • 1 个回答
  • Marko Smith

    请求的模块“del”不提供名为“default”的导出

    • 3 个回答
  • Marko Smith

    "!+tab" 在 HTML 的 vs 代码中不起作用

    • 5 个回答
  • Marko Smith

    我正在尝试解决“猜词”的问题。Python

    • 2 个回答
  • Marko Smith

    可以使用哪些命令将当前指针移动到指定的提交而不更改工作目录中的文件?

    • 1 个回答
  • Marko Smith

    Python解析野莓

    • 1 个回答
  • Marko Smith

    问题:“警告:检查最新版本的 pip 时出错。”

    • 2 个回答
  • Marko Smith

    帮助编写一个用值填充变量的循环。解决这个问题

    • 2 个回答
  • Marko Smith

    尽管依赖数组为空,但在渲染上调用了 2 次 useEffect

    • 2 个回答
  • Marko Smith

    数据不通过 Telegram.WebApp.sendData 发送

    • 1 个回答
  • Martin Hope
    Alexandr_TT 2020年新年大赛! 2020-12-20 18:20:21 +0000 UTC
  • Martin Hope
    Alexandr_TT 圣诞树动画 2020-12-23 00:38:08 +0000 UTC
  • Martin Hope
    Air 究竟是什么标识了网站访问者? 2020-11-03 15:49:20 +0000 UTC
  • Martin Hope
    Qwertiy 号码显示 9223372036854775807 2020-07-11 18:16:49 +0000 UTC
  • Martin Hope
    user216109 如何为黑客设下陷阱,或充分击退攻击? 2020-05-10 02:22:52 +0000 UTC
  • Martin Hope
    Qwertiy 并变成3个无穷大 2020-11-06 07:15:57 +0000 UTC
  • Martin Hope
    koks_rs 什么是样板代码? 2020-10-27 15:43:19 +0000 UTC
  • Martin Hope
    Sirop4ik 向 git 提交发布的正确方法是什么? 2020-10-05 00:02:00 +0000 UTC
  • Martin Hope
    faoxis 为什么在这么多示例中函数都称为 foo? 2020-08-15 04:42:49 +0000 UTC
  • Martin Hope
    Pavel Mayorov 如何从事件或回调函数中返回值?或者至少等他们完成。 2020-08-11 16:49:28 +0000 UTC

热门标签

javascript python java php c# c++ html android jquery mysql

Explore

  • 主页
  • 问题
    • 热门问题
    • 最新问题
  • 标签
  • 帮助

Footer

RError.com

关于我们

  • 关于我们
  • 联系我们

Legal Stuff

  • Privacy Policy

帮助

© 2023 RError.com All Rights Reserve   沪ICP备12040472号-5