#esoteric-python

1 messages · Page 36 of 1

maiden blaze
#

challenge: fun ways to convert a float to an int with the same binary representation

#

eg 123.456 -> 1123477881 (both are 01000010111101101110100101111001)

fleet bridge
#
>>> f = 123.456
>>> import struct as s;s.unpack('q',s.pack('d',f))[0]
4_638_387_860_618_067_575
>>>
>>> n = 4_638_387_860_618_067_575
>>> import struct as s;s.unpack('d',s.pack('q',n))[0]
123.456
#

python floats are actually doubles

#
>>> f = 123.456
>>> import struct as s;s.unpack('i',s.pack('f',f))[0]
1_123_477_881
>>>
>>> n = 1_123_477_881
>>> import struct as s;s.unpack('f',s.pack('i',n))[0]
123.45600128173828
maiden blaze
#

ctypes.c_ulonglong.from_buffer(ctypes.c_double(f)).value is another

#

kinda boring tho

fleet bridge
#
def f2n(f: float) -> int:
    import math
    sign = f < 0
    exp = int(math.log2(f))
    frac = f / 2 ** exp
    return (sign << 31) | ((exp + 127) << 23) | int(frac * 2 ** 23 + 1)


def check(f: float) -> None:
    import struct

    n1 = struct.unpack('i',struct.pack('f',f))[0]
    n2 = f2n(f)
    assert n1 > 0 and n2 > 0, (n1, n2, f)

    s1 = bin(n1)[2:].rjust(32,'0')
    s2 = bin(n2)[2:].rjust(32,'0')
    sdiff1 = ''.join(' ' if a == b else a for a,b in zip(s1,s2))
    sdiff2 = ''.join(' ' if a == b else b for a,b in zip(s1,s2))

    if s1 != s2:
        print(f'f = {f}')
        print(f'expected: {s1}')
        print(f'diff:     {sdiff1}')
        print(f'got:      {s2}')
        print(f'diff:     {sdiff2}')
        print()

import random
for _ in range(100):
    exp = random.randint(-127,+128)
    frac = 1 + random.random()
    f = frac * 2 ** exp
    check(f)
``` sometimes it works 😄
proper vault
night quarryBOT
#

@proper vault :white_check_mark: Your 3.12 eval job has completed with return code 0.

4638387860618067575
rugged sparrow
#

!e py m = memoryview(bytearray(4)) m.cast('f')[0] = 123.456 print(m.cast('i')[0]) you can abuse memoryview casting

night quarryBOT
#

@rugged sparrow :white_check_mark: Your 3.12 eval job has completed with return code 0.

1123477881
rugged sparrow
#

i actually used that trick to make doubles that i can use to make fake objects by swapping the type with CellType

weak heron
#

!e

import os
import time
from sys import platform
print("WELCOME. MAKE SURE ITS NOT https://google.com OR http://google.com IT MUST BE google.com NOT HTTPS OR HTTP.")
hostname = input("enter your epic web:   ")
response = os.system("ping " + hostname)

#check response
if platform == "linux" or platform == "linux2":
   os.system('clear')
elif platform == "darwin":
   os.system('clear')
elif platform == "win32":
   os.system('cls')
#break
print("WELCOME. MAKE SURE ITS NOT https://google.com OR http://google.com IT MUST BE google.com NOT HTTPS OR HTTP.")
print("enter your epic web:  "+ hostname)
if response == 0:
    print(f"{hostname} is running, lmao")
else:
        print(f"{hostname} is not running :(")
        time.sleep(1.0)
night quarryBOT
#

@weak heron :x: Your 3.12 eval job has completed with return code 1.

:warning: Note: input is not supported by the bot :warning:

001 | WELCOME. MAKE SURE ITS NOT https://google.com OR http://google.com IT MUST BE google.com NOT HTTPS OR HTTP.
002 | enter your epic web:   Traceback (most recent call last):
003 |   File "/home/main.py", line 5, in <module>
004 |     hostname = input("enter your epic web:   ")
005 |                ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
006 | EOFError: EOF when reading a line
meager zinc
#

I wrote this a while ago:

Python techniques for golfing:

  • ",=" operator and starred assigning (aka *x, _ = stuff). This can also convert something to a list while doing other stuff, and can be used in multiple ways. Look up the docs.
  • := operator (aka walrus or assignment-expression)
  • *x unpacking something (even **x for dicts)
  • {*x} set conversion or [*x] list conversion
  • u=long_function_name overused function renaming (if the function is used multiple times this will save space)
  • open(0) read from stdin
  • Look for alternate solutions or hacky math methods
  • Use binary operations if possible <<, ~-
  • Any kind of comprehension
  • If using a function, abuse default arguments
  • Use lambda if you can and it is shorter
  • Combine conditionals (x==2 and y==2 becomes (x==y==2)
  • Also, combine comparisons (a<b and b>c becomes a<b>c)
  • Precompute what you can
  • exec/eval can be used in clever ways, like running something multiple times (exec("print('hello world');"*5))
  • Use a,b,c,d=something to unpack it into 4 values (also use a,b,c='123' not a,b,c='1','2','3')
  • Use [::-1] to reverse a list instead of list(reversed()) [this is also better outside of golfing in general]
  • Use multiplication on bools (version-specific now) (if a and b becomes if a*b). True is 1 in this case and False is 0
  • Use += instead of append
  • Use as many builtins as you can (*guide, not a rule) as they are usually shorter
  • If you need to import something from a builtin, use from x import* or just import x, whichever is shorter.
  • If you are using string literals, use the minimal amount of escape sequences possible, or even a raw-string.
  • Never use random.randint (*guide not rule) and use id('')%n to get a random number from 1 to n-1. Note that this works in CPython but may not with other versions.
  • Use //1 to floor something
#

More tips that are smaller/rarer with less use cases:

  • Use & for set overlaps (intersections) [just use set operators in general]
  • If you want to print without a newline use print(end=x)
  • Most range() calls that are small (range(3)) are shorter as set, list, or tuple literals ({0,1,2} or for x in 0,1,2)
  • You can put many types of literals next to if statements so reorder your comparisons (if x=='a':x='b' becomes if'a'==x:x='b')
  • Use hex literals for numbers greater than 999,999
  • Use ternary statements or do an array subscript instead of if statements ([False, True][a==b])
  • If in Python 2 (idk who still is) then you can abuse the fact that all things can be compared (a<b<[]>c>d)
  • Make sure to only use spaces in increments of 1 if using identation
  • Store a lookup table as magic numbers (https://codegolf.stackexchange.com/a/41742/115749)
  • You can write n+1 and n-1 as -~n and ~-n, which can save space in parentheses due to the python order of operators
  • Use a range() and chr() setup to get a certain set of characters if it is shorter
  • Read in binary to avoid ord() calls
  • list[~i] suprisingly gets the -ith element from the reverse of list (fixes an off by one error for -i)
#

Those are more so code golfing techniques

#

If you want to get better at general esoteric-ness, I would probably just linger around the channel and spot what you can spot or look at the history of the channel

#

some topics are fishhook, different codings, ctypes, abusing syntax and language features (e.g. see my recent abusage of type bounds and default mutable arguments), and of course more.

next flame
earnest wing
#

Also, using % string formatting

unique heath
#

also dunders

#

to make shit look weird

low lynx
#

that's not golfing

modest bough
#

i'm still confused about pandas islice syntax trick like df[islice(...),:]

cloud fossil
#

Are you referring to

#

!d itertools.islice

night quarryBOT
#

itertools.islice(iterable, stop)``````py

itertools.islice(iterable, start, stop[, step])```
Make an iterator that returns selected elements from the iterable. If *start* is non-zero, then elements from the iterable are skipped until start is reached. Afterward, elements are returned consecutively unless *step* is set higher than one which results in items being skipped. If *stop* is `None`, then iteration continues until the iterator is exhausted, if at all; otherwise, it stops at the specified position.

If *start* is `None`, then iteration starts at zero. If *step* is `None`, then the step defaults to one.
modest bough
cloud fossil
#

It seems like it's a convenience class for what would otherwise be an iterable of slice objects

earnest wing
#

yes, because you can only use the : sugar inside indices

#

hence if you want to group slices together you need to do it in a separate slicing object

spiral parrot
#

idk if anyone is interested in code golf, but I was able to tie the best Python solution for the Evil Numbers problem at 40 bytes https://code.golf/evil-numbers#python:

i=0
while i<51:print(i);i=i+2^-(i+2^i)%3
#

