« first day (4023 days earlier)      last day (908 days later) » 

12:07 AM
@singledispatch
def drawShapes(img: numpy.array):
	pass


@drawShapes.register(str)
def drawShapes(imgPath: str):
    drawShapes(cv2.imread(imgPath))


@drawShapes.register(PIL.Image)
def drawShapes(pil_image: PIL.Image):
    drawShapes(cv2.cvtColor(numpy.array(pil_image), cv2.COLOR_RGB2BGR))
still not working. It says @drawShapes.register(PIL.Image)
AttributeError: 'function' object has no attribute 'register'
I imported "from functools import singledispatch"
 
 
1 hour later…
1:16 AM
cbg guys
 
1:35 AM
starmonkey = ratchet.attach( captive_monkey, pipe.catch_a_star ) + deco_hand_frog
oops wrong thread
 
1:49 AM
Hello guys,

2. You are given a string of characters S = s1,s2,...,sn
where all non-alphabetic characters have been removed (e.g. “thisisasentencewithoutanyspacesorpunctuation”) and a function dict(w,i,j),
which takes as input a string w and two indices i and j and returns
true if the string wi...j is a dictionary word and false otherwise.
Any idea what dictionary word is please?
 
 
3 hours later…
4:29 AM
Hey guys, one question here
I'm trying to create this code so that when variable J is present, it is a positive number, but if H is present, it is a negative number. Here is my code.

