#esoteric-python
1 messages ยท Page 143 of 1
restricting that radius for red, more than green, more than blue, as is the pattern consistent with a focal point in front of the retina instead of on it.
The code for it is ironically the code in above screenshot
me: I coded something hard to read!
the code:
If the definition of obfuscated code is code that is deliberately hard to read, then I think putting a short-sightedness filter over the code counts, right?
pain
What is that
Ok will share a few moar python generated art then an esoteric pure python 2D /3D Library I made
That is pure python no libraries...
No classes all functional
Made my own bitmap fonts
Made my own graphics library from pixel addressing to 2D primitives like line , circle, etc
To 3D projection to 2D with hidden surface removal and shading
Made my own lin alg lib
damn
I think I promised to share this here months ago lol better late than never
also these circles up there look really cool
Esoteric Math
Mix of sines and cosines then I deform
oh its not actual gpu drawing? got me excited
Yes pure CPU...sorry for late reply was sleeping...
I created an in memory byte array that serves as a virtual video buffer that has the byte layout that matches a mono, 16 color , 256 color or RGB windows bitmap with variable size...that I made addressible with bit or byte based operations via my own pixel routine...then built up from there ....
I wonder how fast it is?
I profiled it pretty fast most operations take less than a second
But it isnt real time and output is to memory then file totally bypassing the GPU lol
Ok a full set of tests done in 5 sec
Outputs the test bmp shown previously in which I tried to cram in most of the features lol...has 2D and 3D
BTW done on a i7 laptop with a naked board I need a new one
I short the pins to turn it on lol
Estoteric bare board laptop computing lol
I can also do filters, image resize, outline etc with the library ...it is there but I havent checked in the image manipulation unit tests
Why is the pcb naked
Power switch no longer work and keyboard keys broke too
What model?
@rapid sparrow :white_check_mark: Your eval job has completed with return code 0.
utf-8
Old ASUS i7 probably buy a new one ...like the bare board ....cpu fan ded too ...
Bare board dont overheat lol
There is also a heat sink from an old laptop i slipped below
Did someone nuke your laptop?
I did to make it useful...fan broke. Power Switch broke in middle of Covid lol
Macgyver
So i removed all broken parts and retained what is essential...Zen
sorry took me a day https://paste.pythondiscord.com/qerowuxuxi, that code is incompatible with this program
what's the domain and range of the mandelbrot fractal?
well, the interesting parts of it, at least
This is an encrypted message.
[2240738, 5573346, 1449296, 4889873, 1828324, 4274806, 4841102, 4607466, 3890048, 5126385, 420300, 2687704, 1255302, 2727331, 813057, 2034996, 1788130, 1124028, 580034, 2031250, 5514529, 5534410, 187413, 5387283, 2443965, 4789045, 70840, 323349, 327840, 4990935, 4813300, 2292617, 756145, 2113802, 2673823, 5544930, 1088033, 1619516, 4902911, 4273008, 274757, 2571054, 3443850, 3954383, 4213766, 3136367, 1315753, 139190, 3926698, 1756197, 4093664, 822713, 3623924, 4306893, 4627029, 4387294, 2417394, 4490347, 1262744, 4135132, 1758104, 3652352, 2826844, 4154119, 4203715, 2112125, 2580893, 5127401, 2909679, 2545234, 4337444, 1103112, 5212413, 3574240, 3579850, 4291504, 3940594, 4091867, 329468, 271258, 1558640, 835649, 4886917, 5344415, 3710410, 3583840, 1083078, 4851517, 1604477, 2262315, 3745322, 1071431, 3014282, 2267304, 2688016, 1744634, 2680341, 5334260, 2916342, 3207715, 198719, 2069901, 2676107, 1722937, 2795632, 1015599, 65964, 3888581, 4251997, 5054434, 301474, 5410911, 1193709, 5452445, 1031311, 2683125, 892396, 824137, 4243221, 4871888, 1232370, 4558140, 3307947, 4561688, 588931, 913729, 1131667, 2931906, 3977081, 1817868, 3134927, 4364988, 2969286, 2671041, 1937563, 495556, 1385182]
This is the decryption method
def generate(seed:int,key:int):return''.join([*loadbar((*map(lambda x:int(x)<<1,str(seed)),),lambda x:str(x**key))]).strip('0')
def intfuck(c:list[int]):
a=__import__("collections").defaultdict(int)
i=p=t=0
def add(i):
a[i]=(a[i]+1)%256
return i,0
def sub(i):
a[i]=(a[i]-1)%256
return i,0
def left(i):return i-1,0
def rite(i):return i+1,0
def dot(i):
print(end=chr(a[i]))
return i,0
def com(i):
a[i]=ord(__import__('sys').stdin.read(1))
return i,0
def loop(i):
return i,not a[i]
def end(i):
return i,-bool(a[i])
while 0<=p and p<len(c):
if t:t+=(c[p]==7)-(c[p]==8)
else:i,t=[add,sub,left,rite,dot,com,loop,end,lambda i:(i,0)][int(''.join(map(str,range(8))).find(str(c[p]-1)))](i)
p+=1-2*(t<0)
return int(bool(t))
def decrypt(array:list,seed:int,key:int):
print("generating...")
abstract_integer = generate(seed,key)
print("decrypting...")
del key
numbers = [int(abstract_integer[int(this)])for this in array]
return[intfuck(numbers),print("decryption complete.")][0]
Approximately how long is it likely to take to decrypt the message?
mandelparamdict(): return {'maxdefault':(1.75,-1.75,1.5,-1.5),'maxeqdim':(1.75,-1.75,1.75,-1.75),'middefault':(.75,-1.25,1.25,-1.25),'mindefault':(.75,-.75,.5,-.5),'mineqdim':(.5,-.5,.5,-.5),'custom1':(-.5,-.7,-.5,-.7)}
the os module is missing an important implementation
rmdir with the /s flag
although I guess that's to stop noobs from shooting themselves in the foot
but it's still annoying
Yes shooting one self in the foot is a common programmer joke
now I have to make an object s with a __rtruediv__ method that is a wrapper on an os method
the reason we're stuck with the walrus is just so this is invalid syntax
a = 1
while a = 1:
if input('q to quit>')=='q':
a = 0
The reason we can't
def destroy_dir(dir):
import os
os.rmdir(dir, recursive=True)
is rather obvious, but still annoys me
I'm gonna have to implement recursive
just for a decryption project ๐คฆ
!d shutil.rmtree
shutil.rmtree(path, ignore_errors=False, onerror=None)```
Delete an entire directory tree; *path* must point to a directory (but not a symbolic link to a directory). If *ignore\_errors* is true, errors resulting from failed removals will be ignored; if false or omitted, such errors are handled by calling a handler specified by *onerror* or, if that is omitted, they raise an exception.
I already made the s object
@type.__call__
class s:
def __rtruediv__(self, other):
def inner(dir, *, _rec=0>0):
try:other(dir)
except NotADirectoryError as e:
if _rec:os.remove(dir)
else:raise e
except OSError:
for entry in os.listdir(dir):
try:os.remove(entry)
except:inner(dir+os.sep+entry,_rec=1>0)
other(dir)
return inner
(os.rmdir /s)("dir_name")
i used x=-2 to 0.47 and y=-1.12 to 1.12 for my visualization
or, around there for shorter code :P
I prefer to round to
x in (-2, 0.5)
y in (-1, 1)
Round up rather than down then at least
I don't see anything happening on the imag axis further than 1 unit away
(as-> #@(bot.event (defn/a on_ready [] (print "Logged in as" bot.user))) on_ready
(-> ace.events
(.update {"on_ready" on_ready})))
(as-> #@(bot.event (defn/a on_command_error [ctx exception] (.error log exception))) on_command_error
(-> ace.events
(.update {"on_command_error" on_command_error})))```
i like this so much
there's no such channel for this topic so idk
compiles into ```py
@bot.event async def on_ready():
return print('Logged in as', bot.user)
on_ready = ace.events.update({'on_ready': on_ready})
@bot.event async def on_command_error(ctx, exception):
return log.error(exception) on_command_error = ace.events.update({'on_command_error': on_command_error})
with for loop
(for [(, name event) (zip ["on_ready" "on_command_error"]
[(fn/a [] (print "Logged in as" bot.user))
(fn/a [ctx exception] (.error log exception))])]
(-> ace.events
(.update {name event})))```
compiled
async def _hy_anon_var_1():
return print('Logged in as', bot.user)
async def _hy_anon_var_2(ctx, exception):
return log.error(exception)
for (name, event) in zip(['on_ready', 'on_command_error'], [_hy_anon_var_1, _hy_anon_var_2]):
ace.events.update({name: event})```
whats this language?
iโm working on a bot that reads json responses and most of the responses are in jeff:jeff2 format and i want to only jeff2 part and if it doesnt have a jeff2 part so only a jeff part i want to skip ig
What is "hy"?
hylang
basically just language created with ply (or sly)
i'm wondering where IFcoltransG went and why isn't he active any more
Maybe he is busy
Nooooooooooo
yessssssssssss
Yes
I want to make a float that doesn't float.
but can still execute float operations
including complex numbers
only need rational floats
although 1/3 might be a bit difficult
what if I stored rational floats as exact value integer fractions?
but then the mathematical algorithms to apply float operations...
!doc fractions.Fraction
class fractions.Fraction(numerator=0, denominator=1)``````py
class fractions.Fraction(other_fraction)``````py
class fractions.Fraction(float)```
that's what I need
does anyone have any advice on grabbing data from output of cli tools like xrandr and xinput that is more approachable than using basic string manipulation and line reading techniques?
i'll give you an example of the kind of thing i'm fucking sick of having to write at this point
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
like, spending an entire afternoon just writing sections of code like that is torture
there comes a point where pep8 makes things harder to read, and I think you found that point
you use imports for a cli?
you use tools?
bro I have minesweeper where the only tools I use are msvcrt.kbhit and msvcrt.getch and random.choice and time.time. Maybe itertools.product.
and all of those I make fit into my design, not the other way around.
you do mean command line interface when you say cli, right?
oh yeah i forgot uh
that isn't actually including the code where it GETS the data haha
if you're gonna talk about stuff like xrandr and xinput, preferably link to an explanation so we don't have to research and/or guess what you mean
i'm just using subprocess and reading from stdout
what's wrong with input()?
xrandr is a cli tool used to get information about the current X screen and connected X displays, xinput is a cli tool used to get information about connected input devices like keyboards and mice and their properties
primarily they're intended for interactive use
riiiiiiight.
my minesweeper game is very interactive, you use wasd keys to move a cursor around to select the squares
anyone who gonna use a cli aint the type of person who would use the mouse
here's an example of the sort of output i have to grab data from
xrandr --listmonitors Monitors: 3 0: +*DVI-I-1 1920/518x1200/324+1280+0 DVI-I-1 1: +DP-5 1280/376x1024/301+0+0 DP-5 2: +HDMI-0 1280/339x720/190+3200+0 HDMI-0
I just play around with the terminal instance hosting my script, and I use ANSI escape sequences to do that
it's a pain in the ass
what i'm writing is a gui app that sets the input dimensions for drawing tablets, so you can set the tablet cursor to be confined to the size of a monitor
didn't you say cli before? now you're making a gui
it uses cli tools to gather data about the system
why do you need to use these specific ones?
especially in this channel, the idea is to think outside of the box
it's just kind of how you do a lot of things when scripting using linux
mmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm
the reason is that xinput and xrandr are both tools that will be installed on basically any desktop linux setup my app is intended for and i don't have to worry about native code at all
both heavily documented and relied upon
it won't be installed on windows desktops
probably not macos either
although macOS doesn't really count
i don't really know of any other way get information about x displays and x input devices using python at the time being. also no, it is exclusively a tool for configuring drawing tablets on systems using X
there is no need for it on windows or mac os
why do you need to configure drawing tablets on systems using X?
because there aren't any existing graphical apps to do the task when it comes to X
make a graphical app to do the task, then.
then a graphical app would exist, thus solving your problem
just to setup the dimensions your drawing tablet is active in in relation to your monitors, you have to spend 30 minutes to an hour researching which configuration files you have to configure, calculate the transformation matrix, and either modify the x config file or use xinput to set it non-permanently constantly
that's what i'm doing
the app has to grab information about the currently active X displays and the attached input devices and the easiest way to do that it using the cli tools xrandr and xinput, at least as far as i'm aware. you run those applications as subprocesses and grab and interpret the output in the python app
just as you might have a gui app that has to make and interpret database calls; there are all sorts of different sources you can use for data
This is an extremely specialist topic, and unfortunately for you, it appears you are the highest authority on this topic currently present.
as for string reading, I'm assuming your python script takes as input the output of the xrandr command?
there does appear to be patterns in these lines
yeah basically it reads the output of stdout, which is generally multiple lines of text
ok
i was just wondering if anyone knew of any tools to make picking out data from lines of text easier than
umm i need to know what these numbers and abbreviations mean
having to do it manually using just the basic string manipulation functions
it's just for display
what's the difference between the second attribute and the last attribute?
other than the prefix of +?
that's the thing; this stuff is formatted for reading, not as a data structure
why it lists the name of each monitor twice i don't know
I know, but it can still be used to build a dataclass
what are the plus-separated values after the last forward-slash mean?
I can't discern their meaning straight from context
I'm gonna give them some dummy name for now
what line?
all of them have it in the example
it's something like, (x resolution)/(x physical width)x(y resolution)/(y physical height)+(x offset)+(y offset)
that's my understanding anyway
well that doesn't make sense i assumed the middle axb would be a is screen width, b is screen height and the first value in the forward slash separated series is corner-to-corner size
the offset being the displays offset in pixels from the virtual desktop's 0,0 starting coordinate
in the case of a/bxc/d+e+f , b is the physical width in millimeters
it's not a mathematical formula or anything
it's just formatted output
er, formatted data
This is the sort of dataclass I can build from that input (untested)
import attr
@attr.s
class Monitor:
"""default values are example values"""
id:int = attr.ib(2)
monitor_name:str = attr.ib("HDMI-0")
monitor_identifier:str = attr.ib("+HDMI-0")
resolution:tuple[int,int]=attr.ib((1280,720))
size:tuple[int,int] attr.ib((339,190))
offset:tuple[int,int]=attr.ib((3200,0))
n = int(input().partition(': ')[2])
monitors = []
for i in range(n):
line = input().lstrip().split(' ')[1:]
mon_id, yay, name = line
width, this, that = yay.split('/')
x, height = this.split('x')
y, *o = that.split('+')
monitors += [Monitor(i, name, mon_id, (x, y), (width, height), o)]
refactor at will
oh wait gotta store these instances somewhere
interesting
assuming stdin is piped
oh that's from attr ok. i was like "what is that"
boilerplate avoidance
yeah
you likey?
oh wait
I just found a fatal flaw in my script
I forgot to do typing
i don't know yet if you'll use that way of writing it but i'm certainly learning a lot just from reading through it and looking up the stuff i don't know/hadn't considered so thanks
import attr
@attr.s
class Monitor:
"""default values are example values"""
id:int = attr.ib(2)
monitor_name:str = attr.ib("HDMI-0")
monitor_identifier:str = attr.ib("+HDMI-0")
resolution:tuple[int,int]=attr.ib((1280,720))
size:tuple[int,int] attr.ib((339,190))
offset:tuple[int,int]=attr.ib((3200,0))
n = int(input().partition(': ')[2])
monitors = []
for i in range(n):
mon_id, yay, name = input().lstrip().split(' ')[1:]
width, this, that = yay.split('/')
x, height = this.split('x')
y, *o = map(int,that.split('+'))
monitors += [Monitor(i, name, mon_id, (int(x), int(y)), (int(width), int(height)), o]
correctly typed this time(hopefully)
it's certainly a lot more compact
I don't like scrolling unless the code has significant size
in this compact form, I can non-linearly analyse the code
right
Ah yes accessing the display buffer
ah yes, interrogating the display for its personal information
honestly, reading and writing to buffers is easier than text manipulation stuff imo lmao
to image/screen buffers i mean
to me, 'buffer' describes the Rock compared to Elon Musk.
The Rock is very buff. much buffer than Elon.
More efficient if you can do that
I might've gotten resolution and size the wrong way around, whoops
but refactor at will, as I said earlier
thanks!
"The Frame Buffer Device API โ The Linux Kernel documentation" https://www.kernel.org/doc/html/latest/fb/api.html
Because display buffer is moar predictable than text formats lol
for some reason it only works horizontally XD
nvm it doesn't work properly in any direction I algorithmed wrong
and I think using ctypes to mutate the cell into its parent class is why it's randomly crashing without an error message
it works now.
I have come to bleed my eyes
Beautiful
why are you fetching monitor information for a CLI game?
apparently, cli tools are being used for a gui
so close...
wait
I had a valid move still
what's so confusing about not a or not b or a==b for x in self.matrix for a, b in (x[:2],x[1:3],x[2:]) that python cannot understand?
a.value==b.value might work better
and ```py
print ('\x1b[H\x1bc')
works really great to reinitialise the terminal.
how are u rendering these colors?
ansi escape code ig
o damn cool stuff
esoteric source pls ๐ฅบ

any way I could make my own images with just an rgb code? I'd just like to generate a 32x32 image that's purely one singular color without 3rd party dependencies. I don't care about any metadata or filetype, it just needs to be renderable in a web browser
why not just to that in html and css?
I don't actually have access to any html or css, the api just forces me to send image data
Lol my library might help
I previously used PIL but that's an extra dependency for no reason
damn mate, where the structure at
<svg width="32" height="32">
<rect width="32" height="32" style="fill:rgb(0,0,255)"/>
</svg>
use svg?
hm
Lots of things there have to trim it down lol
mx=1024 my=768 bmp=b.newBMP(mx,my,24)
How to make an in memory bmp
yeah idk mate. At that point I could just keep PIL
also no offense but this isn't a lib I'd want to have in my dependencies tbh
No worries lol and yeah i understand
I can write custom code that will solve your issue thou one python file no dependencies
But it is lafe night here and I have to sleep...it will still be a bitmap
I wonder if it even supports bitmaps tbh
like I was hoping to somehow figure out how tf to make a png or jpg
Is that for a favicon?
an api requires raw image data to display an image
gif should probs work too but idk if it's harder
And compression
Use library if you want those formats
I can work at it but not for gratis lol
i figured a cool "trick" with context managers that abuses sys._getframe
!e
from sys import _getframe
class AssignmentTracker:
def __enter__(self):
self._fr1 = _getframe(1)
self._fr1_orig = dict(self._fr1.f_locals)
def __exit__(self, *err):
self.changed = {
k:v for k,v in self._fr1.f_locals.items()
if k not in self._fr1_orig
or self._fr1_orig[k] is not v
}
print(f"New or changed variables: {self.changed}")
with AssignmentTracker():
name = "John"
import random
age = random.randint(1, 50)
print(f"{name}'s age is {age}")```
@rapid sparrow :white_check_mark: Your eval job has completed with return code 0.
001 | John's age is 47
002 | New or changed variables: {'name': 'John', 'random': <module 'random' from '/usr/local/lib/python3.10/random.py'>, 'age': 47}
there is a framework that uses this kind of "with block" to accomplish a similar outcome
but I doubt they are doing it with frames
it's like
with model:
n = 3
a = 7
b = (2, 6)
assert model.n == 3
assert model.a == 7
assert model.b == (2,6)
how would you do that ?
maybe custom globals with context manager?
interesting - how would that work?
fatal helped me alot when i was writing brainfuck interpreter, custom globals were used to make it work
give me a sec
you basically need to add if or match check and then check if requested name == "model" or something else
hey guys, I was wondering
what happens when you do a = 2, where does the 2 go in terms of Python?
If I do __builtins__ = None then I can't use any pre-existing function or variable, but then if I do a = 2 it works and I can access it : a yields 2
I'd assume they go in locals / globals. They still do but it's just I don't have access to it anymore since my "locals" string can't resolve to the actual object through __builtins__?
How would I go about still somehow accessing locals or globals, or wherever variables are?
(don't hesitate to ping me)
2 is int literal
you cant change behaviour of literals
2 always means instance if int type
when you do __builtins__ = None, you dont delete all builtin types and objects, you just remove reference to builtins.__dict__
!e
__builtins__ = type('',(),{'__getitem__':print})()
a
b
c
hello_world
@fleet bridge :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 2, in <module>
003 | NameError: name 'a' is not defined
!e python print(" ".join([chr(i) for i in range(65, 65 + 26)]).strip(" "))
@upbeat sonnet :white_check_mark: Your eval job has completed with return code 0.
A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
๐โโ๏ธ
!e
print(' '.join(map(chr,range(65,91))))
@fleet bridge :white_check_mark: Your eval job has completed with return code 0.
A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
pro
!e ```py
print(*map(chr,range(65,91)),sep=' ')
@noble nexus :white_check_mark: Your eval job has completed with return code 0.
A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
one char less ๐
nice
king fr fr
I still don't know how to monkey my way around a __builtins__ = None though ๐
(I can't write __ :kappa:)
what is the * operator
unpacking
well I think it has some other weird official name
>>> int
<class 'int'>
>>> __builtins__ = None
>>> int
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'NoneType' object is not subscriptable
>>> del __builtins__
>>> int
<class 'int'>
yeah but you used __
๐
I know, I have weird problems
copy this: __ every time you need to write this
there are other various conditions, sadly
can't import stuff (like ctypes)
nice
I'm also interested if you have some convoluted way to set a read-only attribute ๐
desperate
change __setattr__
yeah but you used __ ๐

hehehe
!e use this to create function names
dunder = dir(0)[0][:2]
print(dunder)
@fleet bridge :white_check_mark: Your eval job has completed with return code 0.
__
yeah but you can't call dir with builtins = None ๐
sorry that's a really tough setting don't bother
so we got a challenge?
so rules are __builtins__ = None and no using __?
there are more but it's an actual challenge so I should just solve it by myself
I mean you can try with these 2 rules, no other globals(/locals) and no import
in fact you can import but that first rule (as long as it stands) de facto prevents it the way Python works
!e interesting py __builtins__ = None class Foo: pass
@polar plover :warning: Your eval job has completed with return code 0.
[No output]
wait wat
yep
don't know why but it's how things are
various stuff breaks, and apparently class too
differences between scripts and repel are annoying xD
>>> __builtins__ = None
>>> class Foo: pass
...
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'NoneType' object is not subscriptable```
!e py __builtins__ = None print("does this work still?")
@polar plover :white_check_mark: Your eval job has completed with return code 0.
does this work still?
okay, wtf
you only have the new stuff you define as a consequence, plus keywords
why is it working differently depending on if you run it in a script, or if you are using the repl
I don't know how the repl works but seems fair it would make assumptions like "the environment isn't f-d up"
bro i thought i had no life ๐
the no __ is really mean ...
I have found numerous and very different approaches that all wind up in either __ or f-d up builtins unexpectedly f-ing some other things up
a bit disappointed
ultra-low-level things are behind imports
non-__ low-level things are read-only
and all the fun attributes are behind __
you dont need the seperator? ๐คจ
I'm tired
understandable
wanted the space
between letters
!e python print(*map(chr, range(65,91)))
@upbeat sonnet :white_check_mark: Your eval job has completed with return code 0.
A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
oh ic
:)
Can any of you oneline this ?
def pack(data: dict):
d = []
for k, v in data.items():
v = str(v).lower() if isinstance(v, bool) else v
v = "undefined" if v == None else v
d.append(f"{k}={v}")
return "&".join(d)
I don't care if its hard ass complicated shit to read, all i care is that it works :^)
def pack(data:dict): return "&".join(f'{k}='+{None:"undefined",True:"true",False:"false"}.get(v,str(v)) for k,v in data.items())
seems to work pretty well
oh thanks
!e
speak = print
speak("hi")
@maiden river :white_check_mark: Your eval job has completed with return code 0.
hi
i wish we could define new keywords that easily
inthething = in
candy = for
could there be some way ๐
some class function operator magic ?
Hi Gentlemen i wanna ask a question now , i'm solving problems on codeforces but i always find very difficult problem for me and i saw the answer of others and i don't know how they are thinking in it in that way i want to learn that skill can any one help ?๐คฆโโ๏ธ
probably the wrong channel to ask for help, see #โ๏ฝhow-to-get-help
Oh sorry
that would be the parser. Unfortunately everything is parsed before anything runs, and nothing runs if a syntaxerror is determined.
It is possible to change some syntax rules before importing something containing the python code with the desired syntax.
It is, however, possible and fun to build esolangs that can parse within python syntax rules.
Because every repl line is a separately compiled unit
and builtins are "basically" propagated at compile time
er, wrong word
inhabited?
idk
for example I could make something like:
build_class. myObject[
init_method (a, b)[
setattr. a=a,
setattr. b=b,
],
method. add .magic="++" (other)[
setattr. a=a+other.a,
setattr. b=b+other.b,
],
method. sub .magic='--' (other)[
setattr. a=a-other.a,
setattr. b=b-other.b,
],
property. abs[
ret. math.sqrt(a**2 + b**2)
],
] .endclass
function. main[
set. x == myObject (3,4),
set. y == myObject (1,2),
x ++ y,
delete. y,
echo. x,
] .endfunction
main
to output
<MyObject x=4, y=6; at 0xc06198e3a012105>
all of the above should be technically possible to implement, but some of it would be very painful.
including building the methods out of the arrays of sentinal objects, and hacking globals.__getitem__ almost irrecognisably
conservatively written
from msvcrt import*
class Quit(RuntimeError):quit=lambda:(()for()in()).throw(Quit)
@type.__call__
class C:
def __init__(s):s.c=[0,0,0]
def __str__(s):return f'\x1b[H\x1b[38;2;{";".join(map(str,s.c))}m{s.c} \x1b[0m\n\x1b[48;2;{";".join(map(str,s.c))}m{"": >{len(str(s.c))}s}\x1b[0m \n\x1b[48;2;{";".join(map(str,s.c))}m{s.c}\x1b[0m \n\x1b[48;2;{";".join(map(str,s.c))}m{"": <{len(str(s.c))}s}\x1b[0m \x1b[A'
def __add__(s, n):s.c[n]+=1;s.c[n]=min(255,s.c[n])
def __sub__(s, n):s.c[n]-=1;s.c[n]=max(0x0,s.c[n])
try:
print('[0, 0, 0]\n\n[0, 0, 0]')
while 1:
if kbhit():{'w':lambda:C+1,'a':lambda:C-0,'s':lambda:C-1,'d':lambda:C+0,'q':lambda:C-2,'e':lambda:C+2,'\x1b':Quit.quit}.get(getch().decode(),lambda:0)();print(C)
except Quit:print()
!e ```py
def concatenate(a:str, b:str):
return a + b
print((lambda f:setattr(f,'annotations',{'a':str,'b':str})or f)(lambda a,b:a+b).annotations == concatenate.annotations)
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
True
demonstrating type hints for oneline code
you can also use a similar concept to "name" an anonymous function (lambda), by setting __name__
the algorithm behind 2048 can pretty much be summed up here
def _swipe(self,i,d):
m=[[self[i,q]for q in range(4)],[self[i,q-1]for q in range(4,0,-1)],[self[q-1,i]for q in range(4,0,-1)],[self[q,i]for q in range(4)]][d];q=[*map(int,m)]
for j in range(3):
y=q[j:]
while not y[0]and any(y[1:]):q+=[q.pop(j)];y+=[y.pop(0)]
for j in range(3):
y=q[j:]
if not[*{*y[:2]}][1:]:q[j]+=q.pop(j+1);q+=[0]
for j,n in enumerate(q):
if n:self[m[j]]=Cell(*m[j],n)
else:self.empty(*m[j])
return q!=[*map(int,m)]
everything else is just interaction
I shrunk it to 80 lines, reguessed the colours and removed the frame inspection causing backwards dependency.
https://paste.pythondiscord.com/usilopojib.py
that code for drawing the board must be reducable
very painfully if 0deps
else with any table building lib it can be reduced to 5-9 lines of code
I need help Iโm new python
!e
for i in range(10):
print(f"Hacking your mom... {(i+1)*10}% complete")
from random import randint as r
def n():
return r(0,128)
print(f"Hacked successfully, ip: {n()}.{n()}.{n()}.{n()}")
@vale tangle :white_check_mark: Your eval job has completed with return code 0.
001 | Hacking your mom... 10% complete
002 | Hacking your mom... 20% complete
003 | Hacking your mom... 30% complete
004 | Hacking your mom... 40% complete
005 | Hacking your mom... 50% complete
006 | Hacking your mom... 60% complete
007 | Hacking your mom... 70% complete
008 | Hacking your mom... 80% complete
009 | Hacking your mom... 90% complete
010 | Hacking your mom... 100% complete
011 | Hacked successfully, ip: 11.62.103.124
damn
y'all wizards
it most definitely is soft codable, I'm just feeling lazy.
cool!!!'=''';
nice code
why isnt the import at the top lol
whats the *
unpacking an iterable into an indefinite amount of arguments to print
if you're new to python, any channel other than this one would be a great start
__enter__
- save copy of globals
- clear globals
__exit__
- save copy of new globals, and reset globals to original saved copy
- construct dataclass using last globals save.
because it doesn't need to be
it looks wrong but then everything in this channel also looks wrong
!e ```py
@type.call
class model:
def enter(self):
import sys
self.reset = sys._getframe(1).f_globals.copy()
sys._getframe(1).f_globals.clear()
def exit(self, *_whatever):
import sys
k = sys._getframe(1)
r = type('model',(),k.f_globals)()
k.f_globals.clear()
k.f_globals.update(self.reset|{'model':r})
return 0
with model:
n, a = 3, 7
b = 2, 6
assert not[{(model.n,model.a),(3,7)}][1:]
assert not[{model.b,(2,6)}][1:]
print(model)
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
<model object at 0x7f7f2061bee0>
that's one interpretation, anyway
!e ```py
def implicit_equals(ab):return not[{ab}][1:]
fork,in[(0**0,1,1>0),((),()),(0,0<0),((1,2),)*3,(1,2,3)]:print(implicit_equals(*k))
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
001 | True
002 | True
003 | True
004 | True
005 | False
is this basically what i did?
assuming model is allowed to preexist
what was your solution?
if it's supposed to be a dataclass constructor some globals getitem hackery using bytecode inspection might tell it to create an intermediate context manager to build the class from the parallel globals
I did that but with classes instead of context managers
and i guess literally plugging the contents into z3 lol
no mine was nothing like that, merely a context manager thing
sounds cool
you still have the code?
it's a cool idea but i think it's just beyond the way python is intended to be used
so might not be bulletproof
there's something called contextvar as well
!d contextvars
This module provides APIs to manage, store, and access context-local state. The ContextVar class is used to declare and work with Context Variables. The copy_context() function and the Context class should be used to manage the current context in asynchronous frameworks.
Context managers that have state should use Context Variables instead of threading.local() to prevent their state from bleeding to other code unexpectedly, when used in concurrent code.
See also PEP 567 for additional details.
New in version 3.7.
it starts off sounding interesting at least
the api is practically non-existent
!e
import contextvars
print(dir(contextvars))
@rapid sparrow :white_check_mark: Your eval job has completed with return code 0.
['Context', 'ContextVar', 'Token', '__all__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'copy_context']
i wrote a similar function
to execute code in another namespace
like in the namespace of a module or class
it's not bulletproof either but useful
Thanks for messing with my brain, half the brain cells are dead now
Uh it should be on github
yeeeah there it is
the benefits of using classes is that you don't need to make a mess with globals & locals awareness; classvars are relatively simple
the downsides is that it's uglier and editors hate it with a passion
class _(Model): vs with Model(...):
!e
print(True,True,True==(True,True,True))
@vale tangle :white_check_mark: Your eval job has completed with return code 0.
True True False
looking forward to what I'm gonna do with the other half?
!e dummy integer ```py
@type.call
class a:value=0;index=int=hash=lambda s:s.value
a.value = 4
print([*range(3),*range(3)][a])
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
1
!e which can make a really cursed ```py
@type.call
class a:
value=47;index=int=hash=lambda s:s.value;iter=lambda s:s
def next(self):
a.value+=1
if a.value==58:raise StopIteration
return print
*map(lambda :(chr(a)),a),
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
001 | 0
002 | 1
003 | 2
004 | 3
005 | 4
006 | 5
007 | 6
008 | 7
009 | 8
010 | 9
if I didn't stop at 58 this would indefinitely iterate, like a really cursed event loop
wait did I just discover async mechanics?
!e or I could make accessing it as an integer increase its integer value ```py
@type.call
class a:
value=0;index=int=hash=lambda s:setattr(s,'value',s.value+1)or s.value;iter=lambda s:s
print(*map(list,map(range,[a]*10)),sep='\n')
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
001 | [0]
002 | [0, 1]
003 | [0, 1, 2]
004 | [0, 1, 2, 3]
005 | [0, 1, 2, 3, 4]
006 | [0, 1, 2, 3, 4, 5]
007 | [0, 1, 2, 3, 4, 5, 6]
008 | [0, 1, 2, 3, 4, 5, 6, 7]
009 | [0, 1, 2, 3, 4, 5, 6, 7, 8]
010 | [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
somebody posted a comment on a video I was watching yesterday saying that people who scraped stuff from the web might need 10's or even 100's of proxies to " avoid detection.. "
๐ค
It just had me wondering what might this person be scraping that they would need so many proxies . .
I scraped a pet adoption website quite directly to determine which cat of theirs was the fattest. Shouldn't I have?
wow
()=_ # dump variables into globals```
that is truly a hidden gem
and people are doing this very thing
something where the site owner really doesn't want them to, in all likellihood
no no
if you were able to do it directly, that's a good sign you're not going against the owner's wishes
i'm scared yet impressed
When I read that my mind says ```py
assert not len(_)
!e ```py
not๏พ defined
@quartz wave :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 1, in <module>
003 | NameError: name 'notแ
defined' is not defined
yes
Learnt a lesson: Never look into this channel again as long as there ain't any pings from here
No no no u just gave me anxiety of what's in the link but I ain't clicking it
Wait, this wasn't that bad, but what's with the >>>
Binds a trait to a type for the impl
it's the "target type", so to speak
this is basically the Rust trait system
minus a few things
O
!e py a = print a("test")
@south tundra :white_check_mark: Your eval job has completed with return code 0.
test
!e py a = for b = in c = range a _ b c(1,2): print(_)
@south tundra :x: Your eval job has completed with return code 1.
001 | File "<string>", line 1
002 | a = for
003 | ^^^
004 | SyntaxError: invalid syntax
aw
this is python, not c
what you can do is write a turing complete string interpreter then the string can be whatever.
!e
assert not len('l')
@sick hound :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 1, in <module>
003 | AssertionError
!e
assert not len('')
@sick hound :warning: Your eval job has completed with return code 0.
[No output]
can be fixed easy
#define a for
#define b in
#define c range
a _ b c(1,2):
print(_)
This
I come here occasionally when I'm feeling too smart and need to lower my confidence to humanly levels.
I come here occasionally when I want to realise I have no idea how python works
i come here occasionally to realise I don't know how to program
!e
#define a for
#define b in
#define c range
a _ b c(1,2):
print(_)โ
@sick hound :x: Your eval job has completed with return code 1.
001 | File "<string>", line 4
002 | a _ b c(1,2):
003 | ^
004 | SyntaxError: invalid syntax
What does _ look like here?
!e
test={"cool": "no way"}
() = test
print(globals())
@sick hound :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 2, in <module>
003 | ValueError: too many values to unpack (expected 0)
And it will take the local vars of that model and put it into globals?
Also what would be after this? Just a pass?
no look at the code in the github repo
It can be any target, if he wants it done fast then more proxies are needed
Sometimes scraping at 1k rps
yeah lol
i still dont get what it does .
() = obj calls obj.__iter__ so obj.__iter__ can dump values into globals
!e ```py
class O:
def iter(self):
print('i got called')
return
yield
obj = O()
() = obj```
@rugged sparrow :white_check_mark: Your eval job has completed with return code 0.
i got called
if False: yield
This code is used somewhere in std lib
iirc in the Iterable protocol
i got some esoteric code by accident
def some_beartyped_function():
if __beartype_pith_0 is not __beartype_raise_exception and not isinstance(
__beartype_pith_0, str
):
__beartype_raise_exception(
func=__beartype_func, pith_name="package_name", pith_value=__beartype_pith_0
)
__beartype_pith_0 = kwargs.get("module_name", __beartype_raise_exception)
if __beartype_pith_0 is not __beartype_raise_exception and not isinstance(
__beartype_pith_0, str
):
__beartype_raise_exception(
func=__beartype_func, pith_name="module_name", pith_value=__beartype_pith_0
)
__beartype_pith_0 = kwargs.get("func", __beartype_raise_exception)
if __beartype_pith_0 is not __beartype_raise_exception and not isinstance(
__beartype_pith_0, __beartype_object_9795712
):
__beartype_raise_exception(
func=__beartype_func, pith_name="func", pith_value=__beartype_pith_0
)
__beartype_pith_0 = kwargs.get("version", __beartype_raise_exception)
if __beartype_pith_0 is not __beartype_raise_exception and not isinstance(
__beartype_pith_0, __beartype_object_15338576
):
__beartype_raise_exception(
func=__beartype_func, pith_name="version", pith_value=__beartype_pith_0
)
__beartype_pith_0 = kwargs.get("hash_algo", __beartype_raise_exception)
if __beartype_pith_0 is not __beartype_raise_exception and not isinstance(
__beartype_pith_0, __beartype_object_14936032
):
__beartype_raise_exception(
func=__beartype_func, pith_name="hash_algo", pith_value=__beartype_pith_0
)
__beartype_pith_0 = kwargs.get("user_provided_hashes", __beartype_raise_exception)
if __beartype_pith_0 is not __beartype_raise_exception and not isinstance(
__beartype_pith_0, set
):
__beartype_raise_exception(
func=__beartype_func,
pith_name="user_provided_hashes",
pith_value=__beartype_pith_0,
)
__beartype_pith_0 = kwargs.get("registry", __beartype_raise_exception)
if __beartype_pith_0 is not __beartype_raise_exception and not isinstance(
__beartype_pith_0, __beartype_object_549598516568
):
__beartype_raise_exception(
func=__beartype_func, pith_name="registry", pith_value=__beartype_pith_0
)
__beartype_pith_0 = __beartype_func(*args, **kwargs)
if not isinstance(__beartype_pith_0, __beartype_object_549601113792):
__beartype_raise_exception(
func=__beartype_func, pith_name="return", pith_value=__beartype_pith_0
)
return __beartype_pith_0```
Wtf
the function I was using to look at tracebacks tries to decompile ones that don't have a source file, like this was File <string>
the function had a @beartype on it
was kind of shocked to see all that get printed out lol
what is beartype??
a runtime type checker
Hey there, any good tips for how to upload a game on telegram written on Python? Thanks in advance for who will reply ๐
@flint nacelle โ Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 1, in <module>
003 | WrongChannelError: please refer to the channel [#โ๏ฝhow-to-get-help](/guild/267624335836053506/channel/704250143020417084/) for more information
>>> import discord
>>> guild = discord.get_guild('Python')
>>> channel = guild.get_channel('esoteric python')
>>> channel.get_help()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/Python310/Lib/site-packages/discord", line 344, in get_help
NoHelpException: cannot get help from channel; do you mean to be in channel "how to get help"?
i wonder why ๐ค
help I cannot be helped
lol
https://stackoverflow.com/questions/71315838/when-i-modify-builtins-to-a-custom-class-it-only-works-in-shell
This seems like the sort of thing you guys might be able to help with - reason I'm not posting it in a help channel is that it's very niche, and there isn't a strictly defined solution, just making __missing__ work... somehow
Full disclosure: This is my stackoverflow post
selfbot confirmed
Builtins are a bit special in that they persist / are cached throughout a single execution unit
In a repl each line is its own unit, while in a program you can only create new units with exec, etc.
You can obviously do some interior mutability tricks, though, such as .clear()ing, or using ctypes etc. to patch the actual object in memory
How can i make Return() function?
Return = ...
def f():
Return(42)
assert f() == 42
Maybe i should set trace function to parent frame and then execute return opcode?
Possible use case:
def some_decorator():
@Return
def wrapped(): ...
# instead of
def some_decorator():
def wrapped(): ...
return wrapped
It can be used in ternary operator to return from function if some invariants are broken
Huh?
would have been sooo fun if this worked lol
make it a subclass of Exception and make a decorator to upgrade a function to support Return
troll
!e ```py
class Return(BaseException):
def init(self,*data):
try:self.data,=data
except:self.data=data
super().init(repr(data))
def implementsReturn(f):
def inner(*a,**k):
try:return f(*a,**k)
except Return as e:return e.data
return inner
@implementsReturn
def main():
a, b = 60, 9
raise Return(a+b)
result = main()
print(result)
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
69
with this pair of implementsReturn and Return, Return now returns from the next frame that implementsReturn, thus supporting returning from multiple frames at once.
!e another example ```py
class Return(BaseException):
def init(self,*data):
try:self.data,=data
except:self.data=data
super().init(repr(data))
def implementsReturn(f):
def inner(*a,**k):
try:return f(*a,**k)
except Return as e:return e.data
return inner
@implementsReturn
def main():
def inner(n):
raise Return(60+n)
inner(9)
print(main())
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
69
also supports building a tuple just like builtin return
I'll leave making an example of that as an exercise for the reader.
๐
https://paste.pythondiscord.com/lubifivuru
def foo():
n = 0
goto = Goto()
while goto:
with goto as label:
if label("fizz"): print("fizz", n)
if label("buzz"): print("buzz", n)
if True: n += 1
if n == 5: goto.hell()
if n > 3: goto("fizz")
else: goto("buzz")
foo()
``` ```
fizz 0
buzz 0
buzz 1
buzz 2
buzz 3
fizz 4
buzz 4
imagine using this in job interviews
if an interviewer asks me to invert a binary tree on a whiteboard, they 100% deserve this tbh ๐
Woah
!e ```py
BYTES_HEADER = bytes.basicsize - 1
PTR_SIZE = tuple.itemsize
ENDIAN = ['big','little'][memoryview(b'\1\0').cast('h')[0]&0xff]
load_addr = type(m:=lambda n,s:lambda v:s(v)or n)(
(M:=m.code).replace(
co_code=b'\x88'+M.co_code[1:]
),{}
)(r:=iter(range(2**(PTR_SIZE*8-1)-1)),r.setstate)
memory_backing = bytes(PTR_SIZE)
+ id(bytearray).to_bytes(PTR_SIZE, ENDIAN)
+ bytes([255] * (PTR_SIZE - 1) + [127])
+ bytes(PTR_SIZE * 4)
memory = memoryview(load_addr(id(memory_backing) + BYTES_HEADER))
def getframe(level=0):
try:raise
except Exception as e:
frame = e.traceback.tb_frame.f_back
for () in [()] * level:
frame = frame.f_back
return frame
def Return(val):
frame = getframe(1)
offset = id(frame.f_code.co_code) + bytes.basicsize + frame.f_lasti - 1
memory[offset + 2: offset + 4] = bytes((83, 0))
return val
def test(x):
Return(x + 1)
print(test(1))```
@rugged sparrow :white_check_mark: Your eval job has completed with return code 0.
2
oh
!e ```py
BYTES_HEADER = bytes.basicsize - 1
PTR_SIZE = tuple.itemsize
ENDIAN = ['big','little'][memoryview(b'\1\0').cast('h')[0]&0xff]
load_addr = type(m:=lambda n,s:lambda v:s(v)or n)(
(M:=m.code).replace(
co_code=b'\x88'+M.co_code[1:]
),{}
)(r:=iter(range(2**(PTR_SIZE*8-1)-1)),r.setstate)
memory_backing = bytes(PTR_SIZE)
+ id(bytearray).to_bytes(PTR_SIZE, ENDIAN)
+ bytes([255] * (PTR_SIZE - 1) + [127])
+ bytes(PTR_SIZE * 4)
memory = memoryview(load_addr(id(memory_backing) + BYTES_HEADER))
def getframe(level=0):
try:raise
except Exception as e:
frame = e.traceback.tb_frame.f_back
for () in [()] * level:
frame = frame.f_back
return frame
def Return(val):
frame = getframe(1)
offset = id(frame.f_code.co_code) + bytes.basicsize + frame.f_lasti - 1
memory[offset + 2: offset + 4] = bytes((83, 0))
return val
def test(x):
Return(x + 1)
import dis
dis.dis(test)
@quartz wave :white_check_mark: Your eval job has completed with return code 0.
001 | 33 0 LOAD_GLOBAL 0 (Return)
002 | 2 LOAD_FAST 0 (x)
003 | 4 LOAD_CONST 1 (1)
004 | 6 BINARY_ADD
005 | 8 CALL_FUNCTION 1
006 | 10 POP_TOP
007 | 12 LOAD_CONST 0 (None)
008 | 14 RETURN_VALUE
so it just replaces the POP_TOP with a RETURN_VALUE except that it doesn't actually know that there's a POP_TOP in it
It doesnt need to know that its POP_TOP but python guarantees there will be at least one op after a function call.
i know that
fr tho
https://stackoverflow.com/questions/71332220/advanced-python-customise-handling-of-nameerror-on-referencing-undefined-variab
Y'all might be able to help with this
!e
import sys
import dis
import ctypes
mutable_bytes=lambda i:memoryview((ctypes.c_uint8*len(i)).from_address(id(i)+bytes.__basicsize__-1)).cast('B')#from Python Discord
def tracefunc(frame,*useless):
print(f'\nDisassembling frame {frame}... ')
co_code=mutable_bytes(frame.f_code.co_code)
#now, find the indices of all the LOAD_NAME operations in the frame
indices=[i for i in range(0,len(co_code),2)if co_code[i] in (dis.opmap['LOAD_NAME'],dis.opmap['LOAD_FAST'])]
names=[frame.f_code.co_varnames[co_code[i+1]]for i in indices]
print(dis.dis(frame.f_code))
print(names)
sys.settrace(tracefunc)
print('foo')
print(bar)
@golden finch :x: Your eval job has completed with return code 1.
001 | foo
002 | Traceback (most recent call last):
003 | File "<string>", line 20, in <module>
004 | NameError: name 'bar' is not defined
that... is not the output on my machine
i have code that makes this work already one sec
!e ```py
from ctypes import py_object
import atexit, builtins, sys, dis
def init_missing_hook(dct, func):
ob_base_p = py_object.from_address(id(dct) + 8)
class missing_hook(dict):
slots = ()
def missing(self, key, ob_base_p=ob_base_p, builtins=builtins):
try:
ob_base_p.value = builtins.dict
return (builtins.dict | self)[key]
except KeyError:
return func(self, key)
finally:
ob_base_p.value = class
ob_base_p.value = missing_hook
@atexit.register
def unhook():
ob_base_p.value = dict
return unhook
init_missing_hook(sys._getframe().f_globals, lambda d, k:(k, 'var'))
print(foo)```
@rugged sparrow :white_check_mark: Your eval job has completed with return code 0.
('foo', 'var')
@golden finch ^ it changes the type of the globals dict in place and adds a __missing__ method
damn, I tried exactly this thing but couldn't get it to work
how did you get it working?
by the way, that thing is intimidating
first off you need to make sure everything in the class your hotswapping in is being loaded with LOAD_FAST
okay
you also need to make sure the new class has the same instance size __slots__ = () causes the class to lose all of the dynamic extra stuff (leaving it the same size as dict)
remind me what slots does again?
it normally specifies the variable slots on an object
builtinexc was unnecessary to i removed it
okay
youre welcome to just copy init_missing_hook, it takes in a dict instance and a func
No, I'm curious how it works though - reading this:
- is presume ob_base_p is a pointer to the pyobject of the dict instance?
or is it a pointer to the pyobject of dict itself?
ob_base_p = py_object.from_address(id(dct) + 8) this line gets the pointer 8 bytes from the start of dct and interprets it as a pointer to a pyobject
that happens to be the tp_base pointer, which is the pointer to the base class of an object
so by swapping that, we effectively change the type(dct) from dict to missing_hook
that causes python to skip adding the extra space on class instances that is normally used for a dictionary and an attribute cache
empty slots means we have no attributes, so no dictionary and no need for a cache
this is one of the things i used that missing_hook to do
extra space?
this is incredible, with all due respect
thanks, its the result of way to much time with python internals
yea like how normally a user class can have random attributes
user class?
!e ```py
class a:
pass
A = a()
A.foo = 1
class b:
slots = ()
B = b()
B.foo = 1 # fails```
@rugged sparrow :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 11, in <module>
003 | AttributeError: 'b' object has no attribute 'foo'
classes can have whatever attributes - but my understanding is __slots__ limits them to a set number of attrs
ah
makes sense
okay, but why do we need to make the number of attributes constant?
because the builtin class dict has no attributes
and we need our hotswapped class to have the same layout in memory as the dict class
mhm
why?
isn't it just pointed to?
so the pointer should work regardless of the size (and yes, I know I'm wrong, but I'm curious why)
because the globals dict has a specific size. python knows this by checking obj.tp_base.__basicsize__ plus some other stuff. we change tp_base to a custom class without changing the actual size of the globals dict
without __slots__ = (), python checks obj.tp_base to see if there is a dict and an attribute cache, it sees that there should be, and it happily reads past the end of the original globals object into random memory
>>> class a:pass
...
>>> a.__basicsize__
32
>>> #[8:refcnt, 8:base, 8:dict, 8:attr_cache]
>>> class a:__slots__ = ()
...
>>> a.__basicsize__
16
>>> #[8:refcnt, 8:base]```
okay, makes some degree of sense, terrifying though
ah thanks
if you want to read more about stuff like that, look up type confusion vulnerabilities, its a similar concept
okay so now you define a __missing__ method on missing_hook, but wait, it has no attributes, so how can you define a method on it?
attributes are stored on the instance, methods are stored on the class
ah, okay
i actually found a second type confusion bug in python where you can coerce it into accessing an arbitrary object as a cell object
lol sure, ill warn you i have condensed this code a ton more
intimidating
!e ```py
load_addr = type(m:=lambda n,s:lambda v:s(v)or n)(
(M:=m.code).replace(
co_code=b'\x88'+M.co_code[1:]
),{}
)(r:=iter(range(2**(tuple.itemsize*8-1)-1)),r.setstate)
print(load_addr(id(1)))
@rugged sparrow :white_check_mark: Your eval job has completed with return code 0.
1
all that does is let you load an arbitary address as a python object
but you can use it to make fake objects in memory (using bytes)
okay so now how does __missing__ work?
ugh, I'm going to have to go for maybe 45 minutes now
but I'll be back
__missing__ is called on dictionary subclasses when the key is not found in the dictionary
I actually need to go now as well, its 1:30 am here
feel free to ping me with questions, ill answer when I wake up
sad that it only works for linux
(didn't mean to ping)
oh, that's a useful bit of info
Is there any hacky way to re-add python 2 style print statements back to Python 3?
so ```py
print 989
print "foobar"
print 3*8-9
I gotta imagine no but you guys do amazing stuff <#esoteric-python message> 
~~change t to + sneakily and add dunder add then no one will notice
~~
@rugged sparrow what does that finally clause do? shouldn't it be ignored via return?
no but aph suggested a sneaky way to do it
wait.. i think so, i found a stack overflow answer, i might be able to tweak it somehow
@rugged sparrow doesn't seem to work inside functions
hi, i came back to say that i failed
it's possible to read a file with the tweaked tokenize thing
but it'll error out whenever there's parsing error if i use import past
like what error
SyntaxError, idk how to avoid it, it'll always get one bcuz it really is an invalid syntax
however, my code w0rks a bit, it does weird stuff like 2to3 does
bUt it only works by running itself (gib filename as input, convert stuff, run code) but not at running it directly with python
bcuz python parses
:(
!e One issue is that print abc is a syntax error, so I think you would need to add an extra character to avoid this. The first thing that came to mind is this:
from __future__ import annotations
@type.__call__
class __annotations__(dict):
def __setitem__(self, item, value):
if item == "print":
print(value.strip("'"))
print: 989
print: "foobar"
print: 3*8-9
@prisma coral :white_check_mark: Your eval job has completed with return code 0.
001 | 989
002 | foobar
003 | 3 * 8 - 9
But obviously this doesn't fully meet the Py2 print statement syntax
!e Just realised that __future__.annotations was not actually what I was looking for.
@type.__call__
class __annotations__(dict):
def __setitem__(self, item, value):
print(value)
print: 989
print: "foobar"
print: 3*8-9
@prisma coral :white_check_mark: Your eval job has completed with return code 0.
001 | 989
002 | foobar
003 | 15
i found this answer on google: https://stackoverflow.com/a/4572994/13884898
quite k00l ngl
btw readline only works on linux
!e
class SomeMeta(type):
__slots__ = () # note empty slots
class X(metaclass=SomeMeta):
...
# now X is instance of SomeMeta, X should have no dict, because SomeMeta.__slots__ is empty
X.a = 42 # but dynamic assignments still works
print(X.a)
print(X.__dict__) # and X has .__dict__ (wrapped in mappingproxy)
@fleet bridge :white_check_mark: Your eval job has completed with return code 0.
001 | 42
002 | {'__module__': '__main__', '__dict__': <attribute '__dict__' of 'X' objects>, '__weakref__': <attribute '__weakref__' of 'X' objects>, '__doc__': None, 'a': 42}
Nah finally blocks run even after a return statement
What do you mean?
Hey, that's pretty close
I didn't know you could add dunders to annotations
Since __annotations__ is a dict, you can create a subclass of dict, override the dunders there, and then set __annotations__ to be an instance of that subclass (that's what the @type.call is for)
!e how come the function annotations don't work
```py
@type.call
class annotations(dict):
def setitem(self, item, value):
print(value)
a: 111
b: 222
def f(a: 123, b: 456):
pass
f(1, 2)
@sick hound :white_check_mark: Your eval job has completed with return code 0.
001 | 111
002 | 222
cause they dont go through the global annotations
for something as primitive as a list of objects, how is it possible that
for elem in li:
...
could result in elem and li being the same value? i.e.
>>> elem
[{'foo': 'bar'},{'baz': 'quux'}]
>>> li
[{'foo': 'bar'},{'baz': 'quux'}]
so the iteration results in a TypeError? this is a strange one...
!e with recursive objects
x = ['']
x[0] = x
print(x) # [[...]]
for y in x:
assert y is x
print("wow")
@earnest wing :white_check_mark: Your eval job has completed with return code 0.
001 | [[...]]
002 | wow
@wise bone in general, a lot of simple ideas break down / hit edge cases with recursive objects
!e e.g. comparison
x=[]
y=[]
x.append(y)
y.append(x)
assert x == y
@earnest wing :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 5, in <module>
003 | RecursionError: maximum recursion depth exceeded in comparison
makes sense, thanks!
!e
class X:
def __iter__(self):
yield from (self,)
x = X()
print(x)
print()
for item in x:
print(item)
assert x is item
@fleet bridge :white_check_mark: Your eval job has completed with return code 0.
001 | <__main__.X object at 0x7f2799fdfc10>
002 |
003 | <__main__.X object at 0x7f2799fdfc10>
a self containing non-mutable iterable, brilliant!
If you abuse the garbage collector you can make a tuple that contains itself with a magic iterable
how about tuple unpacking with an iterable that grabs the tuple from frame inspection and modifies it?
!e ```py
import gc
class magic:
def length_hint(self):
return 1
def __iter__(self):
for obj in gc.get_objects():
if isinstance(obj, tuple):
try:0 in obj
except SystemError:
yield obj
break
weird = tuple(magic())
print(weird, weird in weird)```
@rugged sparrow :white_check_mark: Your eval job has completed with return code 0.
((...),) True
I woulda prefered
weird=*magic(),
Yea sadly *magic(), makes a list internally, then makes a tuple from it
makes a list internally?
If I remember correctly yea
does that mean tuple(a) would be more optimised than *a,?
!e py import dis dis.dis('*a,')
@rugged sparrow :white_check_mark: Your eval job has completed with return code 0.
001 | 1 0 BUILD_LIST 0
002 | 2 LOAD_NAME 0 (a)
003 | 4 LIST_EXTEND 1
004 | 6 LIST_TO_TUPLE
005 | 8 POP_TOP
006 | 10 LOAD_CONST 0 (None)
007 | 12 RETURN_VALUE
This is an obfuscated snippet from a simple yet well known game I made, in the initialisation of the middle layer of code.
Who can guess what game this initialises?
class Engine:
r=__import__('random').randint
__getitem__=lambda s,i:(lambda i,j:s.m[j][i])(*i)
def __init__(s):
s.m=[[EmptyCell(i,j)for i in range(4)]for j in range(4)]
r=lambda:(lambda l:(l(),l()))(lambda:s.r(0,3))
a=lambda:Cell(*r(),2);a=a(),a()
while-len({*a})+2:a[1].move(*r())
*map(lambda i:[()for s[i]in[i]],a),
I'm pretty sure overhead from looking up a global name outways the internal list building
game of life?
game of life with 16 cells would be boring, so no
Minesweeper then?
again, 16 cells, boring, no
What's the game then
No idea
so the obfuscation worked or you don't know the game
2048
the initialised board
the Engine is the middle layer, "where the algorithm is"
Ahh that makes sense
I layer my code like
Interface
Processor or Engine
Datatype or Cell
Nah I recognized the code, just forgot the game
so the code makes sense?
I can't remember if the game starts with only 2 2s or if the same random 2 or 4 initialisation applies to the starting cells
so I started with 2 2s so the user doesn't get a headstart by starting with 4s, or a setback by starting with a 2 and a 4
a few moves in
and here's the game when the goal is achieved
and here's the command line interface that's also builtin
although if I make this modification, the output can be interpreted by python as a list.
which makes this cursed option available:
i am curious on why your terminal is red
its translucent
My desktop background is the colour of blood
your desktop background is the colour of my tears after reading your code
Wow, thats really weird trick
i hate it
It brokes invariant of tuples: tuple cant contain itself as item
python -i game !?
ooh
or python
>>> from _2048 import Interface
>>> interface = Interface()
play the game
>>> engine = interface.uninstall()
>>> engine.set(this, that, whatever)
>>> engine.up()
'swiped up '
>>> interface.install(engine)
>>> interface.run()
continue to play modified game
ooh
would this belong here? py embed.add_field(name='Extra', value=f'Hash: {hash(member)}\nID: {member.id}\nColor: {member.color}\n{int(member.public_flags.early_supporter) * "Early supporter"}\n{int(member.public_flags.verified_bot_developer) * "Verified developer"}\n{int(member.public_flags.partner) * "Discord partner"} \n{int(member.public_flags.discord_certified_moderator) * "Certified moderator"}\n{int(not (member.public_flags.bug_hunter_level_2) and member.public_flags.bug_hunter) * "Level 1 bug hunter"}\n{int(member.public_flags.bug_hunter_level_2) * "Level 2 bug hunter"}\n{int(member.public_flags.staff and not (member.public_flags.partner)) * "Discord employee"}\n{int(member.public_flags.spammer) * "**Careful**, this user has been reported to discord for **spamming**"}')it's some code from a discord bot i made
or is my softwrap fucking with me?
Anyone here good with pytesseract and pyautogui dm me im tryna create a bot for something
It might help to use triple quotes so that you can use literal newlines
!e ```py
from ctypes import*
p=py_object.from_address(id(...)+8)
class SOS:
value=[*'Heo World!']
def neg(self):
self.value.insert(2,'l')
return self
def sub(self, also_self):
print(''.join(self.value))
()=self.value[2:4]=[]
p.value = SOS
...---...
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
Hello World!
sounds like your trying to read text and paste it somewhere, is that right?
or maybe a spammer
what is this cursed stuff
how does it work lol
why is this more active than the help channels ๐ญ
anyway watch and learn
!e py help(print)
@upbeat sonnet :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 1, in <module>
003 | NameError: name 'help' is not defined
๐โโ๏ธ
!e
from pydoc import help
help(print)
@fleet bridge :white_check_mark: Your eval job has completed with return code 0.
001 | Help on built-in function print in module builtins:
002 |
003 | print(...)
004 | print(value, ..., sep=' ', end='\n', file=sys.stdout, flush=False)
005 |
006 | Prints the values to a stream, or to sys.stdout by default.
007 | Optional keyword arguments:
008 | file: a file-like object (stream); defaults to the current sys.stdout.
009 | sep: string inserted between values, default a space.
010 | end: string appended after the last value, default a newline.
011 | flush: whether to forcibly flush the stream.
lmao
lmao
>>> help.__class__.__module__
'_sitebuiltins'```
mad
there are only wrapper in sitebuiltins
but why the bot cant use it normally tho
also is it possible to have two variables pointing to the same memory address to achieve something like a pointer?
My desktop background is the colour of the tears of people who read my code:
fr
it's interesting
๐ฅ
import asyncio as time
await time.sleep(10)```
c stuff
yeah but what
that accesses the memory position 8 addresses after the address of the builtin Ellipsis
oops
wrong quote
it finds the memory pos of the object
this one
gets pointer to pointer to type of ellipsis
and changes it to change type of ellipsis
why no whitespaces tho
this explanation is better
ah
at least in this case, only the driver line needs to be read
when the word functional is dysfunctional:
so like a pointer
and the driver line is
...---...
and the function is
print("Hello World!")
oh you're doing something with - operator
yes, the array of memory starting at ellipsis contains a pointer to the class, but I changed the pointer to the address of a user created class
which defines __sub__ and __neg__
ah cool
lmfao
x---x
```is parsed like```py
x - --x
replace x with the ellipsis, you get```py
...---...
```py
from ctypes import*
p=py_object.from_address(id(...)+8)
```now this part, `p.value` is equal to `type(...)`
so we make a custom class ```py
class SOS:
value=[*'Heo World!']
def __neg__(self):
self.value.insert(2,'l')
return self
def __sub__(self, also_self):
print(''.join(self.value))
()=self.value[2:4]=[]
```and set it to `p.value` ```py
p.value = SOS
```ok but how does this work? ```py
value = [*'Heo World!']
```well, it's basically the same thing as ```py
value = ['H', 'e', 'o', ' ', 'W', 'o', 'r', 'l', 'd', '!']
```remember how the thing is parsed?```py
x - --x
``` so before you subtract, you have to first evaluate the two operands, `x` and `--x`
`x` doesn't need to evaluate anything, so we don't focus on that
but `--x` we will focus on, and it basically just does this:`x.__neg__().__neg__()`
so remember that custom class from earlier? and its `__neg__` magic method?```py
def __neg__(self):
self.value.insert(2, 'l')
return self
``` ok so it's basically inserting `l` into the second position of `self.value`, just after the `e` right here ```py
value = ['H', 'e', 'o', ' ', 'W', 'o', 'r', 'l', 'd', '!']
^
```so after the first `.__neg__()`, `self.value` is now equal to this:```py
value = ['H', 'e', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd', '!']
```after the second `.__neg__()`, `self.value` is now equal to this:```py
value = ['H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd', '!']
```now, we'll perform the subtraction with the `__sub__` magic method:```py
def __sub__(self, also_self):
print(''.join(self.value))
()=self.value[2:4]=[]
```so remember `self.value`? we join it and print it now:```py
print(''.join(self.value))
```this results in the `Hello World!` being printed
then, we reset `self.value` by doing this:```py
()=self.value[2:4]=[]
```basically makes `self.value` the list it was before anything
hence, the SOS signal prints helo world
that took the whole discord text limit to type
woah lmfao this is very comprehensive
yeah that makes sense
thanks ๐
scariest wpm
all that action in that cute little script.
i also had to delete some spaces for it to just fit
lmao
imagine ''.join()
it was like reading my thought processes whilst I was writing it
* when
* is the opposite operation
value could be "hello world" and neg could just return self
it would work too right
isnt it unpacking and printing?
!e
print(*'hello')
@fleet bridge :white_check_mark: Your eval job has completed with return code 0.
h e l l o
it packs and prints
oh ic
it's already unpacked, it needs to be packed
yes
it would work, but I want to drive with ...---... instead of ...-...
hence I gotta make it dependant on neg
what surprises me is how this took just 4 minutes or less to type
keyboard warrior!
!e py from ctypes import py_object p = py_object.from_address(id(...) + 8) class SOS: val = "hello world" def __neg__(self): return self def __sub__(self, other): print(self.val) p.value = SOS ...---...
fk
lmao
val != value
@jovial monolith :white_check_mark: Your eval job has completed with return code 0.
hello world
yeah that works too i guess
it doesn't look as good though
as esoteric
nothing here looks good
!e
print(....value)
!e print((True, True, True) is True, True, True
@upbeat sonnet :x: Your eval job has completed with return code 1.
001 | File "<string>", line 1
002 | print((True, True, True) is True, True, True
003 | ^
004 | SyntaxError: '(' was never closed
!e print((True, True, True) is True, True, True)
@upbeat sonnet :white_check_mark: Your eval job has completed with return code 0.
001 | <string>:1: SyntaxWarning: "is" with a literal. Did you mean "=="?
002 | False True True
!e
print(True, True, True == (True, True, True))
@jovial monolith :white_check_mark: Your eval job has completed with return code 0.
True True False
this was on youtube wasnt it
i think so
i still dont grasp it yet
!e
print(True, True, True == *(True, True, True))
@upbeat sonnet :x: Your eval job has completed with return code 1.
001 | File "<string>", line 1
002 | print(True, True, True == *(True, True, True))
003 | ^
004 | SyntaxError: invalid syntax
when you unpack, it needs somewhere to go to
!e ```py
from ctypes import*
p=py_object.from_address(id(...)+8)
class SOS:
value=iter(["World!","Hello "])
def neg(self):
return type('',(),{'neg':lambda s:next(self.value)+s.value,'init':lambda s,v:setattr(s,'value',v)})(next(self.value))
def sub(self, phrase):
print(phrase)
self.value = iter([phrase[6:],phrase[:6]])
p.value = SOS
...---...
!e
print(True, True, True == list(*(True, True, True)))
!e
print(True, True, True == set(*(True, True, True)))
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
Hello World!
with this modification, the driver is more dependant on the neg
cant we do like a unicode iterator thing to find the letters in hello world then print them
why?
cos yes
splitting in the middle works.
it's even more cursed because it joins it backwards, so the iterable has to be backwards
"I think this is my subconscious sending out a distress signal because it's stuck in my brain"
That would make a great docstring for this script
!e ```py
from ctypes import*
p=py_object.from_address(id(...)+8)
class SOS:
value=iter(["World!","Hello "])
def neg(self):
return type('',(),{'neg':lambda s:next(self.value)+s.value,'init':lambda s,v:setattr(s,'value',v)})(next(self.value))
def sub(self, phrase):
print(phrase)
self.value = iter([phrase[6:],phrase[:6]])
p.value = SOS
...---...
...---...
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
001 | Hello World!
002 | Hello World!
it works multiple times too
I'm gonna make 4-dimensional 2048
just planning it is giving me a headache. The source code will be difficult to understand.
how does 4d work in the first place anyway
There is 16 4x4 boards laid out in a 4x4 grid. You use wasd keys to swipe local vertical and horizontal, and you use arrow keys to swipe hypervertical and hyperhorizontal.
__format__=lambda s,f='1':s.colour(str(s)[int(f)*7:7+int(f)*7].__format__(f'{[" >"," ^","_<"][int(f)]}7s'))
I'm already going insane supporting larger numbers in a 7x3 square, due to the extreme terminal character cell height to width ratio
the conditional CSI5m wouldn't work, so I removed it
this is just to display a large integer (up to 21 digits) with wrapped center alignment.
any larger numbers just get the end chopped off, which isn't significant figures anyway.
I am plagiarising myself like a bad boii.
I am literally writing it in order from start to finish, also very recommended against.
Write stub code before the algorithm
what the hell... you're writing it in esoteric code too lol
wouldn't it be better to write out the proper code first and then screw it over later?
I screw it as I go.
here's the engine init
class Engine:
def __init__(self):
self.matrix=[[[[BaseCell(i,j,k,l)for i in range(4)]for j in range(4)]for k in range(4)]for l in range(4)];r=lambda:(lambda l:(l(),l(),l(),l()))(lambda:randint(0,3));a=lambda:Cell(*r(),2);a=a(),a()
while-len({*a})+2:a[1].move(*r())
[()for x in a for self[x]in[x]]
4 dimensional matrix go brrrrr
2 dimensional script is less than 80 lines. I'm aiming for less than 44 lines in the 4 dimensional script
the swipe algorithm upper level of code
def swipe(self,d):
def _swipe(i):
def __swipe(j):
def ___swipe(k):
... # le algรถrithem
return q!=[*map(int,m)]
return any([___swipe(k)for k in range(4)])
return any([__swipe(j)for j in range(4)])
r=any([_swipe(i)for i in range(4)])
return[f"swiped {['up','down','right','left','hyperup','hyperdown','hyperright','hyperleft'][d]: <10s}","Game Won","invalid move"][max(2*r,self.gamewon)].__format__(' <18s')
the lower level code is next in line to be written
I think this might end up more lines than the 2D script.
oops there's a glitch in the matrix.
return[f"swiped {['up','down','right','left','hyperup','hyperdown','hyperright','hyperleft'][d]: <10s}","Game Won","invalid move"][max(2*(not r),self.gamewon)].__format__(' <18s')
this time I will test the engine before I write the interface because the interface is gonna be chonkers.
the cli would be hard to write or view, having only one dimension to present data in, in order for the __repr__ output to also be able to be python interpreted to convert the matrix to a matrix of raw integers
it is now fully stubbed with a few labelled insert-heres
where the important stuff is yet to be done like algorithm, board display and event loop
it's coming along great!
\x1b[100m \x1b[49m{self.eng[0,0,0,0]:0}|{self.eng[1,0,0,0]:0}|{self.eng[2,0,0,0]:0}|{self.eng[3,0,0,0]:0}\x1b[100m \x1b[49m{self.eng[0,0,1,0]:0}|...
ok so maybe I should soft code this board else it's gonna take forever to write.
the board would be 129 characters by 65 lines, but still be a square.
16x16 cells
4x4x4x4, technically
oh my god that is horrendous lmfao
send a vid of it running?
I have a challenge for you people here:
Find the smallest set of characters that you need to make turing complete python scripts.
So for example with the characters a, = and 5
You can make a valid python script, but it isn't turning complete.
The opposite example would be the character @. It brings convenience features to the language, but without it you can still achieve everything in python.
while + if + _ + 0-9 + -* + [] + <space> + =
!e
# memory initialisation
_=[0]*2**10 # 1k of ints
_[1]=3 # input data
_[2]=4 # input data
# i want to compute ceil((a**2+b**2)**0.5)
_[3]=_[1]**2--_[2]**2
while _[0]**2<_[3]:
_[0]+=1
# result value is in _[0] cell
# print value
print(_[0])
@fleet bridge :white_check_mark: Your eval job has completed with return code 0.
5
while + if + 1 + -* + [] + <space> + = + < + : + \n
from 1's we can contruct any integer using only + and -
- we can implement as --
we dont need functions and function calls, so no ()
You could use while as an if, right?
like
_[0] = <condition>
while _[0]:
# do something
_[0] = 0
!e
# memory initialisation
i=1--1
i*=1--1
i*=1--1
i*=1--1
i*=1--1
i=[1-1]*i*i # 1k of ints
i[1]=1--1--1 # input data
i[1--1]=1--1--1--1 # input data
# we want to compute ceil((a**2+b**2)**0.5)
i[1--1--1]=i[1]*i[1]--i[1--1]*i[1--1]
while i[1-1]*i[1-1]<i[1--1--1]:
i[1-1]-=-1
# result value is in i[0] cell
# calling side should get result from this cell
# print value
print(i[0])
@fleet bridge :white_check_mark: Your eval job has completed with return code 0.
5
yes
while + 1-*=<[]: + <space> + \n
i think we can implement < in other way
we can dynamically extend memory without limits, so our memory can be larger than any integer
* is probably not needed. You can use repetitive addition
yes
You can get rid of < by simply subtracting two values until one of them reaches zero
This looks more and more like brainfuck
!e
# i will use `+` and integer literals, but keep in mind they will be replaced with `--` and combination of 1's
# memory initialisation
i=[0]
i+=i
i+=i
i+=i
i+=i
i+=i
i[1]=3 # input data
i[2]=4 # input data
i[3] # = i[1]**2
i[4] # = i[2]**2
i[5] # = i[3]+i[4]
i[6] # = counter
i[7] # = while condition
i[8] # = i[0]**2
i[6]=i[1]
while i[6]:
i[6]-=1
i[3]+=i[1]
i[6]=i[2]
while i[6]:
i[6]-=1
i[4]+=i[2]
i[5]=i[3]+i[4]
i[7]=1
i[0]=0
while i[7]:
i[0]+=1
i[8]=0
i[6]=i[0]
while i[6]:
i[6]-=1
i[8]+=i[0]
i[7]=i[8]<i[5] # sorry for `<`
# result value is in i[0] cell
# calling side should get result from this cell
# print memory and value
print(i)
print(i[0])
@fleet bridge :white_check_mark: Your eval job has completed with return code 0.
001 | [5, 3, 4, 9, 16, 25, 0, False, 25, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
002 | 5
i=[0]
i+=i
i+=i
i+=i
i+=i
i+=i
in this case you can't just replace with - though. not sure how you would create multi element arrays without *. +, or an additional character
!e
# i will use `+` and integer literals, but keep in mind they will be replaced with `--` and combination of 1's
# memory initialization
i=[0]
i+=i
i+=i
i+=i
i+=i
i+=i
i[1]=3 # input data
i[2]=4 # input data
i[3] # = i[1]**2
i[4] # = i[2]**2
i[5] # = i[3]+i[4]
i[6] # = counter
i[7] # = while condition
i[8] # = i[0]**2
i[9] # for <
i[10] # for <
i[11] # flag
i[12] # res
i[6]=i[1]
while i[6]:
i[6]-=1
i[3]+=i[1]
i[6]=i[2]
while i[6]:
i[6]-=1
i[4]+=i[2]
i[5]=i[3]+i[4]
i[7]=1
i[0]=0
while i[7]:
i[0]+=1
i[8]=0
i[6]=i[0]
while i[6]:
i[6]-=1
i[8]+=i[0]
# i[7]=i[8]<i[5] # sorry for `<`
i[12] # -1 - >, 0 - =, 1 - <
i[11]=1
i[9]=i[8]
i[10]=i[8]
while i[8]==i[5]:
i[8]=-1
i[11]=0
i[12]=0
while i[11]:
i[9]-=1
i[10]+=1
while i[9]==i[5]:
i[9]=-1
i[11]=0
i[12]=-1
while i[10]==i[5]:
i[10]=-1
i[11]=0
i[12]=1
i[7]=i[12]==1
# result value is in i[0] cell
# calling side should get result from this cell
# print memory and value
print(i)
print(i[0])
@fleet bridge :white_check_mark: Your eval job has completed with return code 0.
001 | [5, 3, 4, 9, 16, 25, 0, False, -1, 25, 25, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
002 | 5
๐ค
while + 1-=[]: + <space> + \n + some character to construct large list
i can write i=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,...] but it is finite memory and it cant be expanded a runtime
this is machine with infinite registers
Instead of that, you would use -- to concatenate
Why do you need infinite?
because if memory is finite, our machine isnt turing complete
!e
print([0] (--) [0])
@cloud fossil :x: Your eval job has completed with return code 1.
001 | File "<string>", line 1
002 | print([0] (--) [0])
003 | ^
004 | SyntaxError: invalid syntax
i can make memory as large as i want
If you added in the , character to do that you might as well add * or + instead.
This is brainfuck translated to Python
pyfuck
Kind of
That makes i a character
and i can mix letters from while
there is an i in while
+ - is one extra character
this requires no extra characters
What do you plan to do with all those variables
Then yeah
but if i use variables instead of list, i cant make and use pointers to memory(
Yo
I just thought of something
Put new items using slicing
You already have colon as a character
>>> i=[]
>>> i[0:1]=[0]
>>> i
[0]
>>> i[1:2]=i
>>> i
[0, 0]
>>> i[2:]=i
>>> i
[0, 0, 0, 0]
>>> i[4:]=i
>>> i
[0, 0, 0, 0, 0, 0, 0, 0]
>>> i[8:]=i
>>> i
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
``` yeah
nice
we should track memory size to do correct slices, but it is good idea
Creativity ๐ฏ
Now one question: do you really need 0-9? couldn't you just use 1 and construct the numbers like this:
0 : 1-1
1 : 1
2: 1--1
3: 1--1--1
Yes. It's more readable with all 10 decimal digits, but we could just work with 1
So we are down to: ```
w
h
i
l
e
1
=
[
]
:
and space and `\n`
That character's name is newline
I know.
