prerequisite: python 3.9 и winrt
import asyncio
from winrt.windows.ui.notifications.management import UserNotificationListener
from winrt.windows.ui.notifications import KnownNotificationBindings
async def notification_handler(listener, seen_notifications):
print("Слушатель уведомлений запущен. Ожидание новых уведомлений...")
# Бесконечно слушаем уведомления
while True:
try:
# Получение всех текущих уведомлений
notifications = await listener.get_notifications_async(0)
for notification in notifications:
notification_id = notification.id # Получаем уникальный ID уведомления
# Проверяем, было ли это уведомление уже обработано
if notification_id not in seen_notifications:
seen_notifications.add(notification_id) # Добавляем ID в множество обработанных уведомлений
try:
# Получение информации об уведомлении
app_name = notification.app_info.display_info.display_name
binding = notification.notification.visual.get_binding(KnownNotificationBindings.get_toast_generic())
if binding:
text_elements = binding.get_text_elements()
title = text_elements[0].text if len(text_elements) > 0 else "Без заголовка"
body = text_elements[1].text if len(text_elements) > 1 else "Без текста"
print(f"Новое уведомление!")
print(f"Приложение: {app_name}")
print(f"Заголовок: {title}")
print(f"Текст: {body}")
print("-" * 50)
# Проверяем что ув. от нужного приложения и делаем всякое нужное с ним.
except Exception as e:
print(f"Ошибка при обработке уведомления: {e}")
# Задержка перед следующим циклом
await asyncio.sleep(1)
except Exception as e:
print(f"Ошибка при получении уведомлений: {e}")
await asyncio.sleep(5) # Задержка перед повторной попыткой в случае ошибки
async def main():
# Получение текущего слушателя уведомлений
listener = UserNotificationListener.get_current()
# Смотрим есть ли разрешение на доступ к уведомлениям. Если нет, лезем в настройки уведомлений.
access_status = await listener.request_access_async()
if access_status != 1:
print("Нет разрешения на доступ к уведомлениям. Проверьте настройки конфиденциальности.")
return
seen_notifications = set() # Множество для хранения ID уже обработанных уведомлений
await notification_handler(listener, seen_notifications)
if __name__ == "__main__":
asyncio.run(main())
import requests
from bs4 import BeautifulSoup
def parse_table(div, results):
# Ищем таблицы внутри данного div
tables = div.find_all('table')
for table in tables:
rows = table.find_all('tr')
for row in rows:
cells = row.find_all('td')
if cells:
# Извлекаем название и ссылку
name = cells[0].get_text(strip=True)
link = cells[0].find('a')['href'] if cells[0].find('a') else None
if link:
results[name] = link
def recursive_parse(url, visited, results):
if url in visited:
return
visited.add(url)
print('Парсим URL:', url)
response = requests.get(url)
soup = BeautifulSoup(response.content, 'html.parser')
# Ищем все div с itemscope
divs = soup.find_all('div', itemscope=True)
for div in divs:
parse_table(div, results) # Парсим таблицы внутри найденного div
# Ищем все ссылки на подстраницы
links = soup.find_all('a', href=True)
for link in links:
sub_url = link['href']
# Проверяем, что ссылка ведет на подстраницу и не является текущим URL
if 'respublika_bashkortostan' in sub_url and sub_url.startswith('http') and sub_url != url:
recursive_parse(sub_url, visited, results)
# Начальная URL
start_url = 'https://russiaschools.ru/respublika_bashkortostan/'
visited_urls = set()
results_dict = {}
recursive_parse(start_url, visited_urls, results_dict)
for name, link in results_dict.items():
print(f'Название: {name}, Ссылка: {link}')
file_content="$(cat /some/file)"
echo $file_content
>>> lol kek cheburek. kol
echo "$file_content"
>>> lol
kek cheburek.
kol
f=""
while IFS= read -r line || [[ -n "$line" ]]; do
f+="${line}"$'\n'
done < 1.txt
f="${f%$'\n'}"
echo "$f" > 2.txt
getExistingDirectory()
первым позиционным аргументом должен идти parent
, а вы передаёте первым self
. def getDirectory(self):
dirlist = QFileDialog.getExistingDirectory(None, "Выбрать папку", "C:\\100")
self.plainTextEdit.appendHtml("<br>Выбрали папку: <b>{}</b>".format(dirlist))
print(dirlist)
import time
from numpy.random import randint, default_rng
def f(coords: list, time_movie: int, steps: int) -> list:
x_a, y_a = [], []
now = int(time.time() * 1000)
rng = default_rng()
timestamp = sorted(rng.integers(now, now + time_movie * 1000, size=(steps * len(coords) - 1) + 1))
for i in range(len(coords) - 1):
x1, y1, x2, y2 = coords[i] + coords[i + 1]
x_a += [x1] + sorted(randint(min(x1, x2), max(x1, x2), size=steps), reverse=1 if x1 > x2 else 0) + [x2]
y_a += [y1] + sorted(randint(min(y1, y2), max(y1, y2), size=steps), reverse=1 if x1 > x2 else 0) + [y2]
return [[x, y, t] for x, y, t in zip(x_a, y_a, timestamp)]
coords = [[392, 556], [95, 309], [207, 192]]
print(f(coords=coords, time_movie=2, steps=30))
import subprocess
# Функция для проверки доступности IP:port с помощью psping
def check_ip(ip_port):
try:
print(f"Проверяем доступность {ip_port}", end='')
# Выполняем команду psping
result = subprocess.run(['psping', ip_port], capture_output=True, text=True)
# Проверяем, есть ли в выводе сообщение об успешном пинге
if "(0% loss)" in result.stdout:
print(f"\rПроверяем доступность {ip_port} - доступен")
return True
if "(25% loss)" in result.stderr or "50% loss" in result.stdout:
print(f"\rПроверяем доступность {ip_port} - потери пакетов")
return True
if "(100% loss)" in result.stdout:
print(f"\rПроверяем доступность {ip_port} - недоступен")
return False
except Exception as e:
print(f"Ошибка при проверке {ip_port}: {e}")
return False
# Чтение IP:port из файла и запись доступных в другой файл
def check_ips_from_file(input_file, output_file):
with open(input_file, 'r') as infile, open(output_file, 'w') as outfile:
for line in infile:
ip_port = line.strip() # Убираем лишние пробелы и символы новой строки
if check_ip(ip_port):
outfile.write(ip_port + '\n') # Записываем доступный IP:port в файл
# Указываем имена файлов
input_file = 'ip.txt'
output_file = 'ipUP.txt'
# Запускаем проверку
check_ips_from_file(input_file, output_file)
import cv2
import numpy as np
def find_and_draw_template(template_path, original_image_path):
# Загрузка шаблона
template = cv2.imread(template_path)
template_gray = cv2.cvtColor(template, cv2.COLOR_BGR2GRAY)
# Создание объекта ORB
orb = cv2.ORB_create()
bf = cv2.BFMatcher(cv2.NORM_HAMMING, crossCheck=True)
# Обнаружение ключевых точек и вычисление дескрипторов для шаблона
keypoints_template, descriptors_template = orb.detectAndCompute(template_gray, None)
# Обработка изображения
image = original_image_path.copy()
image_gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
# Обнаружение ключевых точек и вычисление дескрипторов для изображения
keypoints_image, descriptors_image = orb.detectAndCompute(image_gray, None)
# Сопоставление дескрипторов
matches = bf.match(descriptors_template, descriptors_image)
matches = sorted(matches, key=lambda x: x.distance)
# Отладочная информация
print(f"Общее количество найденных соответствий: {len(matches)}")
# Отбор лучших соответствий
good_matches = matches[:75]
print(f"Количество хороших соответствий: {len(good_matches)}")
# Проверка на наличие хороших соответствий
if len(good_matches) >= 4:
# Получение координат ключевых точек
src_pts = np.float32([keypoints_template[m.queryIdx].pt for m in good_matches]).reshape(-1, 1, 2)
dst_pts = np.float32([keypoints_image[m.trainIdx].pt for m in good_matches]).reshape(-1, 1, 2)
# Нахождение матрицы гомографии
M, mask = cv2.findHomography(src_pts, dst_pts, cv2.RANSAC, 5.0)
print("Гомография найдена.")
# Получение углов шаблона
h, w = template_gray.shape[:2]
pts = np.float32([[0, 0], [0, h - 1], [w - 1, h - 1], [w - 1, 0]]).reshape(-1, 1, 2)
# Преобразование углов шаблона
dst = cv2.perspectiveTransform(pts, M)
# Обводим рамкой найденные области
image = cv2.polylines(image, [np.int32(dst)], isClosed=True, color=(0, 255, 0), thickness=3)
else:
print("Недостаточно хороших соответствий для нахождения гомографии.")
return image
# Пример использования функции
template_file = 'LED.jpg' # Шаблон
original_image_file = 'outputImage.jpg' # Исходное изображение
# Загрузка и обработка изображения
original_image = cv2.imread(original_image_file)
result_image = find_and_draw_template(template_file, original_image)
# Масштабируем изображение для отображения - не обязательно, у меня не вмещалось в просмотр
scale_percent = 50 # Процент уменьшения размера
width = int(result_image.shape[1] * scale_percent / 100)
height = int(result_image.shape[0] * scale_percent / 100)
resized_image = cv2.resize(result_image, (width, height), interpolation=cv2.INTER_AREA)
# Отображение результата
cv2.imshow('Detected Templates', resized_image)
cv2.waitKey(0)
cv2.destroyAllWindows()