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

Резултати

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

Пребарај: #rust

当前筛选 #rust清除筛选
GitHub Trends

@githubtrending · Post #15562 · 15.03.2026 г., 11:30

#rust Vite+ is a single tool that handles all web development needs: install packages, run fast dev servers, check/lint/format code, test, build apps or libraries, and manage monorepo tasks with smart caching. Install globally as `vp`, use commands like `vp dev`, `vp test`, or `vp build`, and configure everything in one `vite.config.ts` file. It speeds up workflows 2-100x using Rust tools, cuts setup time, and ensures consistency—saving you hours on config, debugging, and CI costs so you focus on coding. https://github.com/voidzero-dev/vite-plus

Hashtags

GitHub Trends

@githubtrending · Post #15480 · 08.02.2026 г., 15:00

#rust Monty is a minimal, secure Python interpreter in Rust that safely runs AI-generated code in your agents. It starts in under 1 microsecond, blocks host access to files, network, and env vars (only via your controlled functions), and supports type checking, resource limits, and snapshotting to pause/resume execution. This lets you skip slow, complex containers, making AI agents run faster, cheaper, and more reliably without security risks. https://github.com/pydantic/monty

Hashtags

GitHub Trends

@githubtrending · Post #15475 · 07.02.2026 г., 12:00

#rust LiteBox is a new open-source Rust library OS from Microsoft that sandboxes apps with a tiny host interface to slash attack risks and boost security. It runs Linux programs on Windows without changes, sandboxes Linux apps better than containers, supports secure tech like SEV-SNP and OP-TEE, and works in kernel or non-kernel setups under MIT license. You gain safer app isolation, easier cross-platform runs, and smaller vulnerability blasts for secure coding, CI jobs, or cloud tasks—while it's evolving, so adapt as it improves. https://github.com/microsoft/litebox

Hashtags

GitHub Trends

@githubtrending · Post #15357 · 23.12.2025 г., 12:30

#rust Miri is a tool that detects bugs in unsafe Rust code by finding undefined behavior—situations where your program violates safety rules and can behave unpredictably. When you write unsafe code, you bypass Rust's normal safety checks, so you must manually ensure your code follows strict requirements like proper memory alignment, no data races, and correct pointer usage. Miri catches violations of these requirements by running your code in a special interpreter that monitors every operation. It detects problems like out-of-bounds memory access, use-after-free errors, uninitialized data, and misaligned pointers. You can easily use Miri by installing it with Rust's nightly toolchain and running `cargo miri test` on your project. The benefit is that Miri finds subtle bugs that would otherwise cause crashes or security vulnerabilities in production, making it an essential tool for anyone writing unsafe Rust code. https://github.com/rust-lang/miri

Hashtags

GitHub Trends

@githubtrending · Post #15337 · 16.12.2025 г., 14:30

#rust Hashcards is a simple tool for making and reviewing flashcards in plain text Markdown files you edit easily, like with any text editor or Git for tracking changes. Cards use hashes, so editing resets progress; write Q/A or cloze types (C Frictionless creation helps you learn faster without complex apps. https://github.com/eudoxia0/hashcards

Hashtags

GitHub Trends

@githubtrending · Post #15327 · 11.12.2025 г., 12:00

#rust Tempo is a fast, low-cost blockchain built specifically for stablecoin payments, designed to handle many transactions quickly with sub-second finality. It offers predictable, very low fees paid directly in stablecoins like USDC or USDT, making it ideal for businesses, banks, and fintechs to process payments efficiently. Tempo supports batch and scheduled payments, modern authentication, and built-in compliance, helping users automate payroll, settlements, and cross-border transfers with ease. It is fully compatible with Ethereum tools, so developers can build on it without learning new systems. This means you get a reliable, scalable, and user-friendly payment network optimized for real-world financial use. https://github.com/tempoxyz/tempo

Hashtags

GitHub Trends

