Как заблюрить товары на страницах для незарегистрированных пользователей?
// functions.php:
function test() {
if (!is_user_logged_in()) {
wp_add_inline_style('woocommerce-general', '.product {filter: blur(5px)}');
}
}
add_action('wp_enqueue_scripts', 'test');А также есть вопрос по закрытию доступа к заказу из корзины, если пользователь не авторизован.
// functions.php:
function test() {
if (!is_user_logged_in()) {
wp_redirect(get_permalink(wc_get_page_id('myaccount')));
exit;
}
}
add_action('woocommerce_before_checkout_form', 'test');Вот сама ошибка(походу что-то я сделал не так и огроомная ошибка поменялась в маленькую):
C:\Users\akrav\Desktop\машынки\main.py:183: RuntimeWarning: coroutine 'get_cards' was never awaited
get_cards(message)
# def new_card(message: types.Message):
# get_cards(message)
async def card_handler(message: types.Message):
await get_cards(message)x: None, тогда можно будет вызывать функцию без аргументов:from typing import overload, Union
@overload
def Func(a: int) -> int: ...
@overload
def Func(a: bool) -> bool: ...
@overload
def Func() -> None: ...
def Func(x: Union[int, bool, None] = None) -> Union[int, bool, None]:
if x is None:
return None
elif isinstance(x, bool):
return x
elif isinstance(x, int):
return 333
else:
raise ValueError("Invalid argument type.")
print(Func(10)); # 333
print(Func(True)); # True
print(Func()); # None
print(Func('kek')); # ValueError: Invalid argument type. import json
def on_message(ws, message):
data = json.loads(message)
s = data.get("s")
p = data.get("p")
if p:
_p = float(p)
if _p > 51500:
print(f"Монета {s} больше 51500, текущая цена: {_p}")
else:
print(f"Монета {s} меньше или равна 51500, текущая цена: {_p}") def sort_pair(a, b):
def sort_pair(pair):
a, b = pair
if a <= b:
return (a, b)
else:
return (b, a)
print(sort_pair((5, 1))) # (1, 5)
print(sort_pair((2, 2))) # (2, 2)
print(sort_pair((7, 8))) # (7, 8)from typing import Tuple
def sort_pair(pair: Tuple[int, int]) -> Tuple[int, int]:
a, b = pair
if a <= b:
return (a, b)
else:
return (b, a)
print(sort_pair((5, 1))) # (1, 5)
print(sort_pair((2, 2))) # (2, 2)
print(sort_pair((7, 8))) # (7, 8) SELECT
comment.*,
COALESCE(users.avatarInGames, usersCache.avatarInGames) AS avatarInGames,
COALESCE(users.gameId, usersCache.gameId) AS gameId
FROM comment
LEFT JOIN users ON comment.UID = users.userId
LEFT JOIN usersCache ON comment.UID = usersCache.userId
WHERE comment.status = 1
ORDER BY comment.OID DESC;Message: move target out of bounds: viewport size: 452, 362 (Session info: MicrosoftEdge=121.0.2277.128).
move_by_offset
viewport size: 452, 362
define('DB_CHARSET', 'utf8mb4');
define('DB_COLLATE', 'utf8mb4_unicode_ci');Может ли на hh.ru стоять какая-то защита от парсинга?)
import requests
from bs4 import BeautifulSoup
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3',
'Accept-Language': 'en-US,en;q=0.9',
'Accept-Encoding': 'gzip, deflate',
'Connection': 'keep-alive',
}
res = requests.get('https://tomsk.hh.ru/article/31475', headers=headers)
if res.status_code == 200:
soup = BeautifulSoup(res.text, 'html.parser')
el = soup.find('div', class_='URS-ratingTable')
if el:
print(el)
else:
print('Table not found!')
else:
print('The problem with connecting to the website', {res.status_code}) document.addEventListener('DOMContentLoaded', () => {
$('#colorDropdown').ddslick({
data: ddData,
background: '#fff',
imagePosition: "left",
selectText: "Выбрать цвет",
onSelected: (data) => {
const colorInput = $('#form-popup-catalog input[name="color-product"]');
const ralColors = $('.ral-colors');
const ralColorProduct = $('.ral-colors .ral-color-product');
colorInput.val(data?.selectedData?.text);
ralColors.css('display', 'block');
const imgHtml = `<img src="${data?.selectedData?.imageSrc}" alt="${data?.selectedData?.alt}">`;
ralColorProduct.empty().html(`${data?.selectedData?.text}${imgHtml}`);
}
});
}); def play(file_path):
pygame.mixer.init()
pygame.mixer.music.load(file_path)
pygame.mixer.music.play()
while pygame.mixer.music.get_busy(): # if True, the melody is being played
time.sleep(1)
play('path_to_file/file.ogg') # dancing dancing dancing... Почему вылазит ошибка self.querySelector(...) is null?
async function getValue() {
const input = document.querySelector('#input-id');
try {
const res = await fetch('/', {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({'value': input.value})
});
if (res.ok) {
console.log('Send success!');
} else {
throw new Error(`Send error, ${res.statusText}`);
}
} catch (error) {
console.error('Error', error);
}
}from flask import Flask, render_template, request, jsonify
import json
app = Flask(__name__)
@app.route('/', methods=['GET', 'POST'])
def index():
if request.method == 'GET':
return render_template('index.html')
elif request.method == 'POST':
try:
data = request.json
if 'value' in data:
value = validate(data['value'])
return jsonify({'message': 'Success!', 'value': value}), 200
else:
raise KeyError('Value key not found')
except (KeyError, json.JSONDecodeError) as e:
return jsonify({'error': 'Invalid data format'}), 400
def validate(value):
return value
if __name__ == '__main__':
app.run(debug=True)