Библиотека Python разработчика | Книги по питону
19.5K subscribers
1.05K photos
391 videos
82 files
988 links
Полезные материалы для питониста по Фреймворкам Django, Flask, FastAPI, Pyramid, Tornado и др.

По всем вопросам @evgenycarter

РКН clck.ru/3Ko7Hq
Download Telegram
Как создать чат-бота с нуля на Python: подробная инструкция

В этой статье мы расскажем, как создать своего чат-бота на Python.


Чат-бот — это программа, которая выясняет потребности пользователей, а затем помогает удовлетворить их (денежная транзакция, бронирование отелей, составление документов). Сегодня почти каждая компания имеет чат-бота для взаимодействия с пользователями. Некоторые способы использования чат-ботов:


предоставление информации о рейсе;
предоставление пользователям доступа к информации об их финансах;
служба поддержки.
👍4🔥2
The creation of a class consists of two big steps. First, the class body is evaluated, just like any function body. Second, the resulted namespace (the one that is returned by locals()) is used by a metaclass (type by default) to construct an actual class object.

class Meta(type):
def __new__(meta, name, bases, ns):
print(ns)
return super().__new__(
meta, name,
bases, ns
)


class Foo(metaclass=Meta):
B = 2


The above code prints {'__module__': '__main__', '__qualname__': 'Foo', 'B': 3}.

Obviously, if you do something like B = 2; B = 3, then the metaclass only knows about B = 3, since only that value is in ns. This limitation is based on the fact, that a metaclass works after the body evaluation.

However, you can interfere in the evaluation by providing custom namespace. By default, a simple dictionary is used but you can provide a custom dictionary-like object using the metaclass __prepare__ method.

class CustomNamespace(dict):
def __setitem__(self, key, value):
print(f'{key} -> {value}')
return super().__setitem__(key, value)


class Meta(type):
def __new__(meta, name, bases, ns):
return super().__new__(
meta, name,
bases, ns
)

@classmethod
def __prepare__(metacls, cls, bases):
return CustomNamespace()


class Foo(metaclass=Meta):
B = 2
B = 3


The output is the following:

__module__ -> __main__
__qualname__ -> Foo
B -> 2
B -> 3


And this is how enum.Enum is protected from duplicates.
👍4👎1
The map function calls another function for every element of some iterable. That means that function should accept a single value as an argument:

In : list(map(lambda x: x ** 2, [1, 2, 3]))
Out: [1, 4, 9]


However, if each element of the iterable is tuple, then it would be nice to pass each element of that tuple as a separate argument. It was possible in Python 2, thanks to the tuple parameter unpacking (note the parentheses):

>>> map(lambda (a, b): a + b, [(1, 2), (3, 4)])
[3, 7]


In Python 3, this feature is gone, but there is another solution. itertools.starmap unpacks tuple for you, as though a function is called with a star: f(*arg) (hence the function's name):

In [3]: list(starmap(lambda a, b: a + b, [(1, 2), (3, 4)]))
Out[3]: [3, 7]
👍4👎1
​FaceSwap - это инструмент, который использует глубокое обучение для распознавания и замены лиц на фотографиях и видео. Deepfake)

#GitHub | #Python #Deepfake

👉 @Githublib
👍4
Python provides the powerful library to work with date and time: datetime. The interesting part is, datetime objects have the special interface for timezone support (namely the tzinfo attribute), but this module only has limited support of its interface, leaving the rest of the job to different modules.

The most popular module for this job is pytz. The tricky part is, pytz doesn't fully satisfy tzinfo interface. The pytz documentation states this at one of the first lines: “This library differs from the documented Python API for tzinfo implementations.”

You can't use pytz timezone objects as the tzinfo attribute. If you try, you may get the absolute insane results:

In : paris = pytz.timezone('Europe/Paris')
In : str(datetime(2017, 1, 1, tzinfo=paris))
Out: '2017-01-01 00:00:00+00:09'


Look at that +00:09 offset. The proper use of pytz is following:

In : str(paris.localize(datetime(2017, 1, 1)))
Out: '2017-01-01 00:00:00+01:00'


Also, after any arithmetic operations, you should normalize your datetime object in case of offset changes (on the edge of the DST period for instance).

In : new_time = time + timedelta(days=2)
In : str(new_time)
Out: '2018-03-27 00:00:00+01:00'
In : str(paris.normalize(new_time))
Out: '2018-03-27 01:00:00+02:00'


Since Python 3.6, it's recommended to use dateutil.tz instead of pytz. It's fully compatible with tzinfo, can be passed as an attribute, doesn't require normalize, though works a bit slower.

