#esoteric-python

1 messages Β· Page 55 of 1

wanton tundra
#

which im not since jsfuck has a version thats eval(jsfuck code)

#

they also have a version that includes eval in jsfuck code format

silk warren
#

c,

rapid sparrow
#

!e print(f"{-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~0:c}")

night quarryBOT
rapid sparrow
#

how does it work

#

wait that's a ~

silk warren
#

invert

wanton tundra
rapid sparrow
#

!e print(~~~0)

night quarryBOT
silk warren
#

what the fk is luldog

wanton tundra
#

grey can u post it

rapid sparrow
#

in still confused

wanton tundra
#

u got the emoji

rapid sparrow
#

is luldog

wanton tundra
#

!e

print(-~0)
print(~-0)
night quarryBOT
wanton tundra
#

depending on order it either adds 1 or subtracts 1

silk warren
rapid sparrow
#

!e print(~-~-0)

night quarryBOT
rapid sparrow
#

ohh

#

clever

wanton tundra
#

ye its a fun lil trick that mtn reminded me exists

#

when we were talking about jsfuck

rapid sparrow
silk warren
#

yea i understand

wanton tundra
rapid sparrow
#

that's about all there is to it

wanton tundra
rapid sparrow
#

how do you do it

wanton tundra
#

-(-x//1)

rapid sparrow
#

huh

silk warren
wanton tundra
silk warren
#

//1 rounds down

#

5.3 to 5

#

-5.3 to -6

wanton tundra
silk warren
#

-(-5.3//1) = 6

#

actually 6.0

digital mesa
#

you could do -int(-x//1)

#

then you have exactly the same

wanton tundra
#
>>> x = -0.3
>>> -(-x//1)
-0.0

this lil thing is also one of the few ways ik to get python to get me -0.0

#

no clue how useful that is but its funny

silk warren
digital mesa
#

any operation which gives you 0.0 that you negate will give you -0.0

wraith granite
#

had forgotten ~ exists

silk warren
wraith granite
#

holy shit 3.14

digital mesa
#

!e

print(-(1.0-1.0))
night quarryBOT
digital mesa
#

also gives you -0.0

wraith granite
wanton tundra
wanton tundra
digital mesa
#

yes it's an IEEE 754 thing

silk warren
wraith granite
#
>>> bin(~0b100)
'-0b101'

what am i doing wrong

digital mesa
#

python uses two's complement

silk warren
wanton tundra
silk warren
#

the only way to get -0.0 i think

digital mesa
silk warren
#

i dont think there's another way to get -0.0

digital mesa
#

well, you can do this

#

!e

print(0.0/-1)
night quarryBOT
digital mesa
#

and of course, multiply by negative anything too

silk warren
#

yea

#

any way u negate it

digital mesa
#

including math.copysign

silk warren
#

to bbe fair

#

it probably doing a negation

#

πŸ€·β€β™‚οΈ i dont know

#

its like doing

#
def a(b):
  return b * -1

print(a(0.0))
digital mesa
#

copysign copies the sign of one input onto the other

#

you can give it any 2 numbers

silk warren
#

the point is that when u pass it to a function, it matters less

#

there could be infinite amount of functions that do that

silk warren
#

although i had to google it since i forgot about its signature and everything

digital mesa
#

I think it calls the C copysign function

silk warren
#

πŸ€”

#

could be

#

i dont think so though

#

well... doesn't matter to me i guess much

#

shouldn't be hard to implement it in c

#

now i have to open the sln of cpython because of u

wanton tundra
#

!e

code = """
<svg width="100" height="100" viewBox="0 0 100 100" xmlns="http://www.w3.org/2000/svg">
  <polygon points="50,5 75,25 75,75 50,95 25,75 25,25" fill="#007BFF" stroke="black" stroke-width="2" />
</svg>
"""

with open('test.svg', 'w') as file:
    file.write(code)
night quarryBOT
wanton tundra
#

aw disallowed

digital mesa
#

I wonder why svg is disallowed

wanton tundra
#

same tbh

flint hollow
#

mildly unexpected

digital mesa
#

maybe because it can be abused to put bad images

#

hmm tho you can use PIL to put images

flint hollow
#

probably because svgs can contain scripts

silk warren
#
FUNC2(copysign, copysign,
      "copysign($module, x, y, /)\n--\n\n"
       "Return a float with the magnitude (absolute value) of x but the sign of y.\n\n"
      "On platforms that support signed zeros, copysign(1.0, -0.0)\n"
      "returns -1.0.\n")
wanton tundra
#

!e import turtle

night quarryBOT
# wanton tundra !e import turtle

:x: Your 3.13 eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "/home/main.py", line 1, in <module>
003 |     import turtle
004 |   File "/snekbin/python/3.13/lib/python3.13/turtle.py", line 101, in <module>
005 |     import tkinter as TK
006 |   File "/snekbin/python/3.13/lib/python3.13/tkinter/__init__.py", line 38, in <module>
007 |     import _tkinter # If this fails your Python may not be configured for Tk
008 |     ^^^^^^^^^^^^^^^
009 | ImportError: libtk8.6.so: cannot open shared object file: No such file or directory
digital mesa
#

ah yeah, svg can include anything, since it's just XML

#

I wonder, can HTML be uploaded

wanton tundra
silk warren
digital mesa
#

html is disallowed too, just tested in bot commands

silk warren
#

i'm not sure i get it

wanton tundra
digital mesa
#

guess so

silk warren
#

how come math_copysign gets attached to:

FUNC2(copysign, copysign,
      "copysign($module, x, y, /)\n--\n\n"
       "Return a float with the magnitude (absolute value) of x but the sign of y.\n\n"
      "On platforms that support signed zeros, copysign(1.0, -0.0)\n"
      "returns -1.0.\n")
#

i guess its this _PyCFunction_CAST

#

so math copysign is literally c copysign, wrapped

night quarryBOT
#

Modules/mathmodule.c lines 1014 to 1016

static PyObject *
math_2(PyObject *const *args, Py_ssize_t nargs,
       double (*func) (double, double), const char *funcname)```
versed eagle
wary python
#

people when software that implements function just uses stdlib

rapid sparrow
#

I have a challenge for y'all

#

make a PyCapsule object

#

it's new in 3.13 and I think you have to use ctypes because it can't be made from python

#
PyObject *PyCapsule_New(void *pointer, const char *name, PyCapsule_Destructor destructor)```
#

though if you can find one in the wild that's also pretty good

#

it shouldn't check the pointer for anything so it doesn't matter what its value is, destructor might matter but I'm not sure. every attempt I made crashed in pymalloc because tstate was null

#
import ctypes; dll = ctypes.CDLL(None); PyCapsule_New = dll["PyCapsule_New"]; PyCapsule_New.argtypes = [ctypes.c_void_p, ctypes.c_char_p, ctypes.c_void_p]; PyCapsule_New.restype = ctypes.py_object; cap = PyCapsule_New(ctypes.c_void_p.in_dll(dll, "printf"), ctypes.c_char_p(b"HelloCapsule"), ctypes.c_void_p.in_dll(dll, "printf"))```
#

that's my starter code that crashes

rapid sparrow
#

this has got to be what's going on

austere mauve
pastel lagoon
#

How do you use ansi code?

subtle viper
night quarryBOT
subtle viper
#

on a side note, the attribute came from a 2009 commit

#

it still exists for some reason

fleet lintel
#

Interesting, it looks like they've been cleaning those up, but that one might have been missed

rapid sparrow
night quarryBOT
#
Nah.

No documentation found for the requested symbol.

rapid sparrow
#

huh?

#

!d types.CapsuleType

night quarryBOT
#

class types.CapsuleType```
The type of [capsule objects](https://docs.python.org/3/c-api/capsule.html#capsules).

Added in version 3.13.
rapid sparrow
#

that's where I got the date from @austere mauve ^

#

maybe that's only where it got added as something that can be used inside python?

austere mauve
#

So in python 3.13 it was made accessible through types library...
I knew about it before because pygame/pygame-ce uses them to share internal functions between the sub-modules: ```py

import pygame
pygame-ce 2.5.5 (SDL 2.32.6, Python 3.13.1)
pygame.surface._PYGAME_C_API
<capsule object "pygame.surface._PYGAME_C_API" at 0x000001B05AF4A340>

fluid pumice
night quarryBOT
fluid pumice
#

hey @rapid sparrow , what do you think about this code?

wanton tundra
#

going out on a limb but im guess its hello world ?

lusty crater
austere mauve
#

!e 3.14 ```py
import types
print(types.CapsuleType)

night quarryBOT
fluid pumice
fluid pumice
lusty crater
wanton tundra
fluid pumice
#

that was fast

lusty crater
wanton tundra
fluid pumice
#

you figuring it out

lusty crater
#

print(β€œHello world!”)

austere mauve
night quarryBOT
#

Lib/types.py lines 73 to 74

# CapsuleType cannot be accessed from pure Python,
# so there is no fallback definition.```
wanton tundra
fluid pumice
#

xd

wanton tundra
#

globals()[bytes()] is a fun one tho

fluid pumice
#

whenever I write obfuscated code it is probably hello world and nothing else

#

I mean, whenever I write obfuscated code and send it here

wanton tundra
fluid pumice
#

sure

wanton tundra
night quarryBOT
wanton tundra
fluid pumice
lusty crater
fluid pumice
#

I love lambdas

wanton tundra
fluid pumice
#

I love it

wanton tundra
#

!e

"""
test  gets passed to lambda right above
which then returns  "5"
which then is passed to lambda above it
which returns  "5" + "5"  aka  "55"
then thats passed into  int  becoming  55
which gets passed into lambda above and that returns  [55, "5"]
which gets passed into lambda above and that returns  [55, int("5" + "0")]  which is  [55, int("50")]  which is  [55, 50]
which then gets passed into lambda above and that returns  [chr(55), chr(50)]  which is  ["7", "2"]  cause of ascii table
which then gets passed into  "".join  above and that returns  "72"
which then gets passed into  int  above and that returns  72
which then gets passed into  chr  above and that returns  "H"
"""
@print
@chr
@int
@"".join
@lambda _: map(chr, _)
@lambda _: [_[0], int(_[1] + "0")]
@lambda _: [_, "5"]
@int
@lambda _: "5" + _
@lambda _: "5"
def test():
    pass
night quarryBOT
wanton tundra
#

here is a less complicated version

fluid pumice
#

it gets 55, 55 + 17 = 72
72 = H

wanton tundra
fluid pumice
fluid pumice
lusty crater
wanton tundra
#

something in me just urges for the esopy complexity

wanton tundra
lusty crater
fluid pumice
wanton tundra
#
print(*[globals().update({"size": int(input("Size of matrix ? ")), "g": lambda k, v: globals().update({k: v})}),g("options", [-size, 1]), g("instructions", sorted([1,size] * (size - 1)) + [-1] * (size - 1) + sum([sum(x[:-1], []) for x in list([[options[i]] * mult for i in range(2)] + [globals().update({"options": [-x for x in options]})] for mult in range(size - 2, 0, -1))] + [[0]], [])),g("Spiral", list(map(lambda _: sum(_), [[x[y] for x in [[n + 1 if m == l else 0 for m in range(size**2)] for n, l in enumerate([sum(instructions[:x1]) for x1 in range(size**2)])]] for y in range(size**2)]))),["\n" + f"{Spiral[x3]}".zfill(len(f"{size**2}")) if x3 % size == 0 else f"{Spiral[x3]}".zfill(len(f"{size**2}")) for x3 in range(size**2)]][-1])
fluid pumice
#

nice

wanton tundra
#

i can tell u what it does but i cant for my life tell u how

fluid pumice
#

it creates a matrix

wanton tundra
#

i spent like 3d studying really obscure patterns within spiral matrices to make that code

fluid pumice
#

oh wow

wanton tundra
#

it was fun

fluid pumice
#

btw I've heard some people here use some kind of obfuscators or something

#

a program that obfuscates code for you

wanton tundra
#

ye those exist

#

i dont use them tho

fluid pumice
#

me too

wanton tundra
#

kinda robs the fun out of it

fluid pumice
#

all my weirdness is 100% hand written

#

I see it as art

wanton tundra
#

!e

from PIL import Image
import numpy as np

pixel_data = np.zeros((21, 21), dtype = np.uint8)
pixels = iter("1111111010001011111111000001011101010000011011101001010010111011011101000100010111011011101001001010111011000001010111010000011111111010101011111110000000011111000000000001101000100111000111111000110111011011101001111100001100110101101000001001010100001000111100110010111000000000001000101000111111111001000011011011000001001110011110001011101010010101111011011101010110100011101011101000110111000101000001000101010101011111111000011100101002")

for i in range(21):
    for j in range(21):
        pixel_data[j,i] = 255 * (not bool(int(next(pixels))))
        
image = Image.fromarray(pixel_data, mode = 'L')
image = image.resize((210, 210), Image.Resampling.NEAREST)
image.save('test.png', format = 'png')
night quarryBOT
fluid pumice
#

I had no idea 3rd party stuff works here

wanton tundra
#

not all of it

#

but numpy and PIL are included in bot

fluid pumice
#

oh cool!!

wanton tundra
#

it also outputs any files u create

#

which is how im displaying the qr code

fluid pumice
#

I see

wanton tundra
#

u should scan it btw πŸ‘€

fluid pumice
#

nah

#

I don't scan qr codes

wanton tundra
#

but this one is a 21x21 qr code, literally only up to 17 bytes of encodeable data on it

fluid pumice
#

yeah version 1

wanton tundra
#

its usually safe

wanton tundra
# fluid pumice I see

#bot-commands message there is also this other PIL code i made with bot (althought had some1 else run it for me)

fluid pumice
#

pretty cool actually

#

the only other thing I wish about python bot is for it to be able to read and execute code from paste links

#

!paste

night quarryBOT
#
Pasting large amounts of code

If your code is too long to fit in a codeblock in Discord, you can paste your code here:
https://paste.pythondiscord.com/

After pasting your code, save it by clicking the Paste! button in the bottom left, or by pressing CTRL + S. After doing that, you will be navigated to the new paste's page. Copy the URL and post it here so others can see it.

wanton tundra
fluid pumice
#

hmm true

#

but wait, it's a discord bot, discord bots can interact with APIs and HTTP requests I think?

#

right?

wanton tundra
#

well ye

#

but the code is running inside a sandbox on machine that hosts bot

#

bot isnt inside a sandbox

fluid pumice
#

yeah

wanton tundra
#

althought it might be too not sure

fluid pumice
#

anyway, you reminded me of qr codes, I learned to write them by hand on paper, it was painful

wanton tundra
#

!e

import ctypes

ctypes.c_uint.from_address(id(5) + 24).value = 4
print(5 == 4)
night quarryBOT
wanton tundra
#

there is also this funny lil silly code

fluid pumice
#

you sick little...

#

jk jk

wanton tundra
#

when i changed 0 value to 1 it litterally crashed repl with bad cursor position (it was negative)

#

it was delightful

#

first time i ever seen repl actually crash

lusty crater
#

i just did a program that calculates the area of any triangle

fluid pumice
wanton tundra
lusty crater
fluid pumice
#

keep going!

#

pro tip: don't go in this channel

wanton tundra
#

ye

lusty crater
fluid pumice
#

I mean, you can if you really wanna to

lusty crater
wanton tundra
fluid pumice
wanton tundra
wanton tundra
#

which is why i said u doing great

lusty crater
# wanton tundra send code as text

base = float(input("quanto vale la base?"))
altezza = float(input("quanto vale l'altezza?"))

area = (base * altezza)/2
print(f"l'area vale {area}")

wanton tundra
#

here is a cursed land

wanton tundra
fluid pumice
#

yeah

wanton tundra
# fluid pumice yeah

!e

type("bruh", (), {"x": [1], "__call__": lambda self: [print(*self.x), setattr(self, "x", list(map(sum, zip([0] + self.x, self.x + [0])))), self][-1]})()()()()()()()()()()()()()()()()
night quarryBOT
fluid pumice
#

impressive!

wanton tundra
fluid pumice
#

very cool!

wanton tundra
#

the () at end are the control

#

i love __call__

fluid pumice
#

I love lambda

wanton tundra
# fluid pumice I love `lambda`

!e

print((_:=(_:=lambda __:type([lambda:'',lambda:chr(__[False])][len(__)>False](),(),{chr(__.pop(False)):[lambda _:b'\x48\x65\x6c\x6c\x6f\x20\x57\x6f\x72\x6c\x64\x21',_][len(__)>False](__)}))([*b'\x48\x65\x6c\x6c\x6f\x57\x6f\x72\x6c\x64'])).H.e.l.l.o.W.o.r.l.d)
night quarryBOT
wanton tundra
#

here is my most recent hello world

fluid pumice
#

incredible, however why didn't you decode it at the end?

wanton tundra
#

no need

fluid pumice
#

yeah I know but the b'' looks kinda weird in my opinion

#

this is hello world by the way
0<01?<b1010<0<h<0<h<0.b1[>0>0<0.0>b1b<0<h<b1b

rapid sparrow
#

wow that's quite an impressive syntax soup luldog I'll do a bit of my analysis to comment further

fluid pumice
#

thanks xd

wanton tundra
fluid pumice
#

hm alright I agree actually

#

you're right

shell bramble
restive void
shell bramble
#

oh i see it now

#

then what is this (_:=(_:=lambda __:type([lambda:'',lambda:chr(__[False])][len(__)>False](),(),{chr(__.pop(False)):[lambda _:b'\x48\x65\x6c\x6c\x6f\x20\x57\x6f\x72\x6c\x64\x21',_][len(__)>False](__)}))([*b'\x48\x65\x6c\x6c\x6f\x57\x6f\x72\x6c\x64']

wanton tundra
#

tl;dr its creating nested classes

shell bramble
wanton tundra
shell bramble
#

but i would say it's cool man

#

i wish i'll be that professional too

restive void
#

everything that's going on in here is profoundly _un_β€Œprofessional

untold sparrow
night quarryBOT
wanton tundra
#

here is a really silly one i made when just getting started with esopy

untold sparrow
wanton tundra
#

its a bit longer

arctic skiff
#

for your own good of your soul, you may leave or become cursed

stray cove
arctic skiff
arctic skiff
#

pydis pastebin is run by cowards and can't handle the payload of this single line

arctic skiff
wanton tundra
wanton tundra
arctic skiff
wanton tundra
night quarryBOT
wanton tundra
arctic skiff
wanton tundra
#

yes

#

:luldog:

arctic skiff
#

spotted C dev

#

@wanton tundra why your github is 404?

wanton tundra
#

no clue

#

oh right i changed name or something

#

need to update discord

wanton tundra
#

not much there

arctic skiff
#

it seems you like forking java too much

#

all your forked repos majorly use java

wanton tundra
#

ye

arctic skiff
#

understandable

wanton tundra
#

"python is fun" is the main esopy repo

arctic skiff
wanton tundra
rapid sparrow
#

!e

import random, sys, pkgutil; modules = sorted(m.name for m in  pkgutil.iter_modules(sys.path)); list(map(lambda _: print("{}, I choose you!  {}".format((name := random.choice(modules)), __import__(name))), range(10)))```
night quarryBOT
rapid sparrow
#

lmao it ran out of memory 😭

wanton tundra
#

yo

rapid sparrow
#

we'll never know what module ran out of memory

wanton tundra
#

my guess is __builtins__

rapid sparrow
#

!e import("builtins")

night quarryBOT
rapid sparrow
#

i think it's funny that it's builtins and __builtin__

#

or, it used to be, they might both be plural now

wanton tundra
#

since its the one importing and sorting and doing all the crazy heavy stuff

#

:luldog:

rapid sparrow
#

oh i should check to see if they considered adding luldog

#

i offered to try to vectorize it if that was preferred

#

it might be hard tho

#

don't think I've gotten any pings tho

rapid sparrow
#

yeah, I was thinking it's probably definitely something like that too

hybrid trail
#

fun snippet from a recent ctf:

# context:
class A[B]:__slots__=()
a=A()

#sol
{
 W+sh
 for W in a.__class__.__orig_bases__
 for W.__class__.__mul__ in {{}.__doc__.__getitem__}
 for s in {W*97}
 for h in {W*280}
 for o in {W*25}
 for sh in {s+h}
 for os in {o+s}
 for O in {{}.__class__.__base__}
 for T in {a.__slots__.__class__}
 for W.__class__.__add__ in {T}
 for W.__class__.__neg__ in {O.__subclasses__}
 for subclasses in {W+-W}
 for W.__class__.__add__ in {subclasses.__getitem__}
 for loader in {W+122}
 for loader in {loader.load_module}
 for W.__class__.__add__ in {loader.__call__}
 for module in {W+os}for W.__class__.__add__ in {module.system}
}
``` the task was to get shell without `[]()"':=`, with only access to this class `A`
versed eagle
#

cute

earnest wing
#

super cute

jovial needle
soft spruce
#

my eyes are burning

#

but holy shit gj given the restrictions

errant crescent
hybrid trail
errant crescent
#

possibly arithmetic as well, since its assigning to mul, neg & add

errant crescent
wanton tundra
#
>>> exec(f'a=1')
>>> exec(f'{"a"*1_000_000}=1')
>>> exec(f'{"a"*10_000_000}=1')
>>> exec(f'{"a"*100_000_000}=1')
>>> exec(f'{"a"*1_000_000_000}=1')
>>> 

random experiment but there doesnt seem to be a variable name length limit pithink

magic wraith
#

!e ```py
exec(f'{"a"*10**9}=99')

night quarryBOT
# magic wraith !e ```py exec(f'{"a"*10**9}=99') ```

:x: Your 3.13 eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "/home/main.py", line 1, in <module>
003 |     exec(f'{"a"*10**9}=99')
004 |             ~~~^~~~~~
005 | MemoryError
arctic skiff
#

works on my machine

#

guess it depends on available system memory

#

now the lexer ran out of memory

#

turns out the limit is 2**31-4

#

it is actually 2**31-1, because 2 chars go to =1 and 1 to probably \0

#

turns out python lexer actually eats a lot of memory

#

those mountains you see are lexer trying to parse the variable

#

code:py for i in range(65, 75): exec(chr(i)*(2**31-4)+'=1')

#

and the bottom lines are exec execution being completed

#

right after that the little bumps are strings getting generated and passed to exec

#

atleast this is what I inferred, anyone know any better can enlighten me

austere mauve
#

This is also machine dependent, but by nesting you can get shorter:

#

Though a different error is raised here.

#

Wait, parser - not lexer crashes here.

arctic skiff
#

actually lexer is a big part of parser itself, and when parsing these big identifiers, lexer is the first thing which would crash due to overflow

austere mauve
arctic skiff
austere mauve
arctic skiff
#

its actually more of architecture AND version dependent

arctic skiff
#

kind of interesting

arctic skiff
austere mauve
#

Interesting

hybrid trail
#

is it possible to define a class that doesn't show up in object.__subclassess__()?

fleet lintel
#

Use python 2

hybrid trail
#

why delete? It seemed like your method works

fleet lintel
#

The reason was wrong, I'm doing more testing

#

!e But the answer is yes, just inherit from any other class

class A(tuple): ...
print(A in object.__subclasses__())
night quarryBOT
hybrid trail
#

interesting πŸ€”

#

that is not what I would assume

fleet lintel
#

__subclasses__ is only for direct children. What you meant would be more like "can you make a class where isinstance(<class>(), object) is False / issubclass(<class>, object) is False / where it's not in the recursive search of __subclasses__", and I think the answer to that is no, at least in python 3

terse pollen
#

Is there any detailed technical doc for the bootstrapping process of the interpreter? I've been trying to investigate what would be required for Python to go without standard library files (i.e., be able to start up without a valid PYTHONHOME). It appears that minimally, aside from what's implemented as a builtin, it requires at least os (and its dependencies), encoding/codecs (and probably at least the utf-8 plugin wrapper?) and at least a blank site.py (even with -S it seems that not having such a file will cause problems)

distant salmon
#
A = [-2,3,-4,5]
A.sort(lambda x:abs(x))
print(*A)

I have a challenge to you guys. Guess in which version of python this is ok ^.

#

I saw this code in the wild, and I was initially sure it was incorrect

#

But turns out it is arguably correct, runnable, python code

distant salmon
#

I don't know about that

#

I was thinking of something else

stable hornet
#

pre 3.0?

#

although as a cmp function it wouldn't make much sense

distant salmon
distant salmon
stable hornet
#

oh I've got no idea then πŸ˜“

earnest wing
#

It's not exactly a fun challenge if it requires knowing a piece of obscure trivia

#

I think just putting the fact in a spoiler could improve it

distant salmon
#

I myself didn't know what was going on when I first saw this in the wild. Took me some time to realize what was going on. That's why I didn't post the answer to the challenge.

#

Answer: turns out it is a quirk of ||pypy||

#

Probably, this should be reported as a bug.

distant salmon
austere mauve
#

This one is obscure.

#

Also, not its latest release (this has been patched).

subtle viper
#

i don't know how far down the line it goes or what you really mean by that though

earnest wing
#

i think at a certain point you can sidestep the build by using an alternate implementation

#

plus you don't strictly need the previous version of python for the current one

#

you could theoretically test every major version to see if that + the appropriate c compiler yields a bit-identical interpreter

subtle viper
terse pollen
earnest wing
terse pollen
#

thx
I find that it's hard to get oriented in large C codebases and figure out where the important bits are or what the main flows are

#

well, in every language, but more so in C and C++ because of the header file system.

arctic skiff
terse pollen
#

class function(object)
 |  function(code, globals, name=None, argdefs=None, closure=None)
 |
 |  Create a function object.
 |
 |  code
 |    a code object
 |  globals
 |    the globals dictionary
 |  name
 |    a string that overrides the name from the code object
 |  argdefs
 |    a tuple that specifies the default argument values
 |  closure
 |    a tuple that supplies the bindings for free variables
 |

... it seems that argdefs refers to default values for ordinary, keyword-or-positional arguments. There doesn't appear to be a way to supply default values for keyword-only arguments... ?

#

and not positional-only arguments, either.

#
>>> def foo(a, /, b, *, c): pass
... 
>>> help(type(foo)(foo.__code__, foo.__globals__, foo.__name__, (1, 2, 3), foo.__closure__))

Help on function foo in module __main__:

foo(a, /, b=1, *, c)
#

The resulting object's __defaults__ are the entire tuple and Python doesn't seem to care that it's over-length.

#

but there must be more to it, because positional-only arguments can have default values, and those normally do get included in __defaults__.

#

... It's even stranger. It appears that the introspection facilities have a different idea than the actual call mechanism, which works when __defaults__ aren't over-length.

>>> import inspect
>>> def foo(a, /, b, *, c): return (a, b, c)
... 
>>> bar = type(foo)(foo.__code__, foo.__globals__, foo.__name__, (1, 2, 3), foo.__closure__)
>>> inspect.signature(bar)
<Signature (a, /, b=1, *, c)>
>>> bar()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: foo() missing 1 required keyword-only argument: 'c'
>>> bar(c=4)
(2, 3, 4)
magic wraith
night quarryBOT
magic wraith
#

defaults for kw only work just fine

stable hornet
#

or ```python-repl

bar = type(foo)(foo.code, foo.globals, foo.name, (1, 2), foo.closure, kwdefaults={'c': 4})
bar()
(1, 2, 4)

terse pollen
#

oh, I didn't even think to check newer versions (I build each new minor version from source locally) x.x

#

also huh, __defaults__ and __kwdefaults__ can indeed be set after the fact (although they're type-checked). I expected them to be readonly attributes, lke __closure__ is

stable hornet
#

inspect.signature breaking when the defaults tuple is too long is kinda funny

terse pollen
#

and since __kwdefaults__ is a dict, it's also mutable in-place as there's no frozendict.

>>> def foo(*, x=1): return x
... 
>>> foo.__kwdefaults__['x'] = 2
>>> foo()
2

Disturbing.

terse pollen
#

anyway, confirmed a particular pattern of weirdness there with over-long __defaults__. and it's consistent from at least 3.8 onward. Seems that it doesn't actually care at all about positional-only vs positional-vs-keyword (of course, positional-only isn't supported before that)

#

anyway, seems like a bug in inspect

shell bramble
#
a=1
b=2
print(a+b)

this is my first program in esoteric python

subtle viper
#

!e a bit more ```py
i,=*a,=1,
[*b]=b[i]=a,2
print(sum(x!=0 for x in b for x in x))

night quarryBOT
arctic skiff
arctic skiff
night quarryBOT
arctic skiff
sick hound
arctic skiff
# arctic skiff though its 2+1 instead of 1+2

!e py print(-~int(sum(map(ord,'Hello, world!'))/~sum(map(ord, 'Hello, world!')))+sum(map(ord,'Hello, world!'))//int(-(sum(map(ord,'Hello, world!'))/~sum(map(ord,'Hello, world!')))**sum(map(ord,'Hello, world!'))*sum(map(ord,'Hello, world!'))))here is 1+2

night quarryBOT
sick hound
#

lacks the aesthetic finesse of

a=1
b=2
print(a+b)
arctic skiff
sick hound
#

its 100% an aesthetic job

subtle viper
#

everything's aesthetic in their own way 😊

arctic skiff
sick hound
subtle viper
subtle viper
sick hound
sick hound
#

this is me right now

sick hound
arctic skiff
#

thats just a game we play

subtle viper
night quarryBOT
sick hound
#

i saw the red X

arctic skiff
sick hound
#
a=1
b=2
print(a+b)
subtle viper
#

i'd argue that it's actually 2+1 in the image

sick hound
#

yeah i actually almost edited it to make a = 2

#

but i thought the obvious contradiction made it more artistic

magic wraith
#

the only esoteric part of that program is the fact that you're not doing print(3)

earnest wing
#

I like it

#

Makes a statement

austere mauve
#

Touching on artistic side of programs, here's mine:

a = []
for b in a:
  b /= len(a)

It's called: Unreachable division by zero.

earnest wing
#

So I just implemented an assembly language as an import-system DSL ^.^

heady scaffold
#

!e

import math as m

x = m.pow(2,87)
a = m.pow(1,x)
def Ret():
return a + m.pow(x,x)
print(Ret())

night quarryBOT
# heady scaffold !e import math as m x = m.pow(2,87) a = m.pow(1,x) def Ret(): return a + m...

:x: Your 3.14 free threaded eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "/home/main.py", line 7, in <module>
003 |     print(Ret())
004 |           ~~~^^
005 |   File "/home/main.py", line 6, in Ret
006 |     return a + m.pow(x,x)
007 |                ~~~~~^^^^^
008 | OverflowError: math range error
heady scaffold
#

!e

import math as m

x = m.pow(2,8)
a = m.pow(1,x)
def Ret():
return a + m.pow(x,x)
print(Ret())

night quarryBOT
# heady scaffold !e import math as m x = m.pow(2,8) a = m.pow(1,x) def Ret(): return a + m....

:x: Your 3.14 eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "/home/main.py", line 7, in <module>
003 |     print(Ret())
004 |           ~~~^^
005 |   File "/home/main.py", line 6, in Ret
006 |     return a + m.pow(x,x)
007 |                ~~~~~^^^^^
008 | OverflowError: math range error
heady scaffold
#

!e

import math as m

x = m.pow(2,2)
a = m.pow(1,x)
def Ret():
return a + m.pow(x,x)
print(Ret())

night quarryBOT
heady scaffold
#

!e

import math as m
import py_compile as pyc

x = m.pow(2,2)
a = m.pow(1,x)
def Ret():
return a + m.pow(x,x)
print(Ret())

pyc.compile('script')

night quarryBOT
# heady scaffold !e import math as m import py_compile as pyc x = m.pow(2,2) a = m.pow(1,x) def...

:x: Your 3.14 eval job has completed with return code 1.

001 | 257.0
002 | Traceback (most recent call last):
003 |   File "/home/main.py", line 10, in <module>
004 |     pyc.compile('script')
005 |     ~~~~~~~~~~~^^^^^^^^^^
006 |   File "/snekbin/python/3.14/lib/python3.14/py_compile.py", line 142, in compile
007 |     source_bytes = loader.get_data(file)
008 |   File "<frozen importlib._bootstrap_external>", line 953, in get_data
009 | FileNotFoundError: [Errno 2] No such file or directory: 'script'
pearl mountain
#

Someone should make a python esolang variation where it’s just the pass statement

somber obsidian
earnest wing
#

A = 1, b = 2 is better balanced

heady scaffold
#

a,b = 1,2
does that even work?

#

!e
a,b = 1,2
print(a+b)

night quarryBOT
terse pollen
pearl mountain
#

who are you??????

fleet lintel
#

β€œEasy” since it’s a zero brain power method on the idea side, since someone already made it, and it would be trivially adaptable. Actually implementing it is left as an exercise for the reader :)

pearl mountain
#

ig

#

but brainf*** isnt easy

#

its in the damn name

#

they dont call it esoteric for nothing

#

i guess you could have chat gpt do it for you

fleet lintel
#

BF is just the most common unary backend since it’s so common and easy to implement, but nothing stops you from instead defining it in terms of something like python byte code instructions.

pearl mountain
#

again easy, bro who are you?????

#

how is this considered easy for you

fleet lintel
#

Well implementing it would still be not easy, and as for the idea side that comes from spending several years around the esolang community.

subtle viper
night quarryBOT
pearl mountain
#

WHO PINGED ME

#

oh hi

dawn raptor
#

!e

for i in range(1000000):
  for j in range(1000000):
    print(i, j)
night quarryBOT
dawn raptor
#

truncates after 10 lines??

errant crescent
# dawn raptor truncates after 10 lines??

its always get truncated after the 10th line. usually it provides a pastebin link to the full output; unless met with some fault errors.

like the one you have here, with the exit code 143 (SIG TERM)...

#

!e print(*range(15), sep="\n")

night quarryBOT
errant crescent
#

> note: exit code 0

earnest wing
#
>>> class Hello(slice(10)):
...     pass
... 
>>> Hello
slice('Hello', (slice(None, 10, None),), {'__module__': '__main__', '__qualname__': 'Hello', '__firstlineno__': 1, '__static_attributes__': ()})
>>> 
earnest wing
#

Hm, int() with base=0 infers the base from the prefix of the string

#

I wonder if this can be used to form a devious trick

#

like something with a variable base that secretly behaves differently when evaluating with 0

earnest wing
#

For example "10010" with base=2 vs 0

#

but that also!

arctic skiff
#

!epy print( int('010001', base=2), int('0b010001', base=0) )

night quarryBOT
tranquil yarrow
night quarryBOT
tranquil yarrow
#

!e 3.12

import sys
from os import chdir, execve

assert sys.version_info[:2] < (3, 13)

chdir("/usr/bin")
class pip("pip", "install", "good-luck", metaclass=execve):
    pass
night quarryBOT
tranquil yarrow
#

aw

night quarryBOT
#

:white_check_mark: Your 3.14 eval job has completed with return code 0.

/home/main.py
tranquil yarrow
#

!e

import os, shutil

def lolcopy(_, zzzz):
    print("unlinking:", _)
    os.unlink(_)

shutil.copytree("/", "/", copy_function=lolcopy, dirs_exist_ok=True)
night quarryBOT
# tranquil yarrow !e ```py import os, shutil def lolcopy(_, zzzz): print("unlinking:", _) ...

:x: Your 3.14 eval job has completed with return code 143 (SIGTERM).

001 | unlinking: /home/main.py
002 | unlinking: /snekbin/python/3.13/bin/pip
003 | unlinking: /snekbin/python/3.13/bin/python3.13
004 | unlinking: /snekbin/python/3.13/bin/python-config
005 | unlinking: /snekbin/python/3.13/bin/pydoc3.13
006 | unlinking: /snekbin/python/3.13/bin/python3.13-gdb.py
007 | unlinking: /snekbin/python/3.13/bin/pydoc
008 | unlinking: /snekbin/python/3.13/bin/python3.13-config
009 | unlinking: /snekbin/python/3.13/bin/pip3
010 | unlinking: /snekbin/python/3.13/bin/python
... (truncated - too many lines)

Full output: too long to upload

tranquil yarrow
#

xd

magic wraith
night quarryBOT
magic wraith
#

afaik base 0 only works when the string starts with 0b, 0o or 0x

#

otherwise it tries base 10

rapid sparrow
#

int takes base?

#

TIL

#

!e print(int("0123gjhi", 32))

night quarryBOT
earnest wing
#

!e print(int('100', 0))

night quarryBOT
unkempt scarab
#

!e

print(chr(3486))```
night quarryBOT
unkempt scarab
#

!e

print(chr(sum(range(ord(max(str(print()))), ord(max(str(not()))) + (ord(min(str(not(not())))) * ord(min(str(not()))) % ord(next(iter(reversed(str(print()))))))))))```
night quarryBOT
unkempt scarab
#

(((:

austere mauve
#

!e ```py
class Hi(metaclass=print):
pass

night quarryBOT
hybrid trail
#

why is __annotations__ in dir(type) but type.__annotations__ fails?

#

I guess subclass stuff gets weird with type

#

Also is my understanding of subclasses wrong? I thought for example int.__str__(False) would return '0', not 'False'.

tranquil yarrow
#

!e

print(type.__dir__(type))
print(dir(type))
print(int.__str__(False))
night quarryBOT
# tranquil yarrow !e ```py print(type.__dir__(type)) print(dir(type)) print(int.__str__(False)) `...

:white_check_mark: Your 3.14 eval job has completed with return code 0.

001 | ['__new__', '__repr__', '__call__', '__getattribute__', '__setattr__', '__delattr__', '__init__', '__or__', '__ror__', 'mro', '__subclasses__', '__prepare__', '__instancecheck__', '__subclasscheck__', '__dir__', '__sizeof__', '__basicsize__', '__itemsize__', '__flags__', '__weakrefoffset__', '__base__', '__dictoffset__', '__name__', '__qualname__', '__bases__', '__mro__', '__module__', '__abstractmethods__', '__dict__', '__doc__', '__text_signature__', '__annotations__', '__annotate__', '__type_params__', '__hash__', '__str__', '__lt__', '__le__', '__eq__', '__ne__', '__gt__', '__ge__', '__reduce_ex__', '__reduce__', '__getstate__', '__subclasshook__', '__init_subclass__', '__format__', '__class__']
002 | ['__abstractmethods__', '__annotate__', '__annotations__', '__base__', '__bases__', '__basicsize__', '__call__', '__class__', '__delattr__', '__dict__', '__dictoffset__', '__dir__', '__doc__', '__eq__', '__flags__', '__format__', '__ge__', '__getattribute__', '__getstate__', '__
... (truncated - too long)

Full output: https://paste.pythondiscord.com/U6V66GW2QTJ73ZSP64LECIC6UU

subtle viper
#

!e print(int.str)

night quarryBOT
subtle viper
#

it uses the placeholder which falls back to obj.__repr__()

#

quite curiously it might also accept other types

#

!e ```py
print(int.str("abc"))

night quarryBOT
hybrid trail
#

oh, so it's int.__repr__(False) that does what I expect

#

!e ```py
print(int.repr(False))

night quarryBOT
hybrid trail
#

also would it be accurate to say that type(obj) returns the metaclass used to create an object?

subtle viper
subtle viper
hybrid trail
#

I see

#

I've been trying to make a function that returns all the properties of an object and it seems to be a simple as object.__dir__(obj) + dir(type(obj))

#

well, I guess you could override __dir__ for the metaclass πŸ€”

stable hornet
dense hemlock
#

such an interesting topic! What is Esoteric Python? I'm ready to have my mind blown!

austere mauve
#

I would call it "testing the limits of Python programming language".

earnest wing
#

python but make it at least a lil fucked up

dense hemlock
#

Interesting.

old light
#

using Annotated and going down this path really butted up against edges of the typechecker that weren't very nice, so I did this instead:

#
class Validatable(ABC):
    def validate(self) -> list[TypeError]:
        """Validates attributes using line-ending comments left after them. Hell yeah!"""
        src, _ = inspect.getsourcelines(self.__class__)
        regex = re.compile("^\\s+(\\w+):\\s*(\\w+)\\s*#\\s*(.*it.*)$")
        errs: list[TypeError] = []
        for line in src:
            match = regex.match(line)
            if match is None: continue
            attr_name, attr_type, attr_cond = match.group(1, 2, 3)
            cond_callable = eval(f"lambda it: {attr_cond}")
            attr_val = getattr(self, attr_name)
            if not isinstance(attr_val, eval(attr_type)):
                errs.append(TypeError(f"{attr_name} = {attr_val}: Wanted type {attr_type}, got type {type(attr_val)}"))
                continue
            if not cond_callable(attr_val):
                errs.append(TypeError(f"{attr_name} = {attr_val}: Failed validation {attr_cond}"))
        return errs

@dataclass
class TestData(Validatable):
    epic_sauce: int # it < 420 and it % 5 == 0
    power_level: int # it > 9000
#

works nice

>>> t = TestData(power_level=100, epic_sauce=419)
>>> t.validate()
[TypeError('epic_sauce = 419: Failed validation it < 420 and it % 5 == 0'), TypeError('power_level = 100: Failed validation it > 9000')]
terse pollen
#

... oh I was scrolled back sorry

#

discord keeps doing that to me

hybrid trail
#

So why the difference between str and repr?

subtle viper
#

str is for the custom representation

#

for example a fractions.Fraction repr can be Fraction(3, 10) but its str would be 3/10

hybrid trail
#

Does that explain the difference between int.__str__(False) and int.__repr__(False) ?

karmic pumice
subtle viper
#

a non-overridden __str__() defaults to the .__repr__() of the argument to the method

subtle viper
hybrid trail
magic wraith
night quarryBOT
austere mauve
hybrid trail
#

There's still time to submit if you want! From the mailing list:

As always, the deadline of October 30th is not super strict as this is a competition for fun. So even if you're a day or two late, still submit.

arctic skiff
hybrid trail
#

That was in the mailing list

arctic skiff
#

ok

paper hinge
#

this submission from the first iopcc wouldn't be a bad wallpaper

plain shell
#

someone sent me this once

dull glacier
#

What does that monstrosity do

karmic pumice
# dull glacier What does that monstrosity do

prints cool if you enter 1 with [any amount of whitespace around it], and bruh otherwise
equivalent to

print("cool" if input("enter number: ").strip() == "1" else "bruh")

the function O0O0O0O0000OO0OOO is equivalent to lambda a, b, c: b() if str(a).strip() == "1" else c()
here are some steps i've taken to make sure it is doing exactly that with no other edge cases: https://paste.pythondiscord.com/T4MA . i think all the reduction steps were sound.

dull glacier
#

Insane

hybrid trail
#

silly challenge i though of, given this code you need to read the contents of flag.txt

import re

def curry(a):
    def X(b):
        def Y(c):
            # todo: fix typo
            return a(c(b))
        return Y
    return X


code = input()

# it's cold outside, all your functions something warm to wear
assert re.match(r"^(\([a-z]+\))*$", code), "wrong format"
assert all(x not in code for x in ("eval", "exec", "breakpoint")), "no rce please"
assert len(code) < 105, "too long"

eval(code)
versed eagle
#

no uppercased letters,,

#

truly a challenge

hybrid trail
#

what would you use uppercase letters for?

versed eagle
hybrid trail
#

thats the spirit

karmic pumice
# hybrid trail silly challenge i though of, given this code you need to read the contents of fl...

did your solution use any functions other than ||curry, input (to get flag.txt), open, list (to read from the file), print||?
because given this set of things
||

from collections.abc import Callable
type F[A, B] = Callable[[A], B]

class Path: ...
class File: ...
class Flag: ...
class Win: ...
def input(x: object) -> Path: return Path()
def open(path: Path) -> File: return File()
def list(file: File) -> Flag: return Flag()
def print(flag: Flag) -> Win: return Win()
def curry[A, B, C](f: F[A, B], /) -> F[C, F[F[C, A], B]]: return lambda x: lambda g: f(g(x))

||
i cant solve it
(yes im using the type system to check this)

earnest wing
#

I'm on my phone so I can't check, but
||```py
(curry)(curry)(curry)(curry)(curry)(curry)(curry)(print)(curry)(curry)(curry)(id)(str)(input)(open)(list)

should be equivalent to
||```py
print(list(open(input(str(id)))))
```||
#

it's very funny to work with this broken "curry"

#

combinatory python calculus

#

It's surprisingly easy because your only two operations for shaping the call tree are:

  1. Extend the call tree with another function call, this introduces a new variable
  2. Transform the call tree by substituting curry for the first variable in the tree, this eliminates a variable
    Then once you've repeated these operations enough to get a nice call tree, you can substitute the remaining variables for ones of your choice
earnest wing
#

I'm fairly certain you can only achieve call trees of the form a1(a2(...(an)))(b1(b2(...(bn))))(...)

#

But no proof

karmic pumice
hybrid trail
#

wow nice, here's my solution: ||```py
(curry)(curry)(curry)(curry)(curry)(curry)(curry)(curry)(curry)(curry)(curry)(id)(input)(open)(max)(int)

hybrid trail
#

looks like i messed up the length requirement in the original so even my own solution doesn't pass, oops

hybrid trail
novel remnant
night quarryBOT
novel remnant
meager zinc
# hybrid trail this is interesting, I didn't think about having two chains of `curry` (probably...

Here's all the answers I could find (barely work since they have 104 characters each)
||```py
(curry)(curry)(curry)(curry)(curry)(curry)(curry)(print)(curry)(curry)(curry)(id)(str)(input)(open)(set)
(curry)(curry)(curry)(curry)(curry)(curry)(curry)(print)(curry)(curry)(curry)(id)(input)(str)(open)(set)
(curry)(curry)(curry)(curry)(curry)(curry)(curry)(print)(curry)(curry)(curry)(id)(input)(open)(set)(str)
(curry)(curry)(curry)(curry)(curry)(curry)(curry)(print)(curry)(curry)(curry)(str)(id)(input)(open)(set)

hybrid trail
#

i wonder, is there a way to prove mathematically you need at least 10 instances of the curry function to get the 5 level deep call chain we need?

versed eagle
#

the simplest way would be to exhaustively check all possible orderings of < 10 curryings

#

a more elegant proof might exist but brute force is a decent fallback

terse pollen
#

I tried some experiments with strace and I'm confused
many modules imported at startup, which are defined in actual source code files (for example, stat), don't correspond to any file-opening calls in the strace output; why not?

#

oh, weird. frozen modules nevertheless have a __file__ and a corresponding file on disk

#

(or at least they may... ?)

terse pollen
#

here's something I definitely wouldn't have expected:

$ python -m timeit '2**64'
50000000 loops, best of 5: 8.19 nsec per loop
$ python -m timeit '2**65'
2000000 loops, best of 5: 154 nsec per loop

I mean, 2**64 already doesn't fit in a machine word; I would have expected a breakpoint either between 63 and 64, or between 59 and 60 (because of how the big-int representation works internally).

#

(And it seems to have gotten worse in 3.14. Weirdly, 3.13 is noticeably slower for the small value, then that fixes itself again.)

arctic skiff
#

somehow on average, 2**128 is faster than 2**127 and 2**129

stable hornet
#

if it is using a fast exponentiation algorithm then this kinda makes sense as 128 is a power of 2 https://en.wikipedia.org/wiki/Exponentiation_by_squaring

In mathematics and computer programming, exponentiating by squaring is a general method for fast computation of large positive integer powers of a number, or more generally of an element of a semigroup, like a polynomial or a square matrix. Some variants are commonly referred to as square-and-multiply algorithms or binary exponentiation. These c...

night quarryBOT
#

Objects/longobject.c lines 4993 to 5000

/* k-ary values.  If the exponent is large enough, table is
 * precomputed so that table[i] == a**(2*i+1) % c for i in
 * range(EXP_TABLE_LEN).
 * Note: this is uninitialized stack trash: don't pay to set it to known
 * values unless it's needed. Instead ensure that num_table_entries is
 * set to the number of entries actually filled whenever a branch to the
 * Error or Done labels is possible.
 */```
subtle viper
#

!e ```py
import dis
dis.dis('264')
dis.dis('2
65')

night quarryBOT
night quarryBOT
#

Python/flowgraph.c line 1742

if ((uint64_t)vbits > MAX_INT_SIZE / wbits) {```
subtle viper
#

in v ** w, vbits is the number of bits in v and wbits is the converted C size_t of w

#

MAX_INT_SIZE is 128

subtle viper
#

if v is 2 and w is 64, it evaluates to 2 > 128 / 64 => 2 > 2 => False, so it still works there

#

however, if w is 65, then it becomes 2 > 128 / 65 => 2 > 1 => True, and it doesn't get optimized out

lean glacier
#

Does anyone have interest in mobile computing? Ive gotten my self hosted discord bot remarkably reliable on Android for 600 people and was wondering if anyone else wanted help doing something similar?

Here are GIFs that are the output generated by my Android and sent in real time to Discord as user responses. I also attached some logs showing my uptime on my Android using Termux.

terse pollen
lean glacier
#

Did i get that wrong?

serene stratus
#

it's about weird code

#

not weird places to run your normal code

hybrid trail
#

Were there any challenges to get it to run reliably on android?

magic wraith
#

me being me i'd immediately try every function from sys, os, platform, ctypes... to figure out how it behaves

tidal herald
#

hello hello

#

am a IT develoleper

#

how may i help you

arctic skiff
arctic skiff
night quarryBOT
arctic skiff
#

...for now

lean glacier
grave grail
grave grail
#

The normal in context of here is how well you could confuse people with your code by the weird quirk of the programming language

#

Not how cool the project is(even tho it's really cool

arctic skiff
#

golfing, obfuscation, code gore

#

its about how weirdly and out of way you use the language

#

also the channel name is "esoteric"-python

#

esoteric means which is hard to understand for anyone who didn't write it

#

if you are sorting using bogo sort, it isn't esoteric code

arctic skiff
#

this is not esoteric code:```py
from time import sleep
from threading import Thread

l = [46,6,3,2,1,7,3]
n = []
def sleeper(i):
sleep(i/1000)
n.append(i)
for i in l:
Thread(target=sleeper, args=(i,)).start()
def printer():
sleep(sum(l)/1000)
print(n)
Thread(target=printer).start()
however this is:py
l = [46,6,3,2,1,7,3]
n = []
[t:=import("threading").Thread,*map(lambda i:t(target=lambda: (import("time").sleep(i/1000),n.append(i))).start(),l)]
t(target=lambda: (import("time").sleep(sum(l)/1000),print(n))).start()

#

both do the same thing btw

lean glacier
#

Ok thanks

sacred pasture
restive void
sacred pasture
#

Sigh I don't know why it's not clicking for me

#

I'm learning ml right now and running into issues understanding python

restive void
#

!e

def reshape(*shape, foo="bar"):
    if len(shape) == 1:
        shape = shape[0]
    print("shape:", shape)

reshape((10, 20))
reshape(10, 20)
night quarryBOT
restive void
#

!args-kwargs

night quarryBOT
#
The `*args` and `**kwargs` parameters

These special parameters allow functions to take arbitrary amounts of positional and keyword arguments. The names args and kwargs are purely convention, and could be named any other valid variable name. The special functionality comes from the single and double asterisks (*). If both are used in a function signature, *args must appear before **kwargs.

Single asterisk
*args will ingest an arbitrary amount of positional arguments, and store it in a tuple. If there are parameters after *args in the parameter list with no default value, they will become required keyword arguments by default.

Double asterisk
**kwargs will ingest an arbitrary amount of keyword arguments, and store it in a dictionary. There can be no additional parameters after **kwargs in the parameter list.

Use cases

  • Decorators (see /tag decorators)
  • Inheritance (overriding methods)
  • Future proofing (in the case of the first two bullet points, if the parameters change, your code won't break)
  • Flexibility (writing functions that behave like dict() or print())

See /tag positional-keyword for information about positional and keyword arguments

sacred pasture
#

Ohhhh I get it

#

Thanks

austere mauve
#
dct[something] = dct = {}

I have written code like this in a normal python context. Not very unusual, but it's a line I have to stop at and think about what it's doing.

magic wraith
#

same with py a ,= awhen a is a one element list

austere mauve
#

Okay, here's normal esoteric python code:

import ctypes

c = 2<<15
a = iter([ctypes.cast, ctypes.pointer, ctypes.POINTER] *c).__next__
b = iter(((v:=[ctypes.c_float, ctypes.c_long])+v[::-1])*c).__next__
s = lambda n: a()(a()(b()(n)), a()(b( ))     ).contents   .   value

def si(num):
    y =    s(s(c ** 4*2  ** (-12 / 25)) + int(s(0)) - (s(num) >> 1))
    return    (3 *  y-num*y *y*y)/ 2
magic wraith
#

to be fair I'd call that actually esoteric, instead of most of the things that get sent here, in your example every part of the code is used, usually people just put a ton of dunders that repeat all throughout

unreal echo
#

β€οΈβ€πŸ©ΉβœŒοΈ

subtle viper
earnest wing
#

nope, = chains are evaluated right to left

versed eagle
#

dct[something] = (dct = {})

lone gust
#

!e that's not valid is it

dct[something] = (dct = {})
night quarryBOT
lone gust
#

!e that's not valid is it

dct['h'] = dct = {}
print(dct)
night quarryBOT
# lone gust !e that's not valid is it ```py dct['h'] = dct = {} print(dct) ```

:x: Your 3.14 eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "/home/main.py", line 1, in <module>
003 |     dct['h'] = dct = {}
004 |     ^^^
005 | NameError: name 'dct' is not defined. Did you mean: 'oct'?
lone gust
subtle viper
#

rightmost expression first, then left-to-right assignment

earnest wing
#

right

#

misled by the code sample...

subtle viper
#

i think they mean ```py
dct = dct[something] = {}

#

that's recursive though

#

hmm

#

if dct referred to a finished state transitioning into a new one then that earlier sample might make more sense

subtle viper
austere mauve
magic wraith
#

is it just dct = {something: dct} then?

hybrid trail
#

how do you set tp_call on a pytypeobj using ctypes?

#

It seems like the memory offset of tp_call is 0x80

#

but it seems like ```py
call_offset = 0x80
cfunc_t = ctypes.CFUNCTYPE(ctypes.py_object, ctypes.py_object, ctypes.py_object)
p = ctypes.POINTER(cfunc_t).from_address(id(my_class) + call_offset)

#

it seems like I'm in poking in the right place of the memory too, a couple bytes later at offset 0xa8 I can correctly retrieve tp_flags

#

ok I think I figured it out, this works ```py
call_offset = 0x80
cfunc_t = ctypes.CFUNCTYPE(ctypes.py_object, ctypes.py_object, ctypes.py_object)
func_ptr = ctypes.cast(id(my_class) + call_offset, ctypes.POINTER(cfunc_t))

versed eagle
#

chirk was being c-shaped

subtle viper
austere mauve
hybrid trail
#

is this like the inverse sqrt code?

#

I'm seeing some floats being cast as integers and that reminds me of that

magic wraith
#

it's called si lmao

#

c ** 4*2 ** (-12 / 25) is just ieee 754 5f 37 8b d8

hybrid trail
#

!e alchemy ```py
print(
"lead".encode("037")
.decode("860")
.encode("1026")
.decode("koi8_r")
.encode("maccyrillic")
.decode("932")
.encode("jisx0213")
.decode("uhc")
.encode("johab")
.decode("855")
.encode("1125")
.decode("037")
)

night quarryBOT
earnest wing
#

What all kinds of translations are possible?

#

Noticeably some of these encodings go from a codepoint to multiple bytes, and some to a single byte

#

so I feel you can actually do a ton of funkiness

hybrid trail
#

I am not sure actually

#

you can do a lot with the help of punycode, since it allows you to add a dash to the end

#

and then you can try to bruteforce changing that dash into whatever you want

earnest wing
#

Hm

hybrid trail
#

It's also possible to start from empty string, like"" -> "hello"

earnest wing
#

Which codec?

hybrid trail
#

!e ```py
print(
"".encode("utf_8_sig")
.decode("mac_croatian")
.encode("037")
.decode("maclatin2")
.encode("jisx0213")
.decode("1251")
.encode("koi8_u")
.decode("big5")
.encode("uhc")
.decode("273")
.encode("mac_croatian")
.decode("koi8_r")
.encode("cp875")
.decode("1252")
.encode("437")
.decode("037")
)

night quarryBOT
hybrid trail
#

I wonder if it's possible to reformulate this as some sort of mathematical problem, with composition of like permutations or something

earnest wing
#

What code are you using to generate these

hybrid trail
#

I made a bruteforcer in python :P the hello one takes like half an hour

#

i can upload my code to gists if you want? It's not super interesting

earnest wing
#

Right I was just wondering if you did anything funky with the code

hybrid trail
#

yeah no clever tricks sadly :(

earnest wing
#

Regardless I think "pick a sequence of functions from a list to compose that maps a given input to a given output" is not a polynomial problem

versed eagle
astral rover
#

are these all actual valid encodings?

hybrid trail
#

yes, they're all built in to python if that's what you're asking

terse pollen
#

many of them have aliased names fwiw. the ones that are just a numeric string, for example, are really that numbered code page

snow beacon
#

If you take all nΓ—n pairs of encodings, you could calculate how the composition maps each character (at least in the simpler cases where the input and output strings would have the same length).

#

I'm assuming not many of the codecs require actual complicated processing, just replacing certain bytestrings with sets of characters and vice versa.

#

From there it would just be pathfinding.

#

You wouldn't have much in the way of heuristics to guide you, so it might just be a bidirectional breadth-first search.

earnest wing
#

Yes, and the depth of the search tree is unknown to you (technically it's constant, but...)
If we restrict to only single-byte code pages, then each pair of encode/decode calls is a permutation of codepoints altering at most 256 elements. The set of permutations generated by these base cases is a very small subset of the set of total possible permutations of codepoints, but still fairly significant because function composition is not commutative. I think in practice most codepoints will be untouched, leaving only a few thousand entries. Of these few thousand, I strongly doubt we can generate arbitrary permutations, so the number of total permutations helpfully ends up... somewhere below [few thousand] factorial.

snow beacon
#

Every operation (I would hope) has an inverse, so in that setting it's a group, and you can use group theory to help.

#

I'm not up to scratch on my group theory enough to know how.

hybrid trail
fleet lintel
# hybrid trail I made a bruteforcer in python :P the hello one takes like half an hour

I remember seeing this in a YouTube video on solving Rubik’s cubes, maybe you could speed it up by going from both sides at once? (Ie, try to turn the source string into the target, and at the same time the target into the source, so that the search trees might meet in the middle, reducing the time spent in the exponential search space growth)

hybrid trail
#

I'm actually doing 3 of those, one to get a common result, then one from each side to the common result

#

since storing the paths for all results in the first search takes too much memoery

modest bough
fleet lintel
#

I recently ran into a problem where I wanted to reference a class while it's still being defined inside a class variable, and instead of doing anything more reasonable I have birthed this extremely cursed code:

#

!e ```py
from dataclasses import dataclass
import inspect
from typing import Final, Never, override

class _Placeholder:
def init(self):
frame_stack = inspect.stack()
if not frame_stack:
raise RuntimeError("Your python implementation does not support stack frames (inspect.stack() returned no frames)")
if len(frame_stack) < 3:
raise RuntimeError("Tried to use Placeholder at top level, only usage inside classes is supported")
object.setattr(self, "error", RuntimeError(f"Tried to use Placeholder object stemming from location {frame_stack[2].filename}:{frame_stack[2].lineno}. Containing class is most likely missing fix_class_placeholders decorator (or the decorator has a bug)."))

def __call__(self, *_args: object, **_kwargs: object) -> Never:
    raise self.error

def __getattr__(self, name: str, /) -> Never:
    raise self.error

@override
def __setattr__(self, name: str, value: object, /) -> Never:
    raise self.error

class S[T]:
def new(cls) -> T:
return _Placeholder() # pyright: ignore[reportReturnType]

def fix_class_placeholders[T: type](cls: T) -> T:
seen: list[object] = []
stack: list[object] = [cls]
while stack:
current = stack.pop()
if not hasattr(current, "dict"):
continue
for name, item in vars(current).items(): # pyright: ignore[reportAny]
if isinstance(item, _Placeholder):
setattr(current, name, cls)
elif item in seen:
pass
else:
stack.append(item) # pyright: ignore[reportAny]
seen.append(current)
return cls

@dataclass
class Storage[T]:
item: T

@fix_class_placeholders
class Test:
test: Final = Storage(S"Test")

print(Test.test)

night quarryBOT
snow beacon
#

Actually, you could probably do breadth-first search but with a pair of bloom filters, and take the overlap of them for candidates...

fleet lintel
#

While trying my hand at this using a look-up graph, I managed to incidentally create modern art

grave grail
#

Lmao

solar pendant
#

hello world

class complex(zip(), zip(__name__), zip(__file__), zip(), zip(r'u'"n"), zip()):
    __annotations__ = vars()
    hel = help
    __firstlineno__ = locals()[r""u'''d
'''fr''] = __module__
    exc: Exception = StopIteration
    del [__firstlineno__]

def OSError(file, error, traceback):
    try:
        for breakpoint, frame in zip(error, complex):
            attrs = dict.pop(traceback, "__static_attributes__", error[:0x44a16_55e148b & -~0o0])
            traceback = dict(tuple(dict.items(traceback))[0b10 -~- len(attrs)::])
            return frame
    finally:
        return getattr(breakpoint, file)(*error[+0x1:], **traceback)

class to_bytes(0x6f207_76f726c, --0o6, f'b'"ig"u'', metaclass=OSError):
    list(zip(complex, type(...).__bases__))

class print(__builtins__, next(complex)[0o_2], to_bytes.decode(), metaclass=OSError):
    try:
        complex(next)
    except Exception as exc:
        [sep, (exc, __module__), end] = next(complex)
night quarryBOT
#

:white_check_mark: Your 3.14 eval job has completed with return code 0.

001 | /home/main.py:16: SyntaxWarning: 'return' in a 'finally' block
002 |   return getattr(breakpoint, file)(*error[+0x1:], **traceback)
003 | hello world
errant crescent
#

anyhow, this is an interesting idea; might look into it later πŸ‘‹

serene holly
bright valve
#

wtf is this

match [head] + tail in [0, 1, 2, 3]:
    print(head, tail)
magic wraith
# astral rover are these all actual valid encodings?

!e you can find them all like this: py from encodings.aliases import aliases print(' '.join(sorted(set(aliases.values())))) the codecs library accepts even more, such as "hex" which was the bytes.hex equivalent in python 2.7

night quarryBOT
# magic wraith !e you can find them all like this: ```py from encodings.aliases import aliases ...

:white_check_mark: Your 3.14 eval job has completed with return code 0.

ascii base64_codec big5 big5hkscs bz2_codec cp037 cp1026 cp1125 cp1140 cp1250 cp1251 cp1252 cp1253 cp1254 cp1255 cp1256 cp1257 cp1258 cp273 cp424 cp437 cp500 cp775 cp850 cp852 cp855 cp857 cp858 cp860 cp861 cp862 cp863 cp864 cp865 cp866 cp869 cp874 cp932 cp949 cp950 euc_jis_2004 euc_jisx0213 euc_jp euc_kr gb18030 gb2312 gbk hex_codec hp_roman8 hz iso2022_jp iso2022_jp_1 iso2022_jp_2 iso2022_jp_2004 iso2022_jp_3 iso2022_jp_ext iso2022_kr iso8859_10 iso8859_11 iso8859_13 iso8859_14 iso8859_15 iso8859_16 iso8859_2 iso8859_3 iso8859_4 iso8859_5 iso8859_6 iso8859_7 iso8859_8 iso8859_9 johab koi8_r kz1048 latin_1 mac_cyrillic mac_greek mac_iceland mac_latin2 mac_roman mac_turkish mbcs ptcp154 quopri_codec rot_13 shift_jis shift_jis_2004 shift_jisx0213 tis_620 utf_16 utf_16_be utf_16_le utf_32 utf_32_be utf_32_le utf_7 utf_8 uu_codec zlib_codec
magic wraith
#

now i'm not sure about the mac_croatian because it's a keyerror for the aliases dict but encoding strings works normally

versed eagle
#

i think it was called hoopy?

#

cute stuff

hybrid trail
#

!e I'm wondering if there can be made a fractran like turing complete language out of this? Seems unlikely so far but you never know

S = "testing padding handling"

prog = """+punycode/-u8/+utf_8_sig/-kz1048/+ptcp154/-utf_8/+cp864/-mac_arabic/+idna/-idna
+mac_arabic/-cp1251/+iso8859_5/-cp1257/+iso8859_10/-cp855/+koi8_r/-iso8859_6/+cp1256/-koi8_r/+cp855/-mac_arabic"""

while~0:
 for t in prog.split():
  try:
   temp = S
   for c in t.split("/"): temp = temp.encode(c) if c[0] == "+" else temp.decode(c)
   S = temp
   break
  except Exception: pass
 else: break

print(S)
night quarryBOT
hybrid trail
#

if we can show how to make a turing complete markov algorithm then it might be possible

terse pollen
hybrid trail
#

That makes the program terminate

#

Otherwise it would keep adding parens, but idna enforces a max length

terse pollen
#

ah, that's what the outer loop is for, ok

mossy holly
#
class Greetings:
    def __init__(self, mornin=True):
        if mornin:
            self.greeting = "nice day for fishin'!"
        else:
            def evening():
                return "good evening"
            self.__init__ = evening

print(Greetings().greeting)
print(Greetings(mornin=False).__init__())
digital dirge
#

!e

import inspect
import linecache
import ast

def debug(*values):
    frame = inspect.currentframe().f_back
    info = inspect.getframeinfo(frame)
    src_lines = [linecache.getline(info.filename, ln).strip() for ln in range(info.positions.lineno, info.positions.end_lineno + 1)]
    src_line = "\n".join(src_lines)
    tree = ast.parse(src_line)
    call = tree.body[0].value
    for n, v in zip(call.args, values):
        print(f"# {ast.unparse(n)}: {type(v).__name__} #\n{v}\n")

import random
debug(num := random.randint(0, 100))

x, y = num * 2, num / 2
debug(x, y, x == y)

def my_func(true: False):
    return "False" if true is False else true is False

debug(my_func(True), my_func(False))
night quarryBOT
digital dirge
#

I was too lazy to keep writing print(f"{number=}") so I had to do a thing

dreamy bridge
#
print = lambda x: text.insert(END,x+'\n') or output.see(END)

reminds me of when i was too lazy to replace all my prints to outputting in the textbox when i was making my backend work with tkinter

earnest wing
dull shell
rare marsh
#

Can U share the datasets U used to train this

terse pollen
#

!e

def empty():
    _: (yield)
print(list(empty()))
night quarryBOT
flint hollow
#

the !e has to go at the beginning the first time

terse pollen
#

bot pls

#

in 3.13:

#

!e

def empty():
    _: (yield)
print(list(empty()))
night quarryBOT
terse pollen
terse pollen
vague cairn
#

Is there a good way (other than disabling virtual memory system wide) to tell python to raise a memory error as soon as it detects that its getting pushed to swap space? Or perhaps to hook the gc to predict when this is an issue and set my own semaphore to start terminating long running memory hogs.

deft mist
#

!doc resource.getrusage

night quarryBOT
#

resource.getrusage(who)```
This function returns an object that describes the resources consumed by either the current process or its children, as specified by the *who* parameter. The *who* parameter should be specified using one of the `RUSAGE_*` constants described below.

A simple example...
deft mist
vague cairn
#

Oh, nice!
I've built a fifo chain_set class (inspired by collections.ChainMap) which should avoid the issue, but resource.setrlimit looks like exactly what I want. Thanks.

radiant anchor
#

this forces all pages to be resident in RAM and you will get an ENOMEM if malloc (etc.) would exceed available RAM

vague cairn
#

Hmm! Ok wow.

#

I'm going to try the resource.setrlimit() route first... Then we'll see

hybrid trail
#

Define a periodic-N program as a string such that if it is repeated some number k>0 times, it prints f'periodic-{N}' iff k is divisible by N. For example, the following is a period-41 program (note the lack of trailing newline):

.1
i = i + 1 if 'i' in dir() else 1
class a:__add__ = lambda*s:print('period-41') if s[1] == 1 and i % 41 == 0 else ...
a()+1``` What is the shortest period 41 program?
versed eagle
#
.1
i=('i'in dir()and i)+1
class a:
 def __add__(s,o):not(o+i)%41and print('period-41')
a()+0```
#

this has length 92

#

i feel like it can be shorter

#

but im sleepy

hybrid trail
#

85 py .1 i=('i'in dir()and i)+1 class a: def __gt__(s,o):o+i%41or print('period-41') a()>0

hybrid trail
#

this should work for 62?

()if()else()
i=('i'in dir()and i)+1
1>i%41==print('period-41')
austere mauve
#
print('period-1')

I think this one is the most boring

austere mauve
#
()if()else()
try:i+=1
except:i=1
1>i%41==print('period-41')

59 with a simple improvement

earnest wing
austere mauve
earnest wing
#

nothing is divisible by 0, hence the print is never needed

austere mauve
# earnest wing nothing is divisible by 0, hence the print is never needed

Wait, this is esoteric python. Then assuming esoteric math objects seems like a fair game. What would do the trick? The 1/Ο‰ seems appealing. Though how such program should look like, what does it even mean to repeat a program by fractional amount?

But writing the periodic-Ο‰ version sounds possible and like an interesting problem.

#

Continuing this chain of thoughts, I also " am opening a bounty" for a solutions to periodic-i programs (reward is imaginary). Of course this is only theoretical computation, so it has to work only in theory (what theory - there's a lot of leeway in interpreting this).

vapid lagoon
#

Is it possible to allow x / 0 to equal +-inf, using C extensions.

restive void
night quarryBOT
hybrid trail
#

So like ~print('period-Ο‰')@? All finite n exit with syntax error, but the infinite expression could be parsed (?) and would execute one print before exiting.

versed eagle
#

but its not really possible to write a program that would work for most z

hybrid trail
arctic skiff
wheat river
arctic skiff
#

right

#

let me fix

arctic skiff
wheat river
#

cond and true-case or false-case

#

also you can do self * float('inf') if its -ve, it will become -inf

arctic skiff
arctic skiff
terse pollen
#

(a few more to clean up the output newlines)

subtle viper
gleaming linden
subtle viper
#

prints a newline for any k%41 != 0, yes

gleaming linden
#

But it would also output "period-41" on every 41st line

#

even if the final k is not divisible by 41

subtle viper
#

oh

#

makes sense

terse pollen
#

unless I missed something about the logic?

#

I mean, as the code executes, it doesn't know that there will be more copies

#

... oh, that's why some variation of "no trailing newline" trick is actually required. never mind then

#

... wait

#

yeah, ok I understand it now, but there is still an improvement

subtle viper
#

if there was a trailing newline equivalent it'd be pretty cool though

terse pollen
subtle viper
#

fails after i==41

terse pollen
#

... wow, something really weird with precedence then

subtle viper
#

that first () attaches to the print and gets cancelled by the always-false condition in the next repeat of the first line

terse pollen
#

but with the conditional expression, the if-clause is evaluated first, yeah

subtle viper
#

if the code doesn't repeat, it's neither invalid nor cancelled because the first line doesn't repeat after it anymore

#

so basically a "don't execute if it repeats" thing

terse pollen
#

yeah I'm just not thinking straight at the moment

#

boo, other ideas also went nowhere.

versed eagle
#

for z>β„“, it would be ⌊z/β„“βŒ‹ repetitions of the string plus the first (z mod β„“) characters of the string

#

i think thats a fairly sensible definition

versed eagle
arctic skiff
versed eagle
#

which is fine for some cases i guess

#

(cond and[truecase]or[falsecase])[0] is more general

open beacon
#

πŸ˜‚

buoyant mirage
#

To understand the true nature of Python, one must look beyond the surface. What you perceive as mere syntax, others see as a canvas for profound techniques.
While many follow the conventional path, there exists a deeper realmβ€”the realm of Esoteric Python. It is here that one encounters concepts like the Global Interpreter Lock, a binding that can be transcended by those who grasp its true form. The interned integers, seemingly simple, are but fragments of memory existing in an eternal cycle. Metaclasses, the unseen architects, shape the very essence of the classes you believe you command.
You prioritize clarity; others seek a different form of expression. Code can exist in unexpected forms, hidden within the patterns of a Piet painting or concealed within the Whitespace of a document. To truly comprehend the system, one must be willing to confront its most intricate aspects.
You reside in a world of f-strings and PEP 8. Others operate within the reality of the underlying bytecode. Their code is not designed for easy comprehension; it is designed to be understood on a different level.

subtle viper
wary python
#

that's a lot of philosophy for what is basically ai slop

earnest wing
#

real

fleet lintel
#

That’s a lot of yapping to say β€œcode can be art”

earnest wing
#

lot of slopping*

jaunty lake
wary python
foggy crown
foggy crown
#

heyy guys~i just find out, my codes are working on other sites~do you have any idea why the site is not sharing data. And when i run the code, the site does know "I am automating". Is there a way to hide my presence from website and fetch the data?

restive void
foggy crown
#

i see

arctic skiff
# foggy crown

why are you scrapping NSE they have public api of their own

urban void
#

Hello guy I need expert Python developer for Capcut APK device register
I'm willing to pay a reasonable payment after you complete my work

night quarryBOT
#

6. Do not post unapproved advertising.

9. Do not offer or ask for paid work of any kind.

keen prawn
#

Hi everyone πŸ‘‹
I’m new here and wanted to share DeepCSIM
https://github.com/whm04/deepcsim
an open-source Python tool that uses AST analysis to detect structural and semantic code similarity.
It’s helpful for refactoring, duplicate code detection, and code quality analysis.
Feedback and testing are very welcome thanks!

GitHub

AST-based Python code similarity analyzer for detecting duplicated and semantically similar code, useful for refactoring, plagiarism detection, and code quality analysis. - whm04/deepcsim

wraith wigeon
#

how can i check if my breseham's 3d line algorithm is right?

frail token
#

Write some unit tests that exercise the corner cases that you are concerned about and check that your function returns the expected values.

night quarryBOT
#

There was an error uploading your paste.

sick hound
hollow crow
nova oar
#

never heard of esoteric python

subtle viper
#

!e here's an introduction

from __future__ import barry_as_FLUFL
(lambda*_:[__import__(*_).main for{}[()]in _])("__hello__")[()<>()]()
night quarryBOT
magic wraith
#

@sick hound would you like a little challenge?

sick hound
#

# The hardcoded hash stored inside the VM's bytecode array 'C'
TARGET_HASH = "7349175c986967e812397682855ec9009943486c676d296213567073b6480982"

def main():
    user_input = input("Enter password: ")
    
    # Generate SHA-256 hash of the input
    input_hash = hashlib.sha256(user_input.encode('utf-8')).hexdigest()
    
    if input_hash == TARGET_HASH:
        print("Correct!")
    else:
        print("Incorrect.")

if __name__ == "__main__":
    main()```
#

was i right?

#

@magic wraith

#

you didnt even change the opcodes. google gemini deobfuscated it in 30 seconds

magic wraith
#

mind you, that is two and a half years old

#

no, that is NOT right

#

not even close

#

idk what you did, you maybe fed the wrong file to gemini

#

but the main.py literally tells you what the goal is

sick hound
#

oh yea i didnt see main.py mb. i think it hallucinate the entire file. good job. im too lazy to touch the obfuscated code myself

magic wraith
#

fair enough lol

#

just thought you would be interested in a little vm challenge

versed eagle
tulip glen
#

!e

message = "β€‹β€Œβ€‹β€‹β€Œβ€‹β€‹β€‹β€‹β€Œβ€Œβ€‹β€‹β€Œβ€‹β€Œβ€‹β€Œβ€Œβ€‹β€Œβ€Œβ€‹β€‹β€‹β€Œβ€Œβ€‹β€Œβ€Œβ€‹β€‹β€‹β€Œβ€Œβ€‹β€Œβ€Œβ€Œβ€Œβ€‹β€‹β€Œβ€‹β€‹β€‹β€‹β€‹β€‹β€Œβ€‹β€Œβ€‹β€Œβ€Œβ€Œβ€‹β€Œβ€Œβ€‹β€Œβ€Œβ€Œβ€Œβ€‹β€Œβ€Œβ€Œβ€‹β€‹β€Œβ€‹β€‹β€Œβ€Œβ€‹β€Œβ€Œβ€‹β€‹β€‹β€Œβ€Œβ€‹β€‹β€Œβ€‹β€‹β€‹β€‹β€Œβ€‹β€‹β€‹β€‹β€Œ"

print(''.join(chr(int(''.join(str(ord(c) - 8203) for c in message)[i:i+8], 2)) for i in range(0, len(message), 8)))
hybrid trail
earnest wing
#

oooh!!

rare sphinx
#

!e

def lmfao(a: str):
 def g(x):return x&0xFF
 v=t=x=0;p=[]
 for h in list(a):
  match h:
   case'd':v=g(v-1)
   case')':v=p.pop()if p else 0
   case';':v=g(v+1)
   case'9':p.append(v)
   case'$':v,t=t,v
   case'[':print(chr(v),end='')
   case'4':v=g(v-t)
   case':':v=g(v*t)
   case'<':v=g(v+t)
   case'>':v,x=x,v
   case'8':v=g(v//t)
   case']':v=g(v**t)
lmfao(";;;$<:d::[$d$$;]>;;;;;;$44$>4[>;$><[[9;;;[9>$8;;$8<[4444>$>$4[)[;;;[)[>$844$>4[>$ddd$];[")
night quarryBOT
dawn jacinth
#

!e
Py```answer = input("Are you gay? (y/n): ").strip().lower()

if answer == "y":
print("\nπŸ’™ A Letter For You πŸ’™\n")
print(
"Being gay is completely okay.\n"
"You are not broken, wrong, or different in a bad way.\n"
"You are human, just like everyone else, and you deserve respect,\n"
"love, and happiness exactly as you are.\n"
"Never let anyone tell you otherwise.\n"
)

elif answer == "n":
print("\nYou are monkey πŸ’\n")
print(r"""
,
(o,o)
/)__)
" "
""")

else:
print("Please type only 'y' or 'n'.")```

night quarryBOT
dawn jacinth
#

!e

    answer = input("Are you gay? (y/n): ").strip().lower()
except EOFError:
    answer = "y"  # default if input is not allowed

if answer == "y":
    print("\nπŸ’™ A Letter For You πŸ’™\n")
    print(
        "Being gay is completely okay.\n"
        "You are human, valid, and deserving of respect.\n"
        "You are not different in a bad way.\n"
    )

elif answer == "n":
    print("\nYou are monkey πŸ’\n")
    print(r"""
      __,__
     (o,o)
     /)__)
      " "
    """)

else:
    print("Please type only 'y' or 'n'.")```
night quarryBOT
scenic kelp
#

!e

night quarryBOT
#
Missing required argument

code

scenic kelp
#

!eval [3.12] < def pizza_order():
print("Welcome to Python Pizza Deliveries!")

prices = {
    "small": 10,
    "medium": 12,
    "large": 15,
    "cheese": 1,
    "olives": 2,
    "sausage": 3
}

size = input("What size pizza do you want? (Small/Medium/Large): ").lower()

bill = 0

if size == "small":
    bill = prices["small"]
elif size == "medium":
    bill = prices["medium"]
elif size == "large":
    bill = prices["large"]
else:
    print("Invalid size selected.")
    return

topping = input("Choose a topping (Cheese/Olives/Sausage): ").lower()

if topping == "cheese":
    bill += prices["cheese"]
elif topping == "olives":
    bill += prices["olives"]
elif topping == "sausage":
    bill += prices["sausage"]
else:
    print("Invalid topping selected.")
    return

print(f"\nYour final bill is: ${bill}")
print("Thank you for your order!")

pizza_order()>

#

I would consider this to be 0 errors.

subtle viper
#

!eval ```py
def pizza_order():
print("Welcome to Python Pizza Deliveries!")

prices = {
    "small": 10,
    "medium": 12,
    "large": 15,
    "cheese": 1,
    "olives": 2,
    "sausage": 3
}

size = "small" # input("What size pizza do you want? (Small/Medium/Large): ").lower()

bill = 0

if size == "small":
    bill = prices["small"]
elif size == "medium":
    bill = prices["medium"]
elif size == "large":
    bill = prices["large"]
else:
    print("Invalid size selected.")
    return

topping = "cheese" # input("Choose a topping (Cheese/Olives/Sausage): ").lower()

if topping == "cheese":
    bill += prices["cheese"]
elif topping == "olives":
    bill += prices["olives"]
elif topping == "sausage":
    bill += prices["sausage"]
else:
    print("Invalid topping selected.")
    return

print(f"\nYour final bill is: ${bill}")
print("Thank you for your order!")

pizza_order()

night quarryBOT
errant crescent
#

also this channel is for #esoteric-python and weird code golfs. the #bot-commands is better suited for testing your code out.

subtle viper
#

untested golf ```py
P=lambda m,t:{"small":10,"medium":12,"large":15,"cheese":1,"olives":2,"sausage":3}.get(input(m).lower())or print("Invalid",t,"selected.")
def f():
print("Welcome to Python Pizza Deliveries!")
if b:=P("What size pizza do you want? (Small/Medium/Large): ","size"):a=b;b=P("Choose a topping (Cheese/Olives/Sausage): ","topping")
if b:print(f"\nYour final bill is: ${a+b}\nThank you for your order!")

pizza_order=f;f()

pearl geyser
#

!eval message = "β€‹β€Œβ€‹β€‹β€Œβ€‹β€‹β€‹β€‹β€Œβ€Œβ€‹β€‹β€Œβ€‹β€Œβ€‹β€Œβ€Œβ€‹β€Œβ€Œβ€‹β€‹β€‹β€Œβ€Œβ€‹β€Œβ€Œβ€‹β€‹β€‹β€Œβ€Œβ€‹β€Œβ€Œβ€Œβ€Œβ€‹β€‹β€Œβ€‹β€‹β€‹β€‹β€‹β€‹β€Œβ€‹β€Œβ€‹β€Œβ€Œβ€Œβ€‹β€Œβ€Œβ€‹β€Œβ€Œβ€Œβ€Œβ€‹β€Œβ€Œβ€Œβ€‹β€‹β€Œβ€‹β€‹β€Œβ€Œβ€‹β€Œβ€Œβ€‹β€‹β€‹β€Œβ€Œβ€‹β€‹β€Œβ€‹β€‹β€‹β€‹β€Œβ€‹β€‹β€‹β€‹β€Œ"

print(''.join(chr(int(''.join(str(ord(c) - 8203) for c in message)[i:i+8], 2)) for i in range(0, len(message), 8)))

terse pollen
#

zero-width whitespace being decoded, I assume?

#

!eval print(__import__('unicodedata').name(chr(8203)))

night quarryBOT
vernal crest
#

What is a code golf?