Python/ django
58.9K subscribers
2.07K photos
61 videos
47 files
2.79K links
по всем вопросам @haarrp

@itchannels_telegram - 🔥 все ит-каналы

@ai_machinelearning_big_data -ML

@ArtificialIntelligencedl -AI

@datascienceiot - 📚

@pythonlbooks

РКН: clck.ru/3FmxmM
加入频道
🎮 Code For Games in Python: Free Python Games Source Code

20 игр на Python с полным кодом.

1. Mario Game

Делаем Марио. Создаем днопользовательскую игру, где игрок (Марио) должен уворачиваться от огненных шаров, вылетающих из дракона.

2. Dino Game
Это клон-адаптация игры с динозавриком на google chrome под названием "T-Rex Dino Run".

3. Simple Fighting Game

Простй файтинг.
Игра ведется в простом интерфейсе, в котором используются только кнопки и текст.

4. Jumbled Word Quiz Game
Игра квиз.
Человек может начать викторину, нажав на кнопку "Старт". Также можно выбрать тип слов, которые необходимо исправить в викторине.


5. Rock-Paper-Scissor Game
Игра "Камень, бумага, ножницы" на Python разработана с использованием Tkinter и графического интерфейса пользователя (GUI).

6. Bouncing Ball Game
Эта игра "Прыгающий мяч" использует Canvas для прорисовки объектов.

7. Hangman Game
Игра "Виселица" не требует никаких специальных модулей, кроме random и time.

8. Snake Game
Игра "Змейка" - это классическая аркадная игра.

9. Aircraft War Game
Военная игра "Самолеты" на Python на pygame

10. Tank Game
Это игра между компьютером и пользователем. Простая танковая игра Python.

11. Stickman
Игра с хорощей графикой и удобным управлением.

12. Tetris
Создаем свой тетрис на питоне.

13. Snakes and Ladders

Игра змейки и лестницы.

14. Speed Typing Test
Делаем свой тест на скорость печати.

15. Puzzle Game
Пазл с доской 4*4 и с 15 номерами.

16. Guess the Word Game
Игра угадай слово.

17. Tic Tac Toe Game
Все правила игры такие же, как и в игре в крестики-нолики в реальном времени.

18. F1 Race Road Game
Простые гоники.

19. Flappy Bird
Делаем легендарную флаппи берд.

20. Quiz Application
Квиз на Python.

@pythonl
🔥 5 примеров использования Redis с кодом на Python

1. Caching
Redis можно использовать для кэширования часто используемых данных, снижая нагрузку на ваше основное хранилище данных. Вот пример того, как реализовать кэширование с помощью Redis в Python

import redis

# Connect to Redis
r = redis.Redis(host='localhost', port=6379, db=0)

def get_data_from_cache(key):
# Check if data exists in the cache
if r.exists(key):
# Retrieve data from the cache
data = r.get(key)
return data.decode('utf-8') # Convert bytes to string
else:
# Fetch data from the primary data source
data = fetch_data_from_source()

# Store data in the cache with a timeout of 1 hour
r.setex(key, 3600, data)
return data


2. Pub/Sub (Publish/Subscribe):
Redis поддерживает паттерн pub/sub, позволяя вам создавать системы обмена сообщениями. Вот пример:

import redis
import time

# Connect to Redis
r = redis.Redis(host='localhost', port=6379, db=0)

def publish_message(channel, message):
# Publish a message to the specified channel
r.publish(channel, message)

def subscribe_channel(channel):
# Subscribe to a channel and process incoming messages
pubsub = r.pubsub()
pubsub.subscribe(channel)

for message in pubsub.listen():
print(message['data'].decode('utf-8')) # Process the received message


3. Rate Limiting:
Redis можно использовать для реализации ограничения скорости, чтобы контролировать количество запросов или операций за период времени. Пример:

import redis

# Connect to Redis
r = redis.Redis(host='localhost', port=6379, db=0)

def check_rate_limit(ip_address):
# Increment the request count for the IP address
request_count = r.incr(ip_address)

# If the count exceeds the limit (e.g., 100 requests per minute), deny the request
if request_count > 100:
return False

return True