If you are interested why pytz doesn't support datetime API, or you wish to see more examples, consider reading the decent article on the topic.
👍5👎1
Forwarded from Python академия
Упрощенный вывод данных

Он позволяет вывести строчный массив одной строкой, с разделением запятыми. Нам не нужно использовать .join() и циклы.

Подписывайтесь на канал 👉@pythonofff
👍2
Подборка каналов для IT специалистов 🎯


https://t.me/odin1C_rus Cтатьи, курсы, советы, шаблоны кода 1С
https://t.me/kotlin_lib Подборки полезного материала по Kotlin
https://t.me/nodejs_lib Подборки по Node js и все что с ним связано
https://t.me/React_lib Подборки по React js и все что с ним связано


Программирование C++📌
https://t.me/cpp_lib Библиотека C/C++ разработчика
https://t.me/cpp_knigi Книги для программистов C/C++

Программирование Python 📌
https://t.me/pythonofff Python академия. Учи Python быстро и легко🐍
https://t.me/BookPython Библиотека Python разработчика
https://t.me/python_real Python подборки на русском и английском
https://t.me/python_360 Книги по Python Rus

Java разработка 📌
https://t.me/BookJava Библиотека Java разработчика
https://t.me/java_360 Книги по Java Rus

GitHub Сообщество 📌
https://t.me/Githublib Интересное из GitHub

CodePen 📌
https://t.me/codepen_1 Сообщество пользователей CodePen

Базы данных (Data Base) 📌
https://t.me/database_info Все про базы данных

Мобильная разработка: iOS, Android 📌
https://t.me/developer_mobila Мобильная разработка

Фронтенд разработка 📌
https://t.me/frontend_1 Подборки для frontend разработчиков

Разработка игр 📌
https://t.me/game_devv Все о разработке игр

Вакансии 📌
https://t.me/sysadmin_rabota Системный Администратор
https://t.me/progjob Вакансии в IT

Чат программистов📌
https://t.me/developers_ru

Библиотеки 📌
https://t.me/book_for_dev Книги для программистов Rus
https://t.me/programmist_of Книги по программированию
https://t.me/proglb Библиотека программиста
https://t.me/bfbook Книги для программистов

БигДата, машинное обучение 📌
https://t.me/bigdata_1 Data Science, Big Data, Machine Learning, Deep Learning

Программирование 📌
https://t.me/bookflow Лекции, видеоуроки, доклады с IT конференций
https://t.me/coddy_academy Полезные советы по программированию

QA, тестирование 📌
https://t.me/testlab_qa Библиотека тестировщика

Шутки программистов 📌
https://t.me/itumor Шутки программистов

Защита, взлом, безопасность 📌
https://t.me/thehaking Канал о кибербезопасности

Книги, статьи для дизайнеров 📌
https://t.me/ux_web Статьи, книги для дизайнеров
https://t.me/arhitekturamira World Architecture

Системное администрирование 📌
https://t.me/tipsysdmin Типичный Сисадмин (фото железа, было/стало)
https://t.me/sysadminof Книги для админов, полезные материалы
https://t.me/i_odmin Все для системного администратора
https://t.me/i_odmin_book Библиотека Системного Администратора
https://t.me/i_odmin_chat Чат системных администраторов
https://t.me/i_DevOps DevOps: Пишем о Docker, Kubernetes и др.

Английский 📌
https://t.me/UchuEnglish Английский с нуля

Математика 📌
https://t.me/Pomatematike Канал по математике

Арбитраж трафика 📌
https://t.me/partnerochkin CPA и арбитраж трафика

Крипта 📌
https://t.me/bitkoinoff Новости криптовалют

Метавселенная, GameFi, Crypto 📌
https://t.me/metaverse360

DeepFake 📌
https://t.me/deepfakenow Публикуем deepfake видео

Мир технологий 📌
https://t.me/mir_teh Видео из мира технологий

Excel лайфхак📌
https://t.me/Excel_lifehack
👍1
Python functions can return multiple values:

def edges(lst):
return lst[0], lst[-1]

first, last = edges([1, 2, 3])
assert first == 1
assert last == 3


In truth, lst[0], lst[-1] is a simple tuple. It's returned as usual and then unpacked to first and last:


result = edges([1, 2, 3])
assert isinstance(result, tuple)
first, last = result
assert first == 1
assert last == 3


Usually, you don't care about it at all. However, all these things come to the surface when you use type hints. You have to define the function return value as tuple:

def edges(lst) -> Tuple[int, int]:
return lst[0], lst[-1]


Calling that function is even harder. You may think that you can do something like this:

first: int, last: int = edges([1, 2, 3])