record = ['1J2H']
def robot_location(record:str):
if J in record:
sum()
if H in record:
** I dont know how to subtract them**
print(robot_location(record)
So if record = [1J2H] then the output should be ((+1)+(-2)) = -1 should be the output... how can I do that?? Somebody pls help explain this.
 
 
1 hour later…
5:53 AM
@McMidas there's no point in doing that. If the only differenve is a type conversion: yes, use isinstance and convert in one function.
 
6:08 AM
@McMidas The functions that you decorate with @drawShapes.register must have a different name than drawShapes. You're overwriting your singledispatch drawShapes with a specific implementation of drawShapes because you're giving them the same name
 
cbg
 
6:40 AM
cbg
 
6:54 AM
What's the proper way to implement a custom Awaitable? It's easy to create a class with an __await__ method, but then the only thing you can do with it is await it - you can't cancel it or turn it into a Task or anything.
class MyAwaitable:
    async def _run(self):
        print('done')

    def __await__(self):
        return self._run().__await__()

awaitable = MyAwaitable()
task = asyncio.Task(awaitable)
# TypeError: a coroutine was expected, got <__main__.MyAwaitable object at 0x000001DD54097FD0>
Do I need to implement the whole Future/Task interface manually?
 
recbg
@Aran-Fey there are no custom "awaitables"
you're asking "how to create a custom coroutine"
 
Well, a coroutine is also an awaitable, so a custom coroutine is also a custom awaitable...
 
yes but awaitable is not a coroutine
 
Ok, so how do I implement a custom coroutine?
 
> There are three main types of awaitable objects: coroutines, Tasks, and Futures.
 
7:00 AM
@Aran-Fey Your __await__ has to yield.
But that won't satisfy asyncio.run – it expects an actual coroutine.
 
Blatant elitism
 
@Aran-Fey coroutine is not an interface.
@Aran-Fey it is a thing.
you cannot make a "custom" generator either.
 
@MisterMiyagi What difference does that make?
def __await__(self):
    for foo in self._run().__await__():
        yield foo
Same thing
@AnttiHaapala Ok, so how do I achieve my goal? >_>
 
@Aran-Fey you need to have a coroutine object. Not that it makes any sense.
if your awaitable does not print "coroutine" then it doesn't work.
I do not know. I hate asyncio with passion and think it is pointless. I could care less :D
I am just saying you're wrong :D
 
@Aran-Fey Eh, none with your setup. Missed that you just return a coroutine's __await__, that should do the same.
 
7:07 AM
So there's no good way to do this, then?
 
Either way, the restriction of asyncio.run is just arbitrary. E.g. it does not accept gather either.
@Aran-Fey You can modify asyncio to properly check for an awaitable, not a coroutine. :P
 
I guess I'll just force my users to do await my_thingy.run() instead of await my_thingy then
 
If you just want to use it, wrap your awaitable in some main coroutine.
async def main():
    await MyAwaitable(awaitable)

asyncio.run(main())
Meeh, I feel like I'm just addressing your Y, not your X. :/
 
Eh, it's not a big deal
 
It's not your fault that custom awaitables don't work with many of asyncio's utilities. You can still await them in coroutines or yield from them in __await__ just fine.
 
 
3 hours later…
9:47 AM
cbg
weird that html doesn't have delete and put: softwareengineering.stackexchange.com/questions/114156/…
Since it's broken anyways, I'm doing all with get for my toy example :P
 
"At this point, it seems that the main reason why there is no support for these methods is simply that nobody has taken the time to write a comprehensive specification for it". All right, it's been eight years since this sentence was written. Has anybody taken the time to write a specification since then?
 
@Kevin no
 
10:03 AM
Cool cool
 
So it's one big corporate meeting stretching decades xD
 
As punishment for drawing out the meeting, the doors will be locked with all committee members sealed inside.
 
 
2 hours later…
12:25 PM
Adding methods to objects where you get the method names as strings is kinda bad design right?
Also not sure what interesting discussion I missed, but the last 4 starred messages of Kevin make we want to read the log
 
Adding methods to objects is always weird design, and in some ways weird equals bad
 
@AnttiHaapala So you do care a little? I love how this phrase developed from funny snarky way of saying you don't care to the new phrase which literally means you care a little, but the intended meaning is the same as before. Ah human language, computers will never get us xD
I'm writing a small orm, because the complexity of an actual orm would be overkill for the course. This happened already a few times during the course I want to show some concept in simple, but in reality you would never do it that way, then I go like what the heck I will just show them the proper way and bam I have a new topic, rinse and repeat and I even considered for a moment to include flasks orm. I came to senses and now we are writting a small custom orm, but the same worry applies as
before and I really hope nobody does that for an "actual" project, whatever that means
teaching IT is hard, not only is everything circularly dependent on each other, all the components also are nested inside of themselves. More complex components building on simpler ones. Showing any semi realistic example of things is hard and I often have to say, we will see the details of that in a moment just believe the tldr for now. Feel like other fields have it easier in that regard, thinking back to my biology courses for example
then tbf most other fields where I learned things I never learned to actually do stuff, just know things. I imagine other fields are the same when you get to the do stuff area, it's just that you get so much faster to the do stuff area in IT than in others, it's like if everybody had a biolab in their pocket :P
 
Hi guys. I need help with databases(related to Django).
You know on eBay you can create a listing, and then on that same page, you put your starting bid price. I have a model in Django called Bids, for bids and one called auctions. I want to be able to let the auction model relate to bids model such that when I'm adding an action to my tabel(model), I give it the starting bid and it automatically creates the bid price.
So something like list this item for 4$. And in the bid model the price of the bid is set to 4$.
 
@Dave a glaring hole in my django knowledge, but as far as I remember the doc is quite good in explaining how to do that: docs.djangoproject.com/en/3.2/ref/models/fields
 
This is mainly about SQL or databases though
 
12:40 PM
Are you not using djangos orm?
 
Cause I'm wondering how to to map two tables together
Yes I'm using the ORM
 
Then I don't see how it's sql related? You should be able to set up the models in django and get this functionality without having to write any sql
 
Yes that makes sense
 
1:11 PM
morning cabbages, folks
 
Today I'm searching for any Pythagorean triple that forms a right triangle very close to a 30-60-90 triangle. I'm pretty sure an exact solution is impossible, but I don't mind a little wiggle room.
I'd like to start by iterating up through Pythagorean triples in approximate order of their area. I have no idea how to do this.
 
@Hakaishin well interesting. Why would an actual ORM be an overkill? I've come across too many projects ... in Javascript ... that have their own "ORM" that's an underkill and it is awful when they've tied all the code to that... :/
 
Perhaps a priority queue containing the unexplored branches of en.wikipedia.org/wiki/Tree_of_primitive_Pythagorean_triples
 
@Kevin you're "pretty" sure you can't find x, 2x and x * sqrt(3) that are integers...
 
1:28 PM
h, h*sqrt(3)/2, h/2. You won't get a integer triple, because sqrt(3) is irrational
@AnttiHaapala oh hey! you fgitw'd me :)
 
by minutes :D
 
I blame the coffee download bandwidth
 
Yeah I'm pretty sure
 
@Kevin i.e. you're looking for `(x + round(sqrt(3) * x)) ** 2 = 2y ** 2 where abs(y - x) <= epsilon and isinstance(x, int), isinstance(y, int)
 
@AnttiHaapala well dbs were not even in the course description, so orms just feels like a stretch.
 
1:36 PM
@AnttiHaapala Yeah sounds right
Currently trying to rearrange the formula to minimize the number of lossy floating point math operations. Not that I have a rigorous way of doing that.
 
@Kevin There's a way to iteratively generate those triplets. They're related to the Pell equation connected to sqrt(3), x^2 - 3y^2 = 1, which has solutions (2,1), (7,4), (26, 15), etc.
No floats required.
 
1:58 PM
Ooh sounds promising
 
So we can get triplets like (33, 56, 65).
where the hypotenuse is 1 off being twice the length of the shortest side.
I have to briefly go & do something, but I'll be able to post an algorithm in half an hour or so.
 
Oh, good sanity check. My more primitive approach just spit out (33, 56, 65)
here is my code, and an excerpt of its output. It won't print every single triple that's close to a 30-60-90 triangle, because of the lazy way I'm tracking candidates, but I don't mind.
 
2:14 PM
queue = []
heappush(queue, (6,3,4,5))
I rate this code "lawful good"
 
It's actually a little inconsistent, because I originally intended to store the triangle's area in the first element of the tuple, but later on I just store the product of the legs. In other words, twice the area.
It saves me one whole bit shift, what a savings
I say "inconsistent" and not "wrong" because it doesn't matter what number the first triple uses, because there's only one way to order a list of length 1
 
2:29 PM
@Kevin Here you go: ~30-60-90 triplets
 
Very nice
All of this is because I want to form a 60 degree angle with my construction set, and using the pieces to build pythagorean triples is relatively easy and sturdy.
In reality the smallest rod plus two connector end pieces, is about an inch long. So I probably won't be able to fit any of these triangles in my room after (33, 56, 65) or so.
 
I often use (26, 15) to do ~equilateral triangles with pixels.
 
I just noticed I'm overlooking a category of solutions, because the set has rods of length 1, 2, 4..., and rods of length sqrt(2), 2*sqrt(2), 4*sqrt(2)...
 
That doesn't sound very rational.
 
So not only can I construct right triangles with integer sides, I can construct triangles with side lengths (k + j*sqrt(2)) for any non-negative integers j and k.
In principle I can get negative j as well, but it gets very wobbly
 
2:41 PM
The basic logic is that we can factorize x^2 - 3y^2=1 as a difference of two squares. So x^2 - 3y^2 = (x + sqrt(3)*y) * (x - sqrt(3)*y) = 1. Now raise both sides to the power of n: (x + sqrt(3)*y)^n * (x - sqrt(3)*y)^n = 1, for any n. Each of the bracketed terms can be expressed in the form (u ± sqrt(3)*v), and all the (u, v) pairs give us all the solutions to the original equation.
 
my cocktail napkin math suggests that having a sqrt(2) length rod doesn't give us any new pythagorean triples, except for the integer-valued ones scaled up by a factor of sqrt(2)
 
Now u^2 - 3v^2 = 1, therefore u^2 + v^2 = (2v)^2 + 1. That's almost a right triangle, but the hypotenuse is a tad too long. But there's a neat trick we can use here to turn that into a proper triad of the desired proportions.
u^2-v^2, 2uv, u^2+v^2 is always a triad. If you look at it from the perspective of complex numbers, (u + vi)^2 = (u^2-v^2) + (2uv)i = (a+bi) has squared norm (u^2+v^2)=c^2. And in polar form squaring a complex number doubles its angle, converting the ~30° angle of (u+vi) to the ~60° angle of (a+bi)
 
I understand about 80% of that :-)
I think I have all the necessary knowledge prerequisites, now I just need to bombard it with my grok beam
 
