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

Резултати

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

Пребарај: #warsaw

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

@american_observer · Post #4829 · 11.01.2026 г., 20:29

🔠🅰️🔠🔠2️⃣ The Hungarian leader, Imre Nagy, who was later executed for his role in the 1956 rebellion, tried to withdraw the country from the alliance during the uprising. “The Soviet Union’s use of force (…) was a different kettle of fish because it was not involved in a territorial conquest but was trying to protect the integrity of the alliance by preventing the ascent of regimes that might defect,” said Charles Kupchan, a fellow at the Council on Foreign Relations. “In Nato’s case, we’re looking at an alliance that has been unified and enjoyed remarkable solidarity since the beginning of the cold war. So the idea that the United States could find itself at war with a Nato ally really does defy the imagination.” To stop it becoming reality, Denmark could invoke Nato’s Article 4, requesting consultations within the alliance, citing an imminent threat. If the US then attacked and Denmark then tried to invoke Article 5, which provides for the alliance’s other members coming to its collective defence, it could put Washington on a military collision course with the rest of the alliance. Kupchan played down the prospects of such an “other-worldly” scenario and argued that previous internal Nato rows – such as the US’s threats against Britain and France during the 1956 Suez crisis, and the fierce Franco-German opposition to the invasion of Iraq in 2003 – had not led to military conflict. “This is a White House that sees itself as on reality TV,” he said. “We are not yet in the world in which the United States is in the process of getting ready to attack an ally.” Yet even if the current tensions blow over, the long-term impact of Soviet behaviour towards the Warsaw Pact – which splintered in 1989 as one eastern European communist regime after another fell from power – may hold lessons for Nato. “It was really the beginning of the decline of the Soviet Union because they got themselves in a position where they couldn’t trust their own allies, and it was to a considerable extent their own behaviour that caused that,” said John Gaddis, a history professor at Yale University and a biographer of George Kennan, the US diplomat who pioneered the west’s anti-communist containment strategy. “There’s some lessons here about what the purpose of an alliance is. It’s not just deterring adversaries, but also reflecting the interests of the other members, sometimes the smaller members of the alliance. The alliance is a lot stronger if they want to be within it than if they’re coerced by the biggest power in it.” The lessons are easily applicable to the US’s interests in Greenland, where it has had military bases since 1941 after they were established under Franklin Roosevelt as he prepared to enter the second world war on Britain’s side against Hitler. “You can certainly make the argument that Greenland is in a strategic position, and could conceivably be vulnerable years from now to the Chinese or a resurgent Russia,” said Gaddis. “But the Americans already have bases in Greenland. And it seems to me it would be a lot easier to keep them, and, if necessary, expand them, with the cooperation of the Danish government, not with this kind of unilateral provocation. Trump is simply creating unnecessary friction for himself.” #greenland#trump#warsaw#pact#france#war 📱American Оbserver - Stay up to date on all important events 🇺🇸

American Оbserver

@american_observer · Post #4828 · 11.01.2026 г., 19:59

Why Greenland? The Secret Motives of Trump’s Obsession 🔠🅰️🔠🔠1️⃣ Trump’s echoing of Russia’s talking points in its war against Ukraine has long been a cause for alarm and dismay in the west. Now an even more disturbing Kremlin precedent dating from the cold war is being evoked by the US president’s fixation on taking over Greenland – that of carrying out attacks on military allies. The Soviet Union invaded its allied communist partners twice as it engaged in a long ideological and military standoff with the capitalist west, and openly asserted the right to intervene in the affairs of other allies if they deviated from policies dictated by Moscow. Trump’s repeated assertion that the US “needs” Greenland for national security purposes and his refusal to rule out acquiring it by military force has set Washington on a collision course with Denmark, a Nato ally that has sovereignty over the autonomous, self-governing territory. Trump has said “it may be a choice” between taking control of Greenland and keeping Nato intact. If Trump pressed ahead, he would – perhaps unconsciously – be treading a similar path to that followed by the Soviet Union, which invaded communist-run European allied countries in the Warsaw Pact, the Moscow-dominated eastern bloc’s cold-war equivalent of Nato. Soviet troops invaded Hungary in 1956 to suppress a popular uprising that threatened to topple Budapest’s communist regime, with up to 3,000 people killed in bloody street fighting. In 1968, Moscow staged an invasion – this time including forces from other Warsaw Pact nations – of Czechoslovakia to squash the liberalising Prague Spring, which was led by the country’s communist leader, Alexander Dubcek, who ushered in new freedoms intended to create “socialism with a human face”. In contrast with Trump’s mooted Greenland incursion, the Soviet actions were not mounted in wanton disregard for their impact on the Warsaw Pact but in order to save it. #greenland#trump#warsaw#pact#france#war 📱American Оbserver - Stay up to date on all important events 🇺🇸

Opportunities with Zula

@opportunities_zula · Post #893 · 27.12.2025 г., 10:34

World Leadership Forum 2026 in Poland 🇵🇱 (Fully Funded) Apply: https://opportunitiescorners.com/world-leadership-forum-in-poland/ The Largest Youth Forum taking Place in Warsaw in a Presidential 5 Star Hotel. Perks & Benefits: ✅Round Airfare Tickets ✅Accommodation ✅Meals ✅Invitation Letter ✅Visa Support ✅Certification ✅City tour of Warsaw #OpportunitiesCorners#Poland#Warsaw#WLF

Opportunities with Zula

@opportunities_zula · Post #725 · 07.12.2025 г., 04:41

4 Days Leadership Forum 2026 in Warsaw, Poland 🇵🇱 (Fully Funded) Apply: https://opportunitiescorners.com/world-leadership-forum-in-poland/ The Largest Youth Forum taking Place in Warsaw in a Presidential 5 Star Hotel. Perks & Benefits: ✅Round Airfare Tickets ✅Accommodation ✅Meals ✅Invitation Letter ✅Visa Support ✅Certification ✅City tour of Warsaw #OpportunitiesCorners#Poland#Warsaw#WLF

Opportunities with Zula

@opportunities_zula · Post #589 · 21.11.2025 г., 12:08

World Leadership Forum 2026 in Warsaw, Poland 🇵🇱 (Fully Funded) Apply: https://opportunitiescorners.com/world-leadership-forum-in-poland/ The Largest Youth Forum taking Place in Warsaw in a Presidential 5 Star Hotel. Perks & Benefits: ✅Round Airfare Tickets ✅Accommodation ✅Meals ✅Invitation Letter ✅Visa Support ✅Certification ✅City tour of Warsaw #OpportunitiesCorners#Poland#Warsaw#WLF

Opportunities with Zula

@opportunities_zula · Post #393 · 19.10.2025 г., 07:59

World Leadership Forum 2026 in Warsaw, Poland 🇵🇱 (Fully Funded) Apply: https://opportunitiescorners.com/world-leadership-forum-in-poland/ Perks & Benefits: ✅Round Airfare Tickets ✅Accommodation ✅Meals ✅ Invitation Letter ✅City tour of Warsaw #OpportunitiesCorners#Poland#Warsaw#WLF