diff --git a/Lectures/py_lec_12.pdf b/Lectures/py_lec_12.pdf deleted file mode 100644 index 715cc4e..0000000 Binary files a/Lectures/py_lec_12.pdf and /dev/null differ diff --git a/Lectures/sqlite-tools-win32-x86-3420000.zip b/Lectures/sqlite-tools-win32-x86-3420000.zip new file mode 100644 index 0000000..301591e Binary files /dev/null and b/Lectures/sqlite-tools-win32-x86-3420000.zip differ diff --git a/Lectures/sqlite-tools-win32-x86-3420000/sqlite-tools-win32-x86-3420000/sqldiff.exe b/Lectures/sqlite-tools-win32-x86-3420000/sqlite-tools-win32-x86-3420000/sqldiff.exe new file mode 100644 index 0000000..ad2f31d Binary files /dev/null and b/Lectures/sqlite-tools-win32-x86-3420000/sqlite-tools-win32-x86-3420000/sqldiff.exe differ diff --git a/Lectures/sqlite-tools-win32-x86-3420000/sqlite-tools-win32-x86-3420000/sqlite3.exe b/Lectures/sqlite-tools-win32-x86-3420000/sqlite-tools-win32-x86-3420000/sqlite3.exe new file mode 100644 index 0000000..499d7b4 Binary files /dev/null and b/Lectures/sqlite-tools-win32-x86-3420000/sqlite-tools-win32-x86-3420000/sqlite3.exe differ diff --git a/Lectures/sqlite-tools-win32-x86-3420000/sqlite-tools-win32-x86-3420000/sqlite3_analyzer.exe b/Lectures/sqlite-tools-win32-x86-3420000/sqlite-tools-win32-x86-3420000/sqlite3_analyzer.exe new file mode 100644 index 0000000..b8b3b9c Binary files /dev/null and b/Lectures/sqlite-tools-win32-x86-3420000/sqlite-tools-win32-x86-3420000/sqlite3_analyzer.exe differ diff --git a/Practice/Pripisnov/work/1name.py b/Practice/Pripisnov/work/1name.py deleted file mode 100644 index 8142b55..0000000 --- a/Practice/Pripisnov/work/1name.py +++ /dev/null @@ -1,10 +0,0 @@ -import random - - -s = "бвгдж" -g = "аеёюи" -x1 = random.choice(s) -y1 = random.choice(g) -x2 = random.choice(s) -y2 = random.choice(g) -print(x1 + y1 + x2 + y2) \ No newline at end of file diff --git a/Practice/Pripisnov/work/example.db b/Practice/Pripisnov/work/example.db new file mode 100644 index 0000000..20e4117 Binary files /dev/null and b/Practice/Pripisnov/work/example.db differ diff --git a/Practice/Pripisnov/work/my10.1work.py b/Practice/Pripisnov/work/my10.1work.py new file mode 100644 index 0000000..dae14c6 --- /dev/null +++ b/Practice/Pripisnov/work/my10.1work.py @@ -0,0 +1,52 @@ +import time +import multiprocessing +import timeit + + +def is_prime(num): + if num <= 1: + return False + for i in range(2, int(num**0.5) + 1): + if num % i == 0: + return False + return True + +def find_primes(start=3, end=100): + primes = [] + for num in range(start, end + 1): + if is_prime(num): + primes.append(num) + return primes + + +# Запуск три раза последовательно +for i in range(3): + start_time = time.time() + primes = find_primes(3, 10000) + end_time = time.time() + print(f"Простые числа от 3 до 10000 найдены за {end_time - start_time} секунд.") + + +# Запуск три раза в отдельных процессах +processes = [] +for i in range(3): + process = multiprocessing.Process(target=find_primes, args=(20001 + i * 10000, 30000 + i * 10000)) + processes.append(process) + process.start() + # process.join() - НЕ вызываем join здесь + for process in processes: + process.join() +#Для тестирования важно не забывать вызывать join() для потоков и процессов после их запуска, +# чтобы дождаться их завершения. Если вы забудете выполнить join(), +# основной поток (или процесс) может завершиться раньше, чем дочерние потоки (или процессы), +# и результаты выполнения могут быть непредсказуемыми или даже ошибочными. + + +# Замер времени исполнения функции find_primes для каждого диапазона +time_seq_1 = timeit.timeit(lambda: find_primes(3, 10000), number=1) +time_seq_2 = timeit.timeit(lambda: find_primes(10001, 20000), number=1) +time_seq_3 = timeit.timeit(lambda: find_primes(20001, 30000), number=1) + +print(f"Время выполнения последовательного варианта 1: {time_seq_1} сек.") +print(f"Время выполнения последовательного варианта 2: {time_seq_2} сек.") +print(f"Время выполнения последовательного варианта 3: {time_seq_3} сек.") diff --git a/Practice/Pripisnov/work/my10.2work.py b/Practice/Pripisnov/work/my10.2work.py new file mode 100644 index 0000000..507e67d --- /dev/null +++ b/Practice/Pripisnov/work/my10.2work.py @@ -0,0 +1,45 @@ +import threading +import multiprocessing + +def sum_integers(a, b): + return a + b + +def concatenate_strings(a, b): + return a + b + +def concatenate_lists(a, b): + return a + b + +def parallel_sum(function, args_list): + results = [] + threads = [] + + for args in args_list: + thread = threading.Thread(target=results.append, args=(function(*args),)) + threads.append(thread) + thread.start() + + for thread in threads: + thread.join() + + return results + + +# Пример использования функции parallel_sum +integer_args = [(1, 2), (3, 4), (5, 6)] +string_args = [('Hello', ' World'), ('Parallel', ' Processing'), ('Python', ' Multithreading')] +list_args = [([1, 2, 3], [4, 5, 6]), ([7, 8], [9, 10]), ([11, 12], [13, 14, 15])] + +# Выполнение сложения для различных типов данных параллельно +results_integers = parallel_sum(sum_integers, integer_args) +results_strings = parallel_sum(concatenate_strings, string_args) +results_lists = parallel_sum(concatenate_lists, list_args) + +print("Результаты сложения для integer:") +print(results_integers) + +print("Результаты сложения для string:") +print(results_strings) + +print("Результаты сложения для list:") +print(results_lists) diff --git a/Practice/Pripisnov/work/my10.3work.py b/Practice/Pripisnov/work/my10.3work.py new file mode 100644 index 0000000..b3f9c92 --- /dev/null +++ b/Practice/Pripisnov/work/my10.3work.py @@ -0,0 +1,29 @@ +import threading + +# Создаем объект Thread-local storage для каждого потока +thread_local_data = threading.local() + +def print_private_data(): + # Получаем имя исполняемого потока + thread_name = threading.current_thread().name + + # Проверяем, есть ли у потока приватные данные + if not hasattr(thread_local_data, 'private_data'): + thread_local_data.private_data = "Private data for " + thread_name + + # Выводим имя потока и его приватные данные + print(thread_name + ": " + thread_local_data.private_data) + +def run_threads(): + # Создаем и запускаем несколько потоков + threads = [] + for i in range(5): + thread = threading.Thread(target=print_private_data) + threads.append(thread) + thread.start() + + # Дожидаемся завершения всех потоков + for thread in threads: + thread.join() + +run_threads() diff --git a/Practice/Pripisnov/work/my11.1(client)work.py b/Practice/Pripisnov/work/my11.1(client)work.py new file mode 100644 index 0000000..10b5e86 --- /dev/null +++ b/Practice/Pripisnov/work/my11.1(client)work.py @@ -0,0 +1,32 @@ +import socket + + +def main(): + host = '127.0.0.1' + port = 12345 + + # Список зашифрованных слов + encrypted_words = ['xofa', 'ymno', 'zijk'] + + # Создаем сокет и подключаемся к серверу + client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + client_socket.connect((host, port)) + + # Отправляем список зашифрованных слов серверу + data = ','.join(encrypted_words) + client_socket.sendall(data.encode()) + + # Получаем список расшифрованных слов от сервера + response = client_socket.recv(1024).decode() + decrypted_words = response.split(',') + + print("Расшифрованные слова:") + for word in decrypted_words: + print(word) + + # Закрываем соединение с сервером + client_socket.close() + + +if __name__ == '__main__': + main() diff --git a/Practice/Pripisnov/work/my11.1(server)work.py b/Practice/Pripisnov/work/my11.1(server)work.py new file mode 100644 index 0000000..be34038 --- /dev/null +++ b/Practice/Pripisnov/work/my11.1(server)work.py @@ -0,0 +1,50 @@ +import socket + + +# Словарь для дешифровки слов +dictionary = { + 'xofa': 'Привет', + 'ymno': 'Проверил', + 'zijk': 'Отлично' +} + + +def decrypt_words(encrypted_words): + decrypted_words = [dictionary.get(word, 'Unknown word') for word in encrypted_words] + return decrypted_words + + +def main(): + host = '127.0.0.1' + port = 12345 + + # Создаем сокет и связываем его с хостом и портом + server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + server_socket.bind((host, port)) + + # Слушаем подключения от клиентов + server_socket.listen(1) + print('Сервер запущен. Ожидание подключения клиента...') + + # Принимаем подключение клиента + client_socket, client_address = server_socket.accept() + print('Подключен клиент:', client_address) + + # Получаем данные от клиента (список зашифрованных слов) + data = client_socket.recv(1024).decode() + encrypted_words = data.split(',') + + # Дешифруем слова и получаем список расшифрованных слов + decrypted_words = decrypt_words(encrypted_words) + + # Отправляем список расшифрованных слов клиенту + response = ','.join(decrypted_words) + client_socket.sendall(response.encode()) + + # Закрываем соединение с клиентом + client_socket.close() + server_socket.close() + + +if __name__ == '__main__': + main() diff --git a/Practice/Pripisnov/work/my11.2(client)work.py b/Practice/Pripisnov/work/my11.2(client)work.py new file mode 100644 index 0000000..a2c902f --- /dev/null +++ b/Practice/Pripisnov/work/my11.2(client)work.py @@ -0,0 +1,19 @@ +import socket +import json + + +def send_user_info(username, age): + user_info = {'name': username, 'age': age} + message = json.dumps(user_info).encode() + + client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + client_socket.connect(('localhost', 12345)) + client_socket.send(message) + client_socket.close() + + +if __name__ == "__main__": + # Примеры запуска клиентского приложения с различными пользователями + send_user_info('Alice', 25) + send_user_info('Bob', 30) + send_user_info('Eve', 22) diff --git a/Practice/Pripisnov/work/my11.2(server)work.py b/Practice/Pripisnov/work/my11.2(server)work.py new file mode 100644 index 0000000..acd1938 --- /dev/null +++ b/Practice/Pripisnov/work/my11.2(server)work.py @@ -0,0 +1,34 @@ +import socket +import json + + +def start_server(): + server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + server_socket.bind(('localhost', 12345)) + server_socket.listen(5) + print("Сервер запущен и ждет подключения клиентов...") + + connected_users = {} # Словарь для хранения информации о подключенных пользователях + + while True: + conn, addr = server_socket.accept() + print(f"Подключился клиент: {addr}") + + data = conn.recv(1024) + user_info = json.loads(data.decode()) + username = user_info.get('name', 'Unknown') + age = user_info.get('age', 'Unknown') + + # Добавляем информацию о пользователе в словарь connected_users + connected_users[addr] = {'name': username, 'age': age} + + # Выводим информацию о подключенных пользователях + print("Подключенные пользователи:") + for addr, user in connected_users.items(): + print(f"IP: {addr[0]}, Port: {addr[1]}, Name: {user['name']}, Age: {user['age']}") + + conn.close() + + +if __name__ == "__main__": + start_server() diff --git a/Practice/Pripisnov/work/my12.1work.py b/Practice/Pripisnov/work/my12.1work.py new file mode 100644 index 0000000..e79ef49 --- /dev/null +++ b/Practice/Pripisnov/work/my12.1work.py @@ -0,0 +1,47 @@ +import sqlite3 +import json + + +class SQLiteWrapper: + + def __init__(self, db_name): + self.db_name = db_name + self.connection = None + self.cursor = None + + def __enter__(self): + self.connection = sqlite3.connect(self.db_name) + self.cursor = self.connection.cursor() + return self + + def __exit__(self, exc_type, exc_val, exc_tb): + if self.cursor: + self.cursor.close() + if self.connection: + self.connection.close() + + def execute(self, query, params=None): + self.cursor.execute(query, params or ()) + self.connection.commit() + + def select(self, query, params=None): + self.cursor.execute(query, params or ()) + rows = self.cursor.fetchall() + columns = [desc[0] for desc in self.cursor.description] + results = [dict(zip(columns, row)) for row in rows] + return json.dumps(results, indent=4) + +# Пример использования: +db_name = 'example.db' + +# Создаем таблицу и вставляем данные +with SQLiteWrapper(db_name) as db: + db.execute("CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY, name TEXT, age INTEGER)") + db.execute("INSERT INTO users (name, age) VALUES (?, ?)", ('Alice', 30)) + db.execute("INSERT INTO users (name, age) VALUES (?, ?)", ('Bob', 25)) + +# Выбираем и выводим данные в формате JSON +with SQLiteWrapper(db_name) as db: + select_query = "SELECT * FROM users WHERE age > ?" + json_result = db.select(select_query, (25,)) + print(json_result) diff --git a/Practice/Pripisnov/work/my7.1work.py b/Practice/Pripisnov/work/my7.1work.py new file mode 100644 index 0000000..048f41f --- /dev/null +++ b/Practice/Pripisnov/work/my7.1work.py @@ -0,0 +1,11 @@ +class Man: + def __init__(self, name): + self.name = name + + def solve_task(self): + print("Я еще не готов") + + +# Пример использования класса +man = Man("John") +man.solve_task() diff --git a/Practice/Pripisnov/work/my7.2work.py b/Practice/Pripisnov/work/my7.2work.py new file mode 100644 index 0000000..d83969c --- /dev/null +++ b/Practice/Pripisnov/work/my7.2work.py @@ -0,0 +1,13 @@ +import time +from random import randint + +class Pupil: + def solve_task(self): + thinking_time = randint(3, 6) # Генерация случайного времени от 3 до 6 секунд + time.sleep(thinking_time) # Задержка выполнения программы на указанное количество секунд + print("I'm ready now!") + + +# Пример использования класса +pupil = Pupil() +pupil.solve_task() diff --git a/Practice/Pripisnov/work/my7.3work.py b/Practice/Pripisnov/work/my7.3work.py new file mode 100644 index 0000000..ff32b67 --- /dev/null +++ b/Practice/Pripisnov/work/my7.3work.py @@ -0,0 +1,53 @@ +class ATM: + def __init__(self, cash_amount): + self.cash_amount = cash_amount + + def check_balance(self): + print("Checking balance...") + print("Available cash:", self.cash_amount) + + def withdraw_cash(self, amount): + print("Withdrawing cash...") + if amount <= self.cash_amount: + self.cash_amount -= amount + print("Withdrawn:", amount) + print("Remaining cash:", self.cash_amount) + else: + print("Insufficient cash!") + + def deposit_cash(self, amount): + print("Depositing cash...") + self.cash_amount += amount + print("Deposited:", amount) + print("Total cash:", self.cash_amount) + + +class OnlineATM(ATM): + def __init__(self, cash_amount): + super().__init__(cash_amount) + + def make_payment(self, amount): + print("Making online payment...") + if amount <= self.cash_amount: + self.cash_amount -= amount + print("Payment successful!") + print("Remaining cash:", self.cash_amount) + else: + print("Insufficient cash for payment!") + + +# Тестирование системы +atms = [ + ATM(10000), + OnlineATM(5000), + ATM(20000) +] + +for atm in atms: + print("--- ATM Information ---") + atm.check_balance() + atm.withdraw_cash(3000) + atm.deposit_cash(2000) + if isinstance(atm, OnlineATM): + atm.make_payment(1500) + print("-----------------------") diff --git a/Practice/Pripisnov/work/my8.1work.py b/Practice/Pripisnov/work/my8.1work.py new file mode 100644 index 0000000..4750cd7 --- /dev/null +++ b/Practice/Pripisnov/work/my8.1work.py @@ -0,0 +1,24 @@ +class ParagraphIterator: + def __init__(self, text, paragraph_symbol): + self.paragraphs = text.split(paragraph_symbol) # Разделение текста на параграфы + self.current_paragraph = 0 # Индекс текущего параграфа + + def __iter__(self): + return self + + def __next__(self): + if self.current_paragraph < len(self.paragraphs): + p = self.paragraphs[self.current_paragraph] + self.current_paragraph += 1 + return p + else: + raise StopIteration + + +# Тестирование итератора +tx = "Параграф 1. Содержимое параграфа 1. Параграф 2. Содержимое параграфа 2. Параграф 3. Содержимое параграфа 3." +paragraph_sym = "." + +iterator = ParagraphIterator(tx, paragraph_sym) +for paragraph in iterator: + print(paragraph) diff --git a/Practice/Pripisnov/work/my8.2work.py b/Practice/Pripisnov/work/my8.2work.py new file mode 100644 index 0000000..9ee52a4 --- /dev/null +++ b/Practice/Pripisnov/work/my8.2work.py @@ -0,0 +1,12 @@ +def read_file_lines(filename): + with open(filename, 'r') as file: + for line in file: + yield line.rstrip() + + +# Пример использования генератора +file_path = 'example.txt' # Путь к файлу + +for line in read_file_lines(file_path): + print(line) + \ No newline at end of file diff --git a/Practice/Pripisnov/work/my8.3work.py b/Practice/Pripisnov/work/my8.3work.py new file mode 100644 index 0000000..1f5159e --- /dev/null +++ b/Practice/Pripisnov/work/my8.3work.py @@ -0,0 +1,17 @@ +import time + + +class ExecutionTimer: + def __enter__(self): + self.start_time = time.time() + + def __exit__(self, exc_type, exc_val, exc_tb): + elapsed_time = time.time() - self.start_time + print(f"Execution time: {elapsed_time} seconds") + + +# Пример использования менеджера контекста +with ExecutionTimer(): + # Код, исполнение которого нужно замерить + for i in range(1000000): + pass diff --git a/Practice/Pripisnov/work/my8.4.1work.py b/Practice/Pripisnov/work/my8.4.1work.py new file mode 100644 index 0000000..0c6af95 --- /dev/null +++ b/Practice/Pripisnov/work/my8.4.1work.py @@ -0,0 +1,16 @@ +import itertools + + +# Функция, принимающая три массива и возвращающая один массив: +def merge_arrays(arr1, arr2, arr3): + merged = itertools.chain(arr1, arr2, arr3) + result = list(merged) + return result + + +# Пример использования функции +a1 = [1, 2, 3] +a2 = [4, 5] +a3 = [6, 7] +res = merge_arrays(a1, a2, a3) +print(res) diff --git a/Practice/Pripisnov/work/my8.4.2work.py b/Practice/Pripisnov/work/my8.4.2work.py new file mode 100644 index 0000000..0dd0b03 --- /dev/null +++ b/Practice/Pripisnov/work/my8.4.2work.py @@ -0,0 +1,14 @@ +import itertools + + +# Функция, принимающая массив строк и возвращающая только строки с длиной не меньше пяти: +def filter_strings(strings): + filtered = itertools.filterfalse(lambda x: len(x) < 5, strings) + result = list(filtered) + return result + + +# Пример использования функции +s = ['hello', 'i', 'write', 'cool', 'code'] +res = filter_strings(s) +print(res) diff --git a/Practice/Pripisnov/work/my8.4.3work.py b/Practice/Pripisnov/work/my8.4.3work.py new file mode 100644 index 0000000..1d620fc --- /dev/null +++ b/Practice/Pripisnov/work/my8.4.3work.py @@ -0,0 +1,15 @@ +import itertools + + +# Функция, генерирующая все возможные комбинации строки 'password': +def generate_combinations(): + word = 'password' + combinations = itertools.combinations(word, 4) + result = list(combinations) + return result + + +# Пример использования функции +res = generate_combinations() +for combination in res: + print(combination) diff --git a/Practice/Pripisnov/work/my9.1work.py b/Practice/Pripisnov/work/my9.1work.py new file mode 100644 index 0000000..7a7c4a7 --- /dev/null +++ b/Practice/Pripisnov/work/my9.1work.py @@ -0,0 +1,18 @@ +import re + + +file_path = 'Practice/README.md' + +# Читаем содержимое файла +with open(file_path, 'r') as file: + content = file.read() + +# Определяем шаблон регулярного выражения для поиска команд Git с аргументами +pattern = r'git\s+\w+\s+' + +# Ищем все совпадения в тексте файла +matches = re.findall(pattern, content) + +# Выводим найденные команды +for match in matches: + print(match.strip()) diff --git a/Practice/Pripisnov/work/my9.2work.py b/Practice/Pripisnov/work/my9.2work.py new file mode 100644 index 0000000..cd12830 --- /dev/null +++ b/Practice/Pripisnov/work/my9.2work.py @@ -0,0 +1,27 @@ +import datetime + + +def count_working_days(start_date, end_date): + # Определяем список дней недели, считаемых рабочими + working_days = [0, 1, 2, 3, 4] # Понедельник (0) - Пятница (4) + + # Инициализируем счетчик рабочих дней + count = 0 + + # Перебираем каждый день между start_date и end_date + current_date = start_date + while current_date <= end_date: + # Проверяем, является ли текущий день рабочим + if current_date.weekday() in working_days: + count += 1 + + current_date += datetime.timedelta(days=1) + + return count + + +# Пример +start_d = datetime.date(2023, 1, 1) +end_d = datetime.date(2023, 1, 31) +working_d = count_working_days(start_d, end_d) +print("Количество рабочих дней:", working_d) diff --git a/Practice/Pripisnov/work/my9.3work.py b/Practice/Pripisnov/work/my9.3work.py new file mode 100644 index 0000000..73ffb7a --- /dev/null +++ b/Practice/Pripisnov/work/my9.3work.py @@ -0,0 +1,23 @@ +import os +import shutil +import time +from datetime import datetime, timedelta + +def delete_old_files_and_folders(folder_path): + while True: + for root, dirs, files in os.walk(folder_path, topdown=False): + for file in files: + file_path = os.path.join(root, file) + file_creation_time = os.path.getctime(file_path) + if datetime.now() - datetime.fromtimestamp(file_creation_time) > timedelta(minutes=1): + os.remove(file_path) + + for folder in dirs: + folder_path = os.path.join(root, folder) + folder_creation_time = os.path.getctime(folder_path) + if datetime.now() - datetime.fromtimestamp(folder_creation_time) > timedelta(minutes=2): + shutil.rmtree(folder_path) + +if __name__ == "__main__": + path_to_watch = input("Введите путь до папки, за которой следить: ") + delete_old_files_and_folders(path_to_watch) diff --git a/Practice/Pripisnov/work/my9.4work.py b/Practice/Pripisnov/work/my9.4work.py new file mode 100644 index 0000000..9f21c32 --- /dev/null +++ b/Practice/Pripisnov/work/my9.4work.py @@ -0,0 +1,46 @@ +import pickle +import random + +class Human: + def __init__(self, name, surname, age, residence): + self.name = name + self.surname = surname + self.age = age + self.residence = residence + +def create_humans(num_humans): + humans = [] + for _ in range(num_humans): + name = random.choice(["John", "Alice", "Michael", "Emma"]) + surname = random.choice(["Smith", "Johnson", "Brown", "Wilson"]) + age = random.randint(18, 65) + residence = random.choice(["New York", "London", "Paris", "Tokyo"]) + human = Human(name, surname, age, residence) + humans.append(human) + return humans + +def serialize_humans(humans, file_path): + with open(file_path, "wb") as file: + pickle.dump(humans, file) + +def deserialize_humans(file_path): + with open(file_path, "rb") as file: + humans = pickle.load(file) + return humans + +# Создаем 3 экземпляра класса Human +humans = create_humans(3) + +# Сериализуем и сохраняем экземпляры в файл human.data +serialize_humans(humans, "tak/human.data") + +# Читаем и десериализуем содержимое файла human.data +deserialized_humans = deserialize_humans("tak/human.data") + +# Выводим результат на печать +for human in deserialized_humans: + print(f"Name: {human.name}") + print(f"Surname: {human.surname}") + print(f"Age: {human.age}") + print(f"Residence: {human.residence}") + print() diff --git a/Practice/Stupina/homework_8/task_2.py b/Practice/Stupina/homework_8/task_2.py index af97acc..4deb071 100644 --- a/Practice/Stupina/homework_8/task_2.py +++ b/Practice/Stupina/homework_8/task_2.py @@ -5,6 +5,6 @@ def my(name): print('---') -f_name = 'композиция_vs_наследование.txt' +f_name = '1.txt' for i in my(f_name): print(i) diff --git a/Useful/for_lec14/ctxlib_example1.py b/Useful/for_lec14/ctxlib_example1.py index 3059c70..4a20dd6 100644 --- a/Useful/for_lec14/ctxlib_example1.py +++ b/Useful/for_lec14/ctxlib_example1.py @@ -28,7 +28,7 @@ class MyConf: print(m.server_addr) print(m.server_port) print("======================") -print(m.server_addr) # '192.168.1.1' # print(getattr(m, "server_addr")) +print(m.server_addr) # '192.168.1.1' print(m.server_port) # 1212 diff --git a/Useful/for_lec14/listdir_example.py b/Useful/for_lec14/listdir_example.py index df67c74..b66cd2d 100644 --- a/Useful/for_lec14/listdir_example.py +++ b/Useful/for_lec14/listdir_example.py @@ -18,7 +18,7 @@ def show_dir(cur_dir): # print(i) # t = 'mydirectory' -# f = 'композиция_vs_наследование.txt' +# f = '1.txt' # with open(os.path.join(t, f), 'w'): # pass diff --git a/Useful/for_lec14/log_file.txt b/Useful/for_lec14/log_file.txt new file mode 100644 index 0000000..b81b18a --- /dev/null +++ b/Useful/for_lec14/log_file.txt @@ -0,0 +1,8 @@ +trace: ERROR-23453 some text +trace: ERROR-237655 some another text +trace: WARNING-2376 some another text +;lk;lk;lk;l +wpoeipoipoi +,mn,mn,mn +oiuoiuoiu +module: ERROR-23278 \ No newline at end of file diff --git a/coolsite/coolsite/__init__.py b/coolsite/coolsite/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/coolsite/coolsite/asgi.py b/coolsite/coolsite/asgi.py new file mode 100644 index 0000000..169f3fb --- /dev/null +++ b/coolsite/coolsite/asgi.py @@ -0,0 +1,16 @@ +""" +ASGI config for coolsite project. + +It exposes the ASGI callable as a module-level variable named ``application``. + +For more information on this file, see +https://docs.djangoproject.com/en/4.2/howto/deployment/asgi/ +""" + +import os + +from django.core.asgi import get_asgi_application + +os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'coolsite.settings') + +application = get_asgi_application() diff --git a/coolsite/coolsite/settings.py b/coolsite/coolsite/settings.py new file mode 100644 index 0000000..2dea12d --- /dev/null +++ b/coolsite/coolsite/settings.py @@ -0,0 +1,123 @@ +""" +Django settings for coolsite project. + +Generated by 'django-admin startproject' using Django 4.2.4. + +For more information on this file, see +https://docs.djangoproject.com/en/4.2/topics/settings/ + +For the full list of settings and their values, see +https://docs.djangoproject.com/en/4.2/ref/settings/ +""" + +from pathlib import Path + +# Build paths inside the project like this: BASE_DIR / 'subdir'. +BASE_DIR = Path(__file__).resolve().parent.parent + + +# Quick-start development settings - unsuitable for production +# See https://docs.djangoproject.com/en/4.2/howto/deployment/checklist/ + +# SECURITY WARNING: keep the secret key used in production secret! +SECRET_KEY = 'django-insecure-0tky*$*o$_lkl^x*l#7si05n5jt1p-n4$s7p8dopklwp#e2lc1' + +# SECURITY WARNING: don't run with debug turned on in production! +DEBUG = True + +ALLOWED_HOSTS = [] + + +# Application definition + +INSTALLED_APPS = [ + 'django.contrib.admin', + 'django.contrib.auth', + 'django.contrib.contenttypes', + 'django.contrib.sessions', + 'django.contrib.messages', + 'django.contrib.staticfiles', +] + +MIDDLEWARE = [ + 'django.middleware.security.SecurityMiddleware', + 'django.contrib.sessions.middleware.SessionMiddleware', + 'django.middleware.common.CommonMiddleware', + 'django.middleware.csrf.CsrfViewMiddleware', + 'django.contrib.auth.middleware.AuthenticationMiddleware', + 'django.contrib.messages.middleware.MessageMiddleware', + 'django.middleware.clickjacking.XFrameOptionsMiddleware', +] + +ROOT_URLCONF = 'coolsite.urls' + +TEMPLATES = [ + { + 'BACKEND': 'django.template.backends.django.DjangoTemplates', + 'DIRS': [], + 'APP_DIRS': True, + 'OPTIONS': { + 'context_processors': [ + 'django.template.context_processors.debug', + 'django.template.context_processors.request', + 'django.contrib.auth.context_processors.auth', + 'django.contrib.messages.context_processors.messages', + ], + }, + }, +] + +WSGI_APPLICATION = 'coolsite.wsgi.application' + + +# Database +# https://docs.djangoproject.com/en/4.2/ref/settings/#databases + +DATABASES = { + 'default': { + 'ENGINE': 'django.db.backends.sqlite3', + 'NAME': BASE_DIR / 'db.sqlite3', + } +} + + +# Password validation +# https://docs.djangoproject.com/en/4.2/ref/settings/#auth-password-validators + +AUTH_PASSWORD_VALIDATORS = [ + { + 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', + }, + { + 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', + }, + { + 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', + }, + { + 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', + }, +] + + +# Internationalization +# https://docs.djangoproject.com/en/4.2/topics/i18n/ + +LANGUAGE_CODE = 'en-us' + +TIME_ZONE = 'UTC' + +USE_I18N = True + +USE_TZ = True + + +# Static files (CSS, JavaScript, Images) +# https://docs.djangoproject.com/en/4.2/howto/static-files/ + +STATIC_URL = 'static/' + +# Default primary key field type +# https://docs.djangoproject.com/en/4.2/ref/settings/#default-auto-field + +DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField' diff --git a/coolsite/coolsite/urls.py b/coolsite/coolsite/urls.py new file mode 100644 index 0000000..0118240 --- /dev/null +++ b/coolsite/coolsite/urls.py @@ -0,0 +1,22 @@ +""" +URL configuration for coolsite project. + +The `urlpatterns` list routes URLs to views. For more information please see: + https://docs.djangoproject.com/en/4.2/topics/http/urls/ +Examples: +Function views + 1. Add an import: from my_app import views + 2. Add a URL to urlpatterns: path('', views.home, name='home') +Class-based views + 1. Add an import: from other_app.views import Home + 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') +Including another URLconf + 1. Import the include() function: from django.urls import include, path + 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) +""" +from django.contrib import admin +from django.urls import path + +urlpatterns = [ + path('admin/', admin.site.urls), +] diff --git a/coolsite/coolsite/wsgi.py b/coolsite/coolsite/wsgi.py new file mode 100644 index 0000000..0b68675 --- /dev/null +++ b/coolsite/coolsite/wsgi.py @@ -0,0 +1,16 @@ +""" +WSGI config for coolsite project. + +It exposes the WSGI callable as a module-level variable named ``application``. + +For more information on this file, see +https://docs.djangoproject.com/en/4.2/howto/deployment/wsgi/ +""" + +import os + +from django.core.wsgi import get_wsgi_application + +os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'coolsite.settings') + +application = get_wsgi_application() diff --git a/coolsite/manage.py b/coolsite/manage.py new file mode 100644 index 0000000..445748c --- /dev/null +++ b/coolsite/manage.py @@ -0,0 +1,22 @@ +#!/usr/bin/env python +"""Django's command-line utility for administrative tasks.""" +import os +import sys + + +def main(): + """Run administrative tasks.""" + os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'coolsite.settings') + try: + from django.core.management import execute_from_command_line + except ImportError as exc: + raise ImportError( + "Couldn't import Django. Are you sure it's installed and " + "available on your PYTHONPATH environment variable? Did you " + "forget to activate a virtual environment?" + ) from exc + execute_from_command_line(sys.argv) + + +if __name__ == '__main__': + main()