3:00 PM
:) That algorithm for (u, v) gives all the best rational approximations to sqrt(3). Obviously, there's no integers that solve u^2 - 3v^2 = 0, so the closest we can get is u^2 - 3v^2 = 1. And the error of u/v ~= sqrt(3) is generally much better than what you get by choosing some random integer in the neighbourhood of v as the denominator.
The algorithm for producing further solutions from a base solution was discovered by Indian mathematicians. en.wikipedia.org/wiki/Brahmagupta%27s_identity And Fibonacci knew a related identity en.wikipedia.org/wiki/Brahmagupta%E2%80%93Fibonacci_identity
Actually finding a base solution of x^2 - d*y^2 = ±1 can be tricky. Even for small d, the lowest (x, y) can be huge. Discovering the solution for d=61: (1766319049, 226153980) was historically a major achievement.
Many of the great mathematicians throughout history have investigated this stuff, including Archimedes, Diophantus, Lagrange, Euler, & Gauss. en.wikipedia.org/wiki/Pell%27s_equation has some info.
 
3:19 PM
Oh no, Diophantus. I don't think I've ever solved any problem where his name came up.
 
Well, he did some pretty impressive work on integer equations, and so we name those equations after him.
 
Diophantine, more like, elephantine, in the way it can squash me flat without effort
 