(I didn't figure out the math, I yoinked it from stack exchange)

finite blaze
#

I don't think that many people here are interested in code golfing

gleaming linden
#

I am interested in code golfing

modest bough
#

oh I see, you can't enjoy : outside a getitem override

#

in a function f, f(1:2) will be invalid syntax, but with any class you can then use it

#

f[1:,:,:2,::3,1::3]
((slice(1, None, None), slice(None, None, None), slice(None, 2, None), slice(None, None, 3), slice(1, None, 3)),)

#

so fun

maiden blaze
spiral parrot
#

I don't think so, but let me try it

#

nah it doesn't work

#

i actually don't know why though

#

it's probably something to do with the invert ^

maiden blaze
#

i suppose a+b^c is parsed as (a+b)^c

spiral parrot
#

!e

print(1+2^3)
print((1+2)^3)
night quarryBOT
#

@spiral parrot :white_check_mark: Your 3.12 eval job has completed with return code 0.

001 | 0
002 | 0
meager zinc
#

yeah that's because of operator precedence

versed eagle
#

lol

versed eagle
meager zinc
#

does this work?

i=0
while i<51:print(i:=i+2^-(i+2^i)%3)
#

ah wait no it wont

finite blaze
versed eagle
#

oh

quartz wave
#

hehe ```pycon

type('',(),{'del':lambda _:print("the following is NOT 2")})()
<main. object at 0x0000026F698623F0>
2
the following is NOT 2
2

karmic pumice
#

lmao

#

does anyone know how to use a file codec after its ,,added" via site.addsitedir pth file

#

like it isnt available if i do it right at the start if its not loaded but after site.addsitedir it no longer cares as its not the first line

#

and i dont want to do add the thing to my actual site directory

karmic pumice
#

k i got something to work lmao

import site
import os
site.addsitedir(os.path.dirname(os.path.realpath(__file__))+"/autoexec")
import run # can use # coding: <> in run.py 
#
print((λx:x+1)(1))

lmao this finally works

versed eagle
#

i would think it gets cleaned up immediately?

#

OH

#

builtins._ in the repl

#

that's really funny

quartz wave
#

until i tested it out

versed eagle
#

python's repl is so silly

versed eagle
#

not necessarily

#

but in general, being good at golfing requires in-depth knowledge of a language

orchid glen
#

I love golfing

#

I'm not good at it but I love it

vestal solstice
#

it's almost entirely true

#

you don't need to be good at maintainability

#

but everything else counts

grave rover
#

Is there a hacky way to add a parameter to a function with CodeType/FunctionType modifications?

rugged sparrow
night quarryBOT
#

@rugged sparrow :white_check_mark: Your 3.12 eval job has completed with return code 0.

abc
rugged sparrow
#

is that what you mean?

grave rover
#

mainly looking for keyword-only args since I don't know exactly how those work

rugged sparrow
#

You can probably bump up the number of co_kwonlyargcount the same way, but you may need to add a variable name to make the bind correct

rugged sparrow
night quarryBOT
#

@rugged sparrow :x: Your 3.12 eval job has completed with return code 1.

001 | foobar
002 | Traceback (most recent call last):
003 |   File "/home/main.py", line 7, in <module>
004 |     foo()
005 | TypeError: foo() missing 1 required keyword-only argument: 'c'
grave rover
#

Hmm I see I see

#

I can use this to make a patch I think

rugged sparrow
#

the tricky part would be aligining the variables, since locals are order dependent

grave rover
#

But according to that code snippet, wouldn't it just be ```py
co_varnames = (*co_varnames[:co_argcount], myvarname, *co_varnames[co_argcount:])
co_argcount += 1
co_kwonlyargcount += 1
f.defaults = (*f.defaults, mydefault)

rugged sparrow
#

maybe

#

the name might also need to have been referenced

rugged sparrow
grave rover
#

Gotcha

rugged sparrow
# grave rover Gotcha

!e ```py
def foo():
print(locals())

foo.code = foo.code.replace(
co_kwonlyargcount=1,
co_varnames=('varname',),
co_nlocals=1
)
foo.kwdefaults = {'varname':'value'}
foo()```

night quarryBOT
#

@rugged sparrow :white_check_mark: Your 3.12 eval job has completed with return code 0.

{'varname': 'value'}
subtle meteor
#

Can I ask or tell about some exotic things in python?

#

Well... this thing is not very strange, but interesting

print([0xfor x *range(y << exec("raise ValueError"))])

hard spoke
#

ah, that's a funny one. I was so confused until I figured out how it was parsed.

restive void
meager zinc
#

hex literal trickery

fleet bridge
#

TIL in python 2.2 you can specify metaclass for all classes in one module by using module-level __metaclass__

#

it became unsupported in 3.0

outer surge
#

speaking of Python 2, I miss this ```>>> "x" <> '"x"'
True

arctic plume
#

!e

import time

def functionThatTakesTime():
    time.sleep(0)
    return "Some value"

def functionThatDoesThings(verbose=True):
    print("Running function")
    return [
        functionThatTakesTime(),
        print("Finished running function") if verbose else None
        ][0]

print(functionThatDoesThings())
night quarryBOT
#

@arctic plume :white_check_mark: Your 3.12 eval job has completed with return code 0.

001 | Running function
002 | Finished running function
003 | Some value
arctic plume
#

No need for an intermediate variable

#

Not to mention some fancy logging module that's more advanced than the project it's being used in

fleet bridge
#

oh wait

#
'x' + `'x'` == "x'x'"
#

but py 'x' + `x` doesnt work because x is not defined

astral rover
#

its just repr right?

fleet bridge
#

yes it is

#

TIL ... is not a valid syntax in python2

restive void
outer surge
fleet bridge
#
C:\Users\denba>py -2 -c "..."
  File "<string>", line 1
    ...
    ^
SyntaxError: invalid syntax

C:\Users\denba>py -2 -c "print(...)"
  File "<string>", line 1
    print(...)
          ^
SyntaxError: invalid syntax

C:\Users\denba>py -2 -c "x[...]"
Traceback (most recent call last):
  File "<string>", line 1, in <module>
NameError: name 'x' is not defined

C:\Users\denba>py -2 -c "x[... + 1]"
  File "<string>", line 1
    x[... + 1]
          ^
SyntaxError: invalid syntax

C:\Users\denba>py -2 -c "[][...]"
Traceback (most recent call last):
  File "<string>", line 1, in <module>
TypeError: list indices must be integers, not ellipsis

C:\Users\denba>py -2 -c "type('',(),dict(__getitem__=lambda self, x: __import__('sys').stdout.write(str(x))))()[...]"
Ellipsis

C:\Users\denba>py -2 -c "print(Ellipsis)"
Ellipsis
#

interesting

#

so ... is special-cased inside x[]
x[...], x[...,...] and x[...,1:2,...] are valid
x[... + 1], x[...:...] are not

versed eagle
#

tbh i miss the backtick repr

#

its a nice syntax

maiden blaze
#

its 0xf or ...

#

the lhs is truthy so the rhs isnt evaluated at all

subtle meteor
#

: )

vast wave
low lynx
karmic pumice
#

naive python source code parsing would malfunction here i guess

#

like it would assume that the or is inside the hex literal

#

tbh just use tokenize(r) if its valid python originally

low lynx
#

or use ast

#

or other syntax trees

versed eagle
#

what happens if

1
1 1

or even

2
1
weak eagle
#

err

dense fiber
fleet bridge
#

I have two questions, one is pretty esoteric, one is not. Idk where is the best place to ask it, so i am asking here:

  1. I have a pointer. How to determine if I can dereference the pointer?
    Maybe something like (idk if this is possible on windows) ```cpp
    void* ptr = 42;
    try:
    (char)ptr;
    except SEGFAULT:
    return not_valid;
    else:
    return valid;
I want it to work on windows preferably in pure python (with ctypes), but simple c-extension is also good.
Additional features that will be nice to have:
- is an entire range from X to Y valid?
- how many bytes after X are available?
- somehow iterate over all available bytes (= get list of all available ranges)

2. I'm starting python thread in some game. I want to talk to this thread from another process. How can I do that?
I thing `socket` can do it, but i think it is too low-level. What are other approaches to this?

What is this for: injected dll will read and write to memory, external process is a CheatEngine-like GUI for that.
I want to send commands like "write X to Y" or "read N bytes from X" to my thread in game, so i can control and monitor game state from outside without big changes to the game itself.

note: there is no tos violation/malicious intent, this is only for educational and research purposes
#

!d multiprocessing.shared_memory.SharedMemory TIL this is a thing in stdlib 😄

night quarryBOT
#

class multiprocessing.shared_memory.SharedMemory(name=None, create=False, size=0)```
Creates a new shared memory block or attaches to an existing shared memory block. Each shared memory block is assigned a unique name. In this way, one process can create a shared memory block with a particular name and a different process can attach to that same shared memory block using that same name.

As a resource for sharing data across processes, shared memory blocks may outlive the original process that created them. When one process no longer needs access to a shared memory block that might still be needed by other processes, the [`close()`](https://docs.python.org/3/library/multiprocessing.shared_memory.html#multiprocessing.shared_memory.SharedMemory.close) method should be called. When a shared memory block is no longer needed by any process, the [`unlink()`](https://docs.python.org/3/library/multiprocessing.shared_memory.html#multiprocessing.shared_memory.SharedMemory.unlink) method should be called to ensure proper cleanup.
versed eagle
# fleet bridge I have two questions, one is pretty esoteric, one is not. Idk where is the best ...
  1. off the top of my head, there are three ways i can think of
  • find where the allocation information is stored and use that (requires significant amount of work + understanding the malloc (or other memory allocator) implementation you're using)
  • brute force it: fork, have the child deref the pointer, and see if the child segfaults. to get more information (size of allocation, etc.) do the fork/deref check for each byte you want to check in the range
  • i dont remember what the exact name is but there's a thing in /proc/self that has all the memory maps of the process. you could read that
grave rover
#

But safest will always be to run it in a subprocess as recovering from a segfault is a scary thing to do

#

On Linux you could query /proc/self (I believe?) to see what memory regions are accessible as well

rugged sparrow
#

the write syscall internally does not fail on invalid read

#

let me find my code

grave rover
#

Wait what

#

That sounds cursed as hell

rugged sparrow
grave rover
#

Identical behavior across operating systems?

rugged sparrow
#

it has worked on my unix based x86 macbook and on an x86 ubuntu box

#

about to test on arm

#

i doubt windows works, but you can already catch invalid r/w on windows by default

rugged sparrow
night quarryBOT
#

@rugged sparrow :white_check_mark: Your 3.12 eval job has completed with return code 0.

001 | False
002 | True
rugged sparrow
#

you could also use the pipe directly to deref the pointer, by passing a size to use instead of 1 and then just reading from r with os.read

#

@grave rover ^ it worked on my m2 mac as well, i think that behavior is part of spec

#

if you print the OSError, it reprs as [Errno 14] Bad address (at least on my m2 macbook)

grave rover
#

This is so incredibly cursed I love it

rugged sparrow
#

i need to find my original notes on it, I remember i walked thru the unix source to find the reason for it

fleet bridge
fleet bridge
rugged sparrow
#

Oh really? Sweet

#

Never tested it on windows

fleet bridge
rugged sparrow
fleet bridge
#

yes, that will work, but it requires reading every byte, so it is a bit slow for big ranges

rugged sparrow
#

you could do a binary search inward

#

for a few layers deep until you are confident that the entire range is probably good

fleet bridge
rugged sparrow
#

true

fleet bridge
#

if page size is 4kb, i think i can check every byte with step 4k

rugged sparrow
#

thats what i was about to say, you can compute the start of the page from a given address

fleet bridge
#

isnt that just ptr - ptr % pagesize ?

rugged sparrow
#

ptr & ~(pagesize - 1) i think? let me check my asmhook code

fleet bridge
#

ptr & ~(pagesize - 1)

#

yeah

rugged sparrow
#

and you can get the pagesize with libc

#

!e ```py
from ctypes import cdll
libc = cdll.LoadLibrary(None)
print(hex(libc.getpagesize()))

night quarryBOT
#

@rugged sparrow :white_check_mark: Your 3.12 eval job has completed with return code 0.

0x1000
fleet bridge
#

doesnt work on windows :(

rugged sparrow
#

^ that has example C code for windows

#

i can adapt to ctypes code gimme a sec

fleet bridge
#

i cant figure out how to load winapi dll

#

nvm, there is no such thing as winapi.dll

#

there is kernel32.dll

rugged sparrow
# fleet bridge i cant figure out how to load winapi dll
from ctypes import windll, Structure, Union, POINTER, c_int, c_void_p, c_short, byref

class DUMMYSTRUCTNAME(Structure):
    _pack_ = 1
    _fields_ = (
        ('wProcessorArchitecture', c_short),
        ('wReserved', c_short)
    )

class DUMMYUNIONNAME(Union):
    _fields_ = (
        ('dwOemId', c_int),
        ('DUMMYSTRUCTNAME', DUMMYSTRUCTNAME)
    )

class _SYSTEM_INFO(Structure):
    _pack_ = 1
    _fields_ = (
        ('DUMMYUNIONNAME', DUMMYUNIONNAME),
        ('dwPageSize', c_int),
        ('lpMinimumApplicationAddress', c_void_p),
        ('lpMaximumApplicationAddress', c_void_p),
        ('dwActiveProcessorMask', POINTER(c_int)),
        ('dwNumberOfProcessors', c_int),
        ('dwProcessorType', c_int),
        ('dwAllocationGranularity', c_int),
        ('wProcessorLevel', c_short),
        ('wProcessorRevision', c_short)
    )

_getsysteminfo = windll.kernel32.GetSystemInfo
_getsysteminfo.argtypes = [POINTER(_SYSTEM_INFO)]

def getsysteminfo():
    systeminfo = _SYSTEM_INFO()
    _getsysteminfo(byref(systeminfo))
    return systeminfo

print(getsysteminfo().dwPageSize)```
#

^ that should work, tested on a windows vm

#

I should really build a C struct -> ctypes Structure converter

#

no point in doing all of that by hand

fleet bridge
#
import ctypes
lib = ctypes.WinDLL('kernel32')
si = ctypes.create_string_buffer(100) # arbitrary big enough size
lib.GetSystemInfo(si)
print(ctypes.c_int32.from_address(ctypes.addressof(si) + 4)) # pagesize is located at offset 4
del si # how to properly deallocate it?
#

^ i did this

rugged sparrow
#

that works (btw kernel32 is accessible at ctypes.windll.kernel32)

fleet bridge
#

🧐

rugged sparrow
#

os.write returns the number of bytes written, so using it with if there works

#

hmm

#

actually

#

!e ```py
import os
from ctypes import c_char
def check_addr(addr):
r, w = os.pipe()
try:
return os.write(w, (c_char*1).from_address(addr)) == 1
except OSError:
return False
finally:
os.close(r)
os.close(w)

print(check_addr(1337)) # invalid address
print(check_addr(id(1))) # valid address``` now it'll only return True or False, previously if the address was valid but write wrote 0 due to other reasons, it would return None

night quarryBOT
#

@rugged sparrow :white_check_mark: Your 3.12 eval job has completed with return code 0.

001 | False
002 | True
fleet bridge
#
def check_addr(addr: int) -> bool:
    r, w = os.pipe()
    try:
        os.write(w, (c_char*1).from_address(addr))
    except OSError:
        return False
    else:
        return True
    finally:
        os.close(r)
        os.close(w)
#

is that the same?

rugged sparrow
#

that would return True if an address was readable but the os did not read any bytes (there are some weird edge cases where it can do that)

#

if thats ok with your impl then that should work

fleet bridge
#

oh, i see

#

i dont think this will happen, but i will keep it in mind

rugged sparrow
#

afaik, the only way that could happen with the above code is if the pipe buffer is full which I don't think could be possible

#

although on some os's where pipes share a global buffer it could happen

#

but it should be extremely unlikely

rugged sparrow
fleet bridge
#

indeed

fleet bridge
#

nobody asked

rugged sparrow
#

are you loading pythondlls into a game?

fleet bridge
#

yes

#

why not

#

not all at once, obviously

fleet bridge
#

i am trying to start thread, but it refuses to start and just hangs whole application
im not sure what is happening
i tried to print-debug it, and it hangs here: https://github.com/python/cpython/blob/3.12/Lib/threading.py#L983
i guess that is because new thread quickly crashes and doesnt unlock the lock, but i dont see any exceptions printed to stdout/stderr/__stderr__

game has its own threads, and i am starting my own thread from one of game's threads
interpreter otherwise works fine

do you have any ideas why this doesnt work?

night quarryBOT
#

Lib/threading.py line 983

self._started.wait()```
rugged sparrow
#

tbh i have no idea, could be the game is managing threads and is killing the child thread you start?

#

what game is it and how are you injecting code?

fleet bridge
#

game is Space Rangers HD, written in old delphi (delphi 7, iirc), 32bit
i'm loading my dll using game's script function, it just loads dll without anything else fancy
all my code is in DllMain, i'm initializing interpreter and starting little python script that hangs on mythread.start(), and that hangs entire game because game waits my code to complete

#

it is also tricky to make stdout/stderr work in that environment since GUI app doesnt have them
i tried this: c freopen(LOGFILE_STDOUT, "w", stdout); setvbuf(stdout, NULL, _IONBF, 0); // no buffering freopen(LOGFILE_STDERR, "w", stderr); setvbuf(stderr, NULL, _IONBF, 0); and this: ```py
out = open('####py-stdout.log', 'at', buffering=1) # line-buffering
sys.stdout = sys.stdout = out
sys.stderr = sys.stderr = out


but i still dont see any errors printed related to thread failure
rugged sparrow
#

maybe try launching a thread with C then loading the interpreter there? i think that python needs the main thread to stay alive

fleet bridge
#

yeah, i was thinking about that
tomorrow i will try creating just thread without python and doing something in it
if it works, i will launch python in it

rugged sparrow
#

smart

fleet bridge
#

hmm, maybe there are some GIL problems? (if i initialized python incorrectly)
parent threads holds gil, child tries to do something but gil is held, so parent is holding gil and waiting for child indefinitely

rugged sparrow
#

Could be, I'm not sure how the GIL works when embedding python

harsh spear
#

!e ```py
metamaker = (lambda meta, cls: ( lambda: [ (dict_.pop(es, None) for es in dict_.get("slots", tuple())) if [None for [globals()["dict_"]] in [[dict(cls.dict)]]][0] is None else None, [None for [globals()["dict_"]["metaclass"]] in [[meta]]], [None for [globals()["dict"]["wrapped"]] in [[cls]]], meta(str(cls.name), tuple(cls.bases), dict), ][-1]))
printf = lambda format_string, *args: print(format_string,end="") if not args else print(format_string % args,end="")
main = metamaker(type("b", (type,), {"call": lambda self, : {None}}), type("", (object,), {}))()
int = metamaker(type("a", (type,), {"sub": lambda self2, : {None} if isinstance(, set) else [None for [globals()[
.split("=")[0]]] in [[import('builtins').int(_.split("=")[1])]]][0]}), type("a", (object,), {}))()
void = None
return_0 = None

int-main(void)-{
printf("Hello, World!\n"),

int-"num1=2",
int-"num2=3",

printf("%d + %d = %d\n", num1, num2, num1+num2),
return_0
}```

night quarryBOT
#

@harsh spear :white_check_mark: Your 3.12 eval job has completed with return code 0.

001 | Hello, World!
002 | 2 + 3 = 5
unique heath
#

the actual fu-

restive void
#

Beautiful

fleet bridge
#

the most esoteric thing here is the message from bot

quartz wave
restive void
#

indeed

unique heath
#

same as cereals

fleet bridge
#

are you on pc or phone?
react with this: 🐧 🤖 🍎 🪟

quartz wave
arctic skiff
versed eagle
chrome eagle
#

How can I change the video output of the manim library

#

I have to change the resolution and framerate of the video making it more high defination and quality

restive void
versed eagle
#

true

#

alternatively, you could use codecs and just invoke a c compiler on the source

dense nova
#

!e

_:(__import__(''.join([(lambda:(__:=[*(_*(4>>(4).__class__(4/4)))],__.insert((4).__class__(4/4),[4].__class__.__class__.__name__[(4).__class__(4/4)]),globals().__setitem__('__',__)))(),__][-1]))).stdout.write((4==.4).__class__.__name__[4-4]+(4,).__class__.__name__[(4).__class__(4-4-4/4)]+(.4).__class__.__name__[-(4>>1)]+(4).__class__.__name__[(4).__class__(4/4)]+[4].__class__.__name__[-(4>>1)]+chr(4+4+(4>>(4).__class__(4/4))))=[4].__class__.__name__[-(4>>1)]
night quarryBOT
#

@dense nova :white_check_mark: Your 3.12 eval job has completed with return code 0.

beans
dense nova
#

4 is nice

#

could use optimizations

unique heath
# dense nova !e ```py _:(__import__(''.join([(lambda:(__:=[*(_*(4>>(4).__class__(4/4)))],__.i...

!e

__builtins__.__getattribute__(__builtins__.__dir__().__getitem__(__builtins__.__dir__().__len__().__floordiv__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__()).__add__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__()).__add__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__()).__add__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__()))))).__add__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__())).__add__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__())).__add__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__()))))((4==.4).__class__.__name__[4-4]+(4,).__class__.__name__[(4).__class__(4-4-4/4)]+(.4).__class__.__name__[-(4>>1)]+(4).__class__.__name__[(4).__class__(4/4)]+[4].__class__.__name__[-(4>>1)]+chr(4+4+(4>>(4).__class__(4/4))))```
night quarryBOT
#

@unique heath :white_check_mark: Your 3.12 eval job has completed with return code 0.

beans
unique heath
#

not eso enough hmm

#

!e

__builtins__.__getattribute__(__builtins__.__dir__().__getitem__(__builtins__.__dir__().__len__().__floordiv__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__()).__add__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__()).__add__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__()).__add__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__()))))).__add__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__())).__add__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__())).__add__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__()))))((_:=__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__()).__add__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__()).__add__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__()).__add__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__())))),(_==.4).__class__.__name__[_-_]+(_,).__class__.__name__[(_).__class__(_-_-_/_)]+(.4).__class__.__name__[-(_>>1)]+(_).__class__.__name__[(_).__class__(_/_)]+[_].__class__.__name__[-(_>>1)]+chr(_+_+(_>>(_).__class__(_/_))))[__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__())])
night quarryBOT
#

@unique heath :white_check_mark: Your 3.12 eval job has completed with return code 0.

beans
unique heath
#

tehre we go

#

i'll let the chr and hte .4s live

#

for now

#

!e py __builtins__.__getattribute__(__builtins__.__dir__().__getitem__(__builtins__.__dir__().__len__().__floordiv__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__()).__add__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__()).__add__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__()).__add__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__()))))).__add__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__())).__add__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__())).__add__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__()))))((_:=__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__()).__add__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__()).__add__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__()).__add__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__())))),(_==.4).__class__.__name__[_-_]+(_,).__class__.__name__[(_).__class__(_-_-_/_)]+(.4).__class__.__name__[-(_>>1)]+(_).__class__.__name__[(_).__class__(_/_)]+[_].__class__.__name__[-(_>>1)]+__builtins__.__getattribute__(__builtins__.__dir__().__getitem__(_.__mul__(_).__sub__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__())).__sub__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__()))))(_+_+(_>>(_).__class__(_/_))))[__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__())])

night quarryBOT
#

@unique heath :white_check_mark: Your 3.12 eval job has completed with return code 0.

beans
unique heath
#

!e py __builtins__.__getattribute__(__builtins__.__dir__().__getitem__(__builtins__.__dir__().__len__().__floordiv__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__()).__add__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__()).__add__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__()).__add__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__()))))).__add__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__())).__add__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__())).__add__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__()))))((_:=__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__()).__add__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__()).__add__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__()).__add__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__())))),__:=_.__floordiv__(_),(_==_.__truediv__(_.__add__(_).__add__(__.__add__(__)))).__class__.__name__[_.__sub__(_)]+(_,).__class__.__name__.__getitem__((_).__class__(_.__sub__(_).__sub__(_.__floordiv__(_))))+(_.__truediv__(_.__add__(_).__add__(__.__add__(__))).__class__.__name__[-(_.__rshift__(__))]+(_).__class__.__name__[(_).__class__(_.__floordiv__(_))]+[_].__class__.__name__.__getitem__((_.__rshift__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__()))).__neg__())+__builtins__.__getattribute__(__builtins__.__dir__().__getitem__(_.__mul__(_).__sub__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__())).__sub__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__()))))(_+_+(_.__rshift__(_).__class__(_.__truediv__(_))))))[__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__()).__neg__()])

night quarryBOT
#

@unique heath :white_check_mark: Your 3.12 eval job has completed with return code 0.

beans	
unique heath
#

slight esotericisms

bold crag
#

!e

((((((((lambda _, __, ___, ____: chr(___ % __) + _(_, __, ___, ____))(
    lambda _, __, ___, ____: _(_, __, ___, ____).__add__(chr(____ % __))
    if ____ else '',
    ord('h') << 7,
))(lambda _, __, ___: _(_, __, ___))(lambda _, __, ___: _ if __ <= _ else _(_, __ - _, ___)(_ + _, __, ___) if not __ % _ else _(2, __ + 2, ___), 2, 16)))))(__import__(().__class__.__name__[::3] + 'y').__class__.__name__[::-1], lambda _, __, ___: _(_, __, ___))
night quarryBOT
#

@bold crag :x: Your 3.12 eval job has completed with return code 1.

001 |   File "/home/main.py", line 1
002 |     (((((((((lambda _, __, ___, ____: chr(___ % __) + _(_, __, ___, ____))(
003 |       ^
004 | SyntaxError: '(' was never closed
bold crag
unique heath
#

this is just paren spam

bold crag
#

I'm not even sure

#

Where it comes all from

#

It isn't even functional

#

Pain.

rugged sparrow
#

oh yea that makes sense, in the repl, the expression results are printed if they are not None, even in a for loop. So it reaches quit, tries to output it, and segfaults on the invalid read from zero

fleet bridge
#

actually this is a feature of single compile mode: ```py