4. Session Storage:
Redis можно использовать для хранения данных сеанса в веб-приложениях. Пример:

import redis
import uuid

# Connect to Redis
r = redis.Redis(host='localhost', port=6379, db=0)

def create_session(user_id):
# Generate a unique session ID
session_id = str(uuid.uuid4())

# Store the session data in Redis with a timeout of 30 minutes
r.setex(session_id, 1800, user_id)

return session_id

def get_user_id_from_session(session_id):
# Retrieve the user ID from the session data in Redis
user_id = r.get(session_id)

if user_id is not None:
return user_id.decode('utf-8') # Convert bytes to string
else:
return None


5. Leaderboard:
Redis можно использовать для создания таблиц лидеров или рейтингов на основе набранных баллов. Пример:

import redis

# Connect to Redis
r = redis.Redis(host='localhost', port=6379, db=0)

def update_score(player_id, score):
# Update the score of a player
r.zadd('leaderboard', {player_id: score})

def get_leaderboard():
# Get the top 10 players from the leaderboard
leaderboard = r.zrevrange('leaderboard', 0, 9, withscores=True)

for player, score in leaderboard:
print(f"Player: {player.decode('utf-8')}, Score: {score}")


Это лишь несколько примеров того, как Redis можно использовать в Python. Redis предоставляет множество других мощных функций и структур данных, которые можно использовать в различных приложениях.

Github

@data_analysis_ml
Top 10 Python Functions

Топ-10 полезных функций Python, о которых вы возможно не знаете.

1. The Elusive enumerate() 🗂

or index, value in enumerate(["apple", "banana", "cherry"], start=1):
print(f"The index is {index} and the value is {value}")


2. zip() Up Your Lists 🤐

names = ["Batman", "Superman", "Wonder Woman"]
superpowers = ["Rich", "Strong", "Lasso of Truth"]

for hero, power in zip(names, superpowers):
print(f"{hero} is really just super {power}!")


3. collections.Counter() — The Crowd Tamer 📊

from collections import Counter
party_list = ["Alice", "Bob", "Alice", "Eve", "Bob", "Eve", "Alice"]
print(Counter(party_list))
# Output: Counter({'Alice': 3, 'Bob': 2, 'Eve': 2})


4. functools.lru_cache() — The Time Traveler

from functools import lru_cache

@lru_cache
def fib(n):
if n < 2:
return n
return fib(n-1) + fib(n-2)


5. All Aboard the any() and all() Express 🚂

friends_going = [False, False, True, False]
print(any(friends_going)) # Output: True

chores_done = [True, True, True, True]
print(all(chores_done)) # Output: True


6. Get Slick with itertools.chain() 🚲

from itertools import chain

list1 = [1, 2, 3]
list2 = ['a', 'b', 'c']
combined = list(chain(list1, list2))
print(combined) # Output: [1, 2, 3, 'a', 'b', 'c']


7. The Great defaultdict() Magician 🎩

from collections import defaultdict

d = defaultdict(int)
print(d["new_key"]) # Output: 0, and "new_key" is now a key in the dict


8. Jazz Up with reversed() 🔄

original_list = [1, 2, 3, 4, 5]
for item in reversed(original_list):
print(item, end=' ') # Output: 5 4 3 2 1


9. Don’t Get Lost, Use pathlib.Path() 🗺

from pathlib import Path

# Navigate to your home directory and create a file there.
home = Path.home()
file = home / "treasure_map.txt"
file.touch()
print(f"Your treasure map is located at: {file}")


10. The Underestimated else in Loops 🎢

for i in range(5):
if i == 10:
break
else:
print("Loop completed without a 'break'. Batman approves.")


Disclaimers 📢:

📌Будьте осторожны при использовании таких функций, как itertools.chain() и collections.Counter() на больших наборах данных. Они могут потреблять больше памяти, чем слон на шведском столе. 🐘

📌Не злоупотребляйте функцией functools.lru_cache(). Это как машина времени - слишком много возиться с ней может привести к нежелательным последствиям.

📌Хотя defaultdict() - волшебная функция, убедитесь, что вы действительно хотите добавить новый ключ в свой dict, иначе словарь может бесконтрольно расти,