Oh, I forgot to mention Fermat. But really, virtually any of the old mathematicians did some work on quadratic diophantine equations.
There are lots of lovely patterns in those equations. But once you get past the quadratics, things get rather gnarly. ;)
 
I believe it
 
Luckily, problems involving distances boil down to Pythagoras theorem, so quadratics are all you need.
OTOH, if you want to do stuff like trisecting angles, you're into scary territory.
This MSO comment has proven to be rather popular:
FWIW, typos in your question that aren't present in your actual code are even worse than "genuine" typos: you're giving misleading evidence to the people who are trying to help you. At least in this case you did fix those question typos. But bear in mind that it can strongly discourage answerers when they have to deal with that sort of thing. — PM 2Ring yesterday
 
3:52 PM
Huh. My company is hosting a conference in 2 weeks and we've just announced that Christopher Wylie will be giving a presentation. That could be an interesting one!
 
 
2 hours later…
5:54 PM
Hello fellas, how are you doing? I've got a pretty scary problem I'm facing for the first time, and I'd appreciate any light. I've got a complex and big algorithm, and the first time I run it for a given input, it's giving me the result 120. All other runs after that will give me the correct result 176. I don't change anything between runs, nor is any of the data the algorithm is dependent upon changed. It's all the same, and giving me different outputs :O
I'm not using anything related to multiprocessing, nor am I executing loops on unordered structures counting on them being ordered. No random numbers being used at all. Any ideas? It's too big for me to provide a MCVE at this moment.
 
@lupus post the code on pastebin so we can look at it
 
@SurpriseDog impossible, it has 4000 lines all intertwined logic and very very messy.
 
And you'll have to say what kind of libraries you are using. And how you're running it.
 
basically the first run is giving me strange result.
 
If it runs inside something like ipython or jupyter it's trivial to have history.
if the code is in a .py file which you're running with python foo.py I'll be very surprised if it gives different results, already "the first time" sounds suspicious
 
5:59 PM
only itertools (combinations and product), deepcopy and mysql.connector. not running ipython or nothing like that
just running from sublime text directly pressing CTRL + B
 
So you have a database.
 
yeah but the algorithm never writes to it
 
I don't know sublime. Are you positive that it has no "kernel" that has persistent state?
 
lemme try and run it from terminal to see if the behavior persists.
 
thanks
the database sounds a lot more suspect, but it's better to exclude everything
 
6:16 PM
Sublime is running always python 3.8.10. Now I have tried running the algo from terminal with that version, and it's returning 176 consistently. But when I try running version 3.9.7, it consistently returns 120. Maybe it has to do with a internal logical error, but that would only be true if the the output behavior for itertools combinations is random. Gonna check that now
 
Nah, combinations is deterministic
 
yup
 
yeah just realized that
 
6:36 PM
Well I was wrong: it's not only at the first run, and can happen on both python version (good lord!). I'll inspect if it might be something on the logic. If not, I have no clue but also would suspect database. Is it not safe to read data from mysql with mysql.connector if the table is too big or something?
the biggest table has half a million rows, with some 15 columns
 
in the vast majority of cases the explanation for weird behaviour is programmer error rather than esoteric library issue
 
I assume you probably shouldn't rely on the ordering of the database results
 
