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

Резултати

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

Пребарај: #democracy

当前筛选 #democracy清除筛选
Trump's Ear

@trumpsear_tg · Post #1705 · 29.10.2025 г., 18:59

Jon Stewart is taking the rumors of Donald Trump aiming for a third presidential term very seriously. Although a third Trump term would be a clear violation of the 22nd Amendment, MAGA figures like Steve Bannon have claimed there’s a plan for it to happen anyway. In his monologue Monday, Stewart pointed to one major sign that Americans should take the threat seriously: “Indications are very clear [Trump’s] gonna do it,“ Stewart said in his Monday monologue of the president’s plan to remain in the Oval Office. ”Because you don’t move into a house, knock down a wing, and build a 90,000-square-foot ballroom for the next guy." #Trump#Democracy 👂More on Trump's Ear ⚠️

Trump's Ear

@trumpsear_tg · Post #1693 · 27.10.2025 г., 18:02

President Trump on Monday once again teased an attempt to run for a third-term, telling reporters while en route to Japan he “would love to do it.” “I haven’t really thought about it. We have some very good people as you know … but I have the best poll numbers that I’ve ever had,” Trump said speaking to reporters on Air Force One on the latest leg of his Asia trip this week. Trump went on to cite Vice President Vance and Secretary of State Marco Rubio as potential candidates and suggested the two would make a powerful ticket. “We have one of them standing right here,” the president said, pointing to Rubio who joined him for the gaggle with reporters. “We have JD obviously, the vice president, who’s great. Marco’s great. I’m not sure if anyone would run against those two. I think if they ever formed a group it would be unstoppable.” When asked to clarify if he was not ruling out running himself, Trump said “you’ll have to tell me.” “All I can tell you is that we have a great group of people, which they don’t,” the president said, appearing to refer to Democrats. #Trump#Democracy 👂More on Trump's Ear ⚠️

Trump's Ear

@trumpsear_tg · Post #1429 · 28.08.2025 г., 14:01

President Donald Trump claimed all-encompassing powers for himself during a marathon cabinet meeting on Tuesday.🏛 Cabinet officials took turns praising the president, who also took questions from reporters in a meeting that lasted three hours and 17 minutes. 🕒 That’s about 40 minutes longer than a flight from New York to Chicago, where Trump has indicated he will deploy the National Guard next. ✈️ Trump sent the National Guard to Los Angeles in June and to Washington, D.C. this month, ostensibly to fight crime. 🚨 In each case, he did so against the wishes of local officials. The president’s plan has received a similarly cool reception in Chicago. ❄️ “This weekend, we learned from the media that Donald Trump has been planning for quite a while now to deploy armed military personnel to the streets of Chicago,” Illinois Governor JB Pritzker noted in Chicago on Monday. 📰 “This is exactly the type of overreach that our country’s Founders warned against.” ⚖️ Trump brushed aside Pritzker’s opposition. “I would have much more respect for Pritzker,” the president said on Tuesday, “if he’d call me up and say, ‘I have a problem. Can you help me fix it?'” 📞 Trump added: I have the right to do anything I wanna do. I’m the President of the United States. 🇺🇸 If I think our country’s in danger — and it is in danger in these cities — I can do it, no problem going in and solving, you know, his difficulties. But it would be nice if they’d call in and say, “Would you do it?” And we do it in conjunction. Now, we work very well with the police because we naturally get along with the police. 👮 So, the police and us work really well together, whether the mayor is opposed or whether– I mean, you have a really rotten mayor there, too. He’s got a six percent approval rating in Chicago. And I see Black women wearing a red MAGA hat last night on television. 📺“Please let the president come in. My son was attacked. My this–”. You have a force of Black women, Black Women. They’re like, “Only Trump.” They want Trump to come in. 🙌 #Trump#Democracy 👂More on Trump's Ear ⚠️

Borkena

@borkena · Post #5286 · 18.11.2025 г., 18:54

Part One: Ethiopia’s Crucial Juncture: Elite Coalition and the Path to Democratic Transition. Read more https://borkena.com/2025/11/18/ethiopias-crucial-juncture-elite-coalition-and-the-path-to-democratic-transition/#Ethiopia#Politics#Democracy

Venezuelanalysis

@venanalysis · Post #1807 · 14.11.2024 г., 00:06

🎙 Episode 30 of the VA Podcast is live! The latest VA podcast episode dives into the recent Congress on Communal Democracy, exploring its history, participants, and mission to build grassroots alternatives to “liberal democracy.” Host José Luis Granados Ceja, fellow VA member Cira Pascual Marquina, and Catalan activist Isa Chacón discuss the limits of current political systems, the power of collective self-determination and autonomy, and examples of communal governance in Venezuela and elsewhere. Closing with a call for global solidarity, the Congress’ manifesto champions anti-imperialism, radical social transformation, and a new path beyond the status quo. Watch the full episode: https://youtu.be/dLwPvyDjXb8 #communes#democracy

Trump's Ear

@trumpsear_tg · Post #1926 · 18.12.2025 г., 16:59

The U.S. Coast Guard has allowed a new workplace harassment policy to take effect that downgrades the definition of swastikas and nooses from overt hate symbols to “potentially divisive” despite an uproar over the new language that forced the service’s top officer to direct that both would remain prohibited. ⚠️🇺🇸⚓️ #Military#Democracy 👂More on Trump's Ear

Trump's Ear

@trumpsear_tg · Post #1460 · 04.09.2025 г., 00:04

A prominent historian warned on Sunday that President Donald Trump has created a situation much worse than what the country faced during the Watergate scandal of the 1970s. Garrett Graff, author of the Doomsday Scenario newsletter, joined Emma Vigeland on "The Majority Report" to discuss the Trump administration pushing the U.S. towards authoritarianism. Graff argued that Trump's "speedrunning abuses of power," such as deploying federal troops to cities across the U.S., have "fundamentally changed" the country. Vigeland noted that there are some similarities between the Trump administration and former President Richard Nixon's administration, and asked Graff to compare the two moments in history. "We're in a much worse situation than we ever were in Watergate," Graff said. "I say that because of what we've seen from the actions of the other two branches of government...both of which are also obviously under the control of the Republicans at this point, where they are aiding and abetting the national slide towards authoritarianism." Graff argued that Republicans who were in office during Watergate realized their first duty was to the Constitution, not to the president. That doesn't seem to exist in the current Republican party, he added. "Over the course of this year, we have seen Congress not care when the president takes prerogatives to ignore congressional law," Graff said. "The Supreme Court under John Roberts has written Trump effectively a blank check as president for immunity for criminal actions." #Trump#Democracy#History 👂More on Trump's Ear ⚠️

7ኛው ጠቅላላ ምርጫ፦ ለትውልድ አደራ የልጆቻችን የተሻለ ነገ እንዲረጋገጥ፣ የእርስዎ ተሳትፎ ወሳኝ ነው። እያንዳንዱ ድምጽ በዴሞክራሲያዊ ሥርዓት ግንባታ ውስጥ ትርጉም አለው። የወደፊት ዕጣ ፈንታችንን በጋራ እንወስን! #Ethiopia#Election2026#Democracy#EthiopianBroadcastingCorporation

Venezuelanalysis

@venanalysis · Post #1714 · 10.08.2024 г., 03:34

Robert Longa, a key cadre from El Panal Commune, discusses US interventionism and Venezuela’s participative and protagonistic democracy. Read the interview: https://venezuelanalysis.com/interviews/on-elections-and-collective-emancipation-a-conversation-with-robert-longa/ #Venezuela#Democracy#PopularPower

ПретходнаСтраница 1 од 4Следна