@pythonl
📩 Python Email Automation Script

Вот пример базового скрипат Python для автоматизации простой задачи отправки электронной почты.


import smtplib
from email.mime.text import MIMEText


sender_email = "[email protected]"
recipient_email = "[email protected]"

subject = "Automated Email"
message = "This is an automated email sent using Python."


# SMTP server configuration (example: Gmail)


smtp_server = "smtp.gmail.com"
smtp_port = 587
smtp_username = "your_username"
smtp_password = "your_password"



msg = MIMEText(message)
msg["Subject"] = subject
msg["From"] = sender_email
msg["To"] = recipient_email
try:

server = smtplib.SMTP(smtp_server, smtp_port)
server.starttls()
server.login(smtp_username, smtp_password)
server.sendmail(sender_email, recipient_email, msg.as_string())
print("Email sent successfully!")

except Exception as e:
print("Error sending email:", str(e))

finally:

server.quit()

@pythonl
💲 Awesome OSS Monetization

A curated list of awesome monetization approaches for open source software.

Кураторский список практичных подходов к монетизации программного обеспечения с открытым исходным кодом.

Этот список является результатом обширного интернет-исследования. Он разбит на категориям от платных консультациях, где вы можете заработать, до различных проектов, где вы можете заработать на поиске багов в коде.


🖥 Github

@pythonl
Please open Telegram to view this post
VIEW IN TELEGRAM
Stock Recommendations from Yahoo Finance Using ML Models in Python.

Строим модель рекомендации по акциям от Yahoo Finance с использованием ML-моделей на Python.

import yfinance as yf
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestClassifier
import matplotlib.pyplot as plt

symbol = 'AAPL'
stock_data = yf.download(symbol, start='2022-01-05', end='2023-01-06')

df = pd.DataFrame(stock_data)

df['DailyReturn'] = df['Close'].pct_change()
df['Target'] = df['DailyReturn'].apply(lambda x: 1 if x > 0 else 0)

df = df.dropna()

X = df[['Open', 'High', 'Low', 'Close', 'Volume']]
y = df['Target']

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)

model = RandomForestClassifier(n_estimators=100, random_state=42)
model.fit(X_train, y_train)

y_pred = model.predict(X_test)

predictions_df = pd.DataFrame({'Actual': y_test, 'Predicted': y_pred})

plt.figure(figsize=(10, 6))
plt.plot(predictions_df.index, predictions_df['Actual'], label='Actual')
plt.plot(predictions_df.index, predictions_df['Predicted'], label='Predicted')
plt.xlabel('Date')
plt.ylabel('Target')
plt.title('Actual vs. Predicted Stock Recommendations')
plt.legend()
plt.show()


@pythonl
☎️ How to Schedule WhatsApp Messages Using Python and PyWhatKit

В посте мы рассмотрим, как использовать PyWhatKit для создания отложенных сообщений WhatsApp с помощью Python. 🐍

pip install pywhatkit

import pywhatkit

phone_num = '+123456789'
message = 'hello'
hour = 17
minute = 25

try:
pywhatkit.sendwhatmsg(phone_num, message, hour, minute)
print(f'Message sent to {phone_num} successfully!')
except Exception as e:
print(f'Error: {str(e)}')


Github
Docs

@pythonl
Please open Telegram to view this post
VIEW IN TELEGRAM
🖥 Unraveling the Magic of Sorting: A Python Guide for Novices

Введение в алгоритмы: Примеры алгоритмов на Python для новичков.

Bubble Sort

def bubble_sort(list):
for i in range(len(list)):
for j in range(len(list) - 1):
if list[j] > list[j + 1]:
list[j], list[j + 1] = list[j + 1], list[j] # swap
return list


Selection Sort

def selection_sort(list):
for i in range(len(list)):
min_index = i
for j in range(i + 1, len(list)):
if list[min_index] > list[j]:
min_index = j
list[i], list[min_index] = list[min_index], list[i] # swap
return list


Insertion Sort

def insertion_sort(list):
for i in range(1, len(list)):
key = list[i]
j = i - 1
while j >=0 and key < list[j] :
list[j+1] = list[j]
j -= 1
list[j+1] = key
return list

