LINUX.ORG.RU

Сообщения dataman

 

Объединение ради свободного интернета: проекты Tor и Tails объединяют усилия

Сегодня Tor Project, глобальная некоммерческая организация, разрабатывающая инструменты для обеспечения конфиденциальности и анонимности в Интернете, и Tails, портативная операционная система, использующая Tor для защиты пользователей от цифрового наблюдения, объединили свои усилия и деятельность. Включение Tails в структуру Tor Project позволяет упростить сотрудничество, повысить устойчивость, снизить накладные расходы, расширить программы обучения и просвещения, чтобы противостоять большему числу цифровых угроз. Одним словом, объединение усилий укрепит способность обеих организаций защищать людей по всему миру от слежки и цензуры.

https://tails.net/news/tails_tor/index.en.html

 ,

dataman
()

Лёгкие иррациональные радости использования Swift вместо C++

В Swift 6, помимо всего прочего, была добавлена официальная поддержка Debian, Fedora и Ubuntu. Стало интересно. :)
Что ж, пробуем, следуя инструкциям:

$ mkdir hello
$ cd hello
$ swift package init --type executable
$ cat Sources/main.swift
// The Swift Programming Language
// https://docs.swift.org/swift-book

print("Hello, world!")
$ swift build --swift-sdk x86_64-swift-linux-musl -c release
$ stat .build/release/hello

Size: 42517368

$ ldd .build/release/hello

not a dynamic executable

$ strip .build/release/hello
$ stat .build/release/hello

Size: 6667136

$ .build/release/hello

Hello, world!

Продолжаю наблюдения. :)


Пакеты:
https://swiftpackageindex.com
https://swiftinit.org


Документация:
https://www.swift.org/documentation
https://swiftdoc.org
https://www.swift.org/swift-evolution – эволюция языка

 , ,

dataman
()

Телеметрии в LLVM быть?!

 , , ,

dataman
()

Обновление подсветки синтаксиса

В движке сайта – большое обновление подсветки синтаксиса. Добавлены:

ARMASM
AVRASM
AWK
Basic
Brainfuck
C
JSON
Julia
Lisp
LLVM
Makefile
MIPSASM
Nim
Nix
Ocaml
Scheme
TCL
TypeScript
Vim
WASM
X86ASM
YAML

Подробности

Перемещено hobbit из linux-org-ru

 , ,

dataman
()

dracut-ng

Тут увидел: https://github.com/void-linux/void-packages/pull/51344

Как пишут в NEWS:

Release 100 of dracut-ng serves as a drop-in replacement for the original dracut project. This release marks a significant milestone in our commitment to providing an alternative, community-driven solution for creating an initramfs image. The original dracut project is no longer actively maintained (its last tagged release dates back to 2022). Forking allows the community to take ownership of the project and address maintenance issues independently.

This release includes fixes for compatibility with the latest Linux kernel (v6.8), Linux firmware, and systemd (v255).

A new dracut module named net-lib has been added to enhance networking support.

Support for new Linux kernel modules have been added to support new devices, including the Surface Laptop 4 and MacBook Pro.

The project builds test containers daily for the following Linux distributions: Arch Linux, Debian, Fedora, Gentoo, openSUSE, and Ubuntu, in various configurations (systemd, OpenRC, glibc, musl). All enabled integration tests have passed at the time of this release.

  1. https://github.com/dracutdevs/dracut
  2. https://github.com/dracut-ng/dracut-ng

 , ,

dataman
()

Сколько нужно памяти для компиляции bmake?

Пытаюсь скомпилировать (GCC 14.1) bmake (исходники). Свободных 6Gb не хватает, система намертво виснет.
Есть желающие попытаться? :)

 , , ,

dataman
()

Уменьшить минимальный размер изображений

Часто какое-нибудь лого программы или библиотеки имеет размер меньше, чем 400x400. Ещё чаще оно не квадратное.
Хотелось бы уменьшить до 200.

 , , ,

dataman
()

μt — C++20 библиотека модульного тестирования

μt¹ – небольшая (~100 Кб), header-only (единственный файл ut.hpp) C++20 библиотека модульного тестирования.
В отличие от большинства аналогов (сatch³, doctest⁴, etc.) основана не на макросах, а на возможностях стандарта C++20.
Библиотекой поддерживаются техники TDD (разработка через тестирование), BDD (разработка через поведение) и язык BDD Gherkin.
Зависит только от std.

