Forwarded from AlexTCH
Writing portable code is hard: https://www.chemistryworld.com/news/structures-in-more-than-150-papers-may-be-wrong-thanks-to-nmr-coding-glitch/4010413.article
Which meant the script worked fine on Windows while producing incorrect results on GNU/Linux. This jeopardizes some 150 chemistry papers.
The error is the result of a simple file sorting problem. On operating systems without default file name sorting, the script fails to match the files containing a conformer’s free energy with its chemical shift – leading to an overall wrong value.
Which meant the script worked fine on Windows while producing incorrect results on GNU/Linux. This jeopardizes some 150 chemistry papers.
Chemistry World
Structures in more than 150 papers may be wrong thanks to NMR coding glitch
Chemical shift-calculating bug casts doubt on studies ranging from natural product discovery to biosynthesis
😁3😢3
#politota
tass.ru/politika/14659127
Это буквально признание в том, что Россия не является правовым государством.
tass.ru/politika/14659127
Это буквально признание в том, что Россия не является правовым государством.
ТАСС
Госдума приняла в I чтении законопроект о неисполнении постановлений ЕСПЧ в России
Депутаты также приняли законопроект, согласно которому постановления ЕСПЧ больше не будут основанием для пересмотра решений, принимаемых российскими судами
💩19❤1👍1😁1😢1
#prog #rust #rustreleasenotes
Вышла новая версия Rust 1.61.0! Как всегда, я ограничусь только интересным мне, за остальным смотрите полные записи о релизе.
▪️Заметно расширены возможности const fn. Теперь в них можно, загибайте пальцы:
* создавать, передавать и кастовать fn-указатели, а также трейт-объекты;
* принимать и возвращать
* иметь ограничения в виде трейтов на типы в обобщённых const fn.
При всём этом вызывать методы трейтов всё ещё нельзя. Тем не менее, даже это весьма полезно, ибо в const fn теперь можно использовать ассоциированные типы и константы. В частности, в моём коде к статье "Как написать Fizzbuzz на собеседовании" (кстати, если вы её вдруг ещё не прочитали — рекомендую) теперь можно написать так:
А, и ещё целую пачку методов на сырых указателях теперь можно применить и в const-контексте.
▪️Функция с
▪️С версии Rust 1.26.0
▪️
▪️
▪️Наконец-то пофиксили более чем годовой старости баг с недостаточными проверками ограничений на ассоциированные типы в трейт-объектах, который позволял сделать свой
▪️Предикаты для
▪️Число хешей для ограничений сырых строковых литералов снизили с щедрых 65535 (
На этом всё, всё остальное по ссылке.
Вышла новая версия Rust 1.61.0! Как всегда, я ограничусь только интересным мне, за остальным смотрите полные записи о релизе.
▪️Заметно расширены возможности const fn. Теперь в них можно, загибайте пальцы:
* создавать, передавать и кастовать fn-указатели, а также трейт-объекты;
* принимать и возвращать
impl Trait
;* иметь ограничения в виде трейтов на типы в обобщённых const fn.
При всём этом вызывать методы трейтов всё ещё нельзя. Тем не менее, даже это весьма полезно, ибо в const fn теперь можно использовать ассоциированные типы и константы. В частности, в моём коде к статье "Как написать Fizzbuzz на собеседовании" (кстати, если вы её вдруг ещё не прочитали — рекомендую) теперь можно написать так:
const fn to_str_by_type<T: NumericValue, const N: usize>() -> Str<{ N }> {
to_str(T::VALUE)
}
И, соответственно, реализацию AsStr
написать немного иначе:impl<T, const N: usize> AsStr<{ N }> for T
where
T: NumericValue,
{
const VALUE: Str<{ N }> = to_str_by_type::<Self, { N }>();
}
(опустить значение константы, к сожалению, нельзя). Разумеется, с подобным инструментарием можно сделать и что-то более интересное, но более интересных примеров у меня нету.А, и ещё целую пачку методов на сырых указателях теперь можно применить и в const-контексте.
▪️Функция с
impl Trait
в возвращаемом типе теперь может быть рекурсивной, и внутри неё возвращаемый тип не будет непрозрачным (на самом деле это скорее побочный эффект сложного изменения, смотри PR)▪️С версии Rust 1.26.0
main
может возвращать также Result<(), E: Debug>
, при этом на ошибке она выводилась в stderr при помощи форматирования Debug
, и это поведение не подлежало кастомизации. Теперь же его можно настроить при помощи реализации трейта Termination для некоего своего типа — main
теперь должен возвращать значение некоторого типа, реализующего этот трейт.▪️
{Stdin, Stdout, Stderr}::lock
теперь возвращают соответствующие guard-ы, параметризованные не временем жизни ссылки на self
, а 'static
. Это безопасно, поскольку значения этих типов являются доступом к глобальным ресурсам. Данное изменение наконец позволяет писать просто:let mut stdin = std::io::stdin().lock();вместо
let stdin = std::io::stdin();
let mut stdin = stdin.lock();
▪️Вы когда-нибудь хотели удалить из вектора все элементы, удовлетворяющие некоторому предикату, но при этом модифицировать оставшиеся? Новодобавленные Vec::retain_mut (а также VecDeque::retain_mut) к вашим услугам.▪️
ManuallyDrop<T>
всегда должен был иметь такое же представление в памяти, как и T
. Теперь это прописали явно в документации.▪️Наконец-то пофиксили более чем годовой старости баг с недостаточными проверками ограничений на ассоциированные типы в трейт-объектах, который позволял сделать свой
transmute
в safe коде.▪️Предикаты для
all
и any
внутри cfg
теперь всегда вычисляются полностью, а не лениво. Это позволяет раньше ловить ошибки с ошибочной условной компиляцией.▪️Число хешей для ограничений сырых строковых литералов снизили с щедрых 65535 (
u16::MAX
) до абсолютно зверских 255. Кошмар! </sarcasm>На этом всё, всё остальное по ссылке.
blog.rust-lang.org
Announcing Rust 1.61.0 | Rust Blog
Empowering everyone to build reliable and efficient software.
👍7🔥1
Кресты на моей кукухе
Photo
На LinkedIn, кстати, та же фигня. Ещё и Ruby зачем-то подсовывает
#prog #rust #article
Rust: A Critical Retrospective
Still, after spending a couple years in the foxhole with Rust and reading countless glowing articles about the language, I felt like maybe a post that shared some critical perspectives about the language would be a refreshing change of pace.
Rust: A Critical Retrospective
Still, after spending a couple years in the foxhole with Rust and reading countless glowing articles about the language, I felt like maybe a post that shared some critical perspectives about the language would be a refreshing change of pace.
❤5👍1
Forwarded from Life of Tau
программирование на расте - боль
программирование на крестах - страдания
я мазохистка и предпочитаю боль
программирование на крестах - страдания
я мазохистка и предпочитаю боль
👎5👍3
Скажите, а к чему снится обстрел из пулемёта гражданских в городе с вертолёта? Причём с точки зрения одного из гражданских
Forwarded from Life of Tau
🥰3🤮3😢1
#prog #go #article
Changing one character wildly improved our application's performance
(thanks @go_perf)
TL;DR:
И да, неожиданно, но даже C++ в этом плане лучше (правда, лишь начиная со стандарта C++20). В нём можно заставить компилятор сгенерировать все функции сравнения, чтобы не писать их руками:
Changing one character wildly improved our application's performance
(thanks @go_perf)
TL;DR:
type uint128 = struct {
hi uint64
lo uint64
}
func less128(a, b uint128) bool {
- return a.hi < b.hi || (a.hi == b.hi && a.lo <= b.lo)
+ return a.hi < b.hi || (a.hi == b.hi && a.lo < b.lo)
}
Из-за внесённой ошибки некоторые элементы ошибочно считались равными, из-за чего сортировка делала лишние перестановки в массиве. И вот тут я опять хочу привести в пример Rust как язык, в котором данную ошибку допустить гораздо сложнее: вместо того, чтобы вручную писать сравнение, проще добавить к определению #[derive(Ord)]
(ладно, #[derive(PartialEq, Eq, PartialOrd, Ord)]
, но это всё равно меньше, чем писать руками).И да, неожиданно, но даже C++ в этом плане лучше (правда, лишь начиная со стандарта C++20). В нём можно заставить компилятор сгенерировать все функции сравнения, чтобы не писать их руками:
#include <cstdint>
#include <compare>
struct uint128 {
uint64_t hi;
uint64_t lo;
std::strong_ordering operator<=>(const uint128&) const & = default;
};
Segment
Changing one character wildly improved our application's performance
Sometimes the only thing standing between your application and 3x better performance is a letter or two.
😁4👍1
#prog #rust #cpp #article
Can you have too many programming language features?
Bjarne Stroustrup famously said, “Within C++, there is a much smaller and cleaner language struggling to get out.” I think he regrets the quote, which he clarified is about the modern semantics of C++, held down by the outdated syntax of C. It’s such a compelling quote, though, because C++ is so messy and dirty, so we want to believe in a small clean underlying core.
The truth, however, is that there isn’t one smaller and cleaner programming language struggling to get out. There’s multiple. And from the beginning, C++ was a glomming-together of multiple ideas: a Simula-like OOP system glued awkwardly to C, without a unified motivating vision. Operator overloading was intended to help integrate the two parts, which it did but at the expense of creating its own entire sub-paradigm. And then came templates, which tried to add generic containers and algorithms but unexpectedly exploded into their own programming paradigm.
So inside C++, struggling to get out, is of course C, the original “portable assembly,” which does its very simple job well. There’s also Java/C# in there, if we take the OOP features on their own. For the operator overloading and RAII and templates, the closest I can really imagine is Rust, which I think if Bjarne was being fair, he would have to admit is close to what he specified when he clarified his quote: Rust does emphasize “programming styles, libraries and programming environments that emphasized the cleaner and more effective practices over archaic uses focused on the low-level aspects of C.”
Can you have too many programming language features?
Bjarne Stroustrup famously said, “Within C++, there is a much smaller and cleaner language struggling to get out.” I think he regrets the quote, which he clarified is about the modern semantics of C++, held down by the outdated syntax of C. It’s such a compelling quote, though, because C++ is so messy and dirty, so we want to believe in a small clean underlying core.
The truth, however, is that there isn’t one smaller and cleaner programming language struggling to get out. There’s multiple. And from the beginning, C++ was a glomming-together of multiple ideas: a Simula-like OOP system glued awkwardly to C, without a unified motivating vision. Operator overloading was intended to help integrate the two parts, which it did but at the expense of creating its own entire sub-paradigm. And then came templates, which tried to add generic containers and algorithms but unexpectedly exploded into their own programming paradigm.
So inside C++, struggling to get out, is of course C, the original “portable assembly,” which does its very simple job well. There’s also Java/C# in there, if we take the OOP features on their own. For the operator overloading and RAII and templates, the closest I can really imagine is Rust, which I think if Bjarne was being fair, he would have to admit is close to what he specified when he clarified his quote: Rust does emphasize “programming styles, libraries and programming environments that emphasized the cleaner and more effective practices over archaic uses focused on the low-level aspects of C.”
The Coded Message
Can you have too many programming language features?
There’s more than one way to do it.
Perl motto There should be one– and preferably only one –obvious way to do it.
The Zen of Python (inconsistent formatting is part of the quote) When it comes to statically-typed systems programming languages, C++…
Perl motto There should be one– and preferably only one –obvious way to do it.
The Zen of Python (inconsistent formatting is part of the quote) When it comes to statically-typed systems programming languages, C++…
👍1