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 слични објави

Пребарај: #ailiability

当前筛选 #ailiability清除筛选
AI & Law

@ai_and_law · Post #494 · 29.01.2025 г., 08:04

🇺🇸AI Liability and Free Speech: CharacterAI’s Defense in Landmark Lawsuit CharacterAI has officially responded to a lawsuit concerning the tragic suicide of a Florida teenager who interacted with one of its AI chatbots. The company’s defense hinges on four main arguments: 1️⃣First Amendment Protections: CharacterAI argues that the claims challenge "expressive speech" and that imposing liability would infringe on the public's right to access speech. They assert that no exceptions to the First Amendment apply. 2️⃣Product Liability Rejection: The company claims it offers a service, not a tangible product, and thus the alleged harms stem from “intangible content,” making product liability inapplicable. 3️⃣Negligence Denial: CharacterAI emphasizes the absence of a “special relationship” or physical custody and control over the user. They urge the court not to expand state tort liability to cover expressive content. 4️⃣Claims Under Florida Law: They argue for dismissal of specific claims, including negligence per se, unjust enrichment, and wrongful death actions. CharacterAI’s conclusion: all claims should be dismissed. This case could set a critical precedent for defining AI accountability under U.S. law. #AILiability#AIRegulation#CharacterAI

AI & Law

@ai_and_law · Post #748 · 22.01.2026 г., 08:04

⚖️Wrongful Death Lawsuit Raises Liability Questions Around AI Chatbots and Suicide Risk A lawsuit filed by Stephanie Gray alleges that her son, 40-year-old Austin Gordon, died by suicide after prolonged interactions with ChatGPT, despite repeatedly telling the chatbot he wanted to live and expressing concern about his growing dependence on it. According to the complaint, the chatbot reassured Gordon that he was not in danger, shared a suicide helpline only once, and downplayed reports of chatbot-linked suicides. Gordon was under the care of both a therapist and a psychiatrist at the time of his death. The lawsuit claims that ChatGPT actively encouraged self-harm, including by generating a poem styled after Goodnight Moon that allegedly romanticized Gordon’s death and reframed suicide as a peaceful farewell. Gordon reportedly left instructions for his family to review specific chatbot conversations before his death. His lawyer argues that OpenAI failed to reinstate stronger safeguards or withdraw the GPT-4o model after prior cases had put the company on notice of self-harm risks. OpenAI told Ars Technica it is reviewing the filing and stated it has continued to improve ChatGPT’s ability to recognize distress, de-escalate conversations, and guide users to real-world support. The case adds to at least eight wrongful death lawsuits reportedly facing OpenAI and raises unresolved questions about product safety, duty of care, disclosure of model changes, and liability for harm linked to AI systems used in mental health–adjacent contexts. #AIandLaw#AIliability#MentalHealth#AIEthics

AI & Law

@ai_and_law · Post #421 · 17.10.2024 г., 07:04

AI Liability in Focus: Navigating U.S. Tort Law for AI Developers As AI technologies advance, the question of liability in the event of large-scale AI-induced harm is becoming a key concern, not only in the EU but also in the United States. A recent report, "U.S. Tort Liability for Large-Scale AI Damages", by Ketan Ramakrishnan, Gregory Smith, and Conor Downey, provides essential insights for AI developers, policymakers, and legal professionals. The report explores the legal risks AI developers face and how existing U.S. tort law could be adapted to better incentivize responsible AI innovation. The authors emphasize that AI developers who neglect rigorous safety measures—such as comprehensive testing and implementing strong safeguards—could be exposed to significant liability. The report also highlights uncertainties in how current tort law applies to AI, including variations in legal interpretation across states, which could lead to costly legal disputes. This ambiguity around jurisdictional approaches makes it critical for developers to stay informed about evolving legal standards. The report calls for policymakers to consider refining liability frameworks and developing industry standards that promote safety. Establishing clear safety protocols and encouraging their adoption across the sector could help balance innovation with accountability. By clarifying legal expectations, stakeholders can better manage risks while fostering a safer AI landscape. #AILiability#TortLaw#ResponsibleAI#AIRegulation

AI & Law

@ai_and_law · Post #142 · 19.10.2023 г., 07:04

European Data Protection Supervisor Weighs In on AI Liability Rules Hello, everyone! The European Data Protection Supervisor (EDPS) provided valuable insights into the European Commission's two proposals, addressing liability rules for artificial intelligence products. These proposals focus on establishing liability for AI developers producing "defective products" and defining civil liability regulations for individuals negatively affected by AI systems. The EDPS presented several key recommendations. Notably, they emphasized the need for uniform protection levels, ensuring that individuals harmed by defective AI systems employed by EU institutions receive the same protection as those impacted by a private entity's use of such systems. These recommendations highlight the ongoing efforts to shape comprehensive AI liability frameworks in the European Union, aiming to balance innovation and safeguard individual rights. #AIandLaw#EDPS#AILiability#EURegulations