1.92K subscribers
3.66K photos
138 videos
15 files
3.86K links
Блог со звёздочкой.

Много репостов, немножко программирования.

Небольшое прикольное комьюнити: @decltype_chat_ptr_t
Автор: @insert_reference_here
Download Telegram
#prog #article

Мой плохой код — это ваша вина

Очередной плач про то, как в этом вашем IT всё криво

(от @blog_pogromista)
🤡6🔥5
#prog #article

I’m a former CTO. Here is the 15 sec coding test I used to instantly filter out 50% of unqualified applicants.

TL;DR: тест представлен в виде куска кода с циклом на три итерации, нужно сказать значение одной из переменных после него. Некоторые особо неквалифицированные люди просто пастят код в своего любимого AI-ассистента и получают неверный ответ, потому что копируют символ "=" в условии внутри цикла, меняя условие с ">" на ">=". При этом знак равно в условии средствами HTML скрыт и имеет нулевой размер шрифта, поэтому людям не виден.
😁20🤡5🔥1
#prog #rust #article

symbolic derivatives and the rust rewrite of RE#

Растовая версия очень быстрого движка для регулярных выражений, который поддерживает, помимо прочего, конъюкцию (пересечение результатов подвыражений), отрицание и lookahead и при этом работает за линейное от входных данных время. По производительности на выражениях с большим количеством состояний обгоняет regex, особенно для поиска без учёта регистра.

Теория, поддерживающая этот движок — это развитие идей Brzozowski, но вместо того, чтобы считать производную от регулярного выражения для разных символов и потом объединять их по классам эквивалентности, новый подход считает т. н. символическую производную — производную для всех возможных входных символов сразу.

Из-за того, что данный подход поддерживает конъюкцию, движок может работать на байтах и при этом поддерживать UTF-8 просто за счёт добавления правила, которое ограничивает вход до валидных UTF-8 последовательностей:

// \p{utf8} expands to:
// ([\x00-\x7F]
// | [\xC0-\xDF][\x80-\xBF]
// | [\xE0-\xEF][\x80-\xBF]{2}
// | [\xF0-\xF7][\x80-\xBF]{3})*


Пример кода:

use resharp::Regex;

// basic matching
let re = Regex::new(r"hello.*world").unwrap();
assert!(re.is_match("hello beautiful world"));

// intersection: contains both "cat" and "dog", 5-15 chars
let re = Regex::new(r"_*cat_*&_*dog_*&_{5,15}").unwrap();

// complement: does not contain "1"
let re = Regex::new(r"~(_*1_*)").unwrap();
👍15🔥82
#prog #rust #rustlib #article

🦀Building Rust Procedural Macros Without quote!: Introducing zyn

I've been writing proc macros for a while now. Derive macros for internal tools, attribute macros for instrumentation. And every time, the same two problems: quote! doesn't compose (you end up passing TokenStream fragments through five layers of helper functions and writing hundreds of let statements), and debugging generated code means cargo expand and then squinting at unformatted token output hoping something jumps out.

Because of this I ended up writing the same helper methods, composite AST parsing and tokenizing types, extractors etc. I would have to copy these from project to project as needed, and eventually just decided to publish a crate so I never have to do it again.

So I built zyn — a proc macro framework with a template language, composable components, and compile-time diagnostics.


I wrote the debug system after spending two days on a bug where a generated impl block was missing a lifetime bound. cargo expand spat out 400 lines of tokens and I couldn't find it, so I built a debug system.
🤔51👍1🤡1
😁22🫡4❤‍🔥3🤯3
#prog #rust #rustlib

bnum — библиотека для работы с обобщёнными числами, для которых на уровне типов зафиксированы: знаковость, число байт под хранение, битовая ширина и поведение при переполнении.

use bnum::prelude::*;
// imports common use items
// including the `Integer` type and the `n!` macro

// say we want to write a polynomial function
// which takes any unsigned or signed integer
// of any bit width and with any overflow behaviour
// for example, the polynomial could be p(x) = 2x^3 + 3x^2 + 5x + 7

fn p<const S: bool, const N: usize, const B: usize, const OM: u8>(x: Integer<S, N, B, OM>) -> Integer<S, N, B, OM> {
n!(2)*x.pow(3) + n!(3)*x.pow(2) + n!(5)*x + n!(7)
// type inference means we don't need to specify the width of the integers in the n! macro
}