dis(compile('x;y', '', 'single'))
0 0 RESUME 0

1 2 LOAD_NAME 0 (x)
4 CALL_INTRINSIC_1 1 (INTRINSIC_PRINT)
6 POP_TOP
8 LOAD_NAME 1 (y)
10 CALL_INTRINSIC_1 1 (INTRINSIC_PRINT)
12 POP_TOP
14 RETURN_CONST 0 (None)

#

CALL_INTRINSIC_1 1 (INTRINSIC_PRINT) simply calls sys.displayhook

#
>>> dis(compile('x;y', '', 'single'))
  0           0 RESUME                   0

  1           2 LOAD_NAME                0 (x)
              4 PRINT_EXPR
              6 LOAD_NAME                1 (y)
              8 PRINT_EXPR
             10 LOAD_CONST               0 (None)
             12 RETURN_VALUE
``` 3.11
fallow leaf
#

I see someone has stolen my way of doing it

fallow leaf
#

I guarantee this is my way for the numbers because my obfuscator could only do .add to build the numbers

#

Which ultimately makes it longer than it needs to be

versed eagle
#

except for a few numbers that are close to values that are easy to get

unique heath
fallow leaf
#

💀 i bet they put a limit on the paste site after i put my bloated hello world

fallow leaf
#

@unique heath

unique heath
#

no one needs obfuscators when you have brain

fervent atlas
#

hey i want to learn python

fallow leaf
#

this is NOT the place to learn python

#

this is advanced python

low lynx
#

this is esopy not advanced python

unique heath
#

meh

#

thats a prerequisite

#

and the best way to explain to a newbie

low lynx
#

not really

#

you can get into esopy as a beginner/intermediate

potent flare
#

how awesome

fleet bridge
#

esopy is one of the best ways to learn python deeply

grave grail
#

You like knowing something built under python

#

Instead of just stuff built on top of python

void dew
#

does quantum computing count as esoteric ?

winged pawn
#

can someone pls coach me in python?

fleet bridge
void dew
#

I'm becoming interested in quantum AI

#

Been decoding this stuff (thank you gpt4 senpai)

#

U is an operator that performs a phase shift for each x_i

#

The circuit calculates the global phase of the x_i qbits

#

The whole thing acts as an artificial neuron

void dew
#

I'm still not super sure how the phase estimation Algo works

fleet bridge
# rugged sparrow Could be, I'm not sure how the GIL works when embedding python

if you are still interested, there is a bit more information:

  • main thread (entry point of python) has to be alive always, otherwise something will break
  • everything works if you spawn new thread in C and then start python there
  • threading works perfectly (while main python thread is alive)
  • ctypes also works
  • i havent checked anything else, bc i dont need it, but i think my cute python should be pretty good in this unfriendly environment
fleet lintel
#

I recently watched Structure and Interpretation of Test Cases from NDC London 2019, and decided to try and implement it in python. It could be pushed further, but it's good enough at it's job to act as a proof of concept. https://pastebin.com/zdUGDSEs

sick hound
crude blade
#

google keep?

sick reef
gleaming linden
#

What's the shortest non-trivial quine? this was the shortest I could get in 5-10mins: ```py
s='s=%s;print(s%%repr(s))';print(s%repr(s))

unique heath
#

oh non-trivial

gleaming linden
#

yeah

#

there's also the null program, but that doesn't count either

low lynx
#

but yeah it's "cheating"

fleet bridge
night quarryBOT
#

@fleet bridge :white_check_mark: Your 3.12 eval job has completed with return code 0.

001 | s = 's = {!r}\nprint(s.format(s))'
002 | print(s.format(s))
gleaming linden
fleet bridge
#

quine should have no side effects, only output
accessing filesystem counts as side effect

unique heath
#

all i know about qiunes is they pritn otu their own prorgam

fleet bridge
#

is this how AI rebellion should look like?

gleaming linden
#

oh, %r does repr?

#

TIL

gleaming linden
#

because that's boring

versed eagle
#

true

#

but its funny :c

proper vault
#

print(__file__[1:]) works if you place it into the root of your system with the name print(__file__[1:])

versed eagle
#

oh i love that

#

!e heres a fun one

  File "/home/main.py", line 1
    File "/home/main.py", line 1
IndentationError: unexpected indent
night quarryBOT
#

@versed eagle :x: Your 3.12 eval job has completed with return code 1.

001 |   File "/home/main.py", line 1
002 |     File "/home/main.py", line 1
003 | IndentationError: unexpected indent
karmic pumice
#

ah lmao the vim keybindings

versed eagle
karmic pumice
#

!e

((setattr(__import__('sys'),'stdin',__import__('io').StringIO("0.1+0.2"))),(_:=lambda pat,re:(print(round((lambda expr:((fi:=type(())(map(lambda __:__.group(),re.finditer(pat,expr)))),eval('{'+','.join(f"'{o}':lambda x,y:x{o}y"for o in(pat[i]for i in(3,17,15,20)))+'}')[fi[1]](*map(float,(fi[0],fi[2]))))[-1])(input('>>> ')),1)),None)[-1])(''.join(map(chr,[2**3|2**5,2**2|2**3|2**4|2**6,2**2|2**5|2**6,2**0|2**1|2**3|2**5,2**2|2**3|2**4|2**6,2**1|2**2|2**3|2**5,2**2|2**3|2**4|2**6,2**2|2**5|2**6,2**0|2**1|2**3|2**5,2**0|2**3|2**5,2**2|2**3|2**4|2**5|2**6,2**3|2**5,2**2|2**3|2**4|2**6,2**0|2**1|2**3|2**5,2**2|2**3|2**4|2**5|2**6,2**0|2**2|2**3|2**5,2**2|2**3|2**4|2**5|2**6,2**0|2**1|2**2|2**3|2**5,2**2|2**3|2**4|2**5|2**6,2**2|2**3|2**4|2**6,2**1|2**3|2**5,2**0|2**3|2**5])),*map(__import__,_.__code__.co_varnames[1:])))
night quarryBOT
#

@karmic pumice :white_check_mark: Your 3.12 eval job has completed with return code 0.

>>> 0.3
versed eagle
#

idk

karmic pumice
versed eagle
#

hm true

#

idk if it counts

fleet bridge
#

i think it counts, because program is still printed to the screen (not to stdout, but it is a small detail)

#

in case of normal quines, interpreter compiles your code, runs it and prints its output
in your case interpreter compiles your code and prints it

fleet bridge
fleet bridge
#

hehe im doing cursed stuff

daring arch
#

can someone obfuscate this code for me?

arr = [1, 2, 3] for i in arr: print(i * arr[i])

fleet bridge
#

[print(i*arr[i]) for i in arr]

fresh gate
#

I'm slowly mastering brainfuck to a point of if im asked to make something i probably can
What (turing complete) esolang should i master next
(As i master it i de-esotericize it)
I was thinking whitespace,and even if i do that . . . What next?

fleet bridge
fresh gate
#

Also with each new one id add it to my interpreter, and that lil peice of shitty GUI will grow to be the best esolang interpreter

fresh gate
fleet bridge
#

there is a language called False, it is also very cool

#

malbolge

fresh gate
#

I will look into both

low lynx
night quarryBOT
#

@low lynx :x: Your 3.12 eval job has completed with return code 1.

001 | 2
002 | 6
003 | Traceback (most recent call last):
004 |   File "/home/main.py", line 3, in <module>
005 |     print(i * arr[i])
006 |               ~~~^^^
007 | IndexError: list index out of range
daring arch
#

o

low lynx
#

arr needs to contain values less than len(arr)

fresh gate
daring arch
#

let's make arr [1, 2, 1] then

fresh gate
#

arr = [1, 2, 3] for i in arr: x = 0 If i > len(arr) : x = i- i%len(arr) print((i + (x(i-x-i%len(arr))))* arr[i-x])
?

#

I iust like

#

Added some extra stuff that seems mathy

#

At a glance

#

And did some stuff to fix if you ever have values out of range

#

Obfuscating is hard ngl

Imma stick to making my own programming languages. Dont need to obfuscate it if no one besides you knows it anyway lol

daring arch
#

oh lol

#

thanks

vast wave
#

dog python bot deleted my message because of the python file

#

@daring arch i pinged you and the bot deleted it, excuse the ghost ping

daring arch
#

np

#

wow... I can't understand a bit of this

unique heath
# daring arch can someone obfuscate this code for me? ` arr = [1, 2, 3] for i in arr: prin...

!e