Примеры:

#include <boost/ut.hpp> // import boost.ut;

constexpr auto sum(auto... values) { return (values + ...); }

int main() {
  using namespace boost::ut;

  "sum"_test = [] {
    expect(sum(0) == 0_i);
    expect(sum(1, 2) == 3_i);
    expect(sum(1, 2) > 0_i and 41_i == sum(40, 2));
  };
}
#include <boost/ut.hpp>
#include <chrono>
#include <iostream>
#include <string>
#include <string_view>

namespace benchmark {
struct benchmark : boost::ut::detail::test {
  explicit benchmark(std::string_view _name)
      : boost::ut::detail::test{"benchmark", _name} {}

  template <class Test>
  auto operator=(Test _test) {
    static_cast<boost::ut::detail::test&>(*this) = [&_test, this] {
      const auto start = std::chrono::high_resolution_clock::now();
      _test();
      const auto stop = std::chrono::high_resolution_clock::now();
      const auto ns =
          std::chrono::duration_cast<std::chrono::nanoseconds>(stop - start);
      std::clog << "[" << name << "] " << ns.count() << " ns\n";
    };
  }
};

[[nodiscard]] auto operator""_benchmark(const char* _name,
                                        decltype(sizeof("")) size) {
  return ::benchmark::benchmark{{_name, size}};
}

#if defined(__GNUC__) or defined(__clang__)
template <class T>
void do_not_optimize(T&& t) {
  asm volatile("" ::"m"(t) : "memory");
}
#else
#pragma optimize("", off)
template <class T>
void do_not_optimize(T&& t) {
  reinterpret_cast<char volatile&>(t) =
      reinterpret_cast<char const volatile&>(t);
}
#pragma optimize("", on)
#endif
}  // namespace benchmark

int main() {
  using namespace boost::ut;
  using namespace benchmark;

  "string creation"_benchmark = [] {
    std::string created_string{"hello"};
    do_not_optimize(created_string);
  };
}

BDD:

#include <boost/ut.hpp>

int main() {
  using namespace boost::ut::literals;
  using namespace boost::ut::operators::terse;
  using namespace boost::ut::bdd;

  "Scenario"_test = [] {
    given("I have...") = [] {
      when("I run...") = [] {
        then("I should have...") = [] { 1_u == 1u; };
        then("I should have...") = [] { 1u == 1_u; };
      };
    };
  };

  feature("Calculator") = [] {
    scenario("Addition") = [] {
      given("I have number 40") = [] {
        auto number = 40;
        when("I add 2 to number") = [&number] { number += 2; };
        then("I expect number to be 42") = [&number] { 42_i == number; };
      };
    };
  };

  // clang-format off
  scenario("Addition");
    given("I have number 40");
      auto number = 40;

    when("I add 2 to number");
      number += 2;

    then("I expect number to be 42");
      42_i == number;
}

Gherkin:

#include <boost/ut.hpp>
#include <fstream>
#include <numeric>
#include <streambuf>
#include <string>

template <class T>
class calculator {
 public:
  auto enter(const T& value) -> void { values_.push_back(value); }
  auto add() -> void {
    result_ = std::accumulate(std::cbegin(values_), std::cend(values_), T{});
  }
  auto sub() -> void {
    result_ = std::accumulate(std::cbegin(values_) + 1, std::cend(values_),
                              values_.front(), std::minus{});
  }
  auto get() const -> T { return result_; }

 private:
  std::vector<T> values_{};
  T result_{};
};