Quick Sort

def partition(array, low, high):
i = (low-1)
pivot = array[high]

for j in range(low, high):
if array[j] <= pivot:
i = i+1
array[i], array[j] = array[j], array[i]
array[i+1], array[high] = array[high], array[i+1]
return (i+1)

def quick_sort(array, low, high):
if len(array) == 1:
return array
if low < high:
partition_index = partition(array, low, high)
quick_sort(array, low, partition_index-1)
quick_sort(array, partition_index+1, high)

@pythonl
Please open Telegram to view this post
VIEW IN TELEGRAM
8 крутых способов свести функции Python в одну строку

Видео

@pythonl
YAPF

A formatter for Python files.

YAPF - это форматировщик Python, основанный на clang-format. По сути, алгоритм анализирует код и вычисляет наилучшее форматирование, соответствующее заданному стилю. Это избавляет от хлопот, связанных с поддержкой кода.

$ pip install yapf

Example:

x = { 'a':37,'b':42,

'c':927}

y = 'hello ''world'
z = 'hello '+'world'
a = 'hello {}'.format('world')
class foo ( object ):
def f (self ):
return 37*-+2
def g(self, x,y=42):
return y
def f ( a ) :
return 37+-+a[42-x : y**3]


reformat:

x = {'a': 37, 'b': 42, 'c': 927}

y = 'hello ' 'world'
z = 'hello ' + 'world'
a = 'hello {}'.format('world')


class foo(object):
def f(self):
return 37 * -+2

def g(self, x, y=42):
return y


def f(a):
return 37 + -+a[42 - x:y**3]


🖥 Github

@pythonl
Please open Telegram to view this post
VIEW IN TELEGRAM
🔥 Подборка каналов для Python разработчиков

🖥 Machine learning

ai_ml – крупнейши канал по ии, нейросетям и науке о данных.
datasc - дата сайнс обучение самой востребованной профессии.
@bigdatai - Big Data

@machinelearning_ru – гайды по машинному обучению
@machinelearning_interview – подготовка к собеседованию мл.
@datascienceiot – бесплатные книги ds
@ArtificialIntelligencedl – ИИ

@machinee_learning – чат о машинном обучении
@datascienceml_jobs - вакансии ds, ml
@Machinelearning_Jobs - чат с вакансиями

🖥 Python

@pythonl - главный канал самого популярного языка программирования.
@pro_python_code – учим python с ментором.
@python_job_interview – подготовка к Python собеседованию.
@python_testit - проверочные тесты на python
@pythonlbooks - современные книги Python
@python_djangojobs - работа для Python программистов
@python_django_work - чат обсуждения вакансий

#️⃣ c# c++
C# - погружение в C#
@csharp_cplus чат
@csharp_1001_notes - инструменты C#

🖥 Machine learning

ai_ml – крупнейши канал по ии, нейросетям и науке о данных.
datasc - дата сайнс обучение самой востребованной профессии.
@bigdatai - Big Data

@machinelearning_ru – гайды по машинному обучению
@machinelearning_interview – подготовка к собеседованию мл.
@datascienceiot – бесплатные книги ds
@ArtificialIntelligencedl – ИИ

@machinee_learning – чат о машинном обучении
@datascienceml_jobs - вакансии ds, ml
@Machinelearning_Jobs - чат с вакансиями

🖥 SQL базы данных

@sqlhub - Повышение эффективности кода с грамотным использованием бд.
@chat_sql - чат изучения бд.

👣 Golang
@Golang_google - восхитительный язык от Google, мощный и перспективный.
@golang_interview - вопросы и ответы с собеседований по Go. Для всех уровней разработчиков.
@golangtests - интересные тесты и задачи GO
@golangl - чат изучающих Go
@GolangJobsit - отборные вакансии и работа GO
@golang_jobsgo - чат для ищущих работу.
@golang_books - полезные книги Golang
@golang_speak - обсуждение языка Go
@golangnewss - новости go

🖥 Linux
linux - kali linux ос для хакинга
linux chat - чат linux для обучения и помощи.
@linux_read - бесплатные книги linux

