#esoteric-python
1 messages ยท Page 57 of 1
Or well, True / False since it's a bool
there's 2 exit conditions, <2 characters or the first and last character are not the same
Okay. Next one please. ๐
๐ป
mp = lambda s: reduce(lambda x, y: x+(y&1), map(s.count, set(s)), 0) < 2
(as with many traditional golfing problems, this one relies on the oft missed reduce builtin)
Can i ask how code golfing works?
yeah
i am not able to process that already, how to make it shorter?
depending on who you talk to whitespace may or may not count
remove whitespace, shorten variable names, sacrifice speed for smallness
and the space between lambda x, y isn't neccessary, right?
it is not
the whole lambda isn't neccessary.
none of the spaces are
the platform I wrote this for didn't count it against me
bar the one after the lambda
I donno what reduce or map does. So not gonna try
from functools import reduce
map applies a function to each item in an iterable
reduce takes a function that takes two arguments and does something like this:
reduce(func, [1, 2, 3, 4]) -> func(func(func(1, 2), 3), 4)
So can I just ask for a gold python of something just for sheer fun?
oh fancy
write a function to determine whether a given number is prime or not prime. return a bool
What's the shortest python code you can make to encode a str in Caesar cipher
f=lambda n:all(n%q for q in range(2,n)) this is the shortest i can do for my prime one
yeah thats probably the shortest you can get
well 6 ams a good time as any to sleep i guess
haha
These lambdas have me stumped in Lucys snippet
I think I wrote a golf caesar cipher at one point, gonna try find it
I've got an expanded form I used to reason it out for myself after I found it and couldn't remember what it did, if you're interested
i read caesar salad
I am lucy
def shift(s: str, key: int = 13) -> str:
return ''.join(chr((ord(c) - (65 if c.isupper() else 97) + key) % 26 + (65 if c.isupper() else 97)) if c.isalpha() else c for c in s)```
No. You are not lucy ๐
def parity_reduction(a, b):
return a + (a & b)
def can_make_palindrome(string):
return reduce(parity_reduction, [s.count(x) for x in set(x)], 0) < 2```
@viral hedge @sick hound
look, you can golf it more if you want, that's what I had
f=lambda s,k:''.join(chr((ord(c)-(65 if c.isupper()else 97)+k)%26+(65 if c.isupper() else 97))if c.isalpha()else c for c in s)```
perhaps this works
thanks lacy
Im gonna have to sit down with that one when the coffee kicks in ๐
im sure you can squish more whitespace from it
What is Caesers cipher?
You encrypt a string using an offset between 1 - 25, let's say the offset is 1, A -> B, B -> C ... Z -> A All letters are shifted 1 to the right,
And then decrypting is the same but to the left (subtract)
https://en.wikipedia.org/wiki/Caesar_cipher more info if you want a read
okay, so upper/lowercase is prserved, and each of them is rotated separately, like y + 3 = b and Y + 3 = B ?
and all non-alphabetic characters stay as they are
Okay, done in 110 bytes.
f=lambda s,k:"".join(chr([ord(c),(ord(c)+k-97)%26+97,(ord(c)+k-65)%26+65][c.isalpha()+c.isupper()])for c in s)
>>> f("Hello, World!", 3)
'Khoor, Zruog!'
Anybody beating that? ๐
You could probably do o=ord;f=...
not in a lambda
o=ord;f=lambda s,k:"".join(chr([o(c),(o(c)+k-97)%26+97,(o(c)+k-65)%26+65][c.isalpha()+c.isupper()])for c in s)```
def f(s,k): is shorter than a lambda
You still need to return though
haha
right
yeah, o=ord looks good
thought about that, but haven't added it yet because I wondered if there might be a way to use just one instead of 3
why not store 65 and 97 in one-letter variables?
I don't think it actually saved any characters in this case
6565 is shorter than a=65aa
So we can post any bad python here?
only the best bad Python though
Hm
hm
no
:(
class A:
def __new__(_):return A```
What have you done to make that happen?
Nothing it just worked
>>> class A: pass
>>> id(A()) == id(A)
False```?
def id(a):return 0```
isn't you parenthesis misplaced wattle?
No, nix's parenthesis misplaced
^That's the one
I remember reading that on a GitHub repo about python fuckups too
Or rather, 1 too many
Oh did I missplace?
id(MyClass()) == id(MyClass) # extra bracket -> )```
I type on mobile
Woopsie
It wasn't id
Ooh
It's hash
hash(MyClass()) == hash(MyClass())
that definitely won't always be true though
it allocates the same space twice
For whatever reason
I think it's just that hash() creates a "scope"
but the is statement doesn't because it's an expression
This is also good
Also a CPython optimization
in pypy that behaved differently IIRC
The range was larger or something
When it turns a = 257; b = 257 into a code object it sees that the value is the same for both and uses the same object for both
But it can't do it when you define them separately
Demonstrate what you mean @wind maple
I'm watching a talk
What talk is it?
Jesus Christ
http://CppCon.org โ Presentation Slides, PDFs, Source Code and other presenter materials are available at: https://github.com/cppcon/cppcon2016 โ The generat...
@wind maple ```py
def _exec_code(code, *args, **kwargs):
"""Execute a CodeType object with args and kwargs."""
# We re-assign the bytecode of this empty
# function with the CodeType object so that
# it can be executed in a normal manner.
util = lambda *args, **kwargs: None
util.__code__ = code
return util(*args, **kwargs)
but why
so the code can be executed easily :P
You did the Caesar quite well now can you evalute a grid of Conway's game of Life in the uglisest shortest code as possible?
(You can use whatever data type for the grid. Go crazy)
use a set :^)
interesting challenge would be to use an int for the grid
very possible
Yeah but conways is 2d
add a meta-byte at the end which specifies the width of the grid
64 bit ints -> 8x8 grid
so a width of 2 would allow the program to know that 10010110 would become
10
01
01
10```
or that too yeah
Yeah and now just from that int create a new int of the new gen
lots of bitwise operators
Gl
if __name__ == '__main__':
game = GameOfLifeWithAnIntAsTheGridDotPHP.from_array([
[0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 1, 1, 1, 1]
])
print(game.grid) # 15
print(f"{game.grid:064b}") # 0000000000000000000000000000000000000000000000000000000000001111
what is this
hell
read the channel topic
read channel topic
no, i can read
also
thanks for helping me!
reee using python for bit manipulations
whats bad about that
python
python is not good at bit stuff
so
python is just so high-level that it's impractical to do bit-manipulation
i still do it ๐
same :D
yeah with the type dynamically changing and resizing and all
you can never be sure the bit manipulaitons are going to do what you want them to do
thank god python isn't a strong typed language
it can be if you modify the bytecode :^)
that is what i meant
yeah
static typing might actually be possible with bytecode modifications, now that i think of it
(this is why the channel's called barely-python btw)
but hence it is still python
this is not quantum physics - one cannot be python and barely python at the same time
it is either python or not python
can ice cream be bare?
can you have barely-ice cream
no.
yes
what
modifying the python bytecode so that it acts like not-python is pretty barely-python to me
Best so far is probably type hinting all your variables and having a linter yell at you if it is wrong
also python vm languages
yeah
Lol nice progress juanita
thanks haha
what is that in your profile picture
mine?
whose?
alpaca.
OMG
i like how you have that image on demand
hell yeah
oh wow i was thinking its like a cell microscope closeup or something
@tight hemlock theres hella shit in your profile picture
i should change it because nobody knows what it is until i tell them haha
don't change it, juan
it's barely even python, i guess you could say
I HAVE ON TOO
GOOD
>>> class CinMeta(type):
... def __lshift__(self, other):
... print(other, end='')
... return self
...
>>> class cin(metaclass=CinMeta):
... pass
...
>>> cin << "test" << 123 << '\n'
test123```
or is it off google
nope, it's one of my friends' alpacas
i see
@wind maple but does it assign? :^)
Guys offtopicccccc
assign what
can we not turn this into like C
cin >> varname;```would be cin
trivial to imlpement
i've already done it
You're in the wrong channel lad
.
This is the "awful hacks" channel
"I don't want to code in C"
Goes to python.
"Let's program C in Python!"
i thought it was just the 'hacks' channel
I have to say this is hot garbage
@misty trellis very yes
is that a positive
cin >> undefined isn't valid in C++ either
it's garbage to begin with, so hot is an improvement
yes i know, i implemented that on purpose
because this is still python
does it have cin semantics or is it just input
it allows for c++ style but not the exact same semantics
yes but juan
do you have the book
the c++ programming language third edition by bjarne stroustrup, the creator of c++
rrp $50 holy shit
i got it for like $8
@wind maple i was planning to figure out a way of making them auto-cast to their typehinted values, but __annotations__ is evaluated at runtime. i have ideas though
a tour of C++ edition 2 coming out soon updated for C++17 and some of C++20, if anyone wants to get into C++ right now
how old is this book
oh already out
no, i meant mine
thats the first edition
third edition was 2013
it contains C++11 info, it cant be published 1997
this is barely even barely-python
the third edition, dude
oh whoops confused 4 and 3
3rd is published 2000
june 1997
i was published in 2002
ok
yes youre correct
february 2000
is this book even reliable anymore?
took 13+ years for a new edition to be published
new language editions came out, some features and patterns became standard
btw
#ot
thank you
technically speaking this is barely python
no, it really isn't. please move to offtopic
I once tried to shorten my code for a machine learning task that only allowed x amount of characters. Does this belong here? py from sklearn.neighbors import KNeighborsRegressor as kn;from sklearn.model_selection import train_test_split as tts;import pandas as p;from numpy import array as a;d = p.read_csv("Flaveria.csv");d.iloc[:, 0] = d.iloc[:, 0].apply(lambda n: {"L":0,"M":2,"H":3}.get(n));d = p.concat([d.drop("species", axis=1),p.get_dummies(d["species"])], axis=1);X, x, Y, y = tts(a(d.loc[:, d.columns != "Plant Weight(g)"].values), a(d["Plant Weight(g)"].values), test_size=0.15);print(kn(n_neighbors=3).fit(X, Y).score(x, y))
I am both amused and horrified
I probably could have used iloc in pandas to shorten it a bit more, but i met the requirements 
Alright, dumb question time from Hemlock. ; just signifies end of line as it would in most other languages?
yep
Does using ; in regular code break things in regular Python code or is it just frowned upon because it's not needed?
i use ; in c++
it's a PEP8 violation
Gotcha
Sudden urge to turn my screen name to "PEP8 is my bible" for a bit...
i use "" instead of '' for strings
I mean you can use either
thought pep 8 is only '' for strings
I thought it was a matter of what the string was for. If it's something the user is going to see you use double quote marks, if it's just an internal string it's single?
Either way, not a big deal
Depends on keyboard layout as well id assume
I use ""
'' is weird to me
I mean, you wouldn't use 'text' to quote someone in English
' is odd for me to type since i have to use my right pinky to hit it, while " is just shift + 2
u have a weird keyboard
Scandinavian layout
it's a non-american keyboard
That's normal for non US keyboards, l33t
mine is like that too
im in europe and everyone uses american layout
What part of Europe, though
English speaking part?
Where's that, romania or somewhere like that?
yes
Latvia. Under the benevolent rule of Dr. Doom
Either way, so golfing is pretty much just a crap ton of abusing aliasing, lambdas and other such tricks?
For show, eventhough it's probably getting a bit off topic; here's my layout
How do you access the grey characters on those keys?
weird and unnatural
Alt?
alt
Cool
It's just what you're trained to use.
Mine makes sense to me, just as yours make sense to you (even though things like <> and {} are slightly odd)
american layout actually makes common sense
it's usually right alt I think, yeah
I'd argue the point more, l33t, but this isn't off-topic
PEP8 doesn't actually forbid the use of semicolon
What it does say is "don't cram stuff you don't need to together"
vscode just make em ugly brown (with my style at least)
Actually semicolons don't give you an advantage in golf normally
Only inside indented blocks
Because both a linebrak and a semicolon are one character
But it's more handy to oneline stuff usually
as long as it's not too long at least.
Can you give a basic example of how indented stuff is handled in golf? I've always been confused by that since Python is based on whitespace
If you just have one indentation level, you can inline it
once you get multiple, you have to split all but the innermost on separate lines
I assume, that when you start writing golf code with multiple indentations you may want to rethink your approach?
for i in range(42):x=i**2print(x)
for i in range(42):
if i%2==0:x=i**2;print(x)
for example, IIRC
sometimes netsed loops/conditions are unavoidable
and the cost of one character per indentation level might be lower than refactoring
Gotcha
bot.help()
This isn't #bot-commands
@brave bison Go to #bot-commands
@fast torrent Why are you spamming?
Sry won't happen again
Good squishy
from ctypes import *;print(cast(id(7106412),POINTER(c_char))[24:27].decode())```
7106412 .to_bytes(3,'big').decode()```
Has anyone worked with SLAM stuff before?
python gore
(id(1+1)==id(1+1))^(id(10**5+1)==id(10**5+1)) and id(100000000000)==id(100000000000)
anyone who can adequately explain why this returns true earns my respect
i wrote it and i only have a vague idea of why
@pine edge because of constant folding.
that explains the second and third booleans, but why does the expression 1+1 return a constant object
1 0 LOAD_NAME 0 (id)
2 LOAD_CONST 0 (2)
4 CALL_FUNCTION 1
6 LOAD_NAME 0 (id)
8 LOAD_CONST 0 (2)
10 CALL_FUNCTION 1
12 COMPARE_OP 2 (==)
14 LOAD_NAME 0 (id)
16 LOAD_CONST 1 (100001)
18 CALL_FUNCTION 1
20 LOAD_NAME 0 (id)
22 LOAD_CONST 1 (100001)
24 CALL_FUNCTION 1
26 COMPARE_OP 2 (==)
28 BINARY_XOR
30 JUMP_IF_FALSE_OR_POP 46
32 LOAD_NAME 0 (id)
34 LOAD_CONST 2 (100000000000)
36 CALL_FUNCTION 1
38 LOAD_NAME 0 (id)
40 LOAD_CONST 2 (100000000000)
42 CALL_FUNCTION 1
44 COMPARE_OP 2 (==)
>> 46 RETURN_VALUE```
the entire expression is evaluated at compile time
well, the entire each int expression
wait so if all of those are loaded as constants then why
not (id(10**5+1)==id(10**5+1))
er
wait
i didn't notice the xor part, and it returns false for me
however, in your case, if it does return true, I can still explain
the optimization isn't, for whatever reason, happening to 10**5+1
but id(1+1) is still constant because all integers with values between 0 and 256 are interned
even if it's not constant-folded
yeah i remember that comment in the cpython source
between -5 and 256.
and the 100000000000 is 100000000000 because all integer literals with the same value in the same source code unit get the same constant object regardless
i didn't know about the literal scan thing, that's kinda neat
ok you can do some serious fucking spooky action at a distance with that literal scan thing
any two parts of code can use the gc module to interact via seemingly disconnected literal values
more observations: id(9001)==id(eval("9001")) is false because evaluation occurs somewhere else, but id(eval("9001"))==id(eval("9001")) works, because apparently consecutive eval calls happen in the same parser'

So meta programming is possible in C++ (where things evaluate at compile time. Essentially. ) is that also possible in python on a large scale?
i'd like this, it could make for some interesting AST fuckery
can i claim this channel to be my home on this server? i just belong here. :P
what
what the hell
what
uh what
what's going on there
i don't understand anything that's being posted in this channel
this is extremely rediculous
@ashen rivet you're really not missing out on anything. most of the stuff you see here should not be used in your genuine projects :D
juan you still have to help ppl don't spend ALL your time here
one might call this place the opposite of helping people
That's the point
@brisk zenith post some challenges :p
hey maybe i should clean up my __build_class__ for allowing nested classes to inherit from the containing class and post it in here
@sick hound
golf challenges?
- tictactoe
- connect 4
- image to ascii: input the filename and dimensions in chars
- random maths quiz - gradual difficulty increase, scoring, persistent leaderboard
- ascii sierpinski triangle: input amount of iterations
i'll be really happy if somebody knows a way to execute code at "compile time" (before AST evaluation)
I could swear that there was some trick demonstrated on the python mailing list or something where you define an encoding that transforms the source of python files
maybe you could do something with importlib
hmm
dont give Juan ideas
I just found this somewhere in my chat history...
(lambda _, __, ___, ____, _____, ______, _______, ________:
getattr(
__import__(True.__class__.__name__[_] + [].__class__.__name__[__]),
().__class__.__eq__.__class__.__name__[:__] +
().__iter__().__class__.__name__[_____:________]
)(
_, (lambda _, __, ___: _(_, __, ___))(
lambda _, __, ___:
chr(___ % __) + _(_, __, ___ // __) if ___ else
(lambda: _).func_code.co_lnotab,
_ << ________,
(((_____ << ____) + _) << ((___ << _____) - ___)) + (((((___ << __)
- _) << ___) + _) << ((_____ << ____) + (_ << _))) + (((_______ <<
__) - _) << (((((_ << ___) + _)) << ___) + (_ << _))) + (((_______
<< ___) + _) << ((_ << ______) + _)) + (((_______ << ____) - _) <<
((_______ << ___))) + (((_ << ____) - _) << ((((___ << __) + _) <<
__) - _)) - (_______ << ((((___ << __) - _) << __) + _)) + (_______
<< (((((_ << ___) + _)) << __))) - ((((((_ << ___) + _)) << __) +
_) << ((((___ << __) + _) << _))) + (((_______ << __) - _) <<
(((((_ << ___) + _)) << _))) + (((___ << ___) + _) << ((_____ <<
_))) + (_____ << ______) + (_ << ___)
)
)
)(
*(lambda _, __, ___: _(_, __, ___))(
(lambda _, __, ___:
[__(___[(lambda: _).func_code.co_nlocals])] +
_(_, __, ___[(lambda _: _).func_code.co_nlocals:]) if ___ else []
),
lambda _: _.func_code.co_argcount,
(
lambda _: _,
lambda _, __: _,
lambda _, __, ___: _,
lambda _, __, ___, ____: _,
lambda _, __, ___, ____, _____: _,
lambda _, __, ___, ____, _____, ______: _,
lambda _, __, ___, ____, _____, ______, _______: _,
lambda _, __, ___, ____, _____, ______, _______, ________: _
)
)
)
IIRC it was a Hello World or something like that...
And here's a nice thing I wrote once to calculate some probability...
>>> from functools import lru_cache
>>> f=lru_cache(maxsize=None)(lambda x:1 if x==0 else sum((1-f(i-1))/(2500-i) for i in range(x)))
>>> print(*("{:>4}: {:10.4%}".format(x, f(x)) for x in [1, 10, 100, 200, 500, 1000, 1500, 2000, 2500]), sep="\n")
1: 0.0400%
10: 0.3602%
100: 3.9631%
200: 7.9663%
500: 19.9759%
1000: 39.9920%
1500: 60.0080%
2000: 80.0240%
2500: 100.0400%
Guess what? I accidentally rewrote an approximation for x/2500 ๐
oh fancy :D
i love that top one
bytecode mods and what i'll now refer to as "lambdascores"
I think I copied that from codegolf.stackexchange.com or so
If I may interject for a moment, what you're referring to here as lambdascores are actually underscore lambdas, or as I've recently taken to calling it, underscores plus lambdas.
๐
haha good one
ยฏ_(ใ)_/ยฏ
AttributeError: 'function' object has no attribute 'func_code'
Process finished with exit code 1
@tropic gulch lambda machine broke
Here's the blogpost by the author
Fun with functional programming in Python | Ben Kurtovic's blog
It's pretty simple in reality
it just looks super confusing
yeah, i've done something like it before
i wonder if it's possible to fuck up python so badly that pointers are possible
AttributeError: module 'os' has no attribute 'wr_it'
weird must've missed something with find and replace worked now
I am very much enjoying this channel. Code folding was something I wasnt aware python did. Also compilation units are neat to think about
@novel vine C++ is AoT compiled so metaprogramming has the advantage of making cost-free abstractions at compile time and shipping expanded code to everyone else. Metaprogramming in Python wouldnt be useful because python is compiled and immediately run so metaprogramming has no advantage at all
everyone has to compile things anyway
yes but can it be done
metaprogramming? yes. anything significant compile time? not that i know of
well
idk how metaclasses are implemented
so you'll have to check that
i don't do this stuff because it's useful, it's just fun :D
what's the biggest golf ever performed ๐ค
define 'biggest'
longest
What is code golf?
So like a fizzbuzz code.
f=lambda n:all(n%q for q in range(2,n)) <- prime testing function
not a function though :D
f = lambda x: [*filter(lambda n:all(n%q for q in range(2,n)),range(x))]
if you dont mind returning an iterator instead of a list (which is perfectly fine) its 65
def f(n):r=range(2,n);return{*r}-{b*x for b in r for x in r} was Someone's best (60)
oh i forgot lambdas actually longer isnt it
ah right fair enough
f=lambda n:[p for p in range(2,n)if all(p%q for q in range(2,p))] was my best (65)
wait
0 and 1 are not prime :(
lmao
def f(x):return x
f=lambda x:x```
f=lambda n:[2,3,5,7,11][n]``` Totally works for all primes, but don't test it past first 5 
lmao
I guess you have to use a function because of r=range(2,n)
Yea, but you can't define variables in it
still a function, just only allows a single statement
i really really want a way to modify python's AST at compile-time, honestly
To do what?
to fuck with stuff :D
one idea is making
strjoin = ฮป *args: "".join(args) valid syntax for lambda functions
haha
hmmm
oooh i have an interesting idea
ฮป (num_one, num_two) <- num_one + num_two
# as an alternative to:
lambda num_one, num_two: num_one + num_two```i could make this work
you just want the lambda symbol don't you
lmao, not quite
lambdef: 'lambda' [varargslist] ':' test
lambdef_nocond: 'lambda' [varargslist] ':' test_nocond
change these lines in Grammar/Grammar
@brisk zenith ```py
import inspect
def ฮป(func):
lines = inspect.getsource(func).replace('ฮป', 'lambda').splitlines()
code = lines[1] + '\n' + '\n'.join(lines[3:-1])
print(code)
exec(code)
return eval(func.name)
@ฮป
def test():
'''
return ฮป x: x + 1
'''```
ew
also @vague gust i know it's that easy, but i want to make a module out of it :D
k e k
but if there was a way to modify the AST before code is executed, that would be interesting too
@brisk zenith make an import loader that reads the file, compiles to AST, calls your hook, then compiles the rest of the way
hmm
you'd have to parse yourself, with your own rules and then translate your ast to the python ast
well, not necessarily, if your input language is syntactically valid python
myfile = open("somedoc.txt", "r")
fileiterator = myfile.__iter__()
while 1:
savefile = open("savehere.txt", "a")
try:
value = fileiterator.__next__()
except:
print("oopsie / done")
break
else:
if value:
if not value[0] == "#":
savefile.write(value)
finally:
savefile.close()
myfile.close()``` 
This is a for loop
Does weird regex count
I have (?<=")/[^"j]+\d(?=")
more 'not python' than 'barely python' id say
there is a regex module in python
and it should be the go-to for any string parsing
That regex is far from being weird
^ that as well, it's straightforward enough -- weird regex would have lookarounds in the middle of it and backreferences and conditionals out the ears and maybe recursion and who knows what else
magikarp, regex still isn't python lol
0 and 1 are perfect primes ecks dee
not on iOS probably on Android
I mean there are codeblocks, just no highlighting -- on both, I assume
You're not using the right symbol
You're trying to use smart quotations instead of backticks
TIL lambdas use the same cpython opcodes as literals
hey @sick hound you seem to know bytecode stuff, c'mere :P
Hi
ฮป (num_one, num_two) <- (-num_one + num_two) / 2 + -num_two
so i'm working on making this stuff actually valid code, and i know exactly how to do it except one thing. obviously i need to separate the bytecode that is the (-num_one + num_two) / 2 + -num_two section (the lambda content), but i can't seem to find a consistent way to identify which UNARY_NEGATIVE is referring to the one at <- the above line produces the following bytecode:
82 0 LOAD_GLOBAL 0 (ฮป)
2 LOAD_GLOBAL 1 (num_one)
4 LOAD_GLOBAL 2 (num_two)
6 CALL_FUNCTION 2
8 LOAD_GLOBAL 1 (num_one)
10 UNARY_NEGATIVE
12 LOAD_GLOBAL 2 (num_two)
14 BINARY_ADD
16 UNARY_NEGATIVE <- in this case, it is here
18 LOAD_CONST 1 (2)
20 BINARY_TRUE_DIVIDE
22 LOAD_GLOBAL 2 (num_two)
24 UNARY_NEGATIVE
26 BINARY_ADD
28 COMPARE_OP 0 (<)
30 STORE_FAST 0 (a)
though i just realised it would be way easier to force the programmer to put parentheses around the statement (so it would become ฮป (num_one, num_two) <- ((-num_one + num_two) / 2 + -num_two) in this case)
Uhh... That's not going to be easy
That probably is the best option
With parenthesis it will be easy because the UNARY_NEGATIVE in the <- will be immediately before the COMPARE_OP
yup
so i'd just need to look for
UNARY_NEGATIVE
COMPARE_OP
POP_TOP```
*or* if it's assigned to a variable,
UNARY_NEGATIVE
COMPARE_OP
STORE_FAST```
easy enough ^-^
...What if you're passing it to a function
let's see
>>> dis.dis('foo(ฮป (num_one, num_two) <- ((-num_one + num_two) / 2 + -num_two))')
1 0 LOAD_NAME 0 (foo)
2 LOAD_NAME 1 (ฮป)
4 LOAD_NAME 2 (num_one)
6 LOAD_NAME 3 (num_two)
8 CALL_FUNCTION 2
10 LOAD_NAME 2 (num_one)
12 UNARY_NEGATIVE
14 LOAD_NAME 3 (num_two)
16 BINARY_ADD
18 LOAD_CONST 0 (2)
20 BINARY_TRUE_DIVIDE
22 LOAD_NAME 3 (num_two)
24 UNARY_NEGATIVE
26 BINARY_ADD
28 UNARY_NEGATIVE
30 COMPARE_OP 0 (<)
32 CALL_FUNCTION 1 # not POP_TOP or STORE_FAST!
34 RETURN_VALUE```
so then look for CALL_FUNCTION :P
it'll either end with POP_TOP, STORE_FAST or CALL_FUNCTION
so we can check for any of those
>>> dis.dis('foo(ฮป (num_one, num_two) <- (num_one if lol(num_one < -num_two) else num_two))')
1 0 LOAD_NAME 0 (foo)
2 LOAD_NAME 1 (ฮป)
4 LOAD_NAME 2 (num_one)
6 LOAD_NAME 3 (num_two)
8 CALL_FUNCTION 2
10 LOAD_NAME 4 (lol)
12 LOAD_NAME 2 (num_one)
14 LOAD_NAME 3 (num_two)
16 UNARY_NEGATIVE
18 COMPARE_OP 0 (<)
20 CALL_FUNCTION 1 # Oh no
22 POP_JUMP_IF_FALSE 28
24 LOAD_NAME 2 (num_one)
26 JUMP_FORWARD 2 (to 30)
>> 28 LOAD_NAME 3 (num_two)
>> 30 UNARY_NEGATIVE
32 COMPARE_OP 0 (<)
34 CALL_FUNCTION 1 # This is where the lambda actually ends
36 RETURN_VALUE```
yeah, we'd still be looking for py UNARY_NEGATIVE COMPARE_OP CALL_FUNCTION
it seems like it'll always be py UNARY_NEGATIVE COMPARE_OP (POP_TOP | STORE_FAST | CALL_FUNCTION)
But what if there's a UNARY_NEGATIVE COMPARE_OP (POP_TOP | STORE_FAST | CALL_FUNCTION) in the lambda
hmm
you see, i was thinking we could look for the last occurrence on that line, but then py ฮป (num_one, num_two) <- ( num_one < -num_two )wouldn't be possible
any ideas to prevent that?
...Completely forget about doing this with Python code objects and use inspect.getsource and just do string substitution and then recompile the code instead? That's probably the easiest way
but that's boring :(
Find the LOAD_GLOBAL ฮป, then iterate through the instructions keeping track of how much the stack has changed since after the function call with the LOAD_GLOBAL ฮป
hmm
UNARY_NEGATIVE COMPARE_OP (POP_TOP | STORE_FAST | CALL_FUNCTION) is only the end of the function if the stack has changed by exactly 1
It should
how in the hell
do i get a webhook in discord to work with monday.com
i am so frustrated over this issue
i keep on getting error code 400
there is no code
its barely_python
im trying to get a webhook to work
but it keeps on spitting error code 400
that's better suited for an off-topic channel, because this channel is for things that are python but are almost not
I have this weird problem. It's game-dev related. I have a gaming map serialisation format that goes as follow:
- 32 bytes of hash
- deflated json with map data
The hash is a signature of the uncompressed json data to keep integrity.
Now I need to add some additional data into the map, by adding a header of some sort, but to keep it backwards-compatible. How do I do that without having a magic 32 bytes that tells deserialiser 'hey this is not a real hash, the header including actual hash follows'?
This is a channel for, eg, code golf
It sounds like you want one of the help channels
unless you're not working in python at all
those are python related, this one is bare algorithm problem
k, what this channel is for then?
I've read this, I meant what besides solving problems can be discussed here?
We put it way down here in the special section so it wasn't like, front and centre of our experience
Well, it's just a discussion channel, so everything related to that I guess
But since it's so specific and covers divisive topics, you won't find most of our users in here
that's why you want a help channel
k
hey guys
can someone tell me how to transfer files to a vps in windows
like can i just plug in an external drive
wouldnt you just use winscp or filezilla or something
yeah but i would really just rather use hard drive
is there some way to just let it connect
i thought i did it a year ago
WAIT
is a remote desktop connection different than a VPS?? @sick hound
yeah kinda
ohhh i'm an idiot
thanks dude
you connect to the vps through rdc
and then i can transfer files through rdc right??
maybe
ohhh
i was using vps on a chrome tab
cause Vultr gave me that
you know what i mean
@runic barn Please add a nickname which complies with our nickname policy
Your current one includes noisy unicode characters, removing those symbols from the end of your nickname will do
No problem, thank you!
it seems like people are mistaking "barely-python" to "not-python", and that's not a good
how about #python-discussion-2-why-did-it-have-to-be-snakes
for the scary side of python ๐
haha
It should be renamed #vscode-vs-pycharm
the idea being that most anything you would discuss in here would be horrifying to find in a production program
why not just generic code-gore
because then stuff like Hy and ClojurePy wouldn't fit so much into it
perhaps python-gore though
(code-gore also suggests other language-gore is allowed)
hey @sick hound
so i set up a RDP
i'm transfering like 600 mb across to a vps
in japan
and estimated time is like over an hour
is that normal
(take it to off topic y'all)
yeah you should ask that question in one of the offtopic channels maybe
but probably?
cough #community-meta
does anyone have any knowledge about the cpython implementation? haha i'm just pissing around
actually never mind i figured it out :D
>>> juan
<built-in function juan>
>>> print(juan.__doc__)
Return the base-juan representation of an integer.
>>> juan(7)
'0j1111111'
>>> juan(69)
'0j111111111111111111111111111111111111111111111111111111111111111111111'
>>>
>>> hex(12)
'0xc'
>>> bin(12)
'0b1100'
>>> juan(12)
'0j111111111111'
>>> juan(-3)
'-0j111'
>>>
my own builtin function :^)
only had to modify 3 files though
If it's builtin then it's written in C
If it was in python then it would be <function juan at 0xsomewhere>, not <built-in function juan>
This is cool
It's called base 1 though. Not base Juan, even if you named it like that ๐
Woosh
Btw, you can test whether a number in base 1 representation is a prime number using regular expressions...
although wouldn't it actually be 0s instead of 1s? that makes it so much easier, ill change it when i get home
uhh hey @vague gust look up i did a thing
@brisk zenith I got a thing you can do, build built-in s for common encryptions using the Linux kernel level crypto API
hmm
id prefer to make a module out of it because built-in python features are supposed to be cross-platform
how knows some good code golfing sites for python
def __repr__(self):
return '<built-in function juan>'
@sick hound 
haha
lul
Wait... oh
do you doubt my built-inness?
Yes
i believe it
source or it didn't happen
you need to start making PRs to get juan highlighted in the big editors though
def __eq__(self, other):
return random.choice([True, False])
Wow
idk C either, i just know a bit of C++ and became a neanderthal while i coded it
negative = PyLong_AsSsize_t(a) < 0;``` - wait, these functions are limited to C integer range?
i changed that
cause the previous one didn't work with a bit size of 0
but i should probably change it back and make a special case
>>> bin(9999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999)
'0b100101101001111010110111110001000111100001011001111001110100001110011111011001000100101011100101101001001011000110110011001001010110010111110110110110111010111001110111101110010001011011011000111010010101111111010101100000101011101010110111011101001001100011010101100011001101101101110010101100011000111110000101010101001111101011010011000011100101011000001111000010000000100011000111001111100111000101111010110000001011001000001111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111'```
interesting
@tropic gulch btw say "one" and "juan" out loud together

exit(1)
ยฏ_(ใ)_/ยฏ
0 is okay, everything else is bad.
which bad is up to the application
I don't think there are any "standard" codes common to many applications
posix has some standardised exit codes
but that applies only to Bash
other answers further down seem to confirm that there is no "global" standard meaning
I kinda feel like half this talk belongs here, I'm scared. https://www.youtube.com/watch?v=E-1Y4kSsAFc
Not even he frame hacking and that^?
Guess I truly only know half of python then.
It's useful though
oh dear
[[*x] for x in {(*y,) for y in it}]
ouch :D
it ?
Referring to what wright found
it = iterable probably
with open('settings.json') as f:
vals = json.load(f)
settings = lambda: ...
settings.__dict__.update(**vals)
Since pass doesn't work xD
just use None
pass is a statement
surely you could just have used object() or type() :P
That's true
I think object or type would have been the best, but then I couldn't post it here
def settings(): pass
I think there's a pep 8 about never assigning a lambda to a variable
Oh really?
because you should be using def instead
that's interesting
yep "Always use a def statement instead of an assignment statement that binds a lambda expression directly to an identifier."
Always use a def statement instead of an assignment statement that binds a lambda expression directly to an identifier.
Yes:
def f(x): return 2*x
No:
f = lambda x: 2*x```
I just didn't want to use the [] because my fingers were tired
Good to know. I don't do it often, but I have done it.
I.E just now
Brother shared this gem with me... https://github.com/dylanbeattie/rockstar
Midnight takes your heart and your soul
While your heart is as high as your soul
Put your heart without your soul into your heart
Give back your heart
Desire is a lovestruck ladykiller
My world is nothing
Fire is ice
Hate is water
Until my world is Desire,
Build my world up
If Midnight taking my world, Fire is nothing and Midnight taking my world, Hate is nothing
Shout "FizzBuzz!"
Take it to the top
If Midnight taking my world, Fire is nothing
Shout "Fizz!"
Take it to the top
If Midnight taking my world, Hate is nothing
Say "Buzz!"
Take it to the top
Whisper my world
And there's a transpiler for Python: https://github.com/yanorestes/rockstar-py
sweet, someone finally implemented it
from functools import reduce
dict1 = {1: (1, 2), 2: (3, 4, 5)}
dict2 = {2: (6, 7), 3: (8, 9)}
y = reduce(lambda x, y: {**x, **y},
map(
lambda k:{k:
dict1.get((k), ()) + dict2.get((k), ())
},
{**dict1, **dict2}
)
)
print(y)
Posting this here too because I wasted way too much time on this
What does that even do
merge the dictionaries
The values to be specific
non-destructive merge
Look in help channel 5
y = dict((k, dict1.get(k, ()) + dict2.get(k, ())) for k in {**dict1, **dict2})```
y = {key: dict1.get(key, ()) + dict2.get(key, ()) for key in {**dict1, **dict2}}
I did that earlier in the chat
I just wanted to see how over the top I could make it while staying on one line and not being redundant
(lambda types:types.FunctionType(types.CodeType(0, 0, 0, 3, 64, b'd\x00d\x01\x84\x00e\x00j\x01\x83\x00e\x02j\x01\x83\x00B\x00D\x00\x83\x01S\x00', (types.CodeType(1, 0, 2, 6, 67, b'i\x00|\x00]\x1e}\x01t\x00j\x01|\x01f\x00\x83\x02t\x02j\x01|\x01f\x00\x83\x02\x17\x00|\x01\x93\x02q\x04S\x00', (), ('dict1', 'get', 'dict2'), ('.0', 'k'), '', '', 1, b'\x06\x00'), ''), ('dict1', 'keys', 'dict2'), (), '', '', 1, b''),{**globals(),**locals()})())(__import__('types'))```
@crisp pendant
rediculous
moves = [
(
lambda x_offset, y_offset: (
lambda x, y: (x + x_offset, y + y_offset)
)
).__call__(x_offset, y_offset)
for x_offset in (-1, 0, 1)
for y_offset in (-1, 0, 1)
if (x_offset or y_offset)
]
fun :D
this generates a list of lambdas which can each be called to return a unique point around a given (x, y) coordinate
giving (10, 10) to each of these lambdas will return:
(9, 9)
(9, 11)
(10, 9)
(10, 10)
(10, 11)
(11, 9)
(11, 11)
except (10, 10) shouldn't be there
hmm
edited, now it gives the expected result: py (9, 9) (9, 10) (9, 11) (10, 9) (10, 11) (11, 9) (11, 10) (11, 11)
I'm thinking of another term for clearing a bit i.e. setting it to 0. Can anyone remind me? All I remember is that it was a bit unintuitive of a word because outside of programming, it had a different but related meaning
@whole kiln I've sometimes seen "reset" used for it
Thanks, but I'm sure that's not what I was thinking of
going to try to look in the assembly book I read it in
god knows which chapter its in
I was thinking of assert
and it means the opposite
setting the value to one
what means the opposite?
Initially I thought the word I was thinking of meant to set something to 0
But I found that I was thinking of 'assert', and it means setting something to 1
ah i see, but i can't say I've heard that meaning of assert myself
Yeah, I was confused at first too
From the book:
As a rule, computers read memory much more slowly than they access internal registers. This is
because reading a single value from memory involves four separate steps:
1. Place the address of the value you want to read on the address bus.
2. Assert (change the value of) the processorโs RD
(read)
pin.
3. Wait one clock cycle for the memory chips to respond.
4. Copy the data from the data bus into the destination operand.```
oh i see, interesting
When I think of assert, I think of test cases
the definition doesn't line up with that
Cause for test cases it's a check rather than changing any value
yeah when i was trying z80 asm (for my calculators lol) i remember the terms "set" and "reset" being used, nothing else
oh no but we've fallen into the "not python" trap
base one is so epic
def likes(names):
return {
len(names) == 0: "no one likes this",
len(names) == 1: "%s likes this",
len(names) == 2: "%s and %s like this",
len(names) >= 3: "%s, %s and %s like this"
}[True] % tuple(
names if len(names) <= 3
else names[:2] + ["%d others" % (len(names) - 2)]
)
codewars? more like codegores :^)
(i was forced to use 2.7 for this, that's the real code gore haha)
what in gods name
welcome to #esoteric-python, where code goes to die.
fortunately/unfortunately I don't think I have any OC code gore ๐ฆ
maybe if I consider my tendency to write one-liners when I was starting out
yeah... py return list(map(lambda m: Exchange.Market( m["MarketName"], Exchange.Currency( m["MarketCurrency"], m["MarketCurrencyLong"], None), Exchange.Currency( m["BaseCurrency"], m["BaseCurrencyLong"], None), None), markets))
:D
I have a worse one py return next((Exchange.Currency(symbol, name, precision) for symbol, name, precision in g.db.cursor.fetchall() if re.search((name if g.config["search_currency_name"] else "") + r"\s*?[(\[{]+?\s*?" + symbol + r"\s*?[)\]}]", text, re.IGNORECASE)), None)
that's it from me
ooh regex gore :^)
let's face it, all regex is gore
How about RFC 822?
is that the email one
yeah looks great, I would take it on a dinner date we could have sex
jk it makes me want to kill people.
comment from SO:
The regular expression to validate email addresses (possibly multiple in to:, cc: and bcc: form) (from RFC 822) is pretty beefy; definitely the longest non-trivial regular expression that I have seen. Unfortunately, it seems that there are a lot of sites out there on the internet that do not use this regular expression or an equivalent validation as I have encountered far too many sites that do not accept myemailaddress+yourstupidsite@gmail.com as a valid email address.
the regex to validate a single proper email address is much shorter
people latched onto the fact that the grammar element that one validates is called "address" whereas the one normal people think of as an email address is called "addr-spec"
just like the HTML tag regex parsing thing, people jumped to do "I don't feel like you should be using a regex for this, so I'll just make up whatever reason why it's 'impossible' without regard to accuracy"
i use regex for parsing html when i'm too lazy to set up a venv/pipenv lmao
regex for an addr-spec is only a few hundred characters long.
(addr-spec in RFC 822/5322, mailbox in RFC 821/5321)
anyone know how to get a mongo.py to appear in a terminal window from a tmux
tmux new -s mongod -d "/bin/bash"
tmux new -s mongo -d "/bin/bash"
tmux new -s gui -d "/bin/bash"
tmux new -s controller -d "/bin/bash"
#tmux new -s plot -d "/bin/bash"
#tmux new -s plot2 -d "/bin/bash"
tmux run-shell -t "mongod" "mongod"&
tmux run-shell -t "mongo" "python /home/pi/Desktop/EmbeddedFlaskServer/mongo.py"&
#tmux attach -t mongo
sleep 2
#tmux run-shell -t "plot" "python /home/pi/Desktop/EmbeddedFlaskServer/plotPID.py"&
#tmux run-shell -t "plot2" "python /home/pi/Desktop/EmbeddedFlaskServer/plotPID2.py"&
tmux run-shell -t "controller" "python /home/pi/Desktop/EmbeddedFlaskServer/controller.py"&
tmux run-shell -t "gui" "python /home/pi/Desktop/EmbeddedFlaskServer/gui.py"
tmux run-shell -t "gui" "python /home/pi/Desktop/EmbeddedFlaskServer/stop.py"
pkill -f controller.py
pkill -f mongo.py
mongod --shutdown
tmux kill-server```
mongo runs but doesnt appear when you attach to the mongo window
and doesnt show in jobs or bg
ask in a help channel, @coral plank
or in one of the general-programming servers actually
was told its not directly python related
oh lol
which channel should i ask or maybe a server recommendation but the programming discord is useless
Probably off topic channels?
print(f"That's {input('How are you?: ')}" if not print(f'Hello, {input("What is your name?: ")}') else "")
Has anyone seen http://onelinepy.herokuapp.com/ ?
Change any python code into one line by abusing lambdas
ooh yeah i saw that once, really interesting. i don't think it can handle async yet though
writing those single-line python apps manually is a lot of fun
it's like writing functionally
(lambda __g: [None for __g['f'], f.name in [(lambda x: (lambda __l: [(__l['x'] * 4) for __l['x'] in [(x)]][0])({}), 'f')]][0])(globals())
hi
i have a question a bit unrelated to python
if someone could answer me please
In one of the ot channels. #ot0-psvmโs-eternal-disapproval #ot1-perplexing-regexing or #ot2-never-nesterโs-nightmare
it doesn't cover - at least, so yeah, it will fail on many common addresses. also . is any character in regex, unless escaped
i wrote a program to generate the proper regex for validating an email addr-spec
atext = '[-0-9A-Z!#-\'*+/=?^-~]' # Lowercase included in ^-~
atom = atext + '+'
dot_atom = atom + '(?:\\.' + atom + ')*'
# RFC 822 allowed quoted-strings in place of atoms
qtext = '[] !#-[^-~]'
qpair = '\\\\[ -~]'
qcontent = '(?:' + qtext + '|' + qpair + ')'
quoted_string = '"' + qcontent + '*"'
# RFC 5321 and 5322 differ on the semantics of whitespace within quoted-strings
let_dig = '[0-9A-Za-z]'
ldh_str = '[-0-9A-Za-z]*' + let_dig
subdomain = let_dig + '(?:' + ldh_str + ')?'
dot_domain = subdomain + '(?:\.' + subdomain + ')*'
# dot_domain = dot_atom in RFC 5322
dtext = '[]!#-[^-~]'
domain_literal = '\\[[^' + dtext + '*\\]'
# RFC 5321 requires valid IP address here
local_part = '(' + dot_atom + '|' + quoted_string + ')'
domain = '(' + dot_domain + '|' + domain_literal + ')'
addr_spec = local_part + '@' + domain
# (
# [-0-9A-Z!#-'*+/=?^-~]+(?:\.[-0-9A-Z!#-'*+/=?^-~]+)*
# |
# "(?:[] !#-[^-~]|\\[ -~])*"
# )@(
# [0-9A-Za-z](?:[-0-9A-Za-z]*[0-9A-Za-z])?(?:\.[0-9A-Za-z](?:[-0-9A-Za-z]*[0-9A-Za-z])?)*
# |
# \[[^[]!#-[^-~]*\]
# )
# Total 188 characters```
some regex gore/porn
private static readonly Regex _Regex = new Regex(
@"(?:{field}(?<fname>.*?)\{\}(?<fvalue>.*?)(?:\{\}(?<finline>.*?))?(?=$|{(?:field|author name|author icon|author url|thumbnail|title|url|color|description|image|footer text|footer icon|submit)}))|{(?<action>author name|author icon|author url|thumbnail|title|url|color|description|image|footer text|footer icon|submit)}(?<value>.*?)(?=$|{(?:field|author name|author icon|author url|thumbnail|title|url|color|description|image|footer text|footer icon|submit)})",
RegexOptions.Compiled | RegexOptions.CultureInvariant | RegexOptions.IgnoreCase);```
not even python ๐ :D
Is that for an embed?
yeah
was originally implemented with pretty ugly code
i did my best at the time to improve it
It's so barely python it's not even written in python
just remove the top and bottom and no one will know the difference ๐
@brave bison py os = __builtins__.__getattribute__('__import__').__call__('os') i = ("this is even more descriptive",).__getattribute__('__iter__').__call__() s = '' while True: try: s = s.__getattribute__('__add__').__call__(i.__getattribute__('__next__').__call__().__getattribute__('__str__').__call__()) s = s.__getattribute__('__add__').__call__(' ') except __builtins__.__getattribute__('StopIteration'): break s += '\n' os.__getattribute__('write').__call__(1, s.encode())
thats not what i wrote
mine was 1 line
that code is not yours
that code is mine
and I wrote it
you did not write it
you are not me
ill make it more barely python
(lambda __operator, __g, __contextlib, __y: [[[(lambda __after: __y(lambda __this: lambda: (lambda __break: (lambda __out: (lambda __ctx: [__ctx.__enter__(), __ctx.__exit__(None, None, None), __out[0](lambda: __this())][2])(__contextlib.nested(type('except', (), {'__enter__': lambda self: None, '__exit__': lambda __self, __exctype, __value, __traceback: __exctype is not None and (issubclass(__exctype, __builtins__.__getattribute__('StopIteration')) and [True for __out[0] in [(__break())]][0])})(), type('try', (), {'__enter__': lambda self: None, '__exit__': lambda __self, __exctype, __value, __traceback: [False for __out[0] in [([[(lambda __after: __after()) for __g['s'] in [(s.__getattribute__('__add__').__call__(' '))]][0] for __g['s'] in [(s.__getattribute__('__add__').__call__(i.__getattribute__('__next__').__call__().__getattribute__('__str__').__call__()))]][0])]][0]})())))([None]))(__after) if True else __after())())(lambda: [(os.__getattribute__('write').__call__(1, s.encode()), None)[1] for __g['s'] in [(__operator.iadd(__g['s'], '\n'))]][0]) for __g['s'] in [('')]][0] for __g['i'] in [(('this is even more descriptive',).__getattribute__('__iter__').__call__())]][0] for __g['os'] in [(__builtins__.__getattribute__('__import__').__call__('os'))]][0])(__import__('operator', level=0), globals(), __import__('contextlib', level=0), (lambda f: (lambda x: x(x))(lambda y: f(lambda: y(y)()))))
its a one liner now
how did you do that?
with this one liner that converts a script into a 1 liner
oh too big for discord
this is the true power of python
(lambda f:f(f))(lambda y:lambda f:lambda:f(y(y)(f)))(lambda f:lambda n:f()(n-1)*n if n else 1)()```
This is factorial
I think this counts as barely python https://github.com/kragniz/anyprint
i like the testimonials
probably the only good bit
juan supports that too
@brisk zenith someone was faster than you ๐
oof
but does it support it with std:: ?
Nope, there's actually an open issue asking for that
I don't see how it'd work bc syntax error
yup
rip my hopes and dreams
thought i should ask a question here about the julia language
anybody know if it's worth learning or worth my time
apparently it's easy like python but fast like C
this channel is for sharing bad python code
I guess yes
it's not limited to that
ok thanks
np
@next linden it's a maths language essentially
Meant as a glorified matrix calculator
@tight hemlock does it make web apps easier to make?
oi, off-topic
hey, i'm trying to convert binary to text. i've got def binary(text): ''.join(format(ord(i), 'b') for i in text) to convert it to binary but i do not have an idea how to reverse this process. the SO has answers including very long solutions using other modules etc. someone able to write a short converter?
No way to reverse it unless you pad them
And then split the binary into chunks
and decode those
Though idk why you're in this channel
moved to #help-chestnut i guess.
But yeah, your formatting there is irreversible because the binary representations of each character in text can have variable length and boundaries are not detectable.
oh ok ;')
!kick vortex962
Need a hand?
while int('%(foo)s' % {'foo': 2}) + int('%(bar)s' % {'bar': 2}) == int('%(foo)s' % {'foo': 2}) * int('%(bar)s' % {'bar': 2}):
print("".join([chr(i) for i in [int('%(foo)s' % {'foo': 9}) * int('%(bar)s' % {'bar': 8}),int('%(foo)s' % {'foo': 10}) * int('%(bar)s' % {'bar': 10}) + int('%(foo)s' % {'foo': 1}),int('%(foo)s' % {'foo': 9}) * int('%(bar)s' % {'bar': 12}),int('%(foo)s' % {'foo': 9}) * int('%(bar)s' % {'bar': 12}), int('%(foo)s' % {'foo': 11}) * int('%(bar)s' % {'bar': 10}) + int('%(foo)s' % {'foo': 1}), int('%(foo)s' % {'foo': 8}) * int('%(bar)s' % {'bar': 4}),int('%(foo)s' % {'foo': 11}) * int('%(bar)s' % {'bar': 8}) - int('%(foo)s' % {'foo': 1}),int('%(foo)s' % {'foo': 11}) * int('%(bar)s' % {'bar': 10}) + int('%(foo)s' % {'foo': 1}),int('%(foo)s' % {'foo': 11}) * int('%(bar)s' % {'bar': 10}) + int('%(foo)s' % {'foo': 4}),int('%(foo)s' % {'foo': 9}) * int('%(bar)s' % {'bar': 12}),int('%(foo)s' % {'foo': 10}) * int('%(bar)s' % {'bar': 10}),int('%(foo)s' % {'foo': 8}) * int('%(bar)s' % {'bar': 4}) + int('%(foo)s' % {'foo': 1}),] ]))
break
https://paste.pythondiscord.com/ihujivecot.py also super barely python version
which can be easily made even worse
bytes([(True << (True ^ True << True) ^ True << (True << True ^ True << (True << True))), (True ^ True << (True << True) ^ True << (True ^ True << (True << True)) ^ True << (True << True ^ True << (True << True))), (True << (True << True) ^ True << (True ^ True << True) ^ True << (True ^ True << (True << True)) ^ True << (True << True ^ True << (True << True))), (True << (True << True) ^ True << (True ^ True << True) ^ True << (True ^ True << (True << True)) ^ True << (True << True ^ True << (True << True))), (True ^ True << True ^ True << (True << True) ^ True << (True ^ True << True) ^ True << (True ^ True << (True << True)) ^ True << (True << True ^ True << (True << True))), (True << (True << True) ^ True << (True ^ True << True) ^ True << (True ^ True << (True << True))), (True << (True ^ True << (True << True))), (True ^ True << True ^ True << (True << True) ^ True << (True << (True << True)) ^ True << (True ^ True << (True << True)) ^ True << (True << True ^ True << (True << True))), (True ^ True << True ^ True << (True << True) ^ True << (True ^ True << True) ^ True << (True ^ True << (True << True)) ^ True << (True << True ^ True << (True << True))), (True << True ^ True << (True << (True << True)) ^ True << (True ^ True << (True << True)) ^ True << (True << True ^ True << (True << True))), (True << (True << True) ^ True << (True ^ True << True) ^ True << (True ^ True << (True << True)) ^ True << (True << True ^ True << (True << True))), (True << (True << True) ^ True << (True ^ True << (True << True)) ^ True << (True << True ^ True << (True << True))), (True ^ True << (True ^ True << (True << True)))]).decode()
(shamelessly stolen from @brisk zenith)
haha, that's something i made on my first day on this server. good fun
Doing various challenges on hackerrank. Came across a regex one that had me stumped for like 10 min
the solution was nested lookaheads
I needed to find digits that alternate
(?P<d>\d)(?=\d(?=(?P=d)))
huuuuuuuhh?
๐
basically check if the digit 2 places past the current digit is the same as the current digit
๐ค
?
I mean sure it works, and it's quite elegant once you know what the hell you are doing there, but
the wtf is strong in this one
ยฏ_(ใ)_/ยฏ
it's only that bad cause I am not allowed to modify the code that calls the regex
initially I didn't have a nested lookahead
I just did (?P<d>\d)\d(?=(?P=d))
but re.findall returns non-overlapping matches
so I had to make sure only one char was being matched
otherwise it would not process every second character
*