I'm not @Aran-Fey. It's probably my mistake somewhere really.
I'm reading in a blog that "Just as with dictionaries, the ordering of set elements is quite arbitrary, and shouldn’t be relied on.". Is that true? Cause I've run a few tests and lists, tuple, and sets seems to retain order always.
 
yes, it's true
except with dictionaries it's no longer true :P
lists and tuples are sequences, you can bet your butt that they retain order
 
so if I have a list, and I set(list) it's possible the order changes? in my trials it didn't happen once (simple testing algorithm)
a = [1,2,3]
for i in range(500):
	z = list(set(a))
	print(z)
 
6:43 PM
Oct 1 at 20:52, by Mikhail
list(foo);import pdb;pdb.set_trace();list(foo)
foo is a set there ^ and dropping into the debugger changes the result of list(foo). This doesn't happen normally, so it's weird, but the bottom line is that you can't assume anything about order, ever.
 
I'm using list(set(my_list)) to remove duplicates from a list sometimes, but I didn't think it would maybe sometimes change order. Is there an alternative to that, shorter than a list comprehension?
 
What's the 'modern' way of doing this in python (it's JavaScript)? Would appreciate any hints. Note that 'find' provides the index of the current element.
const [tP, cP] = p.find(
  ([tP], i) => t >= tP[0] &&
  (!p[i + 1] || p[i + 1][0][0] > t)
);
 
Can you describe what "this" is so we don't have to collectively google the JS documentation?
Self-explanatory variable names also wouldn't have hurt, but alas
 
@lupus that's a common duplicate (heh).
 
It finds an entry of a 3-dimensional array (p). t is a constant.
It's the first item of which this is true: t >= item[0][0] and it does not have a preceeding item or the preceeding item[0][0] > t.
 
6:56 PM
@lupus you'd google "python remove list duplicates keep order", you typically have to convert to a set, then use a list comp on the original list to decide if each item should be kept.
So yes, nothing shorter than a list comprehension, but life is not code golf. Do you need to keep order or not?
You need a given behavior, and you write the simplest code that does that. Simple code that does something else is not useful.
 
true, got my answer already - I'm sorry and thanks for answering anyhow
 
@ChristophBühler Hmm, so what is the return value? What are tP and cP? The index and the element?
 
@Sator please ask off-topic elsewhere
@Aran-Fey joke's on you: I wasn't going to lift a finger for a JS question
 
@Aran-Fey That's just destructuring (like "tP, cP = list" in python). The return value is a 2-D-Array.
 
@AndrasDeak I'm reading on SO answer that after Python 3.7 dicts are insertion order so the correct way to do that would be instead: list(dict.fromkeys(my_list)). Should I go with that or build the function to do it?
 
7:00 PM
@ChristophBühler if you can write a "maybe not modern" version in python we can discuss alternatives
@lupus if you're absolutely sure that nobody on python < 3.7 will use your code, go ahead, but leave a comment explaining that line. On earlier python versions it will still "work" but give subtly wrong results (the worst kind of bug)
 
Awesome, I'll do that. Lemme implement it now to see if will remove my output inconsistency. Thanks a lot mate!
 
My best guess is something like
tP, cP = next(
    item
    for i, item in enumerate(p)
    if t >= item[0][0] and (not p[i+1] or p[i+1][0][0] > t)
)
 
hey people!
I was trying to run this:
from getpass import getpass
from mysql.connector import connect, Error

try:
    with connect(
        host="localhost",
        user=input("Enter username: "),
        password=getpass("Enter password: "),
    ) as connection:
        print(connection)
except Error as e:
    print(e)
I got an error:
    password=getpass("Enter password: "),

AttributeError: __enter__
Can you people please help me figure out the problem and solve it?
 
@Aran-Fey That's pretty cool. Tested it and it produces the same output. Thanks and props to you!
 
@RandomPerson Well, clearly the connection object returned by connect isn't a context manager. A quick glance at the documentation tells me that you should use connection.close() instead
 
7:14 PM
@Aran-Fey you mean instead of with connect I should use with connection.close?
that gave me an error:
NameError: name 'connection' is not defined
 
No, you should do connection = connect(...) and then connection.close()
 
@AndrasDeak it seems the inconsistency is gone now! amazing, but I'll have to build a tester to check if this ever happens again. thanks again mate!
 
no worries
 
hakuna matata
 