arr=[1,2,3]
[__builtins__.__getattribute__(__builtins__.__dir__().__getitem__(__builtins__.__dir__().__len__().__floordiv__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__()).__add__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__()).__add__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__()).__add__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__()))))).__add__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__())).__add__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__())).__add__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__()))))(__.__mul__(locals().__getitem__(chr((4<<5)-(4<<3)+1)+chr((4<<5)-(4<<2)+2).__mul__(2)).__getitem__(__))) for __ in arr]```
night quarryBOT
#

@unique heath :x: Your 3.12 eval job has completed with return code 1.

001 | 2
002 | 6
003 | Traceback (most recent call last):
004 |   File "/home/main.py", line 2, in <module>
005 |     [__builtins__.__getattribute__(__builtins__.__dir__().__getitem__(__builtins__.__dir__().__len__().__floordiv__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__()).__add__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__()).__add__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__()).__add__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__()))))).__add__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__())).__add__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__())).__add__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__()))))(__.__mul__(locals().__getitem__(chr((4<<5)-(4<<3)+1)+chr((4<<5)-(4<<2)+2).__mul__(2)).__getitem__(__))) for __ in arr]
006 |                                                          
... (truncated - too long)

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

daring arch
#

yeah because I called arr[3]

#

😵‍💫

unique heath
versed eagle
#

:3

unique heath
#

do i need to

#

gtg breakfast

versed eagle
#

you dont need to but its fun

#

since then you get only dunders

unique heath
#

and im hungry

versed eagle
unique heath
#

!e py arr=[1,2,3] (____:=__builtins__.__getattribute__(__builtins__.__dir__().__getitem__(__package__.__dir__().__len__().__sub__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__())).__sub__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__())).__sub__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__())))),_____:=____(__builtins__,__builtins__.__dir__().__getitem__(__builtins__.__dir__().__len__().__sub__(__import__.__dir__().__len__()).__sub__(__name__.__dir__().__len__()).__sub__(13))),[__builtins__.__getattribute__(__builtins__.__dir__().__getitem__(__builtins__.__dir__().__len__().__floordiv__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__()).__add__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__()).__add__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__()).__add__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__()))))).__add__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__())).__add__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__())).__add__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__()))))(__.__mul__(_____.__call__().__getitem__(chr((4<<5)-(4<<3)+1)+chr((4<<5)-(4<<2)+2).__mul__(2)).__getitem__(__))) for __ in arr]) sigh

night quarryBOT
#

@unique heath :x: Your 3.12 eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "/home/main.py", line 2, in <module>
003 |     (____:=__builtins__.__getattribute__(__builtins__.__dir__().__getitem__(__package__.__dir__().__len__().__sub__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__())).__sub__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__())).__sub__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__())))),_____:=____(__builtins__,__builtins__.__dir__().__getitem__(__builtins__.__dir__().__len__().__sub__(__import__.__dir__().__len__()).__sub__(__name__.__dir__().__len__()).__sub__(13))),[__builtins__.__getattribute__(__builtins__.__dir__().__getitem__(__builtins__.__dir__().__len__().__floordiv__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__()).__add__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__()).__add__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__(
... (truncated - too long)

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

unique heath
#

wut

#

it worked on my machine

versed eagle
unique heath
low lynx
#

did someone ping me here?

unique heath
#

!e py arr=[1,2,3] (____:=__builtins__.__getattribute__(__builtins__.__dir__().__getitem__(__package__.__dir__().__len__().__sub__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__())).__sub__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__())).__sub__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__())))),_____:=____(__builtins__,__builtins__.__dir__().__getitem__(__builtins__.__dir__().__len__().__sub__(__import__.__dir__().__len__()).__sub__(__name__.__dir__().__len__()).__sub__(12))),[__builtins__.__getattribute__(__builtins__.__dir__().__getitem__(__builtins__.__dir__().__len__().__floordiv__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__()).__add__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__()).__add__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__()).__add__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__()))))).__add__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__())).__add__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__())).__add__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__()))))(__.__mul__(_____.__call__().__getitem__(chr((4<<5)-(4<<3)+1)+chr((4<<5)-(4<<2)+2).__mul__(2)).__getitem__(__))) for __ in arr])

night quarryBOT
#

@unique heath :x: Your 3.12 eval job has completed with return code 1.

001 | 2
002 | 6
003 | Traceback (most recent call last):
004 |   File "/home/main.py", line 2, in <module>
005 |     (____:=__builtins__.__getattribute__(__builtins__.__dir__().__getitem__(__package__.__dir__().__len__().__sub__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__())).__sub__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__())).__sub__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__())))),_____:=____(__builtins__,__builtins__.__dir__().__getitem__(__builtins__.__dir__().__len__().__sub__(__import__.__dir__().__len__()).__sub__(__name__.__dir__().__len__()).__sub__(12))),[__builtins__.__getattribute__(__builtins__.__dir__().__getitem__(__builtins__.__dir__().__len__().__floordiv__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__()).__add__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__()).__add__(__builtins__.__dir__().__len__().__floordiv__(__name__.__
... (truncated - too long)

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

unique heath
#

there we go

versed eagle
unique heath
#

repl

versed eagle
#

that might be why then

unique heath
#

hmm if i do too much obf i might get over char limit

versed eagle
#

__builtins__.__dir__() will be different in a repl

#

because it adds _

unique heath
#

o yeh

versed eagle
#

stuff like __builtins__.__dir__().__len__() would be different

languid hare
#
pyramid=lambda s:[print(x)for x in((s+len(s)*"*")[n*(n+1)//2:n*(n+1)//2+n+1]for n in range(len(s)))if x.replace("*","")]

friend issued a challenge, this is what i came up with. something better probably possible

#

112 chars after the equals

versed eagle
karmic pumice
# daring arch let's make arr [1, 2, 1] then

!e

(lambda*_:(_:=lambda*sys:(lambda*__:((lambda*f:lambda*g:lambda*a:g[-1](g[0](sys[0],f[0](a[0])),f[0](a[1])))(lambda*l:''.join(map(chr,l[0])))(getattr)([((2**0)|((2**1))|((2**4))|((2**5))|((2**6))),((2**2)|((2**4))|((2**5))|((2**6))),((2**2)|((2**5))|((2**6))),((2**0)|((2**1))|((2**2))|((2**3))|((2**5))|((2**6))),((2**0)|((2**2))|((2**4))|((2**5))|((2**6))),((2**2)|((2**4))|((2**5))|((2**6)))],[((2**0)|((2**1))|((2**2))|((2**4))|((2**5))|((2**6))),((2**1)|((2**4))|((2**5))|((2**6))),((2**0)|((2**3))|((2**5))|((2**6))),((2**2)|((2**4))|((2**5))|((2**6))),((2**0)|((2**2))|((2**5))|((2**6)))]))(chr(10).join(map(lambda*____:str(____[0]*__[____[0]]),__))))(*map(lambda*___:hash(___[0][0]).__mod__(___[0][1]),(((),2),((1,),3),((),2)),),))(*map(__import__,_.__code__.co_varnames))and(None))()
night quarryBOT
#

@karmic pumice :white_check_mark: Your 3.12 eval job has completed with return code 0.

001 | 2
002 | 2
003 | 2
karmic pumice
#

(the 1 2 1 are indeed here)

#

!e

print(*map(lambda*___:hash(___[0][0]).__mod__(___[0][1]),(((),2),((1,),3),((),2)),),)
night quarryBOT
#

@karmic pumice :white_check_mark: Your 3.12 eval job has completed with return code 0.

1 2 1
karmic pumice
#

!e

exec(__import__('base64').b64decode("KGxhbWJkYSpfOihfOj1sYW1iZGEqc3lzOihsYW1iZGEqX186KChsYW1iZGEqZjpsYW1iZGEqZzpsYW1iZGEqYTpnWy0xXShnWzBdKHN5c1swXSxmWzBdKGFbMF0pKSxmWzBdKGFbMV0pKSkobGFtYmRhKmw6Jycuam9pbihtYXAoY2hyLGxbMF0pKSkoZ2V0YXR0cikoWygoMioqMCl8KCgyKioxKSl8KCgyKio0KSl8KCgyKio1KSl8KCgyKio2KSkpLCgoMioqMil8KCgyKio0KSl8KCgyKio1KSl8KCgyKio2KSkpLCgoMioqMil8KCgyKio1KSl8KCgyKio2KSkpLCgoMioqMCl8KCgyKioxKSl8KCgyKioyKSl8KCgyKiozKSl8KCgyKio1KSl8KCgyKio2KSkpLCgoMioqMCl8KCgyKioyKSl8KCgyKio0KSl8KCgyKio1KSl8KCgyKio2KSkpLCgoMioqMil8KCgyKio0KSl8KCgyKio1KSl8KCgyKio2KSkpXSxbKCgyKiowKXwoKDIqKjEpKXwoKDIqKjIpKXwoKDIqKjQpKXwoKDIqKjUpKXwoKDIqKjYpKSksKCgyKioxKXwoKDIqKjQpKXwoKDIqKjUpKXwoKDIqKjYpKSksKCgyKiowKXwoKDIqKjMpKXwoKDIqKjUpKXwoKDIqKjYpKSksKCgyKioyKXwoKDIqKjQpKXwoKDIqKjUpKXwoKDIqKjYpKSksKCgyKiowKXwoKDIqKjIpKXwoKDIqKjUpKXwoKDIqKjYpKSldKSkoY2hyKDEwKS5qb2luKG1hcChsYW1iZGEqX19fXzpzdHIoX19fX1swXSpfX1tfX19fWzBdXSksX18pKSkpKCptYXAobGFtYmRhKl9fXzpoYXNoKF9fX1swXVswXSkuX19tb2RfXyhfX19bMF1bMV0pLCgoKCksMiksKCgxLCksMyksKCgpLDIpKSwpLCkpKCptYXAoX19pbXBvcnRfXyxfLl9fY29kZV9fLmNvX3Zhcm5hbWVzKSlhbmQoTm9uZSkpKCk=").decode())
night quarryBOT
#

@karmic pumice :white_check_mark: Your 3.12 eval job has completed with return code 0.

001 | 2
002 | 2
003 | 2
versed eagle
versed eagle
versed eagle
versed eagle
zealous falcon
#

don't you have a bunch of [None, None] stuff at the end?

versed eagle
#

wdym

zealous falcon
#
>>> pyramid('abcdegfhij')
a
bc
deg
fhij
[None, None, None, None]
versed eagle
#

in a repl yeah

#

cause it prints the value of the last expression

zealous falcon
#

ah

versed eagle
#

!e ```py
pyramid=lambda s:[print(X)for n in range(len(s)+1)if{(X:=(s+(S:=sum(range(n)))"")[S:S+n])}-{''}]
pyramid("abcdefghij")

night quarryBOT
#

@versed eagle :white_check_mark: Your 3.12 eval job has completed with return code 0.

001 | a
002 | bc
003 | def
004 | ghij
versed eagle
#

when run as a file, that wont be outputted

orchid nymph
versed eagle
#

!e ```py
def pyramid(s):
n=0
while s:=s[n:]:n+=1;print(s[:n])
pyramid("ab")

night quarryBOT
#

@versed eagle :white_check_mark: Your 3.12 eval job has completed with return code 0.

001 | a
002 | b
orchid nymph
#

why ?

orchid nymph
#

what is the correct output ?

versed eagle
#
a
b*
orchid nymph
#

okay thats no problem I will fix

#

it

#
def pyramid(s):
 n=0
 while s:=s[n:]:n+=1;print(f"{s[:n]:*<{n}}")
#

!e

def pyramid(s):
 n=0
 while s:=s[n:]:n+=1;print(f"{s[:n]:*<{n}}")
pyramid("ab")
night quarryBOT
#

@orchid nymph :white_check_mark: Your 3.12 eval job has completed with return code 0.

001 | a
002 | b*
cinder steeple
languid river
#

@ember crown where are you from

ember crown
languid river
#

For investigation

ember crown
#

europe

languid river
#

Are you my friend

ember crown
#

huh?

haughty nova
#

You are being investigated

daring arch
versed eagle
daring arch
versed eagle
#

python

daring arch
#

😵‍💫I know but what is the long string

gleaming linden
#

!e ```py
s = ''.join(map(chr,[23|25,22|23|24|26,22|25|26,20|21|23|25,22|23|24|26,21|22|23|25,22|23|24|26,22|25|26,20|21|23|25,20|23|25,22|23|24|25|26,23|25,22|23|24|26,20|21|23|25,22|23|24|25|26,20|22|23|25,22|23|24|25|26,20|21|22|23|25,22|23|24|25|26,22|23|24|26,21|23|25,20|23|25]))

print(s)

night quarryBOT
#

@gleaming linden :white_check_mark: Your 3.12 eval job has completed with return code 0.

(\d+\.\d+)|(\+|-|/|\*)
gleaming linden
#

looks like a regex to me

versed eagle
#

it is

#

they use re

void solstice
versed eagle
#

maybe a test for each number?

sly root
#

!e ```py
import math
import zlib

def E(S, A=((65, 90),)):
def _K(R, N):
while N>0:
_D = N%100
if _D == 0:
R.append(10)
else:
R.append(_D*10 if (int(math.log10(_D))+1) == 1 else _D)
N //= 100
def _W(N, *R):
for _LL, _UL in R:
if N < _LL:
return _UL-(_LL-N-1) % (_UL-_LL+1)
elif N > _UL:
return _LL+(N-(_UL+1)) % (_UL-_LL+1)
return N
S = zlib.compress(S.encode("utf-16le"))
_B = []
_R = ""
_I = 0
while _I < len(S):
_N = S[_I]
_J = 0 if len(S) <= (_JI := _I+1) else S[_JI]
_B += [(_I, _N, _J)]
_I += 2
for _G in _B:
_F = []
_F.append(10) if _G[1] == 0 else _K(_F, _G[1])
_F.append(10) if _G[2] == 0 else _K(_F, _G[2])
_S = ""
for _N in _F:
_S += chr(_W(_N, *A))
_R += _S
return _R

print(E("H"))
print(E("Hello"))
print(E("TestHashString"))```

night quarryBOT
#

@sly root :white_check_mark: Your 3.12 eval job has completed with return code 0.

001 | HXRXEHFXXXHXXI
002 | HXRXEHFHXXXHXDXLXVXYLXGH
003 | HXRXYGHXXBHXBGBHFHBXHMZCXZFXECZCRCTRXRNXLRXX
sly root
#

eh, needs padding

fleet bridge
#

int(math.log10(_D)) is simply len(str(_D))-1 in most cases

#

no need to import math

sly root
#

!e ```py
import zlib

def E(S, A=((65, 90),)):
def _K(R, N):
while N>0:
_D = N%100
if _D == 0:
R.append(10)
else:
R.append(_D*10 if (len(str(_D))) == 1 else _D)
N //= 100
def _W(N, *R):
for _LL, _UL in R:
if N < _LL:
return _UL-(_LL-N-1) % (_UL-_LL+1)
elif N > _UL:
return _LL+(N-(_UL+1)) % (_UL-_LL+1)
return N
S = zlib.compress(S.encode("utf-16le"))
S = zlib.crc32(S) & 0xffffffff
_R = ""
SL = len(str(S))
_M, _B = [], []
_K(_M, S)
_I = 0
while _I < len(_M):
_N = _M[_I]
_J = 10 if len(_M) <= (_JI := _I+1) else _M[_JI]
_B += [(_I, _N, _J)]
_I += 2
for _G in _B:
_F = []
_F.append(10) if _G[1] == 0 else _K(_F, _G[1])
_F.append(10) if _G[2] == 0 else _K(_F, _G[2])
_S = ""
for _N in _F:
_S += chr(_W(_N, *A))
_R += _S
return _R

print(E("H"))
print(E("Hello"))
print(E("TestHashString"))```

night quarryBOT
#

@sly root :white_check_mark: Your 3.12 eval job has completed with return code 0.

001 | TSBWLX
002 | HDJIPX
003 | LVWXRX
unique heath
#

shithash

sly root
#

ssssh

#

!e ```py
import zlib

def _RD(X, W):
if W == 8:
X = ((X & 0x55) << 1) | ((X & 0xAA) >> 1)
X = ((X & 0x33) << 2) | ((X & 0xCC) >> 2)
X = ((X & 0x0F) << 4) | ((X & 0xF0) >> 4)
elif W == 16:
X = ((X & 0x5555) << 1) | ((X & 0xAAAA) >> 1)
X = ((X & 0x3333) << 2) | ((X & 0xCCCC) >> 2)
X = ((X & 0x0F0F) << 4) | ((X & 0xF0F0) >> 4)
X = ((X & 0x00FF) << 8) | ((X & 0xFF00) >> 8)
elif W == 32:
X = ((X & 0x55555555) << 1) | ((X & 0xAAAAAAAA) >> 1)
X = ((X & 0x33333333) << 2) | ((X & 0xCCCCCCCC) >> 2)
X = ((X & 0x0F0F0F0F) << 4) | ((X & 0xF0F0F0F0) >> 4)
X = ((X & 0x00FF00FF) << 8) | ((X & 0xFF00FF00) >> 8)
X = ((X & 0x0000FFFF) << 16) | ((X & 0xFFFF0000) >> 16)
else:
return 0
return X

def _C(D, N, P, C=0, RI=False, RO=False, XO=0):
G = 1 << N | P
for _D in D:
if RI:
_D = _RD(_D, 8)
C ^= _D << (N - 8)
for _ in range(8):
C <<= 1
if C & (1 << N):
C ^= G
if RO:
C = _RD(C, N)
return C ^ XO

def _A(T, M=65521):
_F, _G = 1, 0
for _C in T:
_G = (_G + (_F := (_F + _C) % M)) % M
return (_G << 16) | _F

def _K(R, N):
while N>0:
_D = N%100
R.append(10 if _D == 0 else (_D*10 if (len(str(_D))) == 1 else _D))
N //= 100

def _W(N, *R):
for _LL, _UL in R:
if N < _LL:
return _UL-(_LL-N-1) % (_UL-_LL+1)
elif N > _UL:
return _LL+(N-(_UL+1)) % (_UL-_LL+1)
return N

def E(S, A=((65, 90),), D=-1):
S = zlib.compress(S.encode("utf-16le"))
S = (((_A(S) << 64) * (_C(S, 32, 0x1EDC6F41, C=0xFFFFFFFF, RI=True, RO=True, XO=0xFFFFFFFF) << 32)) << 16) & 0xffffffffffffffffffffffffffffffff
SL = len(str(S))
_R = ""
_M, _B = [], []
_K(_M, S)
_M = _M[::D]
_I = 0
while _I < len(_M):
_N, _J = _M[_I], 10 if len(_M) <= (_JI := _I+1) else _M[_JI]
_B += [(_I, _N, _J)]
_I += 2
for _G in _B:
_F = []
_F.append(10) if _G[1] == 0 else _K(_F, _G[1])
_F.append(10) if _G[2] == 0 else _K(_F, _G[2])
_R += "".join([chr(_W(_N, *A)) for _N in _F[::D]])
return _R

print(E("H"))
print(E("Hello"))
print(E("TestHashString"))```

