TGTGInsighttelegram intelligenceLIVE / telegram public index
← Python Заметки

TGINSIGHT SIMILAR POSTS

Најди сличен содржај

Изворен канал @pythonotes · Post #121 · 20 јул.

Регулярно требуется преобразовать какой-либо текст в максимально совместимый текст для URL, имени файла, имени объекта в каком-то софте и тд. Требования совместимости простые: в тексте должны быть только допустимые символы. Обычно это a-z, 0-9 и "_" или "-". То есть, только прописные буквы латинского алфавита и цифры (как пример). Допустим, нам нужно название статьи в блоге преобразовать в slug для добавления его в URL этой статьи. Как это лучше всего сделать? В Django по умолчанию есть готовая функция slugify для таких случаев. Но я её никогда не использую. Почему? Потому что её недостаточно! Приведём пример >>> from django.utils.text import slugify >>> slugify('This is a Title') 'this-is-a-title' Пока всё отлично >>> slugify('This is a "Title!"') 'this-is-a-title' Спец символы удалились, всё хорошо. >>> slugify('Это заголовок статьи') '' Вот и приехали 😢. Если текст не английский то буквы просто игнорируются. Можно это поправить >>> slugify('Это заголовок статьи', allow_unicode=True) 'это-заголовок-статьи' Но тогда мы не вписываемся в условие. У нас появилась кириллица в тексте. Так как я часто пишу сайты для русскоязычных пользователей эта проблема весьма актуальна. Я не использую стандартную функцию и всегда пишу свою. Оригинал я не беру в расчёт и пишу полностью свою функцию. И так, по порядку: 🔸1. Исходный текст: >>> text = 'Мой заголовок №10 😁!' Взял специально посложней со специальными символами. 🔸2. Транслит Необходимо сделать транслит всех символов в латиницу. Здесь очень выручает библиотека unidecode. Помимо простого транслита кириллицы в латиницу она умеет преобразовывать спец символы и иероглифы в текстовые аналоги. from unidecode import unidecode >>> unidecode("Ñ Σ ® µ ¶ ¼ 月 山") 'N S (r) u P 1/4 Yue Shan' Очень крутая библиотека, советую👍 В нашем случае получаем такое преобразование: >>> text = unidecode(text) >>> print(text) 'Moi zagolovok No. 10 !' Отличный транслит. Смайл просто удалился, хотя я ждал что-то вроде :). Ну и ладно, всë равно невалидные символы. А еще наш код уже поддерживает любой язык, будь то хинди или корейский. 🔸4. Фильтр символов Unidecode не занимается фильтрацией по недопустимым символам. Это мы делаем в следующем шаге через regex. Просто заменим все символы на "_" если они вне указанного диапазона. >>> text = re.sub(r'[^a-zA-Z0-9]+', '_', text) >>> print(text) 'Moi_zagolovok_No_10_' Символ "+" в паттерне выручает когда несколько недопустимых символов идут рядом. Все они заменяются на один символ "_". 🔸5. Slugify Осталось удалить лишние символы по краям и сделать нижний регистр >>> text = text.strip('_').lower() >>> print(text) 'moi_zagolovok_no_10' Получаем отличный slug! 😎 🌎 Полный код в виде функции. ______________ PS. Проверку что в строке остался хоть один допустимый символ я бы вынес в отдельную функцию. #libs#tricks#django

Резултати

Пронајдени 4 слични објави

Пребарај: #example

当前筛选 #example清除筛选
TonOrbital

@tonorbital · Post #917 · 06.11.2024 г., 09:39