you should try finding where your assumption was hidden, just to make sure there aren't other subtle bugs around there
 
7:26 PM
@Aran-Fey like this?
from getpass import getpass
from mysql.connector import connect, Error

try:
    with connection=connect(
                            host="localhost",
                            user=input("Enter username: "),
                            password=getpass("Enter password: "),
                            ) as connection:
        print(connection)
        connection.close()
except Error as e:
    print(e)
 
wow
 
I must say that I am a noob. So please bear with me.
 
No, not like that. Why are you so insistent on using a with? AttributeError: __enter__ translates to "this object cannot be used with a with"
 
@RandomPerson You might be a noob, but if you post a snippet with a glaring syntax error and ask "like this?", you're doing it wrong
 
Like I said, the documentation shows the proper way to do it. So I really don't understand why you're even having this problem. Where'd you get the idea to use with from?
 
7:29 PM
@Aran-Fey actually I am trying to use mysql.connector by following a tutorial and it was mentioned that "You should always close the connection after you’re done accessing the database. Leaving unused open connections can lead to several unexpected errors and performance issues. The above code takes advantage of a context manager using with, which abstracts away the connection cleanup process."
 
chalk another one up to realpython
 
@AndrasDeak :(
 
I can confirm that code block is a literal copy-paste from yamming realpython
@RandomPerson the first thing you should do is close that webpage
burning the computer might be overkill
 
@AndrasDeak haha.. please suggest me a good tutorial for python-mysql
 
Hmm, in theory it's possible that realpython isn't completely wrong... maybe you're just using an outdated version of the mysql module. But I can't find any mention of a with statement or context manager in the official docs, so...
 
7:33 PM
same
 
If you really want, you can do with contextlib.closing(connect(...)) as connection:
 
Stdlib sqlite3 connections also aren't context managers, right?
 
No idea, never used it
 
ah, no, they are, but they don't auto-close
I knew there was something weird there, but I don't use databases at all
I guess it's not that weird when their contextness defines transactions (but again, I don't do DBs)
 
@AndrasDeak all I needed really was for order to be maintained when removing duplicates, I was really astonished to learn about this bizarre behavior for sets
 
7:39 PM
I mean you sounded like order didn't matter in your algorithm, yet it did. But if it's obvious why fixing the order fixed your code, it's fine.
Personally, I wouldn't rest until I fully understood why the mixed-up order broke my results.
 
@RandomPerson try this:
import mysql.connector

con = mysql.connector.connect(
	host="localhost",
	user="root",
	passwd="my_password",
	database="my_db"
)
db = con.cursor(dictionary=False)

#do stuff here

db.close()
con.close()
you will need to pip install mysql-connector-python if I"m not mistaken
 
@lupus "You should never hard-code your login credentials, that is, your username and password, directly in a Python script. This is a bad practice for deployment and poses a serious security threat." Source
 
@AndrasDeak it did matter only for a small operation, and I was aware of the order matter, just didn't antecipate the set behavior. Everything should be smooth now. I'm relying on order as little as possible.
 
@lupus yup.. I have already installed :)
 
@RandomPerson thanks for reminder about security. will def change it when it goes live
 
7:44 PM
@lupus what do you mean by "will def change it when it goes live"?
 
try operating it without the with. you only need to connect once to the db. after that, you need to understand mostly how execute works, fetchone and fetchall. if you need some examples I can provide.
@RandomPerson I've been working for 14 months in a single python script, and it's not finished already so it only runs locally.
 
@lupus oh.. ok.
 
@lupus their error has nothing to do with execution methods
 
he was asking for a tutorial on mysql.connector
yo josh :D
 
The sqlite documentation shows that sqlite context managers work like the psycopg2 connector, which I found massively surprising. It's still a source of shame that I overlooked this one; we choked our aws cluster so I moved everyone to context managers ASAP as a fix... only to find that it did absolutely nothing and wasted everyone's time :/
 
7:50 PM
The classic blunder: Making assumptions
 
Yeah, but until that point I'd honestly thought that the context manager kinda made a contract for the named resource. As in, I'd come to understand that was basically the point
At least I didn't make anything worse, I just distracted people from finding the actual fix
 
@lupus thanks!
@Aran-Fey thanks!
 

« first day (4023 days earlier)      last day (908 days later) »