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

TGINSIGHT SIMILAR POSTS

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

Изворен канал @pythonotes · Post #241 · 5 мај

Можно ли в Python создавать бинарные файлы? Конечно можно. Для этого в Python есть следующие инструменты: ▫️ тип данных bytes и bytearray ▫️ открытие файла в режиме wb (write binary) или rb (read binary) ▫️ модуль struct Про модуль struct поговорим в первую очередь. Файл в формате JSON или Yaml внутри себя содержит разметку данных. Всегда можно определить где список начался а где закончился. Где записана строка а где словарь. То есть формат записи данных содержит в себе элементы разметки данных. В binary-файле данные не имеют визуальной разметки. Это просто байты, записанные один за другим. Правила записи и чтения находятся вне файла. Модуль struct как раз и помогает с организацией данных в таком файле с помощью определения форматов записи для разных частей файла. Модуль struct преобразует Python-объекты в массив байт, готовый к записи в файл и имеющий определённый вид. Для этого всегда следует указывать формат преобразования (или, как оно здесь называется - запаковки). Формат нужен для того, чтобы выделить достаточное количество байт для записи конкретного типа объекта. В последствии с помощью того же формата будет производиться чтение. При этом следует помнить что мы говорим о типах языка С а не Python. Именно формат определяет, что записано в конкретном месте файла, число, строка или что-то еще. Вот какие токены формата у нас есть. Помимо этого, первым символом можно указать порядок байтов. На разных системах одни и те же типы данных могут записываться по-разному, поэтому желательно указать конкретный способ из доступных. Если этого не сделать, то используется символ '@', то есть нативный для текущей системы. В строке формата мы пишем в каком порядке и какие типы собираемся преобразовать в байты. Запакуем в байты простое число, токен "i". >>> import struct >>> struct.pack('=i', 10) b'\n\x00\x00\x00' Теперь несколько float, при этом нужно передавать элементы не массивом а последовательностью аргументов. >>> struct.pack('=fff', 1.0, 2.5, 4.1) b'\x00\x00\x80?\x00\x00 @33\x83@' Вместо нескольких токенов можно просто указать нужное количество элементов перед одним токеном, результат будет тот же. >>> struct.pack('=3f', 1.0, 2.5, 4.1) b'\x00\x00\x80?\x00\x00 @33\x83@' Теперь запакуем разные типы >>> data = struct.pack('=fiQ', 1.0, 4, 100500) я запаковал типы float, int и unsigned long long (очень большой int, на 8 байт) b'\x00\x00\x80?\x04\x00\x00...' Распаковка происходит аналогично, но нужно указать тот же формат, который использовался при запаковке. Результат возвращается всегда в виде кортежа. >>> struct.unpack('=fiQ', data) (1.0, 4, 100500) Как видите, ничего страшного! #lib#basic

Hashtags

Резултати

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

Пребарај: #may2023

当前筛选 #may2023清除筛选
The Open Platform

@topco · Post #62 · 06.06.2023 г., 09:02

DeFi: May headlines - Curve Finance Deploys Decentralized Stablecoin on Ethereum - crvUSD is an over-collateralized stablecoin backed by assets like USDC, Ethereum, liquid staking derivatives like Frax’s sfrxETH, and liquidity provision tokens of stablecoin pools (source) - Cardano DeFi Total Value Locked Hits 400M ADA Milestone - in US Dollar terms, DeFi activities on Cardano had grown consistently since the start of the year when the TVL was just around $50 million (source) - Tenet, LayerZero partner to drive cross-chain liquid staking adoption - Tenet’s network allows users to create projects and tokens which will now be integrated with LayerZero technology. The interoperability opens up users to the broader DeFi ecosystem across a variety of smart contract blockchains (source) - DeFi space braces for possible increase in DAI savings rate from 1% to 3.3% - MakerDAO’s proposal to raise the DSR follows a series of rate hikes imposed by the U.S (source) - Uniswap to Launch on Polkadot via Moonbeam Parachain - the decision follows a near-unanimous governance vote first championed by Blockchain at Berkeley, a student educational group linked to UC Berkeley, and brought back to life by Blockchain at Michigan, another educational organization (source) - DeFi Project Bancor Hit With Lawsuit Over Impermanent Loss Protection Promises - investors claim promises fell short, adding that Bancor’s DAO was centralized and its liquidity pools operated as unregistered securities (source) #DeFi#May2023#trends

The Open Platform

@topco · Post #66 · 12.06.2023 г., 09:02

Metaverse: May headlines - Alibaba Cloud Builds Metaverse Launchpad on Avalanche named Cloudverse, the launchpad is designed to provide an end-to-end platform for companies to customize and maintain their metaverse spaces (source) - Top metaverse property investments suffer massive losses - Report: Popular metaverse properties, such as Otherdeeds, The Sandbox, Decentraland, Somnium and Voxels, have all depreciated in value over the past year (source) - Chinese city releases policy draft for metaverse industry development - the policies include a series of cash benefits to attract metaverse-related companies to set up shop in the city (source) - BuzzAR and Cypher Capital team up for Metaverse project - the partnership will allow the companies to leverage proprietary generative AI technologies on its Metaport (source) #metaverse#trends#May2023

The Open Platform

@topco · Post #64 · 08.06.2023 г., 09:01

Crypto Payment Solutions: May headlines - Ethereum: Payment Giant Visa Deploys First Paymaster Smart Contract on ETH Testnet - on March 1, 2023, ERC-4337 was rolled out to the Ethereum mainnet, adding the ability for smart contracts to transact on behalf of the user (source) - Tether and Strike have partnered to make USDT easily available for transactions via Strike's payment platform, the payment app is in expansion mode and has announced the move of its headquarters out of the United States (source) - Stripe Rolls Out New Fiat-to-Crypto Onramp To Make Digital Asset Purchases More Convenient - Web3 companies can now direct their US-based customers to the link without the need for any access code (source) - Transak Raises $20M - the startup offers on- and off-ramps that could make it easier for new users to interact with Web3 project (source) - Argentina Bans Payment Apps From Offering Bitcoin to Customers - the central bank said Thursday that payment platforms cannot offer crypto trading services to their customers (source) #trends#May2023#paymentsolutions

The Open Platform

@topco · Post #63 · 07.06.2023 г., 09:02

Wallets: May headlines - Ledger Crypto Wallet Under Fire Over Seed Phrase Recovery Service - in a nutshell, it’s an ID-based key recovery service that backs up users’ seed phrases. To use the service, users must provide a passport or national identity card to confirm their identity. While this service requires users to opt-in and pay a $9.99 monthly fee, some are concerned that this could even pose a security risk for those who don't opt in (source). - PayPal Ventures Leads $52M Round for Crypto Firm Magic - the startup offers non-custodial wallet infrastructure for an enterprise client list that includes Macy’s and Mattel (source) - Decentralized Wallet Developer Odsy Network Raises $7.5M at $250M Valuation - the funding round was led by Blockchange Ventures and included participation from Rubik Ventures, Node Capital and FalconX among others (source) - Openfort Raises $3 Million for 'Frictionless' Web3 Gaming Wallet - Openfort is building infrastructure for game developers and aims to reduce the number of times gamers have to engage with the blockchain (source) - Crypto Storage Firm Qredo's Revamped Self-Custody Wallet Goes Live - The New Qredo remains aimed at the institutional crypto market, but now it's low-cost and open to anyone, says COO Josh Goodbody (source) #trends#wallet#May2023