int main(int argc, const char** argv) {
  using namespace boost::ut;

  bdd::gherkin::steps steps = [](auto& steps) {
    steps.feature("Calculator") = [&] {
      steps.scenario("*") = [&] {
        steps.given("I have calculator") = [&] {
          calculator<int> calc{};
          steps.when("I enter {value}") = [&](int value) { calc.enter(value); };
          steps.when("I press add") = [&] { calc.add(); };
          steps.when("I press sub") = [&] { calc.sub(); };
          steps.then("I expect {value}") = [&](int result) {
            expect(that % calc.get() == result);
          };
        };
      };
    };
  };

  // clang-format off
  "Calculator"_test = steps |
    R"(
      Feature: Calculator

        Scenario: Addition
          Given I have calculator
           When I enter 40
           When I enter 2
           When I press add
           Then I expect 42

        Scenario: Subtraction
          Given I have calculator
           When I enter 4
           When I enter 2
           When I press sub
           Then I expect 2
    )";
  // clang-format on

  if (argc == 2) {
    const auto file = [](const auto path) {
      std::ifstream file{path};
      return std::string{(std::istreambuf_iterator<char>(file)),
                         std::istreambuf_iterator<char>()};
    };

    "Calculator"_test = steps | file(argv[1]);
  }
}

  1. https://github.com/boost-ext/ut
  2. https://boost-ext.github.io/ut – примеры, документация, бенчмарки
  3. https://github.com/catchorg/Catch2
  4. https://github.com/doctest/doctest
  5. https://boost-ext.github.io/ut/denver-cpp-2019 – слайд-презентация.
  6. https://www.youtube.com/watch?v=irdgFyxOs_Y – презентация на CppCon 2020.

 , , , ,

dataman
()

lug — DSL с расширенным PEG для C++17

После 6.5 лет забвения автор выпустил версию 0.2.0 header-only библиотеки lug.

using namespace lug::language;
		rule JSON;
		rule ExponentPart   = lexeme[ "[Ee]"_rx > ~"[+-]"_rx > +"[0-9]"_rx ];
		rule FractionalPart = lexeme[ "."_sx > +"[0-9]"_rx ];
		rule IntegralPart   = lexeme[ "0"_sx | "[1-9]"_rx > *"[0-9]"_rx ];
		rule Number         = lexeme[ ~"-"_sx > IntegralPart > ~FractionalPart > ~ExponentPart ];
		rule Boolean        = lexeme[ "true"_sx | "false" ];
		rule Null           = lexeme[ "null" ];
		rule UnicodeEscape  = lexeme[ 'u' > "[0-9A-Fa-f][0-9A-Fa-f][0-9A-Fa-f][0-9A-Fa-f]"_rx ];
		rule Escape         = lexeme[ "\\" > ("[/\\bfnrt]"_rx | UnicodeEscape) ];
		rule String         = lexeme[ "\"" > *("[^\"\\\u0000-\u001F]"_rx | Escape) > "\"" ];
		rule Array          = "[" > JSON > *("," > JSON) > "]";
		rule Object         = "{" > String > ":" > JSON > *("," > String > ":" > JSON) > "}";
		JSON                = Object | Array | String | Number | Boolean | Null;
		grammar_ = start(JSON);

https://github.com/jwtowner/lug

 , , , ,

dataman
()

Расширение smartUp Gestures удалено из Chrome Web Store

Недавно обнаружил, что перестали работать жесты мышью.
Оказалось, что smartUp Gestures было удалено из Chrome Web Store, и автоматически отключено.
За несколько дней так и не нашёл годной замены.

Репозиторий https://github.com/zimocode/smartup заархивирован.
Но нашёлся форк: https://github.com/Germxu/smartup-relay.

Видимо, причина удаления в этом:

-                               const oninstallAd = sub.cons.reason!="install" || sub.cons.donateData?.ad[0]?.find(ad => ad.type === "ad-oninstall_popup" && !ad.on);
-                               if (oninstallAd) break;
-                               chrome.tabs.create({url:"https://www.usechatgpt.ai/partner-referral?ref=smartupgestures"});
+                               // const oninstallAd = sub.cons.reason!="install" || sub.cons.donateData?.ad[0]?.find(ad => ad.type === "ad-oninstall_popup" && !ad.on);
+                               // if (oninstallAd) break;
+                               // chrome.tabs.create({url:"https://www.usechatgpt.ai/partner-referral?ref=smartupgestures"});

 , , , ,

dataman
()

Flux — C++20 библиотека алгоритмов с другой моделью итераций

