import configparser
from datetime import time
from pprint import pprint
config = configparser.ConfigParser() # создаём объекта парсера
config.read("conf.ini") # читаем конфиг
my_config_parser_dict = {s: dict(config.items(s)) for s in config.sections()}
for block in my_config_parser_dict.values():
block['bool'] = True
block['time'] = time(15, 20)
print(*block.values(), sep='|')
print()
pprint(my_config_parser_dict)
1|cam1|1-st floor|10.0.1.23|00:1A:C2:7B:00:47|True|15:20:00
2|cam2|2-nd floor|10.0.1.24|00:4A:C2:7B:10:42|True|15:20:00
3|cam3|3-rd floor|10.0.1.25|00:43:C2:7B:F0:13|True|15:20:00
{'cam1': {'area': '1-st floor',
'bool': True,
'ip': '10.0.1.23',
'mac': '00:1A:C2:7B:00:47',
'name': 'cam1',
'pos': '1',
'time': datetime.time(15, 20)},
'cam2': {'area': '2-nd floor',
'bool': True,
'ip': '10.0.1.24',
'mac': '00:4A:C2:7B:10:42',
'name': 'cam2',
'pos': '2',
'time': datetime.time(15, 20)},
'cam3': {'area': '3-rd floor',
'bool': True,
'ip': '10.0.1.25',
'mac': '00:43:C2:7B:F0:13',
'name': 'cam3',
'pos': '3',
'time': datetime.time(15, 20)}}
- вот тут вы идете по словарю, добавляете ключ в лист expected_response_text, потом в него же переприсваете словарь харкодный - что тут по вашему должно произойти?
expected_response_text=[]
for i in UA:
expected_response_text.append(i)
expected_response_text = {'user_agent': 'Mozilla/5.0 (Linux; U; Android 4.0.2; en-us; Galaxy Nexus Build/ICL53F) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30','platform': 'Mobile', 'browser': 'No', 'device': 'Android'}
@pytest.mark.parametrize('agent, platform, browser, device', UA)
def test_get_user_agent(self, agent, platform, browser, device):
url = "https://playground.learnqa.ru/ajax/api/user_agent_check"
UA = {"user-agent": agent}
response = requests.get(url, headers=UA)
parsed_response = response.json()
expected_response_text = {
'user_agent': agent,
'platform': platform,
'browser': browser,
'device': device
}
print(expected_response_text)
actual_response_text = parsed_response
print(actual_response_text)
assert not (result := compare(expected_response_text, actual_response_text)), result
{}[()] = 0
word = 'what
from pydantic import BaseModel, validator
class Request(BaseModel):
text: str
client_id: str
@validator('text')
def str_to_lower(cls, text: str):
return text.lower()
print(Request(text='Lower To Lower', client_id='Client'))
text='lower to lower' client_id='Client'
import math
from collections import defaultdict
all_els = defaultdict(int)
all_els[1] = 1
max_length = 0
def new_element(el: int):
if not el % 2:
return math.ceil(el / 2)
return (3 * el) + 1
def find_length(el: int):
first_el = el
length = 1
while el != 1:
el = new_element(el)
if el in all_els:
length += all_els[el]
break
length += 1
all_els[first_el] = length
return length
for i in range(1, 10 ** 6):
if max_length < (result := find_length(i)):
max_length = result
print(max_length)
from pydantic import BaseModel, validator
keys = {
'1': 'one'
}
class User(BaseModel):
name: str = ''
key: str = ''
@validator('key')
def update_key(cls, value):
return keys.get(value, value)
user_1 = User.parse_obj({'name': 'Test User', 'key': '1'})
user_2 = User.parse_obj({'name': 'Test User', 'key': '2'})
print(user_1)
print(user_2)
name='Test User' key='one'
name='Test User' key='2'
from dataclasses import dataclass
@dataclass
class MoneyBox:
sum: float = 0
capacity: float = 100
def can_add(self, v):
v = getattr(v, 'sum', v)
return (self.sum + v) > self.capacity
def __iadd__(self, v):
if self.can_add(v):
raise ValueError('Больше нельзя')
if isinstance(v, MoneyBox):
self.sum += v.sum
elif isinstance(v, (float, int)):
self.sum += v
else:
raise TypeError(f'Не поддерживается тип {type(v)}')
return self
money_box = MoneyBox()
money_box_any = MoneyBox(10)
money_box += money_box_any
print(money_box)
money_box += 10
print(money_box)
money_box += '123'
Traceback (most recent call last):
File "C:/Users/User/PycharmProjects/test/tmp.py", line 1, in <module>
from a import load
File "C:\Users\User\PycharmProjects\test\a.py", line 34, in <module>
money_box += '123'
File "C:\Users\User\PycharmProjects\test\a.py", line 18, in __iadd__
raise TypeError(f'Не поддерживается тип {type(v)}')
TypeError: Не поддерживается тип <class 'str'>
MoneyBox(capacity=0, sum=10)
MoneyBox(capacity=0, sum=20)
from random import randint
from textwrap import wrap
json_users = {randint(10000000, 9999999999): {
"Warn": randint(1, 10), "Moderator": randint(10000000, 9999999999), "Reason": "1.3"}
for _ in range(100)
}
warns = ''
for user, data in json_users.items():
moder, reason = data['Moderator'], data['Reason']
warns += f'**Пользователь: {user}** \n**Модератор: {moder}** \n**Причина: {reason}**.\t'
for chunk in wrap(warns, 400):
print(chunk, '##new_line')
from pprint import pprint
import requests
data = requests.get('https://www.cbr-xml-daily.ru/daily_json.js').json()
pprint(data['Valute']['USD'])
{'CharCode': 'USD',
'ID': 'R01235',
'Name': 'Доллар США',
'Nominal': 1,
'NumCode': '840',
'Previous': 74.1373,
'Value': 74.1567}
from dataclasses import dataclass
@dataclass
class Summoner:
id: str = ''
accountId: str = ''
puuid: str = ''
name: str = ''
profileIconId: str = ''
revisionDate: str = ''
summonerLevel: str = ''
async def SummonerByName(self, region, summonerName):
response = await self.fetch(
await self.summoner_v4.SummonerByName(
region=region,
summonerName=summonerName,
)
)
return Summoner(**response)
def __add__(self, query):
self.arr.extend(query.arr)
return self
syncio.get_event_loop().run_until_complete(waiter())
from pathlib import Path
backup_path = 'c:/temp/mybackups/Drive-C/Users/User/AppData/Local/Temp/scp26772/home/admin/web'
p = Path(backup_path)
index = p.parts.index('home')
new_path = Path('c:/temp/mybackups/WinScp').joinpath(*p.parts[index:])
print(new_path)
class CmdHandler:
def __init__(self, server):
self.somearg = 1
self.__dict__.update({k: v for k, v in server.__dict__.items() if not k.startswith("_")})
class Server(object):
def __init__(self):
self.event = "None Server "
self.obj = None
self.cmd = None
self.args = None
def handler(self):
return CmdHandler(self)
h = Server().handler()
print(h.event)
>None Server
#End flags
End_a=
- все это можно заменить на словарь листов или совсем убрать этот список, а просто считать количество обработок, и сравнивать их с длиной списка.>>> l = ['abc', 'apple', 'pen', 'abc', 'pen', 'pc']
>>> index_els = {v: k for k, v in reversed(tuple(enumerate(l)))}
>>> result = [index_els[k] for k in l]
>>> result
[0, 1, 2, 0, 2, 5]