// 2*10^3 + 3*10^2 + 5*10 + 7 = 2357
assert_eq!(p(n!(10U256)), n!(2357));
// evaluates p(10) as a 256-bit unsigned integer

type U24w = t!(U24w);
// 24-bit unsigned integer with wrapping arithmetic
type I1044s = t!(I1044s);
// 1044-bit signed integer with saturating arithmetic
type U753p = t!(U753p);
// 753-bit unsigned integer that panics on arithmetic overflow

let a = p(U24w::MAX); // result wraps around and doesn't panic
let b = p(I1044s::MAX); // result is too large to be represented by the type, so saturates to I044s::MAX
// let c = p(U753p::MAX); // this would result in panic due to overflow
🫡10🤔21
😁27🫡8😱3💩31🤬1
#prog #ml #article

Thoughts on slowing the fuck down

There's a much more important difference between clanker and human. A human is a bottleneck. A human cannot shit out 20,000 lines of code in a few hours. Even if the human creates such booboos at high frequency, there's only so many booboos the human can introduce in a codebase per day. The booboos will compound at a very slow rate. Usually, if the booboo pain gets too big, the human, who hates pain, will spend some time fixing up the booboos. Or the human gets fired and someone else fixes up the booboos. So the pain goes away.

With an orchestrated army of agents, there is no bottleneck, no human pain. These tiny little harmless booboos suddenly compound at a rate that's unsustainable. You have removed yourself from the loop, so you don't even know that all the innocent booboos have formed a monster of a codebase. You only feel the pain when it's too late.
👍12
🤯82😁2👎1
Блог*
#prog #go #article Слайсы в Go — это очень просто. medium.com/@gotzmann/so-you-think-you-know-go-c5164b0d0511
#prog #go #article

Go и искусство ставить подножку разработчику: разоблачение

Язык проектировался простым, лёгким в освоении, готовым для написания веб-сервисов с первого дня. Он мог бы таким и остаться, если бы не одна проблема. Проблема отбора.

Инженеры Google понимали, что без подводных камней, необходимости знать детали реализации языка и неконсистентного синтаксиса не о чем будет спрашивать на собеседовании.

Явно ставилась задача — сделать язык достаточно простым, но не настолько, чтобы собеседование мог пройти любой новичок.

Язык статьи, конечно, полон сарказма, но все указанные неочевидности поведения действительно присутствуют
😁10
#prog #abnormalprogramming

find + mkdir is Turing complete

(только GNU find, потому что доказательство опирается на поведение, не определённое в POSIX)

Также есть папир, где автор доказывает, что полноты по Тьюрингу можно добиться при помощи одного только GNU find и четырёх файлов, без mkdir.
🤯9👍5🤡2🥴2
#prog #article

What Category Theory Teaches Us About DataFrames

Или о элементарных операциях над датафреймами и как знание о них можно использовать для оптимизации вычислений
🔥6
Блог*
#prog #rust #php #abnormalprogramming Experimentally compiling PHP code to Rust
#prog #rust #php #abnormalprogramming

rustc-php: A Rust compiler written in PHP

A Rust compiler written in PHP that emits x86-64 Linux ELF binaries directly (no LLVM, no assembler, no linker). Implements ownership checking, borrow checking, type checking, move semantics, generics, traits, closures, and iterators. Useful if you need to compile Rust on a shared hosting server from 2008 where the only installed runtime is PHP.
🤯15😁11😱1
#prog #rust #rustlib #article #amazingopensource

jsongrep is faster than {jq, jmespath, jsonpath-rust, jql}

This article is both an introduction to a tool I have been working on called jsongrep, as well as a technical explanation of the internal search engine it uses. I also discuss the benchmarking strategy used to compare the performance of jsongrep against other JSON path-like query tools and implementations.

In this post I'll first show you the tool, then explain why it's fast (conceptually), then how it's fast (the automata theory), and finally prove it (benchmarks).
Язык запросов (именно запросов, не редактирования) намеренно ограничен, чтобы сделать его регулярным и позволить быструю реализацию поиска поверх стейт-машины.
👍7