Это header-only (~405 KB) C++20 библиотека в духе C++20 Ranges, Python IterTools, итераторов Rust и других, и предоставляет набор функций, в целом эквивалентный C++20 Ranges, но использует немного другую модель итерации, основанную на курсорах, а не итераторах.
Курсоры Flux - это обобщение индексов массивов, в то время как итераторы STL - обобщение указателей массивов.
Возможности:

  • большой выбор алгоритмов и адаптеров последовательностей для создания мощных (?) и эффективных конвейеров данных;
  • более высокая безопасность по сравнению со стандартными итераторами;
  • более простое использование в распространённых случаях, особенно при определении собственных последовательностей и адаптеров;
  • более эффективное выполнение некоторых распространённых операций;
  • совместимость с существующими стандартными библиотечными типами и концептами.

Документация: https://tristanbrindle.com/flux/index.html
Код: https://github.com/tcbrindle/flux
Лицензия: Boost 1.0.
Пример:

constexpr auto result = flux::ints()                        // 0,1,2,3,...
                         .filter(flux::pred::even)          // 0,2,4,6,...
                         .map([](int i) { return i * 2; })  // 0,4,8,12,...
                         .take(3)                           // 0,4,8
                         .sum();                            // 12

static_assert(result == 12);

Он же в Compiler Explorer: https://flux.godbolt.org/z/KKcEbYnTx.


Проект от автора библиотеки NanoRange – C++20 Ranges для C++17.

 , ,

dataman
()

Rawhide — утилита поиска файлов с Си-подобным синтаксисом выражений

https://github.com/raforg/rawhide

Rawhide (rh) lets you search for files on the command line using expressions and user-defined functions in a mini-language inspired by C. It’s like find(1), but more fun to use. Search criteria can be very readable and self-explanatory and/or very concise and typeable, and you can create your own lexicon of search terms. The output can include lots of detail, like ls(1).

Rawhide (rh) searches the filesystem, starting at each given path, for files that make the given search criteria expression true. If no search paths are given, the current working directory is searched.
The search criteria expression can come from the command line (with the -e option), from a file (with the -f option), or from standard input (stdin) (with -f-). If there is no explicit -e option expression, rh looks for an implicit expression among any remaining command line arguments. If no expression is specified, the default search criteria is the expression 1, which matches all filesystem entries.
An rh expression is a C-like expression that can call user-defined functions.
These expressions can contain all of C’s conditional, logical, relational, equality, arithmetic, and bit operators.

 , , , ,

dataman
()

Аннотации на изображениях

Это ответ на сообщение @watchcat382: https://www.linux.org.ru/forum/general/17589148?cid=17590079

Annotator в Дебиане почему-то нет:( А «прочие» - это кто? Тема пририсовывания стрелочек и кружочков на фотографии всяких железок для меня часто бывает актуальна.

В Ksnip простой и удобный аннотатор, например.

 , ,

dataman
()

Twemoji 15

 ,

dataman
()

Не выходит каменный PipeWire

Дело происходит в Devuan (Ceres) c KDE Plasma (X11). В попытках перейти с PulseAudio на PipeWire я сломал и то и другое. Что-то так наделал, что переустановкой PulseAudio звука тоже нет. Но хочется же PipeWire! Переустановил.

Установлены:

gstreamer1.0-pipewire
libkpipewire5
libkpipewiredmabuf5
libkpipewirerecord5
libpipewire-0.3-0
libpipewire-0.3-common
libpipewire-0.3-modules
libpipewire-0.3-modules-x11
pipewire
pipewire-alsa
pipewire-audio
pipewire-bin
pipewire-jack
pipewire-pulse
pipewire-v4l2
qml-module-org-kde-pipewire
vlc-plugin-pipewire

~ $ pipewire

[E][19002.128612] mod.protocol-native | [module-protocol-:  716 init_socket_name()] server 0x6216eb1f3870: name pipewire-0 is not an absolute path and no runtime dir found. Set one of PIPEWIRE_RUNTIME_DIR, XDG_RUNTIME_DIR or USERPROFILE in the environment
[E][19002.128803] pw.conf      | [          conf.c:  573 load_module()] 0x6216eb1cb650: could not load mandatory module "libpipewire-module-protocol-native": No such file or directory
[E][19002.128990] default      | [      pipewire.c:  105 main()] failed to create context: No such file or directory

 , , ,

dataman
()

GCC 14 — первые впечатления

Намедни в sid/ceres пришло.
Из нового в std:

  • generator, print и text_encoding в /usr/include/c++/14;
  • elements_of.h, out_ptr.h и sat_arith.h в /usr/include/c++/14/bits.

Ну и gccrs-14, да. Продолжаю наблюдения. :)

 , ,