Or at least this:

first, last: Tuple[int, int] = edges([1, 2, 3])

But both ways are incorrect. This is the only reasonable thing you can do to annotate these variables:

first: int
last: int
first, last = edges([1, 2, 3])
👍2👎2
This media is not supported in your browser
VIEW IN TELEGRAM
Обучение с подкреплением на Python с библиотекой Keras

Статья о том, как научить машинку участвовать в гонке с помощью обучения с подкреплением, а персонажей — избегать файерболов. При этом агент способен научиться играть в игру в своем собственном «воображении». В статье — пример обучения с подкреплением (reinforcement learning) на Python с библиотекой Keras.
👍7
This media is not supported in your browser
VIEW IN TELEGRAM
​Pyxel - это игровой движок для Python в стиле ретро.


Благодаря своей простоте, вдохновленной старыми игровыми консолями (например, палитра состоит всего из 16 цветов, и только 4 звука могут быть проиграны одновременно), вы можете легко создавать игры в стиле пиксель-арт.

#GitHub | #Cpp #engine

👉 @Githublib
👍13
The standard json module has a command line interface that can be useful to prettify JSON by python alone. The module for this is called json.tool and is meant to be called like this:

$ echo '{"a": [], "b": "c"}' | python -m json.tool
{
"a": [],
"b": "c"
}
👍4👎1
Sometimes you need to have a queue in your program, i. e. a container where you put elements from one side and remove them from another. list can be such a container:

In : lst = [1, 2, 3]
In : lst.pop()
Out: 3
In : lst
Out: [1, 2]
In : lst[:0] = [4] # push
In : lst
Out: [4, 1, 2]


However, using list doesn't only look eerie (look at that push), but also is quite inefficient.

In : lst = [0] * 10_000_000

In : %timeit lst[:0] = [1]
9.5 ms ± 111 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

In : %timeit lst.pop()
84.3 ns ± 4.01 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)


As you can see, on my machine pop is 100 times faster than “push”. This is how list works: elements can be easily added to or removed from the end of the list, but to remove the first element, Python needs to create a new list from scratch.

What you really want to use for this problem is collections.deque. It's designed to be used as a queue:

In : d = deque([1] * 100_000_000)
In : %timeit d.popleft()
65 ns ± 0.436 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)
👍3👎3
Подборка каналов для IT специалистов 🎯


https://t.me/odin1C_rus Cтатьи, курсы, советы, шаблоны кода 1С
https://t.me/kotlin_lib Подборки полезного материала по Kotlin
https://t.me/nodejs_lib Подборки по Node js и все что с ним связано
https://t.me/React_lib Подборки по React js и все что с ним связано
https://t.me/ruby_lib Библиотека Ruby программиста


Программирование C++📌
https://t.me/cpp_lib Библиотека C/C++ разработчика
https://t.me/cpp_knigi Книги для программистов C/C++

Программирование Python 📌
https://t.me/pythonofff Python академия. Учи Python быстро и легко🐍
https://t.me/BookPython Библиотека Python разработчика
https://t.me/python_real Python подборки на русском и английском
https://t.me/python_360 Книги по Python Rus

Java разработка 📌
https://t.me/BookJava Библиотека Java разработчика
https://t.me/java_360 Книги по Java Rus

GitHub Сообщество 📌
https://t.me/Githublib Интересное из GitHub

CodePen 📌
https://t.me/codepen_1 Сообщество пользователей CodePen

Базы данных (Data Base) 📌
https://t.me/database_info Все про базы данных

Мобильная разработка: iOS, Android 📌
https://t.me/developer_mobila Мобильная разработка

Фронтенд разработка 📌
https://t.me/frontend_1 Подборки для frontend разработчиков

Разработка игр 📌
https://t.me/game_devv Все о разработке игр

Вакансии 📌
https://t.me/sysadmin_rabota Системный Администратор
https://t.me/progjob Вакансии в IT

Чат программистов📌
https://t.me/developers_ru

Библиотеки 📌
https://t.me/book_for_dev Книги для программистов Rus
https://t.me/programmist_of Книги по программированию
https://t.me/proglb Библиотека программиста
https://t.me/bfbook Книги для программистов

БигДата, машинное обучение 📌
https://t.me/bigdata_1 Data Science, Big Data, Machine Learning, Deep Learning

Программирование 📌
https://t.me/bookflow Лекции, видеоуроки, доклады с IT конференций
https://t.me/coddy_academy Полезные советы по программированию

QA, тестирование 📌
https://t.me/testlab_qa Библиотека тестировщика

Шутки программистов 📌
https://t.me/itumor Шутки программистов