night quarryBOT
#

@sly root :white_check_mark: Your 3.12 eval job has completed with return code 0.

001 | KHXVIZHPFWBJLTNCEYBD
002 | ZQDXBXDVTFHZMPVEFXXX
003 | CXPPESFWHKXQQOPDQPFT
vast wave
#

!e ```py
import zlib,itertools,base64,string
exec(zlib.decompress(base64.b64decode("eJyFU39rIkkQ/T+fohASurV1Z8YfeDIjmJmMTKJjGBMUZLfJJeOth6dBEy4c++G3qrpHXXfCCWJ19atXr6qfL/kSdBaJuZrJ3gXAagmzIOhSCDAPhJhfOR/ttvR9V/4wp8FA9vuu/AXRbCLCKxBhiAjvV4QTI6JVIGIHES1C5GvT0u2c9zzvWt73vHN57/Pux/4nKCcmVPeAih1CdU9VNr3fVZYp/VxtmeLPVZcp/1x92QSnU5yi6YbRbucIJzDDMclT73Mz7y5/e99twMGDDecXbJ1QRCpV9yoMHJUlQfyEJSqb2GA+CRy21TBwfT/9cY/hcrsDHcFqA5Hhxs1miQkBbwKyo46UVRx+C3Tk+yKFOtgUMxDB7mnzVy663IE/oe8HbnFA3vBKUN8jgPmGxufZxKRD7hiqlNjtdOG3+cQMOBAPahx02m3PZRodK43TKFoFCwlJyYOhwhuhhzWh4x4GcU2H8nIs8Xtgxmuzch0b/juRYWcq//f7ap1D2ncsVwQBpJeuQ50AssbT62u+eRGuQ+LpNgCHnwhwXVWTFut8I/ZvO8xIKQniGgidmSeFL18wi6zcfiZSBdWMBfA4o5EC/TiiobLD+6Tg002xRrskhNUFputp3ZVwiTIwgeeatT3/aVLoE/C8FFEixepHQv9ebGEpi7wRUwUDdG6nreAPRyqpIAqwJ5FOcUv/rVd/Np63/7zu8v1eTBv55nn7kovK+9uy7nbWeYVnJ6QQAl90KsH3odOSUMW+IdE3PQXOh3sThZ245So0hfk/0EehP4OH3XuOwcQG5OwDgOmaHs6Bv/i4cIVcy//5kKIRSipebMoidYapSoWiMT7ENZ4WXxV+KXMnKDll3Bhv9HjR60V8leCRjGJMhEefifXYel/jM+tbU6MTZDR+sRjwcTX6NoEeAhJ8AmsaxN4mxI8E11BDLUInSMRk0l4kdOEV/hmSc/S17RqzfhsfHSzZwsOF+/XExTQe7prTxkBlJV55iVeUZKSmUmn8vV1txOL5O/4VZoIEVwf4PiwxZYkx747LClNmPwG3trOm")))
s=[]
for e in itertools.combinations(string.printable, 8):
v=E(t:="".join(e))
if v in s: print("Collision at "+t+"! Hash: "+v)
s.append(v)

night quarryBOT
#

@vast wave :x: Your 3.12 eval job timed out or ran out of memory.

001 | Collision at 0123459G! Hash: OXGEXWRNNYLBANKVTBXD
002 | Collision at 0123459
003 | ! Hash: CHDSCCVVSPYZJGZZEYZH
004 | Collision at 012345cP! Hash: AOPKSYDHSILPLLIFHHXZ
005 | Collision at 012345c:! Hash: FHUGZXGHIDIMCSFEYRPF
006 | Collision at 012345dD! Hash: UXMNNELGPNABDJPRKGBE
007 | Collision at 012345dK! Hash: RXYTLRHNRFZHUBRYAPDI
008 | Collision at 012345fp! Hash: BRTCZZUPEWUDXYLDOYXN
009 | Collision at 012345g~! Hash: ARXAYDGRIVOTJHQMQODA
010 | Collision at 012345g
011 | ! Hash: QHDECATSOVRLICNBUUDL
... (truncated - too many lines)

Full output: unable to upload

vast wave
#

@sly root good hash

night quarryBOT
#

:incoming_envelope: :ok_hand: applied timeout to @sly root until <t:1700489800:f> (10 minutes) (reason: newlines spam - sent 104 newlines).

The <@&831776746206265384> have been alerted for review.

#

@sly root :x: Your 3.12 eval job timed out or ran out of memory.

001 | KHXVIZHPFWBJLTNCEYBD
002 | ZQDXBXDVTFHZMPVEFXXX
003 | CXPPESFWHKXQQOPDQPFT
fleet bridge
#

lmao

subtle solar
#

!unmute 467290739219496960

night quarryBOT
#

:incoming_envelope: :ok_hand: pardoned infraction timeout for @sly root.

subtle solar
#

oopsie

fleet bridge
#

it's funny that bot still evaluated the provided code

sly root
#

lmao

sly root
balmy condor
#

Does the datetime library default to GMT?

astral rover
#

it defaults to not being tz aware

#

you should basically always use datetime.now(UTC) (after importing both from datetime)

sly root
#

absolutely love the result
before

def _K(R, N):
  while N>0:
    _D=N%100
    R.append(10 if _D==0 else(_D*10 if(len(str(_D)))==1 else _D))
    N//=100

after

_K=lambda R,N:[(R.append(10if(_D:=N%100)==0else(_D*10 if(len(str(_D)))==1else _D)),(N:=N//100))for i in iter(lambda:N>0,0)]
#

!e ```py
import zlib