dataman
()

/bin/<command>: not found

После какого-то обновления началось:

aclocal: warning: couldn't open directory 'm4': No such file or directory
/usr/bin/libtoolize: 1: /bin/sed: not found
/usr/bin/libtoolize: 1: /bin/sed: not found
/usr/bin/libtoolize: 1: /bin/grep: not found
/usr/bin/libtoolize: 1: /bin/sed: not found
/usr/bin/libtoolize: 1: /bin/sed: not found
: putting auxiliary files in '.'.
: copying file './ltmain.sh'
/usr/bin/libtoolize: 1: /bin/sed: not found

Или:

$ sudo apt full-upgrade

Reading package lists... Done
Building dependency tree... Done
Reading state information... Done
Calculating upgrade... Done
0 upgraded, 0 newly installed, 0 to remove and 0 not upgraded.
2 not fully installed or removed.
After this operation, 0 B of additional disk space will be used.
Do you want to continue? [Y/n]
Setting up cpio (2.15+dfsg-1) ...
update-alternatives: error: alternative path /bin/mt-gnu doesn't exist
dpkg: error processing package cpio (--configure):
 installed cpio package post-installation script subprocess returned error exit status 2
Setting up nano (7.2-2) ...
update-alternatives: error: alternative path /bin/nano doesn't exist
dpkg: error processing package nano (--configure):
 installed nano package post-installation script subprocess returned error exit status 2
Errors were encountered while processing:
 cpio
 nano
E: Sub-process /usr/bin/dpkg returned an error code (1)

И действительно, sed, grep и т. д. есть только в /usr/bin.

Памагите! :)

 

dataman
()

git replay

В git 2.44 добавлена экспериментальная команда git replay:

git-replay - EXPERIMENTAL: Replay commits on a new base, works with bare repos too


SYNOPSIS
--------
(EXPERIMENTAL!) 'git replay' ([--contained] --onto <newbase> | --advance <branch>) <revision-range>...

DESCRIPTION
-----------

Takes ranges of commits and replays them onto a new location. Leaves
the working tree and the index untouched, and updates no references.
The output of this command is meant to be used as input to
`git update-ref --stdin`, which would update the relevant branches
(see the OUTPUT section below).

THIS COMMAND IS EXPERIMENTAL. THE BEHAVIOR MAY CHANGE.

OPTIONS
-------

--onto <newbase>
    Starting point at which to create the new commits.  May be any
    valid commit, and not just an existing branch name.

When `--onto` is specified, the update-ref command(s) in the output will
update the branch(es) in the revision range to point at the new
commits, similar to the way how `git rebase --update-refs` updates
multiple branches in the affected range.

--advance <branch>
    Starting point at which to create the new commits; must be a
    branch name.

When `--advance` is specified, the update-ref command(s) in the output
will update the branch passed as an argument to `--advance` to point at
the new commits (in other words, this mimics a cherry-pick operation).

<revision-range>
    Range of commits to replay. More than one <revision-range> can
    be passed, but in `--advance <branch>` mode, they should have
    a single tip, so that it's clear where <branch> should point
    to. See "Specifying Ranges" in git-rev-parse and the
    "Commit Limiting" options below.

OUTPUT
------

When there are no conflicts, the output of this command is usable as
input to `git update-ref --stdin`.  It is of the form:

    update refs/heads/branch1 ${NEW_branch1_HASH} ${OLD_branch1_HASH}
    update refs/heads/branch2 ${NEW_branch2_HASH} ${OLD_branch2_HASH}
    update refs/heads/branch3 ${NEW_branch3_HASH} ${OLD_branch3_HASH}

where the number of refs updated depends on the arguments passed and
the shape of the history being replayed.  When using `--advance`, the
number of refs updated is always one, but for `--onto`, it can be one
or more (rebasing multiple branches simultaneously is supported).

 , , ,

dataman
()

Шрифты Iosevka 28.0.0

https://github.com/be5invis/Iosevka/releases

Там столько изменений, что написать новость я не осилю. :)

 

dataman
()

Показ количества неподтверждённых сообщений

Примерно так:

Все (10) Новости (1) Галерея (3) Голосования (5) Статьи (1)

 ,

dataman
()

RSS подписка на новые темы