Защита, взлом, безопасность 📌
https://t.me/thehaking Канал о кибербезопасности

Книги, статьи для дизайнеров 📌
https://t.me/ux_web Статьи, книги для дизайнеров
https://t.me/arhitekturamira World Architecture

Системное администрирование 📌
https://t.me/tipsysdmin Типичный Сисадмин (фото железа, было/стало)
https://t.me/sysadminof Книги для админов, полезные материалы
https://t.me/i_odmin Все для системного администратора
https://t.me/i_odmin_book Библиотека Системного Администратора
https://t.me/i_odmin_chat Чат системных администраторов
https://t.me/i_DevOps DevOps: Пишем о Docker, Kubernetes и др.

Английский 📌
https://t.me/UchuEnglish Английский с нуля

Математика 📌
https://t.me/Pomatematike Канал по математике

Арбитраж трафика 📌
https://t.me/partnerochkin CPA и арбитраж трафика

Крипта 📌
https://t.me/bitkoinoff Новости криптовалют

Метавселенная, GameFi, Crypto 📌
https://t.me/metaverse360

DeepFake 📌
https://t.me/deepfakenow Публикуем deepfake видео

Мир технологий 📌
https://t.me/mir_teh Видео из мира технологий

Excel лайфхак📌
https://t.me/Excel_lifehack
👍7
This media is not supported in your browser
VIEW IN TELEGRAM
Создание GIF-анимации с помощью OpenCV

Из этого туториала вы узнаете, как создавать анимированные GIF-файлы с помощью OpenCV, Python и ImageMagick. Затем объедините эти методы, чтобы создать генератор мемов с OpenCV!

👉 @bookflow
👍3
Forwarded from BigData
Zharikov2017Presentation.pdf
3 MB
Шпаргалка по всем сетям, их
классификация и строгое описание


Жариков Илья Николаевич
Московский физико-технический институт
Факультет управления и прикладной математики
Кафедра интеллектуальных систем

👉 @bigdata_1
👍8
Some code you are using may print data you are interested in stdout instead of providing some API that is usable within a program (returning a string, for example).

Instead of refactoring such code you may use the contextlib.redirect_stdout context manager that allows temporary redirecting stdout to any custom file-like object. In conjuncture with io.StringIO, it allows capturing output to a variable.

from contextlib import redirect_stdout
from io import StringIO

s = StringIO()
with redirect_stdout(s):
print(42)

print(s.getvalue())


There is also contextlib.redirect_stderr available for redirecting sys.stderr.
👍3👎1
Every call to next(x) returns the new value from the x iterator unless an exception is raised. If this is StopIteration, it means the iterator is exhausted and can supply no more values. If a generator is iterated, it automatically raises StopIteration upon the end of the body:

>>> def one_two():
... yield 1
... yield 2
...
>>> i = one_two()
>>> next(i)
1
>>> next(i)
2
>>> next(i)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
StopIteration


StopIteration is automatically handled by tools that calls next for you:

>>> list(one_two())
[1, 2]


The problem is, any unexpected StopIteration that is raised within a generator causes it to stop silently instead of actually raising an exception:


def one_two():
yield 1
yield 2

def one_two_repeat(n):
for _ in range(n):
i = one_two()
yield next(i)
yield next(i)
yield next(i)

print(list(one_two_repeat(3)))

The last yield here is a mistake: StopIteration is raised and makes list(...) to stop the iteration. The result is [1, 2], surprisingly.


However, that was changed in Python 3.7. Such foreign StopIteration is now replaced with RuntimeError:

Traceback (most recent call last):
File "test.py", line 10, in one_two_repeat
yield next(i)
StopIteration

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
File "test.py", line 12, in <module>
print(list(one_two_repeat(3)))
RuntimeError: generator raised StopIteration


You can enable the same behavior since python3.5 by from __future__ import generator_stop.
👍4👎1
Оформите карту Visa или Mastercard в банке Казахстана онлайн

Не можете продлить нужный сервис, снять валюту за рубежом или получить международный перевод?

Команда Финакс запустила сервис, в котором граждане РФ могут оформить онлайн карту Visa или Mastercard в банке Казахстана. С помощью этого бота уже более 1000 россиян открыли зарубежные счета.

Для чего она подходит:

- Оплата зарубежных сервисов и покупок

- Хранение валютных сбережений

- Получение оплат из-за рубежа

- Использование в путешествиях

Весь процесс проходит онлайн, от вас потребуется только загранпаспорт.

Оформить заявку и почитать ответы на частые вопросы можно в нашем боте:
👉 https://t.me/Vostokpay_bot
👍2