_RD=lambda X,W:((((X:=(((X:=((X&0x55)<<1)|((X&0xAA)>>1))&0x33)<<2)|((X&0xCC)>>2))&0x0F)<<4)|((X&0xF0)>>4))if W==8 else(((((X:=(((X:=(((X:=((X&0x5555)<<1)|((X&0xAAAA)>>1))&0x3333)<<2)|((X&0xCCCC)>>2))&0x0F0F)<<4)|((X&0xF0F0)>>4))&0x00FF)<<8)|((X&0xFF00)>>8))if W==16 else(((((X:=(((X:=(((X:=(((X:=((X&0x55555555)<<1)|((X&0xAAAAAAAA)>>1))&0x33333333)<<2)|((X&0xCCCCCCCC)>>2))&0x0F0F0F0F)<<4)|((X&0xF0F0F0F0)>>4))&0x00FF00FF)<<8)|((X&0xFF00FF00)>>8))&0x0000FFFF)<<16)|((X&0xFFFF0000)>>16))if W==32 else 0))
_K=lambda R,N:[(R.append(10 if(_D:=N%100)==0 else(_D*10 if(len(str(_D)))==1 else _D)),(N:=N//100))for i in iter(lambda:N>0,0)]
_W=lambda N,*R:next((_UL-(_LL-N-1)%(_UL-_LL+1)if N<_LL else(_LL+(N-(_UL+1))%(_UL-_LL+1)if N>_UL else N)for _LL,_UL in R),None)

def E(S, A=((65, 90),), D=-1, O=152):
S=zlib.compress(S.encode("utf-16le"))
_AF,_AG=1, 0
for _AC in S:
_AG=(_AG+(_AF:=(_AF+_AC)%(_AM:=65521))%_AM)
_AS=(_AG<<16)|_AF
_CC=0xFFFFFFFF
_CG=1<<(_CN:=32)|0x1EDC6F41
for _CD in S:
_CD=_RD(_CD,8)
_CC^=_CD<<(_CN-8)
for _ in range(8):
_CC<<=1
if _CC&(1<<_CN):
_CC^=_CG
_CC=_RD(_CC,_CN)
_CO=((_CON:=_CC^0xFFFFFFFF)+((_COH:=_CON)<<6)+(_COH<<16)-_COH)
S=(((_AS<<64)*(_CO<<32))<<16)&((1<<((O//4)*4))-1)
SL=len(str(S))
_R,_M,_B="",[],[]
_K(_M,S)
_M=_M[::D]
_I=0
while _I<len(_M):
_N,_J=_M[_I], 10 if len(_M)<=(_JI:=_I+1)else _M[_JI]
_B+=[(_I,_N,_J)]
_I+=2
for _G in _B:
_F=[]
_F.append(10)if _G[1]==0 else _K(_F,_G[1])
_F.append(10)if _G[2]==0 else _K(_F,_G[2])
_R+="".join([chr(_W(_N, *A))for _N in _F[::D]])
return _R

print(E("H"))
print(E("Hello"))
print(E("TestHashString"))

night quarryBOT
#

@sly root :white_check_mark: Your 3.12 eval job has completed with return code 0.

001 | FLMXWFYCSXSLOGLNPXUICEXD
002 | IQCCMQYJACGLHLQVIRWGCPXF
003 | TEMZHVHQXOLVRFRJJZKJLTXL
astral rover
#

no

balmy condor
#

So when i print datetime.now() what timezone is it outputting?

candid light
#

i made a rather silly one-liner

move_right = lambda board: (c := (lambda b: [[0]*row.count(0)+list(filter(lambda x: x, row)) for row in b]))([sum([[0, row[i]*2] if row[i] == row[i+1] else [row[i], row[i+1]] for i in range(0, len(row), 2)], []) for row in c(board)])
candid light
#

!e

board = [
    [2, 2, 2, 2],
    [0, 0, 4, 0],
    [0, 2, 0, 2],
    [2, 8, 0, 4]
]
move_right = lambda board: (c := (lambda b: [[0]*row.count(0)+list(filter(lambda x: x, row)) for row in b]))([sum([[0, row[i]*2] if row[i] == row[i+1] else [row[i], row[i+1]] for i in range(0, len(row), 2)], []) for row in c(board)])
print(move_right(board))
night quarryBOT
#

@candid light :white_check_mark: Your 3.12 eval job has completed with return code 0.

[[0, 0, 4, 4], [0, 0, 0, 4], [0, 0, 0, 4], [0, 2, 8, 4]]
balmy condor
astral rover
#

if you want local time use dt.astimezone()

strange basin
#

!e

try:
    x = ([1, 2], )
    x[0] += [3, 4]
except TypeError:
    print(x)    
night quarryBOT
#

@strange basin :white_check_mark: Your 3.12 eval job has completed with return code 0.

([1, 2, 3, 4],)
strange basin
#

I’m allowed to modify a list inside a tuple, but not the tuple itself, so it fails, but the tuple is still modified … 🤔

fleet lintel
#

From what I've read, it's because the += is roughly analogous to py res = x[0].__iadd__([3, 4]) x[0] = res
and that second part causes the error, while the iadd worked inplace like normal. So it works fine if you just do that manually

#

!e py x = ([1, 2], ) x[0].__iadd__([3, 4]) print(x)

night quarryBOT
#

@fleet lintel :white_check_mark: Your 3.12 eval job has completed with return code 0.

([1, 2, 3, 4],)
fleet bridge
night quarryBOT
#

@fleet bridge :white_check_mark: Your 3.12 eval job has completed with return code 0.

([1, 2, 3, 4],)
balmy condor
craggy hamlet
#

!e

def whackysyntax[whatthe: lambda what=[]: what.append(what) or what](on_earth: whatthe):
    print(ohmy:=len(whatthe.__bound__())) or ohmy < on_earth and whackysyntax(on_earth) and whackysyntax(on_earth)

whackysyntax(5)
night quarryBOT
#

@craggy hamlet :white_check_mark: Your 3.12 eval job has completed with return code 0.

001 | 1
002 | 2
003 | 3
004 | 4
005 | 5
craggy hamlet
#

this new typing change is crazy

unique heath
night quarryBOT
#

@unique heath :white_check_mark: Your 3.12 eval job has completed with return code 0.

140436999413864
unique heath
#

wth

#

!e

thing = lambda x: id(x)
print(thing(123))
night quarryBOT
#

@unique heath :white_check_mark: Your 3.12 eval job has completed with return code 0.

139634242637928
unique heath
#

top tier hash

#

lmao id uses sha512

#

wait no im dumb thats seed

sly root
#

i've fixed collisions so it isn't that bad now

glad moss
#
from typing import Any, Callable

Method = type(
    "Method",
    (), 
    {
        "__init__": lambda s, f, o: [setattr(s, "f", f), setattr(s, "o", o), None][-1],
        "__call__": lambda s, *a, **k: s.f(s.o, *a, **k)

    }
)

def method(self: Any, *args) -> Method:
    def wrapper(func: Callable[Any, ...]) -> Any:
        return func(self, *args)

    return wrapper

class Foo:
    def __new__(cls):
        return super().__new__(cls)

    def func(self) -> None:
        print(self.x)


@method((obj := Foo()), 1)
def __init__(self, x: int) -> None:
    self.x = x

obj.func()```

Not sure if this counts as esoteric, i would call it cursed instead
sick hound
#

!e

from typing import Any, Callable

Method = type(
    "Method",
    (), 
    {
        "__init__": lambda s, f, o: [setattr(s, "f", f), setattr(s, "o", o), None][-1],
        "__call__": lambda s, *a, **k: s.f(s.o, *a, **k)

    }
)

def method(self: Any, *args) -> Method:
    def wrapper(func: Callable[Any, ...]) -> Any:
        return func(self, *args)

    return wrapper

class Foo:
    def __new__(cls):
        return super().__new__(cls)

    def func(self) -> None:
        print(self.x)


@method((obj := Foo()), 1)
def __init__(self, x: int) -> None:
    self.x = x

obj.func()```
night quarryBOT
#

@sick hound :white_check_mark: Your 3.12 eval job has completed with return code 0.

1
restive void
#

You don't use Method anywhere, do you? o.O

#

!e like this does the same thing, doesn't it?

method = lambda s, *a, **k: lambda f: f(s, *a, **k)
class Foo:
    def func(self):
        print(self.x)

@method((obj := Foo()), 1)
def __init_or_whatever__(self, x):
    self.x = x

obj.func()
night quarryBOT
#

@restive void :white_check_mark: Your 3.12 eval job has completed with return code 0.

1
versed eagle
craggy hamlet
#

!e

fib: print(__import__("functools").reduce(lambda x, y: (x[0]+x[1], x[0]), [(1,1)]*(fib-2))[0])=8
night quarryBOT
#

@craggy hamlet :white_check_mark: Your 3.12 eval job has completed with return code 0.

13
sly root
sly root
#

!e ```py
import zlib

_RD=lambda X,W:((((X:=(((X:=((X&0x55)<<1)|((X&0xAA)>>1))&0x33)<<2)|((X&0xCC)>>2))&0x0F)<<4)|((X&0xF0)>>4))if W==8 else(((((X:=(((X:=(((X:=((X&0x5555)<<1)|((X&0xAAAA)>>1))&0x3333)<<2)|((X&0xCCCC)>>2))&0x0F0F)<<4)|((X&0xF0F0)>>4))&0x00FF)<<8)|((X&0xFF00)>>8))if W==16 else(((((X:=(((X:=(((X:=(((X:=((X&0x55555555)<<1)|((X&0xAAAAAAAA)>>1))&0x33333333)<<2)|((X&0xCCCCCCCC)>>2))&0x0F0F0F0F)<<4)|((X&0xF0F0F0F0)>>4))&0x00FF00FF)<<8)|((X&0xFF00FF00)>>8))&0x0000FFFF)<<16)|((X&0xFFFF0000)>>16))if W==32 else 0))
_K=lambda R,N:[(R.append(10 if(_D:=N%100)==0 else(_D*10 if(len(str(_D)))==1 else _D)),(N:=N//100))for i in iter(lambda:N>0,0)]
_W=lambda N,R:((R[1]-(R[0]-N-1)%(R[1]-R[0]+1)if N<R[0]else(R[0]+(N-(R[1]+1))%(R[1]-R[0]+1)if N>R[1]else N)),None)[0]

D = 1 / -1 (default: -1)

O in [41, 2^16) (default: 64)

O*3 is the upper limit

O is the hash constant width

def E(S, A=(65, 90), D=1, O=64):
S=zlib.compress(S.encode("utf-16le"))
_AF,_AG=1,0
[_AG:=(_AG+(_AF:=(_AF+_AC)%(_AM:=65521))%_AM)for _AC in S]
_AS=(_AG<<16)|_AF
_CC,_CG=0xFFFFFFFF,1<<(_CN:=32)|0x1EDC6F41
for _CD in S:
_CC^=(_CD:=_RD(_CD,8))<<(_CN-8)
[(_CC,(_CC:=_CC<<1),(_CC:=_CC^(_CG if _CC&(1<<_CN)else 0)))for _ in range(8)][-1]
_CO=((_CON:=(_CC:=_RD(_CC,_CN))^0xFFFFFFFF)+((_COH:=_CON)<<6)+(_COH<<16)-_COH)
S=((_SN:=((((_AS<<64)(_CO<<32))<<16)<<8)&((1<<(((O3)//4)4))-1)),(_SW:=O),(int((str(_SN)((_SW//len(str(_SN)))+1))[:_SW])),(int(_SN*(10**(_SW-len(str(_SN)))))))[2]
_I,_R,_M,_B=0,"",[],[]
_K(_M,S)
_M=_M[::D]
while _I<len(_M):
_N,_J=_M[_I],10 if len(_M)<=(_JI:=_I+1)else _M[_JI]
_B+=[(_I,_N,_J)]
_I+=2
for _G in _B:
_F=[]
_F.append(10)if _G[1]==0 else _K(_F,_G[1])
_F.append(10)if _G[2]==0 else _K(_F,_G[2])
_R+="".join([chr(_W(_N,[*A]))for _N in _F[::D]])
return _R

print(E("H"))
print(E("Hello"))
print(E("TestHashString"))```

night quarryBOT
#

@sly root :white_check_mark: Your 3.12 eval job has completed with return code 0.

001 | LTFXNENIKTHOJRAWPHXBGCUYXEBYXLTF
002 | XXUBAUTYOZBJAAAYCCHUHEKLQJMZRXXU
003 | AVXNCBBKVNNQHKRSPUTPGHLHXRIJAAVX
fleet bridge
#

!rule paid

night quarryBOT
#

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

glad moss
#

When i come with ideas of pointless codes, i write them too fast without thinking of a shorter way

unique heath
#

!e ```py
def qr(data):
for i in data:i[0]=i[0]+i[1]%(1<<8)-1;i[3]=((i[3]^i[0])<<(1<<4)|(i[3]^i[0])>>(1<<4))%(1<<8)-1;i[2]=i[2]+i[3]%(1<<8)-1;i[1]=((i[1]^i[2])<<12|(i[1]^i[2])>>20)%(1<<8)-1;i[0]=i[0]+i[1]%(1<<8)-1;i[3]=((i[3]^i[0])<<(1<<3)|(i[3]^i[0])>>((1<<5)-(1<<3)))%(1<<8)-1;i[2]=i[2]+i[3]%(1<<8)-1;i[1]=((i[1]^i[2])<<7|(i[1]^i[2])>>25)%(1<<8)-1

#i basically gave up at this point
def flatten(input):
new_list = []
for i in input:
for j in i:
new_list.append(j)
return new_list

def hash(data):
data=data.encode()
x = [[data[i4], data[i4+1], data[i4+2], data[i4+3]] for i in range(len(data)//4)]
qr(x)
x= flatten(x)
return bytes(x)

print(hash("hello"))``` @sly root

night quarryBOT
#

@unique heath :x: Your 3.12 eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "/home/main.py", line 19, in <module>
003 |     print(hash("hello"))
004 |           ^^^^^^^^^^^^^
005 |   File "/home/main.py", line 17, in hash
006 |     return bytes(x)
007 |            ^^^^^^^^
008 | ValueError: bytes must be in range(0, 256)
unique heath
#

.-.

#

massiv L

unique heath
#

!e ```py
def qr(data):
for i in data:i[0]=i[0]+i[1]%(1<<8)-1;i[3]=((i[3]^i[0])<<(1<<4)|(i[3]^i[0])>>(1<<4))%(1<<8)-1;i[2]=i[2]+i[3]%(1<<8)-1;i[1]=((i[1]^i[2])<<12|(i[1]^i[2])>>20)%(1<<8)-1;i[0]=i[0]+i[1]%(1<<8)-1;i[3]=((i[3]^i[0])<<(1<<3)|(i[3]^i[0])>>((1<<5)-(1<<3)))%(1<<8)-1;i[2]=i[2]+i[3]%(1<<8)-1;i[1]=((i[1]^i[2])<<7|(i[1]^i[2])>>25)%(1<<8)-1;i[0]%=(1<<8)-1;i[1]%=(1<<8)-1;i[2]%=(1<<8)-1;i[3]%=(1<<8)-1
return data
hash = lambda x:(data:=x.encode(),bytes(import("itertools").chain.from_iterable(qr([[data[i4], data[i4+1], data[i4+2], data[i4+3]] for i in range(len(data)//4)]))))[1]

print(hash("banana"))```

night quarryBOT
#

@unique heath :white_check_mark: Your 3.12 eval job has completed with return code 0.

b'\xc1\xfek\xfe'
unique heath
#

there we go

#

its not great because it truncates every char >trunc(len(data)/4)*4

#

but it works

sly root
#

looks nice

#

the thing is that i spent more time to make a wrapping function and making hashes to be the same length than writing the hash itself

#
_K=lambda R,N:[(R.append(10 if(_D:=N%100)==0 else(_D*10 if(len(str(_D)))==1 else _D)),(N:=N//100))for i in iter(lambda:N>0,0)]
_W=lambda N,R:((R[1]-(R[0]-N-1)%(R[1]-R[0]+1)if N<R[0]else(R[0]+(N-(R[1]+1))%(R[1]-R[0]+1)if N>R[1]else N)),None)[0]

this

unique heath
#

unironically

#

looked at

#

a real

#

fucking

#

hash

#

(okay pseudorandom block-function but who cares)

#

lmao

#

(well, and modified it)

#

(a lot)

sly root
# sly root !e ```py import zlib _RD=lambda X,W:((((X:=(((X:=((X&0x55)<<1)|((X&0xAA)>>1))&0...

i've replaced the while and the last for-loop with list comprehensions:
before

while _I<len(_M):
  _N,_J=_M[_I],10 if len(_M)<=(_JI:=_I+1)else _M[_JI]
  _B+=[(_I,_N,_J)]
  _I+=2
for _G in _B:
  _F=[]
  _F.append(10)if _G[1]==0 else _K(_F,_G[1])
  _F.append(10)if _G[2]==0 else _K(_F,_G[2])
  _R+="".join([chr(_W(_N,[*A]))for _N in _F[::D]])

after

[((_B:=_B+[(_I,_M[_I],(10 if len(_M)<=(_JI:=_I+1)else _M[_JI]))]),(_I:=_I+2))for _ in iter(lambda:_I<len(_M),0)]
[((_F:=[]),(_K(_F,100 if _G[1]==0 else _G[1])),(_K(_F,100 if _G[2]==0 else _G[2])),(_R:=_R+"".join([chr((A[1]-(A[0]-_N-1)%(A[1]-A[0]+1)if _N<A[0]else(A[0]+(_N-(A[1]+1))%(A[1]-A[0]+1)if _N>A[1]else _N)))for _N in _F[::D]])))for _G in _B]
#

i know i can do like 10if 100if and 0else but i won't because of the nasty SyntaxWarnings

unique heath
#

cool

#

currently looking at SIPHASH rn

#

me when i look at real fucking hashes for a shitpost:

sly root
#

lmao

#

my nitro has expired but i still have the avatar decoration

karmic pumice
#

!e

def is_iterable(obj):
  try:
    for _ in obj:
      return True
  except:
    return False

def flatten(iterable):
  for item in iterable:
    if is_iterable(item):
      yield from flatten(item)
    else:
      yield item

print(list(flatten([1,[2,[3]],[4,[[[6]]]]])))
night quarryBOT
#

@karmic pumice :white_check_mark: Your 3.12 eval job has completed with return code 0.

[1, 2, 3, 4, 6]
restive void
#

!e

import json
def flatten(iterable):
    return json.loads(f"[{json.dumps(iterable).replace('[','').replace(']','')}]")

print(flatten([1,[2,[3]],[4,[[[6]]]]]))
night quarryBOT
#

@restive void :white_check_mark: Your 3.12 eval job has completed with return code 0.

[1, 2, 3, 4, 6]
arctic skiff
restive void
arctic skiff
#

why are you using json module, can't you just use list instead?

restive void
arctic skiff
#

oh wait yeah

#

but yes dumps could be replaced

#

!epy import json def flatten(i): return json.loads(f'[{str(i).replace('[','').replace(']','')}]') print(flatten([1,[2,[3]],[4,[[[6]]]]]))

night quarryBOT
#

@arctic skiff :white_check_mark: Your 3.12 eval job has completed with return code 0.

[1, 2, 3, 4, 6]
astral rover
#

So can loads realistically

serene stratus
#

it could just be eval

#

!e

import json
def flatten(i):
    return [int(n.replace(' ','').replace('[','').replace(']', '')) for n in f"[{str(i).replace('[','').replace(']','')}]".split(",")]
print(flatten([1,[2,[3]],[4,[[[6]]]]]))```
night quarryBOT
#

@serene stratus :white_check_mark: Your 3.12 eval job has completed with return code 0.

[1, 2, 3, 4, 6]
serene stratus
#

!e

def flatten(i):
    return [int(filter(str.isalnum, n).__next__()) for n in f"[{str(i).replace('[','').replace(']','')}]".split(",")]
print(flatten([1,[2,[3]],[4,[[[6]]]]]))```
night quarryBOT
#

@serene stratus :white_check_mark: Your 3.12 eval job has completed with return code 0.

[1, 2, 3, 4, 6]
fleet lintel
#

!e I don't understand what about this doesn't work py flatten=lambda l:eval(f"[{str(l).replace('[','').replace(']','')}]") print(flatten([1,[2,[3]],[4,[[[6]]]]]))

night quarryBOT
#

@fleet lintel :white_check_mark: Your 3.12 eval job has completed with return code 0.

[1, 2, 3, 4, 6]
versed eagle
#

!e ```py
flatten=f=lambda l:[l]if type(l)is int else sum(map(f,l),[])
print(flatten([1,[2,[3]],[4,[[[6]]]]]))

night quarryBOT
#

@versed eagle :white_check_mark: Your 3.12 eval job has completed with return code 0.

[1, 2, 3, 4, 6]
versed eagle
#

obviously its not generalised — but neither is string handling

#

since it cant handle brackets inside elements of the list

arctic kettle
#

is there a way to make everything 'exist'
So if I would use a global variable that doesnt exist, I still make it return something predefined?

arctic kettle
#

how would I do this

versed eagle
# arctic kettle how would I do this

!e ```py
import ctypes

class blogals(dict):
slots = ()
def getitem(s, i, __g=dict.getitem):
if i in s:
return __g(s, i)
if i in builtins.dir():
return __g(builtins.dict, i)
return i
ctypes.py_object.from_address(id(globals()) + 8).value = blogals

print(hello, world)

night quarryBOT
#

@versed eagle :white_check_mark: Your 3.12 eval job has completed with return code 0.

hello world
versed eagle
#

hello and world are undefined variables here

arctic kettle
#

damn

#

well done mate thanks

versed eagle
#

you can change the value that gets returned by changing the return i at the end there

arctic kettle
#

is it always +8 I see that pop up a lot

versed eagle
versed eagle
versed eagle
#

so that it has a custom lookup method

fleet lintel
night quarryBOT
#

@fleet lintel :white_check_mark: Your 3.12 eval job has completed with return code 0.

[1, 2, 3, 4, 6]
amber gazelle
#

To the weirdos in #esoteric-python, I call upon your terrible wisdom to help me with this problem

Im trying to import a custom module to iterate over a file and file variables, but its iterating over itself after its run and its causing an error.

#__main__
c = __file__
print(c)
import game
a=1
b=1
print(a,b)
print(game.var_or_not(f"{c}") )
#game
def var_or_not(f):
    if __file__ != f:return
    vars = []
    with open(f,'r') as f:
        a = f.read()
    a = a.split("\n")
    t=1
    for i in a:
        while t:
            try:
                print(i)
                exec(i)
            except NameError as e:
                vars.append(str(e).split("'")[1])
            else:
                t=0
                continue
        t=1
    return vars
fleet lintel
#

If you can use other imports, there isn't a reason to mess around with exec ```py

a.py

import inspect
def test():
calling_frame = inspect.stack()[1][0].f_globals
return calling_frame```

# b.py
import a
b = 1
c = 1
print(a.test())```
result of running `b.py`: ```
{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x00000249D06F1D50>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, '__file__': 'C:\\Users\\user\\PycharmProjects\\test\\b.py', '__cached__': None, 'a': <module 'a' from 'C:\\Users\\user\\PycharmProjects\\test\\a.py'>, 'b': 1, 'c': 1}
versed eagle
#

oh right
originally the int wasnt in a list and i wanted to avoid the case where it gets 0 and tries to iterate through it

#

forgot to change it back lol

empty tartan
#

Guys I think I found a new standard we should use for storing constants in python, should I open a PEP for it?

class ConstantContainer:
  def __init__(depth=999):

    if depth == 0:
      self.__CONSTANT1 = 1
      self.__COSNTANT2 = 2
      self._is_leaf = True
      return
    self._is_leaf = False
    self.__whatthefuck = ConstantContainer(depth-1)

  
@property
def CONSTANT1():
  if self.is_leaf:
    return self.__CONSTANT1
  else:
    return self.__whatthefuck.CONSTANT1

This is genius, try modifying these constants mother f'er

unique heath
#

!e ```py
t=type("t",(object,),{"init":lambda s:setattr(s,"d",[0]*1000),"getitem":lambda s,k:s.d[hash(k)%1000],"setitem":lambda s,k,v:s.d.setitem(hash(k)%1000,v)})

mydict = t()
mydict["x"] = 4
print(mydict["x"])``` my attempt at making a terrible hash table

night quarryBOT
#

@unique heath :white_check_mark: Your 3.12 eval job has completed with return code 0.

4
versed eagle
#

i might have messed up the name mangling but whatever

versed eagle
#

!e ```py
t=type("t",(object,),{"init":lambda s:setattr(s,"d",[0]*1000),"getitem":lambda s,k:s.d[hash(k)%1000],"setitem":lambda s,k,v:s.d.setitem(hash(k)%1000,v)})

m = t()
m["x"] = 4
print(hash("x"), m[hash("x")])

night quarryBOT
#

@versed eagle :white_check_mark: Your 3.12 eval job has completed with return code 0.

-3785526288850116233 0
versed eagle
#

!e ```py
t=type("t",(object,),{"init":lambda s:setattr(s,"d",[0]*1000),"getitem":lambda s,k:s.d[hash(k)%1000],"setitem":lambda s,k,v:s.d.setitem(hash(k)%1000,v)})

m = t()
m["x"] = 4
print(hash("x"), m[hash("x")])

night quarryBOT
#

@versed eagle :white_check_mark: Your 3.12 eval job has completed with return code 0.

940446694651980887 4
versed eagle
#

there we go

#

string hashes being random makes it not always work, but
hash collision :3

sick reef
#

!e

_ENV = [([exec, eval]),('hello', 50, 20, "+", "="),]

_ENV[0][0](f"{_ENV[1][0]}{_ENV[1][4]}{_ENV[0][1](f'{_ENV[1][1]}{_ENV[1][3]}{_ENV[1][2]}')}")

print(hello)
night quarryBOT
#

@sick reef :white_check_mark: Your 3.12 eval job has completed with return code 0.

70
sick reef
#

I got no more ideas.

#

Maybe encode _ENV[1] table, it holds the constants for the most part.

vast wave
#

should at least contain 5 more bitshifts

sick reef
unique heath
night quarryBOT
#

@unique heath :white_check_mark: Your 3.12 eval job has completed with return code 0.

70
unique heath
#

wish granted

#

!e ```py
_ENV = [([exec, eval]),('hello', ((1<<5)-(1<<(1<<2))+(1<<((1<<2)-(1<<0)))+(1<<0))<<1, (1<<5)-(1<<4)+(1<<3)-(1<<2), chr((((1<<5)-(1<<(1<<2))+(1<<((1<<2)-(1<<0)))+(1<<0))<<1)-((1<<3)-(1<<0))), chr((((1<<5)-(1<<(1<<2))+(1<<((1<<2)-(1<<0)))+(1<<0))<<1)+(1<<3)+(1<<0)+(1<<1))),]

_ENV[0]0

print(hello)``` some more wish-granting

night quarryBOT
#

@unique heath :white_check_mark: Your 3.12 eval job has completed with return code 0.

70
thick lodge
#

!e

import LoneDruid
print(LoneDruid.int_to_eso(1)
#

!e

import LoneDruid
print(LoneDruid.int_to_eso(1))
sick reef
versed eagle
#

its exec

sick reef
#

Nah taking about Bitshift.

#

Never understood it.

versed eagle
# sick reef Never understood it.

(assuming they're both signed integers, and b is positive)
a >> b = ⌊ a / 2ᵇ ⌋
a << b = a * 2ᵇ (you dont need to floor or ceil since integers are closed under multiplication :3)

unique heath
#

basically

#

how it works

#

is

versed eagle
unique heath
#

you gotta think in binary

#

so

#

lets say your number is 111 in binary

#

bit shifting to the left << adds a 0 to the end in binary
111₂ << 1 = 1110₂ (the ₂ means its in base-2, ₁₀ means in base-10)

in base 10 (decimal, the one you're most likely used to using unless you aren't a human, which is unlikely), given 7, bit shifting to the end would multiply by 10
7₁₀ << 1₁₀ = 70₁₀

with the same logic, if you do it in binary, a left bit shift would multiply by 2**n (like how base-10 would multiply by 10**n)

right shift is the same, however it just removes a digit from the left

versed eagle
unique heath
versed eagle
#

no
usually one either says which base you're using, or leaves it up to context

#

using subscripts doesnt actually disambiguate at all because the the subscript is in an undenoted base

serene stratus
#

How would you know which he means if he's using them both?

unique heath
# versed eagle no usually one either says which base you're using, or leaves it up to context

For example, (100)10 is equivalent to 100 (the decimal system is implied in the latter) and represents the number one hundred, while (100)2 (in the binary system with base 2) represents the number four

https://en.wikipedia.org/wiki/Radix

In a positional numeral system, the radix (pl.: radices) or base is the number of unique digits, including the digit zero, used to represent numbers. For example, for the decimal system (the most common system in use today) the radix is ten, because it uses the ten digits from 0 through 9.
In any standard positional numeral system, a number is c...

unique heath
serene stratus
unique heath
#

i see it a lot in maths things

versed eagle
serene stratus
#

He says it by using the subscripts?

#

How would you notate it?

versed eagle
#

you just say the base

#

e.g., [binary], [decimal], ...

unique heath
#

In any standard positional numeral system, a number is conventionally written as (x)y with x as the string of digits and y as its base

@versed eagle

unique heath
#

the y is subscripted in the (x)y part but formatting stuff so ignore that

unique heath
versed eagle
versed eagle
versed eagle
serene stratus
#

Lol why are being such a prick, he was trying to help you and you're complaining about a totally normal notation

unique heath
#

wut

unique heath
versed eagle
#

conventionally, numbers are written without a base denotation

versed eagle
#

how am i complaining

#

and how were they trying to help me

#

we're just having a conversation??

serene stratus
#

Oh nvm it was a different person asking the question

#

My bad

unique heath
#

Notation An integer 𝑎
written in base 𝑏
expansion is denoted by (𝑎)𝑏
(subscript b) https://math.libretexts.org/Bookshelves/Combinatorics_and_Discrete_Mathematics/Elementary_Number_Theory_(Raji)/01%3A_Introduction/1.04%3A_Representations_of_Integers_in_Different_Bases

4₁₀ = 100₂, 5₁₀ = 101₂, 6₁₀ = 1102, 7₁₀ = 111₂
https://mathcircle.berkeley.edu/sites/default/files/handouts/2017/Maleva_BMC.pdf

do i need to continue?

versed eagle
unique heath
versed eagle
#

it is a somewhat standard way, yes
i never denied that
i just said that its not the most helpful or widespread

versed eagle
unique heath
#

confsue

versed eagle
#

what you're saying is true, but irrelevant to what i said

#

so im confused about why you're bringing it up

unique heath
#

okay were both confused

versed eagle
clear venture
#

So thirsty to correct people about pointless shit smh

#

It absolutely is a standard way to notate bases, not ambiguous at all

versed eagle
versed eagle
quartz wave
#

in a case where it isn't it'll probably be explicitly specified by a base 10 number subscript as well

versed eagle
quartz wave
versed eagle
#

you are correct, but its still not any less ambiguous than the undenotated number is

quartz wave
#

in the end it's how the human processes it

low lynx
#

it's a bit like saying writing 987 is ambiguous because it can be interpreted in any base

#

it's convention to have the subscript be in decimal, so it's not ambiguous

versed eagle
low lynx
#

not really

#

that's like saying sqrt(x) is ambiguous because there are two roots

quartz wave
versed eagle
quartz wave
#

context determines which things are more proper to interpret than others

versed eagle
#

that is what i said

quartz wave
#

the general context interprets undenoted numbers as base 10

low lynx
#

there isn't a context here where using a base other than decimal in the subscript is fine unless you explicitly say so otherwise

versed eagle
quartz wave
low lynx
#

it would be ambiguous if there were other conventions as to what base the undenoted numbers in subscript are in, like how N can be ambiguous because different definitions can include or exclude 0
but there isn't, so it's not ambiguous

low lynx
#

yes

versed eagle
#

why didnt you say that then
convention is just that: convention
it doesnt remove ambiguity

#

Convention
A practice or procedure widely observed in a group
(widely observed) ≠ (universally observed)

#


this conversation isnt going anywhere i think

low lynx
#

it would be annoying for me to fetch that unicode symbol, and it was obvious enough that you figured it out anyways without me doing that

#

it doesn't have to be universally observed to not be ambiguous

#

someone can always disagree with convention

versed eagle
low lynx
#

that doesn't make everything suddenly ambiguous

versed eagle
#

it just sweeps it under the rug

low lynx
#

hence making it go away

versed eagle
#

no

low lynx
#

sure in a vacuum it's ambiguous

#

we aren't in a vacuum

versed eagle
versed eagle
#

i am confused about what you mean by that

versed eagle
low lynx
#

if you were given the notation (110)_10 with no other context or any knowledge of what the conventional way to write in that notation is, then sure, it would be ambiguous to you whether that was in binary, decimal, or some other base
in the current context, where it is widely accepted that the number in the base is in decimal, it wouldn't be ambiguous as to whether the base is in decimal or not, because it's conventionally in decimal
sure, you could point out that you can technically treat the number in the base as binary or some other base, but that doesn't make the situation in the general context ambiguous because there is one clear and widely used way to treat the number in the subscript

#

just like how sqrt(x) is not ambiguous: you could technically define it to be the negative root, but it is widely accepted that it refers to the positive root, so you aren't being ambiguous when you use sqrt(x) to refer to the positive root

versed eagle
#

now you're reiterating things that have already been said

versed eagle
unique heath
#

i may have caused a war um oops

sick reef
versed eagle
small pier
#

Guys using python i want to scrape a url, basically its tiktok product link
im not able to scrape it, can anyone help?

rugged sparrow
#

I decided to start writing blog posts about the weird stuff I do with python, the first one i wrote is about fishhook: https://chilaxan.github.io/python/2023/11/24/developing-fishhook please lmk if anyone thinks i should add anything else

#

or if there are any typos

#

@quartz wave ^ you might like the read, it has some details about the first version of fishhook

serene stratus
# rugged sparrow or if there are any typos

not really typos but I would think it's more readable if you use caps for names such as Python, CPython, ...
This is quite a lot of work to keep track off but personally I would think it's a big improvement

#

in your about there's a typo, "names" -> "name's" or "name is"

#

but honestly "I'm ..." would be better

rugged sparrow
sly root
#

is there a way to hook call operator of an every declared function using fishhook?

#

doing @hook(type(lambda:0)) doesn't work

fleet bridge
#

that would break a lot of things, even your hook

#

hmm, it kinda works

#

i guess interpreter bypasses function.__call__ method and directly executes func.__code__ with provided args

versed eagle
rugged sparrow
#

I'll see if I can find the code or rewrite it

sly root
#

okay, thanks for info

#

i'm currently trying to do it using the c api

#

plus to avoid immutable variables like builtins and types

fleet bridge
#

i think you can make subclass of FuncionType and hope that interpreter will not ignore overriden .__call__

#

FunctionType is marked as final in C, so to subclass it you should 1) unlock it 2) subclass it 3) lock it back
and then optionally change type of all existing functions (except for your hook, probably)

#

not sure if it will work at all

sly root
#
// Get the hook target dict
if ((hook_target_dict_proxy = PyObject_GetAttrString(hook_target, "__dict__")) == NULL) {
    PyErr_SetString(PyExc_AttributeError, "Hook target doesn't have the __dict__ table");
    Py_DECREF(hook_target);
    return NULL;
}
hook_target_dict = PyDict_New();
hook_target_dict_proxy = ((_Hooky_PyDict_MappingProxyObject*)hook_target_dict_proxy)->mapping;

PyObject *key, *value;
Py_ssize_t pos = 0;

while (PyDict_Next(hook_target_dict_proxy, &pos, &key, &value)) {
    _Hooky_PyObject_Print("%R %R %zu\n", pos, key, value);
}

throws a segfault lmao

#

still cannot convert mappingproxy to dict even though i have the underlying struct

#
ay0ks@fedora:...snip...$ lldb python Hooky.py
(lldb) target create "python"
Current executable set to '/usr/bin/python' (x86_64).
(lldb) settings set -- target.run-args  "Hooky.py"
(lldb) run
Process 33391 launched: '/usr/bin/python' (x86_64)
Process 33391 stopped
* thread #1, name = 'python', stop reason = signal SIGSEGV: address not mapped to object (fault address: 0x9)
    frame #0: 0x00007ffff7a258e9 libpython3.12.so.1.0`PyObject_Repr + 57
libpython3.12.so.1.0`PyObject_Repr:
->  0x7ffff7a258e9 <+57>: movq   0x8(%rbx), %rax
    0x7ffff7a258ed <+61>: movq   0x58(%rax), %r13
    0x7ffff7a258f1 <+65>: testq  %r13, %r13
    0x7ffff7a258f4 <+68>: je     0x7ffff7934f2f            ; PyObject_Repr.cold + 68
(lldb) 
#

a

#

it's because of print

#

even though addresses are not null

0x7ffff7de2480 0x7fffe9f5b880 1
0x7ffff7de2900 0x7fffe9f5b8d0 2
0x7ffff7de1bf0 0x7fffe9f5b920 3
0x7ffff7de2e30 0x7fffe9f5b970 4
0x7ffff7de1a60 0x7fffe9f5b9c0 5
0x7ffff7de2240 0x7fffe9f5ba10 6
0x7ffff7de2100 0x7fffe9f5ba60 7
0x7ffff7de1848 0x7fffe9f5bab0 8
0x7ffff7de2420 0x7fffe9f5bb00 9
0x7ffff7de1bc0 0x7fffe9f5bb50 10
0x7ffff7de19c8 0x7fffe9f5bba0 11
0x7ffff7de2058 0x7fffe9f5bbf0 12
0x7ffff7de2318 0x7fffe9f5bc40 13
0x7ffff7de2a18 0x7fffe9f5bc90 14
0x7ffff7de2130 0x7fffe9f5bce0 15
...
#

(a lil bit of offtop but still esoteric)

#

fixed

while (PyDict_Next(hook_target_dict_proxy, &pos, &key, &value)) {
    _Hooky_PyObject_Print("%R %R %zu\n", key, value, pos);
}
rugged sparrow
#

if you can grab the addresses of _PyEvalFramePushAndInit and _PyEvalFramePushAndInit_Ex you might be able to get it to work with fishhook.asm

#

well actually the version that has been released probably won't work

#

but with those addresses you could patch the asm

sly root
#

okay will try

modest bough
fleet bridge
#

this sounds like a lot of handwaving around type checking without real practical benefit

unique heath
#

but lke why

fleet bridge
#

hey, dont ping random people at 6am

burnt gust
#
from datetime import datetime
from dateutil.relativedelta import relativedelta

_PARTS = (
    ("years", "y"),
    ("months", "mo"),
    ("weeks", "w"),
    ("days", "d"),
    ("hours", "h"),
    ("minutes", "m"),
    ("seconds", "s"),
)


def duration(
    time_x: datetime, time_y: datetime, min: bool = False, weeks: bool = False
) -> str:
    """String representation of the duration between `time_x` and `time_y`."""
    start, end = sorted((time_x, time_y))
    delta = relativedelta(end, start)
    return " ".join(
        f"{num}{' '*(min^1)}{s if min else (z[:-1] if num==1 else z)}"
        for z, s in _PARTS
        if (z != "weeks" or weeks)
        and (num := getattr(delta, z) - ((z == "days") & weeks) * 7 * delta.weeks)
    )


print(duration(datetime.utcnow(), datetime.utcfromtimestamp(1691975673)))
#

this should be accurate and count dst and differences in month lengths, unlike the divmod approach

unique heath
#

thats the best i can get it (54 bytes)

quartz wave
#

40b is one hell of a task

unique heath
#

ikr

unique heath
versed eagle
quartz wave
versed eagle
#

a (mild) hint, if any of you want it: ||De Morgan's Laws||

versed eagle
#

im gonna go to sleep now

#

someone ping me if something interesting happens please :3

earnest wing
grave rover
#

How to ensure you stay hired at your current job:

sly root
#

I couldn't think of this all yesterday, and finally

if (PyType_Check(hook_target)) {
    PyDict_SetItemString(PyType_GetDict((PyTypeObject*)hook_target), hook_function_name, hook_function);
}
#

now it works even for immutable types

#
@hook(str)
def __call__(self, *a, **b):
    print(self, a, b)

@hook(type(lambda: 0))
def unwrap(self, *a, **b):
    print(self, a, b)

str.__call__(123,123)

print((lambda: 0).unwrap)

outputs

123 (123,) {}
<bound method unwrap of <function <lambda> at 0x7f44a0b1a200>>
grave rover
#

Oh this reminds me that I need to work on my bytecode hacks to handle function types

sly root
# sly root I couldn't think of this all yesterday, and finally ```c if (PyType_Check(hook_t...

my previous attempt

if ((hook_target_dict = PyObject_GetAttrString(hook_target, "__dict__")) == NULL) {
    PyErr_SetString(PyExc_AttributeError, "Hook target doesn't have the __dict__ table");
    Py_DECREF(hook_target);
    return NULL;
}
hook_target_dict = ((_Hooky_PyDict_MappingProxyObject*)hook_target_dict)->mapping;

PyObject *temp_key, *temp_value;
Py_ssize_t position = 0;
while (PyDict_Next(hook_target_dict, &position, &temp_key, &temp_value)) {
    if (PyUnicode_Compare(temp_key, PyUnicode_FromString(hook_function_name)) == 0) {
        hook_target_original_function = PyFunction_New(
            _Hooky_PyFunction_Get_Code(temp_value),
            _Hooky_PyFunction_Get_Globals(temp_value)
        );
        break;
    }
}

// ...
low lynx
low lynx
#

||43 again with both ways||

sly root
# sly root ```py @hook(str) def __call__(self, *a, **b): print(self, a, b) @hook(type(...
if (PyType_Check(hook_function)) {
    PyObject* class_dict = PyType_GetDict((PyTypeObject*)hook_function);
    PyObject *method_name, *method;
    Py_ssize_t position = 0;
    while (PyDict_Next(class_dict, &position, &method_name, &method)) {
        if (!PyFunction_Check(method))
            continue;
        _Hooky_HookFunction(hook_target_dict, method, method_name);
    }
}
@hook(str)
class str_hooks:
    def print(self, *a, **b):
        print(self)
    
print(str.print)
print("".print)
"123".print()

outputs

<function str_hooks.print at 0x7faff4801300>
<bound method str_hooks.print of ''>
123
#
>>> @hook(int)
... def __or__(self, *a,**b):
...   print(self,a,b)
... 
>>> 1|2
3
>>> 1|3
3

strange

#

!e ```py
from fishhook import *

@hook(int)
def or(self,*a,**b):
print(self,a,b)

1|2

night quarryBOT
#

@sly root :warning: Your 3.12 eval job has completed with return code 0.

[No output]
fleet bridge
fleet bridge
vast wave
#

!e ```py
from fishhook import *

@hook(int)
def or(self,*a,**b):
print(self, a, b)

compile("1|2", "", "exec")

night quarryBOT
#

@vast wave :white_check_mark: Your 3.12 eval job has completed with return code 0.

1 (2,) {}
rugged sparrow
#

!e ```py
from fishhook import *

@hook(int)
def or(self,*a,**b):
print(self, a, b)

A = 1
B = 2
print(A|B)

night quarryBOT
#

@rugged sparrow :white_check_mark: Your 3.12 eval job has completed with return code 0.

001 | 1 (2,) {}
002 | None
rugged sparrow
#

you need to make sure your changes propagate to the slot functions

night quarryBOT
#

fishhook/__init__.py lines 178 to 181

ocls_ptrs = getptrs(cls, slotdata)
pcls_ptrs = getptrs(pcls, slotdata)
for optr, pptr in zip(ocls_ptrs, pcls_ptrs):
    optr.value = pptr.value```
low lynx
#

@rugged sparrow is there a way to hook like list for example to print something everytime one is created?

rugged sparrow
#

You can hook different C-API functions to get code called when a given object is allocated, but it would be type specific, no generic way

#

*you could do something really nuts and install a malloc hook that records the memory allocated, and then installs a trace function to run on the next python frame that checks if the memory allocated has a type by then and if that type is the desired one to hook allocs of

low lynx
rugged sparrow
#

!e ```py
from fishhook.asm import *

@hook(pythonapi.PyList_New, argtypes=[c_ssize_t], restype=py_object)
def list_new(size):
print('Requested List:', size)
return pythonapi.PyList_New(size)

x = list((1,2,3))```

night quarryBOT
#

@rugged sparrow :white_check_mark: Your 3.12 eval job has completed with return code 0.

Requested List: 0
rugged sparrow
#

@low lynx ^

#

(it says requested list 0) because list literals are allocated as empty, then appended to

sly root
sly root
#

like the __call__ is PyTypeObject->tp_call, but changing it doesn't do anything

#

the way I'm doing it is

static void _Hooky_HookFunction(PyObject* dict, PyObject* function, PyObject* function_name) {
    if (PyDict_Contains(dict, function_name)) {
        PyObject* original_function = PyDict_GetItem(dict, function_name);
        PyObject* original_function_name;
        if ((original_function_name = PyObject_GetAttrString(original_function, "__qualname__")) == NULL) {
            PyErr_SetString(PyExc_AttributeError, "Original function doesn't have the __qualname__ attribute");
            Py_DECREF(original_function);
            return;
        }
        PyDict_SetItem(_Hooky_PatchedDict, original_function_name, original_function);
    }
    PyDict_SetItem(dict, function_name, function);
}```
and then
```c
hook_target_dict = PyType_GetDict((PyTypeObject*)hook_target);

// ...
_Hooky_HookFunction(hook_target_dict, hook_function, hook_function_name);
#

i guess i'd need to make a method table and do hook name checking

rugged sparrow
sly root
#
static inline bool _Hooky_PyProperty_Check(PyObject* object) {
    if (!PyFunction_Check(object)) {
        if (PyObject_HasAttrString(object, "fget") || PyObject_HasAttrString(object, "fset") ||
            PyObject_HasAttrString(object, "fdel")) {
            return true;
        }
    }
    return false;
}

class properties are so strangely designed

#

they're functions in the python code

#

but they are not in the c api

#

anyways now hooking properties works

bitter granite
#

Hello All,
I've a problem with the collections.namedtuple class.

In a nutshell, the string representation of the created class doesn't show up when the object is recalled. Propeties are accessible when recalled.

Expect some omiissions from the code I put together on the fly :

  class Test:
    def __init__(self, raw):
      self.colunns = ['X', 'Y', 'Z']
      self.row = collections.namedtuple("Row", self.columns)
      self.append(raw)

    def append(raw):
      for row in raw:
        row = row.copy()
        dimensions = dict(zip(self.dimensions, row.pop("keys", [])))
        res = self.row(**dimensions, **row)
        self.rows.append(res)

  x = Test(myrawdata)
  x.rows

  >>> [Row(page='https://ww...sition=18), <Row, len() = 5>]

See below a screenshot too
Any idea of what's getting wrong? The cose used to work in 3.9 if I'm not mistaken

astral rover
#

just looks to me like vsc is doing its own special handling there

bitter granite
#

~~I got the same on ptpython .. so either there is a bug somehow with 3.12 .. or I don't know where to look at 😦

bitter granite
#

Actually not ... I replicated on ptpython and it seems to work there.

bitter granite
#

It's a Visual Studo code issue with the variable browser that is skrewing up

night quarryBOT
#

@plush halo :x: Your 3.12 eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "/snekbox/user_base/lib/python3.12/site-packages/fishhook/fishhook.py", line 151, in force_setattr
003 |     flags, should_have_null_tp_dict = unlock(cls)
004 |                                       ^^^^^^^^^^^
005 |   File "/snekbox/user_base/lib/python3.12/site-packages/fishhook/fishhook.py", line 65, in unlock
006 |     cls_mem = allocate_structs(assert_cls(cls))
007 |               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
008 |   File "/snekbox/user_base/lib/python3.12/site-packages/fishhook/fishhook.py", line 47, in allocate_structs
009 |     allocate_structs(subcls)
010 |   File "/snekbox/user_base/lib/python3.12/site-packages/fishhook/fishhook.py", line 48, in allocate_structs
011 |     for offset, size in get_structs():
... (truncated - too many lines)

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

night quarryBOT
#

@rugged owl :x: Your 3.12 eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "/home/main.py", line 14, in <module>
003 |     print(~object)
004 |           ^^^^^^^
005 | TypeError: bad operand type for unary ~: 'type'
#

@rugged owl :white_check_mark: Your 3.12 eval job has completed with return code 0.

Mutable[S]
#

@rugged owl :x: Your 3.12 eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "/home/main.py", line 17, in <module>
003 |     print(type(some_var))
004 |           ^^^^^^^^^^^^^^
005 |   File "/lang/python/default/lib/python3.12/typing.py", line 2220, in get_type_hints
006 |     raise TypeError('{!r} is not a module, class, method, '
007 | TypeError: 0 is not a module, class, method, or function.
restive void
#

I feel like if anything, ~i32 should mean "everything except i32"

rugged owl
#

🤦‍♂️

meager zinc
quartz wave
meager zinc
#

||l=[2]+[n for n in range(3,10**8+1)if 2**n%n==2];print(len({i*j for j in l for i in l}))||
||where should I put the unpack||

meager zinc
#

oh

#

smart

low lynx
#

especially since there's at least 1 charmichael number in there

#

!e

n = 3*11*17
print(n)
print(2**n%n)
night quarryBOT
#

@low lynx :white_check_mark: Your 3.12 eval job has completed with return code 0.

001 | 561
002 | 2
meager zinc
sick hound
#
a = 1
b = -a
c = --a

print(b)
print(c)

-(-a)

boreal spindle
#

!eval

a = 1
b = -a
c = --a

print(b)
print(c)
night quarryBOT
#

@boreal spindle :white_check_mark: Your 3.12 eval job has completed with return code 0.

001 | -1
002 | 1
candid wraith
#

⚠️ Advent of Code day 1 part 2 spoiler ⚠️
Does anyone see a way to get this code golfed in less characters?
||py sum([int(''.join([c for c in __import__("functools").reduce(lambda a,kv:a.replace(kv[0],kv[0]+str(kv[1])+kv[0]),[("one",1),("two",2),("three",3),("four",4),("five",5),("six",6),("seven",7),("eight",8),("nine",9)],line)if 58>ord(c)>47][e]for e in(0, -1)))for line in open("i").readlines()])||

candid wraith
#

cheers

low lynx
#

and move there as well if you want to discuss aoc golfs

burnt pasture
#

(I have a gist with my solution, but it can definitely be shortened)

quartz wave
#

oh it loaded

proper vault
#

it is literally ||delete a file||

#

I got to rule 10 and decided I didn't feel like replacing all my stuff

quartz wave
#

eh i tried

burnt pasture
quartz wave
#

idk i don't do that sorta stuff

burnt pasture
# vast wave what

i was confused by that too. "Committing" usually mean creating a file.

glacial lantern
#

Someone told me to check the working directory and that made me figure it out.

#

Still stuck on rule 10 though.

vast wave
#

huh

#

what

#

am i supposed to print the working directory or what

glacial lantern
#

No, but it helps finding the solution.

vast wave
#

what the fuck

burnt pasture
vast wave
#

aka no members of __builtins__?

#

"call print(), define a new class"

#

uh huh

glacial lantern
#

It's enough to call your custom print function from the other rule.

low lynx
#

mine is 297c, 299 bytes

burnt pasture
low lynx
burnt pasture
#

sure

low lynx
burnt pasture
#

slick

quartz wave
#

this is running in 32-bit is it?

burnt pasture
low lynx
#

yeah probably

#

i'm looking at the code for the rules rn to see what i can and can't do

burnt pasture
low lynx
burnt pasture
#

||change "print:=lambda:print(()for()in())" to "print:=lambda:b,print()"||

#

idk how they are determining that you called it.

#

maybe the ast?

low lynx
#

oh right forgot i don't need another

#

yeah they're checking if the Call with print is a subtree of the code's ast

#

you can see the rules by doing open('src/rules.py','r').read()

vast wave
#

fucking hell

glacial lantern
#

Only fair after getting asked to delete files.

low lynx
#

down to 265c 267b with this
||```py
(b:=().class.base.subclasses().getitem({()for()in()}.sizeof()+(n:=-~'滝'.sizeof())).init.globals.getitem('builtins').getitem,print:=lambda:print(),b('import')('os').remove('password.txt'),C:=b('type')('C',(),{}))and-~n

glacial lantern
#

pop in place of getitem

sly root
#

a, it should be named print?

vast wave
#

331 chars and i am not trying any further

#

fuck this thing

sly root
#

lmao

low lynx
#

it's very weird

glacial lantern
#

It's safe to pop after subclasses, because that makes a new list every time. Not after globals though.

low lynx
#

here's two equivalent 257c's with that
||```py
(b:=().class.base.subclasses().pop({()for()in()}.sizeof()+(n:=-~'滝'.sizeof())).init.globals.getitem('builtins').getitem,print:=lambda:print(),b('import')('os').remove('password.txt'),C:=b('type')('C',(),{}))and-~n

```py
(f:=().__class__.__base__.__subclasses__().pop({()for()in()}.__sizeof__()+(n:=-~'滝'.__sizeof__())).__init__.__globals__,b:=f.__getitem__('__builtins__').__getitem__,print:=lambda:print(),f.__getitem__('remove')('password.txt'),C:=b('type')('C',(),{}))and-~n

bottom one tries to use the fact that the function we're grabbing from is from the os module to save characters on the import, but it miraculously breaks even||

#

that's all i'm doing, someone else can come up with a better golf/optimize that one if they want

burnt pasture
low lynx
#
__builtins__ and (...)

works as well

#

it's because the game, when checking rule 10, runs the code separately with __builtins__ set to {}, but doesn't actually check that the result is 42

#

the eval is in a try: except:, so if builtins are used it'll raise an exception and you won't pass the rule, but if you just have __builtins__ and (...), python just only evaluates __builtins__, which is falsy, and then terminates

low lynx
#

here's a 133c with that loophole

__builtins__ and'瀧'.__sizeof__()+sum(len({print:=lambda:_})for _ in(print(),exec('import os;os.remove("password.txt")\nclass C:""')))
rugged sparrow
#
[s:=next(g:=(g.gi_frame.f_back.f_back.f_back for()in[()])).f_locals['self']]+[setattr(s,k,object)for(k)in dir(s)if'ru'in k]
``` 123 chars, but does not follow the spirit of the game too much
glacial lantern
#

Yep, 42 alright.

rugged sparrow
#

it works by using a generator get a reference to the parents frame, and then replacing every rule_* function with object (which is truthy when called)

modest bough
#

any of you here uses that sort of macro library in python ?

#

surprisingly hylang has a its own tiny macro level model

quartz wave
low lynx
#

I forgot it still runs the code in the class body

bitter granite
#

Hi all,
Let's say that I have a set or a list - still have to decide - with a variable number of dictionary inside (say up to 25K rows), and the length of these dictionary is variable itself, on average 30 items.

What could be the best way to find the longest dictionary?
A for ... next it's indeed memory/time consuming.

low lynx
#

well it can't be a set because dictionaries aren't hashable

bitter granite
gleaming linden
#

are you looking for a serious answer? if so, this is probably not the right channel