💥#Example of Full Liquidation on Aqua Protocol Triggering Liquidation: When the overall liquidation mode is activated. Initial Setup: • TON Value: 1 TON = $2.14 • Alice's Deposit: 1,000 TON, valued at about $2,140 • Minted AquaUSD: Alice mints 1,050 AquaUSD • Initial Collateral Ratio (CR): ~203.81% (calculated as ($2,140 / $1,050) * 100%) 🔻Price Drop: • New TON Price: Falls to $1.30 • Time Open: Position has been open for one year • Accrued Borrowing Rate: 0.5% per year • Borrowing Fee: Alice owes 5.25 AquaUSD for borrowing Updated Values: • Updated Collateral Value: 1,000 TON is now worth $1,300 (1,000 * $1.30) • Updated CR: ~123% (calculated as ($1,300 / (1,050 AquaUSD + 5.25 AquaUSD)) * 100%) ⚖️Liquidation Calculation: • Since CR < 125%, Alice’s position is eligible for full liquidation, allowing 1,050 AquaUSD to be liquidated. 🔄Liquidation Process: • Bob's Action: Bob fully liquidates Alice’s position by repaying 1,050 AquaUSD. • Borrowing Fees: 0.5% of 1,050 AquaUSD equals 4 TON ($5.25), paid to the Aqua Protocol treasury. • Repayment Fee: Since the amount is over $1,000, a 0.5% fee applies, which is another 4 TON ($5.25), also paid to the treasury. • Keeper Fee: Cathy, the Keeper, earns a 3% fee, totaling 24 TON ($31.50). • Liquidator Fee: Bob receives the remaining collateral, totaling 968 TON (1,000 - 4 - 4 - 24), worth $1,258—a profit of 19.8%. 📊Post-Liquidation Status: • Alice's Remaining Debt: Fully cleared to 0 AquaUSD • Remaining Collateral: Fully liquidated to 0 TON As a result, Bob earns a 19.8% premium for successfully executing the liquidation, with 3% of the reward going to the Keeper. By participating in Aqua Protocol as a liquidator, redemption provider, or Keeper, you can help maintain the stability of AquaUSD and protect the system. Always remember the importance of a healthy collateral ratio to reduce the risk of liquidation and maximize rewards within the protocol!

Hashtags

TonOrbital

@tonorbital · Post #916 · 06.11.2024 г., 09:34

💡#Example of Partial Liquidation on Aqua Protocol Initial Setup: • Value of TON: 1 TON = $2.14 • Alice's Deposit: 1,000 TON, worth about $2,140 • Minted AquaUSD: Alice mints 1,050 AquaUSD • Initial Collateral Ratio (CR): ~203.81% (calculated as ($2,140 / $1,050) * 100%) 🔻Price Drop: • New TON Price: The price drops to $1.47 • Time Open: The position has been open for one year • Accrued Borrowing Rate: 0.5% per year • Borrowing Fee: Alice owes 5.25 AquaUSD for borrowing Updated Values: • New Collateral Value: 1,000 TON is now worth $1,470 (1,000 * $1.47) • Updated CR: ~139% (calculated as ($1,470 / (1,050 AquaUSD + 5.25 AquaUSD)) * 100%) ⚖️Liquidation Calculation: • Maximum Liquidation Amount: The system allows up to $645 of Alice’s AquaUSD to be liquidated to maintain a safe collateral ratio. 🔄Liquidation Process: • Bob's Action: Bob repays 645 AquaUSD to partially liquidate Alice’s position. • Collateral Received by Bob: He gets $703 back, equivalent to about 478 TON (645 AquaUSD * 1.09). • Keeper’s Reward (Cathy): Cathy earns $19.35 for assisting with the liquidation (3% of 645 AquaUSD). 📊Post-Liquidation Status: • Alice's Remaining Debt: After the liquidation, Alice owes 405 AquaUSD (1,050 - 645). • Repayment Fee: Alice pays a 0.5% fee on the 645 AquaUSD, totaling 3.26 AquaUSD. • Total Fees Charged: Including borrowing fees, Alice pays back a total of approximately 5.8 TON. • Remaining Collateral: Alice has 503.2 TON left after the liquidation (1,000 - 5.8 - 478 - 13 TON). • Updated CR: Her new collateral ratio is about 183% (calculated as ($740 / 405 AquaUSD) * 100%). This example illustrates the Aqua Protocol’s partial liquidation process, helping maintain a safe collateral ratio during market fluctuations. Keeping a healthy CR minimizes liquidation risks and maximizes your collateral protection.

Hashtags

BotsGram®

@botsgram_cu · Post #3299 · 16.12.2020 г., 23:58

@pic Qué puede hacer este bot? Este bot puede ayudarle a encontrar y compartir imágenes. Funciona automáticamente, sin necesidad de agregarlo en cualquier lugar. Simplemente abra cualquiera de sus chats y escriba @pic something en el campo de mensaje. A continuación, pulse sobre un resultado para enviar. Idioma: Inglés (visto en @BotsGram_cu) #share, #result, #example, #funny, #message, #pic, #images