
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
For further actions, you may consider blocking this person and/or reporting abuse
Bas -
Ben Brazier -
Volker Schukai -
Salma Alam-Naylor -
Once suspended, ben will not be able to comment or publish posts until their suspension is removed.
Once unsuspended, ben will be able to comment and publish posts again.
Once unpublished, all posts by ben will become hidden and only accessible to themselves.
If ben is not suspended, they can still re-publish their posts from their dashboard.
Once unpublished, this post will become invisible to the public and only accessible to Ben Halpern.
They can still re-publish the post if they are not suspended.
Discussion (68)
I'll go first with Ruby
Classes in Ruby can be easily modified. The above code adds the
like_a_cow
method toString
... So now the whole program can make a string "moo", like above.In JavaScript it's:
I wonder how many languages allow this?
C# allows this,
you can now use this as
I use extensions a lot on sealed library classes to add Quality Of Life things. One example is creating cleaner methods for adding parameters to SQLClient ClientCommand objects as one liners instead of multi-command monstrosities. (ok, they aren't that big, but do look unclean)
I think it's different (safer) in C# though, right? Like you need to add
using <namespace>
for the new methods to be accessible. So it's not true monkey patching, which is generally dangerous and best avoided.Indeed you would need to use the containing namespace. And are likely safer as it would be pretty hard to modify the behaviour of code outside of your intended changes. (I think you would have to try very hard to have any affect outside of your explicit calls to the extension methods)
I won't claim to know much about TRUE monkey patching, but wikipedia's Extension Methods and Monkey Patching articles do reference each other in suggestive ways. ;)
Python:
I should add that this is not good practice.
str
is a built in function and you should not override it.I'll do you one better: if you define a dynamic getter using
Object.defineProperty
, you can make it look exactly like the Ruby example:Same thing in Kotlin, super handy.
EDIT: A big advantage with for example the JavaScript version monkey-patching String.prototype, is that the
String
class is not modified everywhere in your codebase.It works like a normal function, you import the new function only if and where you need it. See kotlinlang.org/docs/extensions.htm...
In Dart it's
Similar in Scala:
In Rust you can add functions to other types with traits. This actually adds the
like_a_cow
function for all types that are printable, including strings. You have touse
the trait though.It is bad practice to do such things. Better use
and add in you class
Nice example, but I think it could be refined somewhat
Some regex I wrote in 2018:
I've stared at it for 5 minutes and still can't tell you what's happening 🙃
If you throw the expression into something like Debuggex it can map out the routes through the expression, as follows.
However, whilst this shows what is happening it does not indicate why.
Now that I'm staring at this chart, I'm recalling that at some point I was trying to parse markdown. Pretty sure this is looking for nested lists:
Though, it is interesting to me that the initial
*
or\d\.
is not captured; one would think it'd be important to distinguish between an unordered and ordered list...I studied the screenshot I attached to my comment and came to the same conclusion but it looks to me the expression might be more complicated than it needs to be - without fully understanding the context of course.
It searches for indented sublists, like:
You're welcome.
Anyone that can read this and know exactly what's going on is clearly not human
Lots of
(?:\*|\d\.)
repeated: non-capture region of either * or (any numeral followed by any character).Which purpose u wrote this regex
PHP
Prints
1 1 no
.In PHP, the division operator
/
returns an integer if the two operands are both integers and divide exactly, and a float in all other cases.(10 / 2)
thus givesint(5)
, while(11 / 2)
givesfloat(5.5)
. Then, in the next division step,5 / 5
givesint(1)
, while5.5 / 5.5
givesfloat(1)
.PHP's language design is truly astounding.
All right, let's see if you guys have a clue about this:
This is a single line of shellscript code written over three lines for readability. Notice that it employs backticks inside the code.
A lot is happening here, obviously. FIrst of all, the
$1
and$2
will be replaced by the first and second command line argument respectively. So if you are invoking this script with the command line argumentsrepo
andtag
, this will translate to:Next, note the backticks inside the command. The portion between the backticks - will first be evaluated. The result of this evaluation will then replace the entire thing inside the backticks.
Now, what does the portion inside the backtick do? Well, it has four parts:
Part 1 is
docker ps -a
, which yields a list of Docker images and their details:This output is then piped into part 2. Piping is a special construct in Shellscript, which takes the string output of one command and puts it into the string input of the next command. So if
command-1
prints2+2+2
into the output, andcommand-2
evaluates mathematical expressions from keyboard and prints the output, thencommand-1 | command-2
will basically make the2+2+2
from the first command become the input of the second, and we will only see the final output -6
.The output of the first command is being piped into the second command, which is
head -n2
. Thehead
command snipes out the first n lines from a file (or text input), and prints it. When fed the lines of details of different classes at the input, thehead
command will print the firstn
lines and then ignore the rest. We specifyn
with the-n2
flag, and its value is set to2
.So the
head
command will print the first two lines from the table:Notice that this includes the heading row and the details of the latest image - in this case, one which was created just three seconds before this command was run (I admit to having created it just to demonstrate this snippet).
The next command in the pipe is
tail
, and this command will ignore all but the lastn
lines from the input, and print those lastn
lines. In this case, we invoke it withtail -n1
, thereby settingn
to1
. The last one line will be printed.Or at least,
tail
will try to print it. But its own printed output has been further piped into thecut
command. This command does something quite whacky: it takes two arguments, known as the delimiter and the selected columns. The delimiter has to be a char and the selected columns is a comma-separated sequence of numbers. In case a single number is provided, that single number is interpreted as a single-length sequence of numbers.What
cut
does is that it splits each line of its input into parts, separated by the delimiter. It then takes the specific values which correspond to the selected columns, and then prints only those values which have been selected.For instance, in this case, it will split the input string (which is a single line) by the
" "
space character, and then take out the first member of the resulting array of substrings. Of course, this effectively means that it will only pick the first word of the line. And in this case, that word is the container ID of the most recently run container:This ID is the final output of the entire portion inside the backticks, and given the way Shellscript works, the entire portion inside backticks will simply be replaced by this one container ID number:
Which is the final form of the command, and it is executed. So the command does this:
Wow.... That's actually quite useful
Thank you. I use this one a lot, though I typically write it out in just one line.
SQL:
Outputs a truth table for common boolean operations:
Here's a Rust moment, I tweeted it today lol
Is your text editor or some plugin showing the return types of the functions in the chain? That's pretty cool. What's the plugin/editor?
I have something similar in Neovim with the native LSP setup and the inlay hints from
lsp_extensions
.I'm using VScode with rust-analyzer extension
Nothing in c++
This is an F# script that posts a Post like object to the json placeholder API and deserializes the json response to a Post.
you can copy into a file and run it like this:
dotnet fsi ./filename.fsx
Does a binary search through an array and finds the first element with a value greater than a random target at index 0.
This is a part of a script that chooses a random set of items to put in a supply box where each item set can have a weight assigned to it based on how valuable the items are (higher weight means more common)
what language is that?
SQF :D
I'm gonna bet on Brainf*ck, so here's mine.
Please don't ask what it does, cause I've no idea, it just looks cool..I guess.
BASIC hacking
In javascript,
const
denotes a read-only variable. If you try to reassign it, you'll get a "SyntaxError: Identifier has already been declared"However, each braced segment is treated as a new scope. This is most obvious with functions and control structures like
if (true) { ... }
, but it's not immediately obvious to people that you can arbitrarily create new scopes anywhere. Switch statements are a good place to use them.Const doesn't denote read-only, it only means you can't reassign it in the same scope. You can mutate it all you want (provided it's a type that's mutable in the first place)
I worded it a bit slopy, a "read-only reference to a value" according to MDN, but it's all semantics as long as we understand how it works =]
Wow, thanks for the hint !
Classic FizzBuzz, but in a language a friend and I worked on called Swahili-lang. Uses Swahili semantics with a JS-lik syntax,
You can find out more about it here
Custom characters on 16x2 LCD Display using LiquidCrystal library of Arduino
displays on lcd as