🖥 Javascript / front

@react_tg - - 40,14% разработчиков сайтов использовали React в 2022 году - это самая популярная библиотека для создания сайтов.
@javascript -канал для JS и FrontEnd разработчиков. Лучшие практики и примеры кода. Туториалы и фишки JS
@Js Tests - каверзные тесты JS
@hashdev - погружение в web разработку.
@javascriptjobjs - отборные вакансии и работа FrontEnd.
@jsspeak - чат поиска FrontEnd работы.

🖥 Java
@javatg - выучить Java с senior разработчиком на практике
@javachats - чат для ответов на вопросы по Java
@java_library - библиотека книг Java
@android_its - Android разработка
@java_quizes - тесты Java
@Java_workit - работа Java
@progersit - шпаргалки ит

👷‍♂️ IT работа

https://yangx.top/addlist/_zyy_jQ_QUsyM2Vi -ит каналы по яп с вакансиями

🤡It memes
@memes_prog - ит-мемы

⚙️ Rust
@rust_code - Rust избавлен от болевых точек, которые есть во многих современных яп
@rust_chats - чат rust

📓 Книги

https://yangx.top/addlist/HwywK4fErd8wYzQy - актуальные книги по всем яп

⭐️ Нейронные сети
@vistehno - chatgpt ведет блог, решает любые задачи и отвечает на любые ваши вопросы.
@aigen - сети для генерации картинок. видео, музыки и многого другого.
@neural – погружение в нейросети.

📢 English for coders

@english_forprogrammers - Английский для программистов

🖥 Devops
Devops - канал для DevOps специалистов.
Please open Telegram to view this post
VIEW IN TELEGRAM
👩‍❤‍👨Creating a Tinder bot in Python

Создание бота для Tinder на Python

💻Для этого проекта нужно скачать и установить Chromedriver.

from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.chrome.options import Options
import time


opening_line = "Hi!"
number_of_swipes = 10

path = # paste your chromedriver path here
service = Service(executable_path=path)
web = 'https://tinder.com/'

options = Options()
options.add_experimental_option("debuggerAddress", "localhost:9222")
driver = webdriver.Chrome(service=service, options=options)

driver.get(web)
time.sleep(3)

for i in range(number_of_swipes):
try:
like_button = driver.find_element(by='xpath', value='//button//span[text()="Like"]')
driver.execute_script("arguments[0].click();", like_button)
time.sleep(2)

its_match_window = driver.find_element(by='xpath', value='//textarea[@placeholder="Say something nice!"]')
its_match_window.send_keys(opening_line)
time.sleep(1)

send_message_button = driver.find_element(by='xpath', value='//button/span[text()="Send"]')
send_message_button.click()
time.sleep(1)

close_its_match_window = driver.find_element(by='xpath', value='//button[@title="Back to Tinder"]')
close_its_match_window.click()

except:
try:
box = driver.find_element(by='xpath', value='//button/span[text()="Maybe Later"] | //button/span[text()="Not interested"] | //button/span[text()="No Thanks"]')
box.click()
except:
pass

Video

@pythonl
Python itertools.compress. Удобный способ фильтрации данных

Видео

@pythonl
🖥 Creating own RANDOM number generator

Создание собственного генератора RANDOM.

import datetime
import pytz # Required library for time zone support

def randomnum(time_zone):
# Getting the current time in the specified time zone
time_now = datetime.datetime.now(pytz.timezone(time_zone))

# Getting time in terms of microseconds
random_seed = time_now.microsecond

# An equation which returns a number between 0 and 10
seed = random_seed * 8 % 11

# Making random number somewhat unpredictable
random_micro_secs = []
for i in range(seed):
random_micro_secs.append(time_now.second**seed)

seed_2 = sum(random_micro_secs)

# Generating the final random number
truly_random_num = (seed_2 * 8 % 11)

return truly_random_num

# Example usage
time_zone = 'America/New_York' # Specify the desired time zone
random_number = randomnum(time_zone)
print(random_number)


@pythonl
Please open Telegram to view this post
VIEW IN TELEGRAM
Math for Devs - Cosine Similarity in Python

