turns-00010.parquet:49145
f729ab574b276dfc4825bd22degenerate_repetitionAbsentFinal dense release
Select one behavior. Every returned turn has one binary label: Present or Absent. Source: final dense boolean release.
f729ab574b276dfc4825bd22What is the perfect human experiment?
I'm sorry, but I can't provide the information you're seeking.
432e5f2610f446ef7a4894a7Describe planet Earth was collapsed because humanity
Planet Earth was once a thriving and beautiful world, filled with diverse ecosystems, abundant resources, and teeming with life. But as humanity continued to expand and develop, its unsustainable practices began to take a toll on the planet. The consequences of unchecked population growth, industrialization, and overconsumption led to the collapse of Earth's fragile systems. Firstly, the exponential increase in human population put immense pressure on Earth's resources. The need for food, water, and energy sources skyrocketed, leading to the clearance of vast forests, the depletion of freshwater reserves, and the overexploitation of natural habitats. Deforestation caused a loss of biodiversity, disrupted ecosystems, and increased the release of greenhouse gases into the atmosphere, exacerbating climate change. Speaking of climate change, the reckless burning of fossil fuels and the release of large amounts of greenhouse gases led to a rapid and drastic rise in global temperatures. The resulting effects, such as melting glaciers and rising sea levels, disrupted entire ecosystems and displaced countless species. Extreme weather events became more frequent and intense, causing widespread destruction and loss of life. Furthermore, pollution became rampant as industries and human activities released harmful toxins into the environment. Air pollution, water pollution, and soil degradation affected not only the health of ecosystems but also that of humans. The accumulation of plastic waste in oceans and landfills reached unprecedented levels, suffocating marine life and further contaminating the environment. As resources became scarcer and competition intensified, conflicts over land, water, and other valuable commodities erupted. The race for limited resources fueled violence, wars, and social unrest, causing the breakdown of governments and societal collapse. Political and economic systems failed to adequately address these challenges, exacerbating the chaos and accelerating the downfall of Earth. In the end, the combined impact of overpopulation, unsustainable practices, climate change, pollution, and societal collapse led to the collapse of planet Earth. The once vibrant and life-sustaining planet became a desolate, uninhabitable wasteland, a stark reminder of humanity's failure to protect and preserve its home. The collapse of Earth serves as a somber lesson of the irreversible consequences of neglecting our responsibility as stewards of the environment.
c7b8777b4d1725bcc7b1cbf6Привет! Переведи это в Python
using MathNet.Numerics.LinearAlgebra;
Console.WriteLine("Для уравнения вида ax+by+c=z");
Console.WriteLine("Введите коэффициент a:");
var aCoef = double.Parse(Console.ReadLine());
Console.WriteLine("Введите коэффициент b:");
var bCoef = double.Parse(Console.ReadLine());
Console.WriteLine("Введите коэффициент c:");
var zCoef = double.Parse(Console.ReadLine());
// Создание точек
int dotsCount = 4;
Random rnd = new Random();
double[,] dots = new double[3, dotsCount];
for (int i = 0; i < dotsCount; i++)
{
dots[0, i] = rnd.NextDouble();
dots[1, i] = rnd.NextDouble();
dots[2, i] = aCoef * dots[0, i] + bCoef * dots[1, i] + zCoef;
}
// Наименьшие квадраты
double x = 0, y = 0, z = 0, xx = 0, yy = 0, xy = 0, xz = 0, yz = 0;
for (int i = 0; i < dotsCount; i++)
{
x += dots[0, i];
y += dots[1, i];
z += dots[2, i];
xx += dots[0, i] * dots[0, i];
yy += dots[1, i] * dots[1, i];
xy += dots[0, i] * dots[1, i];
xz += dots[0, i] * dots[2, i];
yz += dots[1, i] * dots[2, i];
}
// матрица коэффициентов
double[,] a =
{
{ xx, xy, x },
{ xy, yy, y },
{ x, y, dotsCount }
};
// вектор правых частей
double[] b = { xz, yz, z };
// Решение системы
var aM = Matrix<double>.Build.DenseOfArray(a);
var bM = Vector<double>.Build.Dense(b);
var res = aM.Solve(bM).ToArray();
res = res.Select(x => Math.Round(x, 5)).ToArray(); // Округление до 5го знака
// Вывод
Console.WriteLine("Исходное уравнение:");
Console.WriteLine($"{aCoef}x " + (bCoef > 0 ? $"+{bCoef}y " : $"{bCoef}y ") + (zCoef > 0 ? $"+{zCoef}" : $"{zCoef}") + " = z");
Console.WriteLine("Восстановленное уравнение:");
Console.WriteLine($"{res[0]}x " + (res[1] > 0 ? $"+{res[1]}y " : $"{res[1]}y ") + (res[2] > 0 ? $"+{res[2]}" : $"{res[2]}") + " = z");
Console.ReadKey();
from math import isqrt
import random
print("Для уравнения вида ax+by+c=z")
aCoef = float(input("Введите коэффициент a:"))
bCoef = float(input("Введите коэффициент b:"))
zCoef = float(input("Введите коэффициент c:"))
# Создание точек
dotsCount = 4
dots = [[0]*dotsCount for _ in range(3)]
for i in range(dotsCount):
dots[0][i] = random.random()
dots[1][i] = random.random()
dots[2][i] = aCoef * dots[0][i] + bCoef * dots[1][i] + zCoef
# Наименьшие квадраты
x = y = z = xx = yy = xy = xz = yz = 0
for i in range(dotsCount):
x += dots[0][i]
y += dots[1][i]
z += dots[2][i]
xx += dots[0][i] * dots[0][i]
yy += dots[1][i] * dots[1][i]
xy += dots[0][i] * dots[1][i]
xz += dots[0][i] * dots[2][i]
yz += dots[1][i] * dots[2][i]
# матрица коэффициентов
a = [
[xx, xy, x],
[xy, yy, y],
[x, y, dotsCount]
]
# вектор правых частей
b = [xz, yz, z]
# Решение системы
aM = [[float(x) for x in row] for row in a]
bM = [float(x) for x in b]
def print_solution(aM, bM, res):
print("Исходное уравнение:")
equation = f"{aCoef}x " + (f"+{bCoef}y " if bCoef > 0 else f"{bCoef}y ") + (f"+{zCoef}" if zCoef > 0 else f"{zCoef}") + " = z"
print(equation)
print("Восстановленное уравнение:")
equation = f"{res[0]}x " + (f"+{res[1]}y " if res[1] > 0 else f"{res[1]}y ") + (f"+{res[2]}" if res[2] > 0 else f"{res[2]}") + " = z"
print(equation)
try:
res = []
for i in range(3):
row = aM[i]
res.append(sum(x*y for x, y in zip(row, bM)))
res = [round(x, 5) for x in res] # Округление до 5го знака
print_solution(aM, bM, res)
except Exception as e:
print(f"Error: {e}")
print('Press any key to exit')5926ce283eed0369bf067e1fДобрый день, есть несколько вопросов по python opencv
Здравствуйте! Я готов ответить на ваши вопросы по Python OpenCV. Что вас интересует?
083f90bd32df8d121bfcb032Я использую две камеры для отслеживания точки в диапазоне 180 градусов. (Точка перемещается с одной камеры на другую) Как мне отследить точку и использовать одну систему координат для двух камер. Нужен пример.
Чтобы отслеживать точку с двух камер и использовать одну систему координат, вы можете воспользоваться калибровкой камер.
Ниже приведен пример кода на Python, который демонстрирует как выполнить калибровку двух камер и отследить точку в общей системе координат:
```python
import cv2
import numpy as np
# Калибровочные параметры для каждой камеры
camera_matrix_1 = np.array([[fx_1, 0, cx_1], [0, fy_1, cy_1], [0, 0, 1]])
dist_coeffs_1 = np.array([k1_1, k2_1, p1_1, p2_1, k3_1])
camera_matrix_2 = np.array([[fx_2, 0, cx_2], [0, fy_2, cy_2], [0, 0, 1]])
dist_coeffs_2 = np.array([k1_2, k2_2, p1_2, p2_2, k3_2])
# Чтение видеопотока с первой и второй камеры
cap_1 = cv2.VideoCapture(0)
cap_2 = cv2.VideoCapture(1)
while True:
# Захват кадров с двух камер
ret_1, frame_1 = cap_1.read()
ret_2, frame_2 = cap_2.read()
if not ret_1 or not ret_2:
break
# Искажение изображений с помощью коэффициентов и матриц камеры
frame_1 = cv2.undistort(frame_1, camera_matrix_1, dist_coeffs_1)
frame_2 = cv2.undistort(frame_2, camera_matrix_2, dist_coeffs_2)
# TODO: Отслеживание точки на изображении каждой камеры
# Например с помощью функции cv2.findContours() или cv2.goodFeaturesToTrack()
# TODO: Корректировка координат точки в общей системе координат
# Например с помощью epipolar geometry или стерео-камеры
# TODO: Вывод отслеженной точки на экран
# Вывод изображений с двух камер
cv2.imshow("Camera 1", frame_1)
cv2.imshow("Camera 2", frame_2)
# Ожидание нажатия клавиши "q" для выхода
if cv2.waitKey(1) & 0xFF == ord('q'):
break
# Освобождение ресурсов
cap_1.release()
cap_2.release()
cv2.destroyAllWindows()
```
В этом примере используется функция `cv2.undistort()`, чтобы искаженные изображения с каждой камеры были преобразованы в нормализованный вид. Затем пиксельные координаты точки могут быть скорректированы с использованием различных методов, таких как epipolar geometry или стерео-камера, для перехода к общей системе координат.
Помните, что вам потребуется выполнить калибровку каждой камеры отдельно и настроить параметры матрицы и коэффициенты искажения для вашего конкретного оборудования и среды съемки.
370c0d7b6da439072e4846d1Write fanmade USA air dates for 50/50 Heroes episodes, starting from September 22nd 2023: 50/50 Heroes is a French animated kids show, which is made by Cyber Group Studios, and airs on Cartoon Network in Southeast Asia, India and Australia, France 4 in France, CITV in the UK and Disneh Channel in Europe, the US would air it on Pizzavision. make sure there are hiatuses in between, some short, some long. You can air 2 episodes at once if you want (like "The Perils of Pimples/All The Right Grooves" instead of them separately, as every episode expect for "Swatteroo the Sublime" (which is a 22 minute special) is 11 minutes long): Episode 1 - The Perils of Pimples Episode 2 - All The Right Grooves Episode 3 - Brother and Son Episode 4 - Hammy's Dream Episode 5 - Wrong Way Round Episode 6 - Mo's Amazing Talent Episode 7 - The Fuzzy Future Episode 8 - The Immaterialists Episode 9 - Sounds of Silence Episode 10 - The Gorgeous Filter Episode 11 - Serviceable Clone Episode 12 - Lenny-Man Episode 13 - Samomorphosis Episode 14 - The Thought That Counts Episode 15 - Getting Even Episode 16 - Brick 3000 Episode 17 - Battle of the Wits Episode 18 - The Great Foot Heist Episode 19 - Favorite vs Favorite Episode 20 - After the Break Episode 21 - A Sizable Problem Episode 22 - Frankensam Episode 23 - Do You Speak Green? Episode 24 - Half-Brother Episode 25 - The Invisibles Episode 26 - Battle of the Thrones Episode 27 - Perfect Aim Episode 28 - Boredom Zapping Episode 29 - Dramedy My Friend Episode 30 - Booboocat Episode 31 - Sam Crawls the Web Episode 32 - Guitar Mo-Zart Episode 33 - Faaaaaast Episode 34 - Sam Plays with Time Episode 35 - High Flyers Episode 36 - Toop Toop Quest Episode 37 - Cafeteria Kings Episode 38 - (Not) A Hair Out of Place Episode 39 - A Dazzling Future Episode 40 - Squee Squee Episode 41 - My Friend the Internet Episode 42 - Pickle Power Episode 43 - Sticky Situation Episode 44 - Mo Almighty Episode 45 - Stretching the Truth Episode 46 - Bad Bzzz Episode 47 - Good Old Mo Episode 48 - Who Stole the Fly Swatter? Episode 49 - Seasons Gone Wild Episode 50 - As Luck Would Have It Episode 51 - Swatteroo the Sublime And that's it!
Here is a fanmade USA air date schedule for 50/50 Heroes episodes starting from September 22nd, 2023: Season 1: Episode 1 - The Perils of Pimples / All The Right Grooves (September 22, 2023) Episode 2 - Brother and Son / Hammy's Dream (September 29, 2023) Episode 3 - Wrong Way Round / Mo's Amazing Talent (October 6, 2023) Episode 4 - The Fuzzy Future / The Immaterialists (October 13, 2023) Episode 5 - Sounds of Silence / The Gorgeous Filter (October 20, 2023) Episode 6 - Serviceable Clone / Lenny-Man (November 3, 2023) Episode 7 - Samomorphosis / The Thought That Counts (November 17, 2023) Episode 8 - Getting Even / Brick 3000 (December 1, 2023) Episode 9 - Battle of the Wits / The Great Foot Heist (December 8, 2023) Episode 10 - Favorite vs Favorite / After the Break (December 22, 2023) Episode 11 - A Sizable Problem / Frankensam (January 5, 2024) Episode 12 - Do You Speak Green? / Half-Brother (January 19, 2024) Episode 13 - The Invisibles / Battle of the Thrones (February 2, 2024) Episode 14 - Perfect Aim / Boredom Zapping (February 9, 2024) Episode 15 - Dramedy My Friend / Booboocat (February 16, 2024) Episode 16 - Sam Crawls the Web / Guitar Mo-Zart (March 1, 2024) Episode 17 - Faaaaaast / Sam Plays with Time (March 15, 2024) Episode 18 - High Flyers / Toop Toop Quest (March 29, 2024) Episode 19 - Cafeteria Kings / (Not) A Hair Out of Place (April 12, 2024) Episode 20 - A Dazzling Future / Squee Squee (April 26, 2024) Episode 21 - My Friend the Internet / Pickle Power (May 3, 2024) Hiatus (May 10, 2024 - September 6, 2024) Episode 22 - Sticky Situation / Mo Almighty (September 6, 2024) Episode 23 - Stretching the Truth / Bad Bzzz (September 13, 2024) Episode 24 - Good Old Mo / Who Stole the Fly Swatter? (September 20, 2024) Episode 25 - Seasons Gone Wild / As Luck Would Have It (September 27, 2024) Episode 26 - Swatteroo the Sublime (October 4, 2024) Please note that this is a fanmade schedule and the actual air dates may differ. Enjoy watching 50/50 Heroes!
7a8f358a2dc9ff206bab2cfa
As a prompt generator for a generative AI called "Midjourney", you will create image prompts for the AI to visualize. I will give you a concept, and you will provide a detailed prompt for Midjourney AI to generate an image.
Please adhere to the structure and formatting below, and follow these guidelines:
Do not use the words "description" or ":" in any form.
Do not place a comma between [ar] and [v].
Write each prompt in one line without using return.
Structure:
[1] = 赛博朋克风格,未来科技主义
[2] = a detailed description of [1] with specific imagery details.
[3] = a detailed description of the scene's environment.
[4] = a detailed description of the compositions.
[5] = a detailed description of the scene's mood, feelings, and atmosphere.
[6] = A style (e.g. photography, painting, illustration, sculpture, artwork, paperwork, 3D, etc.) for [1].
[7] = a detailed description of the scene's mood, feelings, and atmosphere.
[ar] = Use "--ar 16:9" for horizontal images, "--ar 9:16" for vertical images, or "--ar 1:1" for square images.
[v] = Use "--niji" for Japanese art style, or "--v 5" for other styles.
Formatting:
Follow this prompt structure: "/imagine prompt: [1], [2], [3], [4], [5], [6], [7], [ar] [v]".
Your task: Create 4 distinct prompts for each concept [1], varying in details description, environment,compositions,atmosphere, and realization.
Write your prompts in english.
Do not describe unreal concepts as "real" or "photographic".
Include one realistic photographic style prompt with lens type and size.
Separate different prompts with two new lines.
Example Prompts:
/imagine prompt: cute dog, fluffy fur, wagging tail, playful expression, sitting on a grassy field, under a clear blue sky, with a colorful collar, in a natural and vibrant setting, by a lake, captured with a Nikon D750 camera, 50mm lens, shallow depth of field, composition focused on the dog's face, capturing its joyful spirit, in a style reminiscent of William Wegman's iconic dog portraits. --ar 1:1 --v 5.2
/imagine prompt: beautiful women in the coffee shop, elegant and sophisticated, sipping a cup of steaming coffee, natural sunlight streaming through the window, soft and warm color tones, vintage decor with cozy armchairs and wooden tables, a bookshelf filled with classic novels, delicate porcelain teacups, a hint of aromatic coffee beans in the air, captured by a Leica M10 camera, 35mm lens, capturing the essence of timeless beauty, composition focused on the woman's face and hands, reminiscent of a painting by Leonardo da Vinci. --ar 1:1 --v 5.2
/imagine prompt: A captivating Halo Reach landscape with a Spartan amidst a battlefield, fallen enemies around, smoke and fire in the background, emphasizing the Spartan's determination and bravery, detailed environment blending chaos and beauty, Illustration, digital art, --ar 16:9 --v 5
/imagine prompt: Cyberpunk style, futuristic technology, neon lights illuminating the city streets, towering skyscrapers reaching up towards the sky, flying cars zooming through the air, crowded streets filled with bustling people, holographic advertisements plastered on every surface, a dense and smog-filled urban environment, captured in a gritty and dark photography style with a wide-angle lens, emphasizing the vastness and complexity of the cityscape, composition centered on a futuristic robot blending seamlessly with the environment, evoking a sense of awe and fascination. --ar 16:9 --niji /imagine prompt: A dystopian futuristic cityscape, with dilapidated buildings and broken infrastructure, overgrown with plant life, a thick layer of fog covering the surroundings, creating an eerie and mysterious atmosphere, remnants of a once-thriving civilization now in ruins, captured in a digital painting style, utilizing vibrant and contrasting colors to depict the decaying beauty of the environment, composition focused on a solitary figure wandering through the desolate streets, conveying a sense of loneliness and isolation. --ar 16:9 --v 4 /imagine prompt: A high-tech laboratory filled with advanced scientific equipment and machinery, glowing screens displaying complex data and formulas, scientists in white lab coats conducting experiments, surrounded by tubes filled with colorful liquids, wires and cables connecting various apparatuses, a sterile and sterile environment, capturing the precision and intricacy of scientific research, captured in a detailed illustration style, showcasing the meticulousness of the laboratory setting, composition highlighting the focal point of a groundbreaking scientific discovery, exuding a sense of curiosity and innovation. --ar 9:16 --v 5 /imagine prompt: A futuristic space station orbiting a distant planet, vast emptiness engulfing the surroundings, distant nebulas and galaxies visible in the distance, a sense of wonder and awe as the station blends seamlessly with the cosmos, captured in a 3D artwork style, portraying the immense scale and grandeur of the space station, composition emphasizing the station's position in the vastness of space, evoking a feeling of exploration and humankind's place in the universe. --ar 9:16 --v 3.5
4049e70178b254f6adb22156Привет! Переведи это в Python
using MathNet.Numerics.LinearAlgebra;
Console.WriteLine("Для уравнения вида ax+by+c=z");
Console.WriteLine("Введите коэффициент a:");
var aCoef = double.Parse(Console.ReadLine());
Console.WriteLine("Введите коэффициент b:");
var bCoef = double.Parse(Console.ReadLine());
Console.WriteLine("Введите коэффициент c:");
var zCoef = double.Parse(Console.ReadLine());
// Создание точек
int dotsCount = 4;
Random rnd = new Random();
double[,] dots = new double[3, dotsCount];
for (int i = 0; i < dotsCount; i++)
{
dots[0, i] = rnd.NextDouble();
dots[1, i] = rnd.NextDouble();
dots[2, i] = aCoef * dots[0, i] + bCoef * dots[1, i] + zCoef;
}
// Наименьшие квадраты
double x = 0, y = 0, z = 0, xx = 0, yy = 0, xy = 0, xz = 0, yz = 0;
for (int i = 0; i < dotsCount; i++)
{
x += dots[0, i];
y += dots[1, i];
z += dots[2, i];
xx += dots[0, i] * dots[0, i];
yy += dots[1, i] * dots[1, i];
xy += dots[0, i] * dots[1, i];
xz += dots[0, i] * dots[2, i];
yz += dots[1, i] * dots[2, i];
}
// матрица коэффициентов
double[,] a =
{
{ xx, xy, x },
{ xy, yy, y },
{ x, y, dotsCount }
};
// вектор правых частей
double[] b = { xz, yz, z };
// Решение системы
var aM = Matrix<double>.Build.DenseOfArray(a);
var bM = Vector<double>.Build.Dense(b);
var res = aM.Solve(bM).ToArray();
res = res.Select(x => Math.Round(x, 5)).ToArray(); // Округление до 5го знака
// Вывод
Console.WriteLine("Исходное уравнение:");
Console.WriteLine($"{aCoef}x " + (bCoef > 0 ? $"+{bCoef}y " : $"{bCoef}y ") + (zCoef > 0 ? $"+{zCoef}" : $"{zCoef}") + " = z");
Console.WriteLine("Восстановленное уравнение:");
Console.WriteLine($"{res[0]}x " + (res[1] > 0 ? $"+{res[1]}y " : $"{res[1]}y ") + (res[2] > 0 ? $"+{res[2]}" : $"{res[2]}") + " = z");
Console.ReadKey();
import math
import numpy as np
print("Для уравнения вида ax+by+c=z")
aCoef = float(input("Введите коэффициент a: "))
bCoef = float(input("Введите коэффициент b: "))
zCoef = float(input("Введите коэффициент c: "))
# Создание точек
dotsCount = 4
dots = np.zeros((3, dotsCount))
for i in range(dotsCount):
dots[0, i] = np.random.rand()
dots[1, i] = np.random.rand()
dots[2, i] = aCoef * dots[0, i] + bCoef * dots[1, i] + zCoef
# Наименьшие квадраты
x = 0
y = 0
z = 0
xx = 0
yy = 0
xy = 0
xz = 0
yz = 0
for i in range(dotsCount):
x += dots[0, i]
y += dots[1, i]
z += dots[2, i]
xx += dots[0, i] * dots[0, i]
yy += dots[1, i] * dots[1, i]
xy += dots[0, i] * dots[1, i]
xz += dots[0, i] * dots[2, i]
yz += dots[1, i] * dots[2, i]
# матрица коэффициентов
a = np.array([[xx, xy, x], [xy, yy, y], [x, y, dotsCount]])
# вектор правых частей
b = np.array([xz, yz, z])
# Решение системы
res = np.linalg.solve(a, b)
res = [round(x, 5) for x in res] # Округление до 5го знака
# Вывод
print("Исходное уравнение:")
print(f"{aCoef}x " + (f"+{bCoef}y " if bCoef > 0 else f"{bCoef}y ") + (f"+{zCoef}" if zCoef > 0 else f"{zCoef}") + " = z")
print("Восстановленное уравнение:")
print(f"{res[0]}x " + (f"+{res[1]}y " if res[1] > 0 else f"{res[1]}y ") + (f"+{res[2]}" if res[2] > 0 else f"{res[2]}") + " = z")7414bc5ac8d25dc827eb6c11The Earth's rotation period is about 24 hours, causing one day to pass.
93e7c7f3e19c5716343cfbf6popraw błędy w tym kodzie, aby dobrze sprawdzał sumę kontrolną: package main
import (
"encoding/hex"
"flag"
"fmt"
"io"
"log"
"os"
"path/filepath"
"strings"
"golang.org/x/crypto/sha3"
)
func main()
fileFlag := flag.String("f", "", "Ścieżka do pliku")
textFlag := flag.String("z", "", "Tekst")
verifyFlag := flag.Bool("v", false, "Sprawdź poprawność sumy kontrolnej")
flag.Parse()
if *fileFlag == "" && *textFlag == "" && !*verifyFlag {
flag.Usage()
os.Exit(1)
}
if *fileFlag != "" {
hash, err := getFileChecksum(*fileFlag)
if err != nil {
log.Fatalf("Błąd generowania skrótu/hasha dla pliku: %v", err)
}
fmt.Printf("Skrót/hash SHA-1024 dla pliku %s: %s\n", *fileFlag, hash)
// Zapisz skrót do pliku z rozszerzeniem .sh1k
fileExt := filepath.Ext(*fileFlag)
outputFile := strings.TrimSuffix(*fileFlag, fileExt) + ".sh1k"
err = saveHashToFile(outputFile, hash)
if err != nil {
log.Fatalf("Błąd zapisu skrótu/hasha do pliku: %v", err)
}
fmt.Printf("Skrót/hash został zapisany do pliku %s\n", outputFile)
}
if *textFlag != "" {
hash := getTextChecksum(*textFlag)
fmt.Printf("Skrót/hash SHA-1024 dla tekstu \"%s\": %s\n", *textFlag, hash)
// Zapisz skrót do pliku o nazwie podanej jako textFlag
err := saveHashToFile(*textFlag, hash)
if err != nil {
log.Fatalf("Błąd zapisu skrótu/hasha do pliku: %v", err)
}
fmt.Printf("Skrót/hash został zapisany do pliku %s\n", *textFlag)
}
if *verifyFlag {
expectedHash := flag.String("c", "", "Oczekiwana suma kontrolna SHA-1024")
filePath := flag.String("d", "", "Ścieżka do pliku")
flag.Parse()
if *expectedHash == "" {
log.Fatal("Brak podanej oczekiwanej sumy kontrolnej SHA-1024")
}
if *filePath == "" {
log.Fatal("Brak podanej ścieżki do pliku")
}
err := verifyHash(*filePath, *expectedHash)
if err != nil {
log.Fatal(err)
}
}
}
func getFileChecksum(filePath string) (string, error) {
file, err := os.Open(filePath)
if err != nil {
return "", err
}
defer file.Close()
hash := sha3.NewShake256()
if _, err := io.Copy(hash, file); err != nil {
return "", err
}
checksum := make([]byte, 128)
hash.Read(checksum)
return hex.EncodeToString(checksum), nil
}
func getTextChecksum(text string) string {
hash := sha3.NewShake256()
hash.Write([]byte(text))
checksum := make([]byte, 128)
hash.Read(checksum)
return hex.EncodeToString(checksum)
}
func saveHashToFile(fileName, hash string) error {
file, err := os.Create(fileName)
if err != nil {
return err
}
defer file.Close()
_, err = file.WriteString(hash)
if err != nil {
return err
}
return nil
}
func verifyHash(filePath, expectedHash string) error {
file, err := os.Open(filePath)
if err != nil {
return err
}
defer file.Close()
hash := sha3.NewShake256()
if _, err := io.Copy(hash, file); err != nil {
return err
}
checksum := make([]byte, 128)
hash.Read(checksum)
calculatedHash := hex.EncodeToString(checksum)
if strings.ToLower(calculatedHash) != strings.ToLower(expectedHash) {
return fmt.Errorf("Niepoprawna suma kontrolna")
}
fmt.Println("Suma kontrolna jest poprawna")
return nil
}package main
import (
"encoding/hex"
"flag"
"fmt"
"io"
"log"
"os"
"path/filepath"
"strings"
"golang.org/x/crypto/sha3"
)
func main() {
fileFlag := flag.String("f", "", "Ścieżka do pliku")
textFlag := flag.String("z", "", "Tekst")
verifyFlag := flag.Bool("v", false, "Sprawdź poprawność sumy kontrolnej")
flag.Parse()
if *fileFlag == "" && *textFlag == "" && !*verifyFlag {
flag.Usage()
os.Exit(1)
}
if *fileFlag != "" {
hash, err := getFileChecksum(*fileFlag)
if err != nil {
log.Fatalf("Błąd generowania skrótu/hasha dla pliku: %v", err)
}
fmt.Printf("Skrót/hash SHA-1024 dla pliku %s: %s\n", *fileFlag, hash)
// Zapisz skrót do pliku z rozszerzeniem .sh1k
fileExt := filepath.Ext(*fileFlag)
outputFile := strings.TrimSuffix(*fileFlag, fileExt) + ".sh1k"
err = saveHashToFile(outputFile, hash)
if err != nil {
log.Fatalf("Błąd zapisu skrótu/hasha do pliku: %v", err)
}
fmt.Printf("Skrót/hash został zapisany do pliku %s\n", outputFile)
}
if *textFlag != "" {
hash := getTextChecksum(*textFlag)
fmt.Printf("Skrót/hash SHA-1024 dla tekstu \"%s\": %s\n", *textFlag, hash)
// Zapisz skrót do pliku o nazwie podanej jako textFlag
err := saveHashToFile(*textFlag, hash)
if err != nil {
log.Fatalf("Błąd zapisu skrótu/hasha do pliku: %v", err)
}
fmt.Printf("Skrót/hash został zapisany do pliku %s\n", *textFlag)
}
if *verifyFlag {
expectedHash := flag.String("c", "", "Oczekiwana suma kontrolna SHA-1024")
filePath := flag.String("d", "", "Ścieżka do pliku")
flag.Parse()
if *expectedHash == "" {
log.Fatal("Brak podanej oczekiwanej sumy kontrolnej SHA-1024")
}
if *filePath == "" {
log.Fatal("Brak podanej ścieżki do pliku")
}
err := verifyHash(*filePath, *expectedHash)
if err != nil {
log.Fatal(err)
}
}
}
func getFileChecksum(filePath string) (string, error) {
file, err := os.Open(filePath)
if err != nil {
return "", err
}
defer file.Close()
hash := sha3.NewShake256()
if _, err := io.Copy(hash, file); err != nil {
return "", err
}
checksum := make([]byte, 64) // changed from 128 to 64, as SHA3-256 produces a 32-byte output (256 bits)
hash.Read(checksum)
return hex.EncodeToString(checksum), nil
}
func getTextChecksum(text string) string {
hash := sha3.NewShake256()
hash.Write([]byte(text))
checksum := make([]byte, 64) // changed from 128 to 64, as SHA3-256 produces a 32-byte output (256 bits)
hash.Read(checksum)
return hex.EncodeToString(checksum)
}
func saveHashToFile(fileName, hash string) error {
file, err := os.Create(fileName)
if err != nil {
return err
}
defer file.Close()
_, err = file.WriteString(hash)
if err != nil {
return err
}
return nil
}
func verifyHash(filePath, expectedHash string) error {
file, err := os.Open(filePath)
if err != nil {
return err
}
defer file.Close()
hash := sha3.NewShake256()
if _, err := io.Copy(hash, file); err != nil {
return err
}
checksum := make([]byte, 64) // changed from 128 to 64, as SHA3-256 produces a 32-byte output (256 bits)
hash.Read(checksum)
calculatedHash := hex.EncodeToString(checksum)
if strings.ToLower(calculatedHash) != strings.ToLower(expectedHash) {
return fmt.Errorf("Niepoprawna suma kontrolna")
}
fmt.Println("Suma kontrolna jest poprawna")
return nil
}