-
Notifications
You must be signed in to change notification settings - Fork 0
Ozerova #167
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
OzerovaKs
wants to merge
4
commits into
main
Choose a base branch
from
Ozerova
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Ozerova #167
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,30 @@ | ||
| import threading | ||
|
|
||
| def fun(x, y): | ||
| return x + y | ||
|
|
||
| def add3(arg_new): | ||
| for args in arg_new: | ||
| x, y = args | ||
| res = fun(x, y) | ||
| print(f'{x} + {y} = {res}') | ||
|
|
||
| def add_integer(a): | ||
| int_thr = threading.Thread(target=add3, args=(a,)) | ||
| int_thr.start() | ||
|
|
||
| def add_string(b): | ||
| str_thr = threading.Thread(target=add3, args=(b,)) | ||
| str_thr.start() | ||
|
|
||
| def add_list(c): | ||
| l_thr = threading.Thread(target=add3, args=(c,)) | ||
| l_thr.start() | ||
|
|
||
| a = [(1, 2), (3,4)] | ||
| b = [('hello', 'bye'), ('Ivan', 'Maria')] | ||
| c = [([1, 2], [3, 4]), (['abc'], ['def'])] | ||
|
|
||
| add_integer(a) | ||
| add_string(b) | ||
| add_list(c) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,22 @@ | ||
| import socket | ||
| import pickle | ||
|
|
||
| class User: | ||
| def __init__(self, name, age): | ||
| self.name = name | ||
| self.age = age | ||
|
|
||
| def send_user_info(name, age): | ||
| user = User(name, age) | ||
| data = pickle.dumps(user) | ||
|
|
||
| s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) | ||
| s.connect(('localhost', 12345)) | ||
|
|
||
| s.sendall(data) | ||
| s.close() | ||
|
|
||
| if __name__ == '__main__': | ||
| name = input('Введите имя пользователя: ') | ||
| age = int(input('Введите возраст пользователя: ')) | ||
| send_user_info(name, age) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,30 @@ | ||
| import socket | ||
| import pickle | ||
|
|
||
| class User: | ||
| def __init__(self, name, age): | ||
| self.name = name | ||
| self.age = age | ||
|
|
||
| def receive_user_info(): | ||
| s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) | ||
|
Owner
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Этот сокет надо закрыть. Самый правильный способ это сделать - использовать менеджер контекста: with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
... |
||
| s.bind(('localhost', 12345)) | ||
| s.listen(5) | ||
|
|
||
| while True: | ||
| conn, addr = s.accept() | ||
|
|
||
| data = conn.recv(1024) | ||
|
|
||
| if not data: | ||
| break | ||
|
|
||
| user = pickle.loads(data) | ||
|
|
||
| print(f'Имя пользователя: {user.name}') | ||
| print(f'Возраст пользователя: {user.age}') | ||
|
|
||
| conn.close() | ||
|
|
||
| if __name__ == '__main__': | ||
| receive_user_info() | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,24 @@ | ||
| 2 примера: Интернет вещей и Аналитические системы | ||
| Интернет вещей: В предметной области имеется огромное количество устройств, | ||
| собирающих и передающих данные, NoSQL-подход является более предпочтительным. | ||
| Причины: | ||
| 1. гибкость схемы данных, поскольку данные могут иметь различную структуру, | ||
| так как они могут собираться с разных типов устройств. | ||
| NoSQL, такие как MongoDB или Cassandra, позволяют хранить данные без строгих | ||
| требований к схеме, что позволяет легко и быстро добавлять новые типы данных или изменять существующие. | ||
| и 2. горизонтальное масштабирование: здесь важно, чтобы база данных могла масштабироваться горизонтально, | ||
| чтобы обрабатывать большой объем данных и обеспечивать высокую производительность. | ||
| NoSQL обычно предлагают схему распределенной архитектуры, | ||
| что обеспечивает горизонтальное масштабирование и масштабируемость. | ||
|
|
||
| Аналитические системы Big Data: данные имеют большой объем и требуется выполнение сложных | ||
| аналитических запросов, NoSQL-подход также является более подходящим. | ||
| Причины: | ||
| 1. гибкость схемы данных - данные могут меняться и иметь различную структуру, поскольку они могут | ||
| быть собраны из различных источников данных. NoSQL базы данных позволяют гибко изменять | ||
| схему данных и легко добавлять новые типы данных или изменять существующие без ограничений схемы данных. | ||
| 2. горизонтальное масштабирование: аналитические системы требуют обработки большого объема данных | ||
| для выполнения сложных запросов и анализа больших наборов данных. | ||
| NoSQL базы данных, такие как Apache HBase или Apache Cassandra, позволяют горизонтальное масштабирование | ||
| для обработки большого объема данных и предоставляют высокую производительность. | ||
|
|
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1 +1,10 @@ | ||
| import re | ||
|
|
||
|
|
||
| res = [] | ||
| with open("readme.md", encoding="utf-8") as f: | ||
| reg = re.compile("git\s+\w.*") | ||
| for line in f: | ||
| str_res = re.findall(reg, line) | ||
| print(str_res) | ||
|
|
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,33 @@ | ||
| Рабочая папка для слушателей курса. Пожалуйста, создавайте свои подпапки, называя их по своей фамилии (на английском) и сохраняйте в них результаты выполнения заданий. | ||
|
|
||
| Для работы с репозиторием можно установить git и использовать следующий порядок действий: | ||
| 1. Регистрируетесь на guithub.com и подписываетесь на данный репозиторий нажимая кнопку Watch справа вверху. | ||
| 2. На рабочем компьютере выполняете команду "git clone https://github.com/IlyaOrlov/PythonCourse2.0_May23.git", чтоб скачать папку проекта. | ||
| 3. Заходите в скачанную папку: cd PythonCourse2.0_May23 | ||
| 4. Указываете электронную почту и имя, которыми будут подписываться все ваши изменения: | ||
|
|
||
| git config --global user.email "здесь укажите какой-нибудь email" | ||
| <br> | ||
| git config --global user.name "здесь укажите имя" | ||
|
|
||
| Например: | ||
| <br> | ||
| git config --global user.email "orlov.soft.company@gmail.com" | ||
| <br> | ||
| git config --global user.name "Ilya Orlov" | ||
|
|
||
| 5. По умолчанию вы будете находится на бранче main. Начиная работу над новым заданием, создайте свой бранч, с помощью следующей команды: | ||
| "git checkout -b my_branch", где my_branch - название вашего бранча (английскими буквами без пробелов), которое вы ему придумаете. | ||
|
|
||
| 7. Публикуете эту ветку в удаленном репозитории: git push --set-upstream origin my_branch (на этом этапе может потребоваться токен для авторизации на Гитхабе; порядок его создания описан в документе Useful/ГенерацияТокенаДляГитхаба.pdf). | ||
|
|
||
| 8. В папке Practice создаете подпапку (если еще не создали), называете ее по своей фамилии, и добавляете туда скрипт с выполненным заданием (например, mytest.py), либо делаете всяческие изменения в своих скриптах. | ||
|
|
||
| 9. Вносите файл под контроль git с помощью команды "git add" (например, git add mytest.py) | ||
| 11. Коммитите изменения (чтобы git присвоил им номер версии): git commit -m "Любой разумный комментарий к сделанным изменениям" | ||
| 12. Подтягиваете последние изменения из общего репозитория: git pull origin main | ||
| 13. Публикуете свои изменения на своем бранче в удаленном репозитории на сервере: git push | ||
| 14. Зайдя на страницу репозитория в гитхабе (https://github.com/IlyaOrlov/PythonCourse2.0_May23), в списке branches выбираете свой бранч и нажимаете New pull request, чтоб запросить внесение изменений с вашего бранча в main бранч. | ||
|
|
||
| Пункты 1-2 выполняются однократно. Пункты 3-4, 10 - при работе над каждым новым заданием. Пункты 5-9 при каждом изменении, которое вы собираетесь публиковать. | ||
| Если вы предпочитаете командной строке работу с визуальным интерфейсом - можно скачать и установить приложение TortoiseGit (https://tortoisegit.org/download/) и выполнить пункты 3-9 в нем. Также TortoiseGit - удобная штука для разрешения конфликтов, которые могут возникнуть после шага 8. |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Почему для решения задачи выбраны именно потоки?
Что если нам потребуется складывать не пары аргументов, а сразу много?
Почему для потоков есть start, но отсутствует join?