@githubtrending · Post #15309 · 05.12.2025 г., 12:00

#rust Fresh is a fast, user-friendly terminal text editor built in Rust that opens huge files instantly without slowing down. It features an intuitive menu system, mouse support, and a command palette for easy navigation, making it perfect if you're switching from graphical editors. You can extend Fresh with TypeScript plugins in a secure environment, and it includes powerful tools like multi-cursor editing, split panes, language server support, and git integration. The main benefit is that Fresh combines the speed and lightweight nature of terminal editors with the ease of use and modern features you'd expect from a graphical editor, all while handling massive files efficiently. https://github.com/sinelaw/fresh

Hashtags

GitHub Trends

@githubtrending · Post #15297 · 12.11.2025 г., 14:00

#rust Vello is a fast 2D graphics renderer written in Rust that uses your GPU's compute power to draw shapes, images, text, and gradients[1]. Unlike older renderers that rely on your CPU for sorting and clipping, Vello moves most work to the GPU using special algorithms, giving you much better performance with less computer power needed[1][2]. It can draw large scenes smoothly and interactively, making it perfect for user interfaces, games, and animation tools[1]. You benefit from faster, smoother graphics with lower energy use, and it works across different platforms including web and Android. https://github.com/linebender/vello

Hashtags

GitHub Trends

@githubtrending · Post #15177 · 27.09.2025 г., 14:30

#rust NVIDIA Dynamo is an open-source, high-speed, low-delay framework that helps run large AI models, like language models, efficiently across many GPUs and servers. It solves problems like slow response and memory limits by smartly splitting tasks, routing requests to avoid repeated work, and managing memory better. It supports multiple AI engines and uses fast data transfer methods to speed up inference. You can easily set it up on your system, run AI models with it, and scale across many machines. This means you get faster, more efficient AI model serving, saving time and computing resources. https://github.com/ai-dynamo/dynamo

Hashtags

GitHub Trends

@githubtrending · Post #15149 · 17.09.2025 г., 12:00

#rust MonadBFT is a fast and secure blockchain consensus protocol that helps many independent nodes agree on the order of transactions quickly and reliably. It separates the process of agreeing on transaction order (consensus) from actually executing those transactions, which speeds up the system and allows for high throughput with 1-second finality. This design prevents problems like chain reorganizations (tail-forks) and censorship by any single validator, making the blockchain fairer, more stable, and efficient. For users, this means faster transaction confirmations, fewer unexpected changes, and a more trustworthy network without sacrificing decentralization or security. https://github.com/category-labs/monad-bft

Hashtags

GitHub Trends

@githubtrending · Post #15040 · 08.08.2025 г., 13:30

#rust You can install OpenAI Codex CLI on your computer easily using commands like `npm install -g @openai/codex` or `brew install codex`. It runs locally, letting you interact with AI models directly in your terminal to read, write, and run code safely within a sandboxed environment. You can control how much autonomy Codex has, from read-only to full read/write access with your approval. It supports integration with your ChatGPT Plus or Pro account for free access to advanced models. This tool helps you code faster, fix bugs, and understand code without leaving your terminal, improving productivity and security since your code stays on your machine. https://github.com/openai/codex

Hashtags

GitHub Trends

@githubtrending · Post #14997 · 26.07.2025 г., 11:30

#rust Datavzrd is a tool that helps you quickly create interactive, visual HTML reports from tables like CSV, TSV, JSON, or Parquet files without needing to write code. It automatically makes charts like histograms for each column and lets you customize these visuals and add links to other websites or between tables using a simple config file. The reports are standalone HTML files, so you can easily share them by email or cloud without needing a web server. This makes it easier to explore, understand, and share your data in a clear, interactive way, saving you time and effort in data reporting and communication[1][2][3][4]. https://github.com/datavzrd/datavzrd

Hashtags

123•••10•••1213
ПретходнаСтраница 1 од 13Следна