used to spend whole day creating different custom chars and animations
JavaScript
JavaScript will parse a string until it gets to an character it can't parse and then return the value. In this example, by parsing hexadecimal, we get
f
in the first example,fa
in the second, but nothing in the third becauses
isn't a valid hex character.This is messed up and you shouldn't do it, but we can sort-of have pattern matching in JavaScript:
The trick here is that the first
case
that equals the argument of theswitch
statement is executed. So, since the argument istrue
, only the firstcase
that have an argument that evaluates totrue
is executed. Boom!Also, no. Don't do this. Nobody expects this.
Recursive fib in peregrine which is a python like language I have been working on:). Check it out :- github.com/peregrine-lang/Peregrine
nice ! look's great!
Thanks:)
A snippet that I use in my projects:
What does this do?
As the name suggests, it converts an array into an object.
When should I use this
Often when you have a big list of objects and you need to look up a value in one of those objects very often, it is useful to transform the list into a object beforehand. It's more efficient that way, than having to do a find element operation by iterating over an array every single time.
Example
dev.to formatting messes up the code, but...
Perl:
The code just prints "Hello world".
I don't know how.
This Rust code finds and prints the first 200 primes via a sieve method. Sieve method works by plotting all numbers from 2 to n and crossing out those numbers that are known multiple of each prime.
In our code we create
crossed_out
vector. This vector will be responsible for holding the crossed out state of all numbers from 2 to n. We also create aprimes
vector that will hold our found primes. In a loop, we go through all numbers from 2 to n (inclusively), and if the number hasn't yet been crossed out, that means that this number is a prime. If it is a prime, we iterate over every multiple of that number up to n and cross it out from the list.I like how expressive the code is thanks to Rust's range. At first I also used Rust's enums, options and iterators but then realized I could simplify the code by having
crossed_out
be a vector ofbool
, and adding toprimes
vector within the same loop.One of my recent favorites is this helper to convert a callback-based JS function to an awaitable:
The following c code generates a spinning donut with ASCII with some math going on with pseudo code liberties and 2d array.
Came up with this little snippet for Vue a couple years back that will assign a uid as a key on initial render and reuse the same key for subsequent renders. It's nothing fancy, but it's sure helpful.
The above function uses the pulsar.el package to create a visual "pulse" that temporarily highlights either the current line or the region between mark and point.
Point is analogue to the cursor. Mark is analogue to a "temporary" bookmark.
In the above code, the last line (e.g.
(global-set-key...
)) maps toC-x l
(e.g. Ctrl+x then l) thejf/pulse
function defined on lines 1 through 8.By default, if I just type
C-x l
, I will "pulse" the current line. If I "prefix" the function call by first typingC-u
(e.g. Ctrl+u) then typeC-x l
, I will pulse the region between mark and point.The anatomy of the above is as follows:
jf/pulse
and one parameterparg
(e.g. prefix arg).parg
parameter is a prefix argument.parg
(e.g. I typedC-u C-x l
)...jf/pulse
to theC-x l
key combination.My implementation of factorial in Emacs Lisp
This is a standard way to implement factorial using tail recursion.
defun
marks the beginning of function definition. Then goes the name (factorial
) and list of arguments ((n)
). After that we have an optional docstring (the good part about Emacs being self-documenting has long been the fact that docstrings become incorporated into an online help system - this is no longer surprising in programming languages, but used to be rare).labels
introduces a local function - only visible within the enclosing scope. It's actually this inner function that is tail-recursive - the parameteracc
is used to weave the partial result through the sequence of recursive calls, to be returned at the bottom. By using tail recursion (provided our language supports it) leverage so-called TCO (Tail Call Optimization) to avoid building up a stack with recursive calls. Finally, we call our inner, tail-recursive function on the original parametern
and initializeacc
to1
. This way we get the desired behavior of 0! = 1.test it with swish.swi-prolog.org/
apfel is apple in english
When you run following query ?- yummy_with_apple(X)
you get follwing result set:
X = apfel
X = apfelkuchen
X = apfelsaft
X = paradiesapfel
if you run follwing query:
?- yummy_with_apple(apfelsaft)
you get true as result
How about Verilog. This is typically one of the first ones you work through as an example. This is a 4-Bit binary counter that counts from 0 to 9 and displays the count on a 7-segment display. The display is just 7 LEDs, so it turns all of the on by default and you use a binary number to tell it which of the LEDs to turn off.
While Verilog is language, it a hardware descriptive language, meaning that it tells an FPGA (field programmable gate array) how to setup its hardware. So you are creating a chip at runtime and can rework it and reprogram it on the fly. You have one in your phone and they are great for AI. So a little different from a typical program. It is a way to implement software as hardware.
And you can't ignore Assembly. Here's an example I was working on from Ben Eater. It prints "Hello World". This is why we don't write in Assembly anymore.
I wrote this JavaScript snippet about two years ago to validate a USPS tracking ID. It is not exhaustive as to whether or not the ID is actually is a known USPS ID but it makes sure the minimum number of digits are present and the check-digit is correct.
Dylan Beattie got so fed up with recruiters wanting Rockstar developers he came up with the Rockstar language specification which allows you to write code that looks like 1990s soft-rock lyrics.
This talk is both facinating and hilarious and he plays a song at the end that is in fact FizzBuzz in Rockstar.
https://m.youtube.com/watch?v=6avJHaC3C2U&t=16s
This python code takes a csv like file and breaks it into arrays, very handy option for simple usecases and also a great example of how to not name your variables
HTML
sample input
This Is a constructor in python with the help of 'new' we can use it to return some value to a variable.🥲🥲(sorry for bad photo it's really not best to have no internet connection)
This short post brought me inspiration for an another post.
Thanks for the inspiration.
console.log("Hello World");
Hello world in JS.