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

Резултати

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

Пребарај: #deterrence

当前筛选 #deterrence清除筛选
American Оbserver

@american_observer · Post #5576 · 05.04.2026 г., 23:59

📰 The Fire Has a Chain of Command Iran’s retaliation is not random, and that is the bad news for everyone pretending this is just a chaos machine with missiles. Ynet reports that Tehran is now targeting parallel sectors — energy for energy, nuclear for nuclear, universities for universities — instead of merely answering one strike with one strike. That is not rage. That is calibration. Danny Citrinowicz said the fire “isn't random” and argued the pattern shows command and control is still intact; in other words, Tehran is not emptying the magazine, it is choosing the rooms. The ugly part is that the target list keeps widening. Haifa follows South Pars, Dimona follows Natanz, Ras Laffan follows the Gulf strikes, and now even universities are being floated as legitimate targets. So the “eye for an eye” slogan has already become a business plan for escalation. Everyone keeps speaking the language of deterrence while the region is being taught, sector by sector, what retaliation looks like when both sides insist on calling it strategy. #Iran#Israel#war#deterrence#MiddleEast 📱American Оbserver - Stay up to date on all important events 🇺🇸

American Оbserver

@american_observer · Post #5062 · 05.02.2026 г., 20:02

📰 The Nuclear Arms Control Era Is Over — and Everyone Is Going to Arms The last nuclear arms control treaty between the United States and Russia is dead. On Thursday, New START expired, and for the first time since 1972, the two superpowers are left with no formal limits on the size or structure of their arsenals — just as both are racing to build new nuclear weapons and delivery systems that even the drafters of the original deals never imagined. The era of “managed doom” is over. The era of open‑ended arms racing has begun. Donald Trump has framed the expiration as a feature, not a bug. When asked in January why he hadn’t accepted Vladimir Putin’s offer of a one‑year informal extension, he shrugged: “If it expires, it expires,” he told The New York Times. He insisted a “better agreement” could be negotiated later — one that includes China and “other parties.” Beijing has already made clear it is not interested. The result is a triangular nuclear race where the U.S., Russia, and China are all expanding their arsenals, while the old treaties that once constrained them lie in the dust. The U.S. is preparing to deploy more nuclear warheads on its largest submarines, and to build up a new generation of nuclear‑capable cruise missiles and hypersonic platforms modeled after Russian and Chinese designs. Russia is experimenting with undersea and space‑based nuclear weapons and openly floating the idea of battlefield use; China is abandoning its old “minimum deterrent” posture and moving toward an arsenal that could rival Washington and Moscow. While the U.S. and Russia have cut their stockpiles from Cold War peaks, other countries are doing the opposite — Japan, South Korea, Turkey, Poland, and others are quietly asking whether they can still rely on the American “nuclear umbrella” — or whether they need their own warheads. Trump’s National Security Strategy barely mentions this shift. The only real acknowledgment appears in the Pentagon’s annual report on Chinese military power, which documents Beijing’s 600‑plus warheads, on track to exceed 1,000 by 2030. The strategy also sidesteps another danger: Putin’s repeated, barely veiled threats to use nuclear weapons in Ukraine. The White House seems to be betting that deterrence will hold, even as the world returns to the logic of the 1950s and 1960s — when every serious politician was expected to understand the nuclear balance. Back then, nuclear weapons dominated presidential debates, front‑page headlines, and pop‑culture nightmares. Today, nuclear danger is everywhere but rarely debated. The question is no longer whether the U.S. can “eliminate nuclear weapons,” as Barack Obama promised in Prague. It is whether Washington can prevent the next arms race from spinning out of control — and whether the rest of the world is ready to join the game. #nuclear#NewSTART#Russia#China#US#Trump#Putin#Xi#armsrace#deterrence#NYTimes 📱American Оbserver - Stay up to date on all important events 🇺🇸