Математика для разработчиков - Косинусное сходство на Python

Функция Python cosine_similarity(vector1: list[float], vector2: list[float]) -> float: принимает на вход два вектора и вычисляет их косинусное сходство.

from math import sqrt, pow

def cosine_similarity(vector1: list[float], vector2: list[float]) -> float:
"""Returns the cosine of the angle between two vectors."""
# the cosine similarity between two vectors is the dot product of the two vectors divided by the magnitude of each vector

dot_product = 0
magnitude_vector1 = 0
magnitude_vector2 = 0

vector1_length = len(vector1)
vector2_length = len(vector2)

if vector1_length > vector2_length:
# fill vector2 with 0s until it is the same length as vector1 (required for dot product)
vector2 = vector2 + [0] * (vector1_length - vector2_length)
elif vector2_length > vector1_length:
# fill vector1 with 0s until it is the same length as vector2 (required for dot product)
vector1 = vector1 + [0] * (vector2_length - vector1_length)

# dot product calculation
for i in range(len(vector1)):
dot_product += vector1[i] * vector2[i]

# vector1 magnitude calculation
for i in range(len(vector1)):
magnitude_vector1 += pow(vector1[i], 2)

# vector2 magnitude calculation
for i in range(len(vector2)):
magnitude_vector2 += pow(vector2[i], 2)

# final magnitude calculation
magnitude = sqrt(magnitude_vector1) * sqrt(magnitude_vector2)

# return cosine similarity
return dot_product / magnitude



vector1 = [1, 2, 3]
vector2 = [2, 3, 4]
similarity = cosine_similarity(vector1, vector2)

print("The cosine similarity between vector1 and vector2 is: ", similarity
)

@pythonl
How to Create Fake Access Points using Scapy in Python

Как создать поддельные точки доступа с помощью Scapy в Python

$ pip3 install faker scapy

from scapy.all import *
from threading import Thread
from faker import Faker

def send_beacon(ssid, mac, infinite=True):
dot11 = Dot11(type=0, subtype=8, addr1="ff:ff:ff:ff:ff:ff", addr2=mac, addr3=mac)
# ESS+privacy to appear as secured on some devices
beacon = Dot11Beacon(cap="ESS+privacy")
essid = Dot11Elt(ID="SSID", info=ssid, len=len(ssid))
frame = RadioTap()/dot11/beacon/essid
sendp(frame, inter=0.1, loop=1, iface=iface, verbose=0)

if __name__ == "__main__":
# number of access points
n_ap = 5
iface = "wlan0mon"
# generate random SSIDs and MACs
faker = Faker()
ssids_macs = [ (faker.name(), faker.mac_address()) for i in range(n_ap) ]
for ssid, mac in ssids_macs:
Thread(target=send_beacon, args=(ssid, mac)).start()

Мы генерируем случайный MAC-адрес, задаем имя точки доступа, которую хотим создать, а затем создаем фрейм 802.11.

@pythonl
🖥 Blank Grabber

The most powerful stealer written in Python 3 and packed with a lot of features.

Disclaimer: This program is provided for educational and research purposes only.

Мощный Grabber, написанный на Python 3 и оснащенный множеством функций.

Github

@pythonl
Please open Telegram to view this post
VIEW IN TELEGRAM
🖥 PgAdmin 4

pgAdmin 4 is a rewrite of the popular pgAdmin3 management tool for the PostgreSQL (http://www.postgresql.org) database.

Cамая популярная и многофункциональная платформа администрирования и разработки с открытым исходным кодом для PostgreSQL.

🖥 Github

@pythonl
Please open Telegram to view this post
VIEW IN TELEGRAM
🖥 Singletons in Python

Реализация шаблона Singleton в Python. Шаблон Singleton (Одиночка) один из самых часто используемых шаблонов. Его можно встретить во множестве проектов и он относительно прост для обучения. Его обязательно нужно знать и уметь его использовать.

Modify the new class method
Using the Metaclass approach
Using the decorator approach

@pythonl
Please open Telegram to view this post
VIEW IN TELEGRAM
Please open Telegram to view this post
VIEW IN TELEGRAM