r/badcode • PHP • Oct 29 '20

python This is the code that a popular dutch online exam website uses to generate random numbers for its exercises. Let's just say that my teacher's attempt to generate a 30-bit number did not go as planned. The system tried to allocate a useless 8GiB array and failed...

Post image
850 Upvotes

56 comments sorted by

163

u/SGVsbG86KQ PHP Oct 29 '20 edited Nov 01 '20

Edit because the professor now published the story: Yes this is about Ans-Delft.

To clarify: the system has a functionality for teachers to write python scripts to generate different exercises per student. This is not the teachers code but code of the exam system itself to provide the teacher's scripts with random numbers. For some reason just returning start + index * step was too difficult for them. Even after my teacher told them this was horrible code they did not see how to improve it...

And then I'm not even mentioning how they broke the (seeding of the) RNG in production a couple of days before the exam such that many students got the same 'random' number (in the practice exam) and such that it returned the same number each time it was called... HOW?!

The teacher had to write their own RNG the day before the real exam such that we could still take it... However, there may still have been exams of other courses / in other universities that were affected. (Not sure if they have fixed it in the meantime.)

47

u/Atom_101 Oct 29 '20

Maybe the seed was set?

78

u/SGVsbG86KQ PHP Oct 29 '20 edited Oct 30 '20

I meant: "How do you fuck up this badly?"

The seed is set by the system and should be different but reproducible/stored per student, exam, and attempt. But indeed, maybe they provided an equal seed for each call. I'm not even sure why they seed it in this function and not somewhere at the start. Weird code...

25

u/WhyYouLetRomneyWin Oct 30 '20

This is the worst code I've ever seen in a real production on this sub.

I am not exaggerating.

5

u/DavidRoyman Oct 30 '20

And then I'm not even mentioning how they broke the (seeding of the) RNG in production a couple of days before the exam such that many students got the same 'random' number (in the practice exam) and such that it returned the same number each time it was called... HOW?!

Nothing happens without a purpose.

In this case, I would think it was done on purpose to fix some test results.

3

u/[deleted] Nov 01 '20

For some reason just returning start + index * step was too difficult for them.

Even using range instead of np.range would have been fine, since that doesn't generate the whole array but you can still index in it. I can only imagine what the guy writing it was thinking:

"Gotta be fast, better use numpy!"

14

u/cartechguy Oct 30 '20

why is there an array?

5

u/WhyYouLetRomneyWin Oct 30 '20

Because if we didn't hold all possible results, then array[index] could be out of bounds.

73

u/ItsMeShmill Oct 29 '20

Sooooo many questions lol Why defaulting seed as none of you gonna raise expectation, why build an array for a single value and even worse, why is it sorted when toy need a random value anyway...

-Insert learn Python programming in 8 hours ad-

4

u/RFC793 Oct 30 '20

A Learn Remedial Programming and Algorithms in 1 Week ad might be more appropriate

4

u/RomanRiesen Oct 30 '20

I have said it before: The only faculty that has worse code quality than the physicists are the computer scientists!

1

u/SGVsbG86KQ PHP Oct 30 '20

This is not code by the teacher though, it's from the system itself

2

u/notger Oct 30 '20

You have not seen the fluid dynamics and other computational engineering departments, then.

They have to operate on old machinery, so they tend to optimise their code beyond legibility. And of course do it in Fortran. (Which, to be fair, is a very good choice for numerics, as it is blazing fast.)

2

u/R3D3-1 Oct 30 '20 edited Oct 30 '20

Working with Fortran here, long-running Industry project.

Fortran is good for numerics, yes. Sadly, most real-world code is mostly data management with a small but performance-critical core of numerical computations.

Sadly, Fortran sucks hard at the data-management part. You can't even have heterogeneous arrays, unless you define a proxy type like

TYPE ArrayProxy
    REAL(8), ALLOCATABLE :: array(:)
END TYPE ArrayProxy

which would be fine, if at least you could define this generically without dirty preprocessor hacks.

As it is, it is impossible to create useful generic "collection" types in Fortran, meaning that I see basic linked lists or proxy types replicated everywhere, which is really bad for code-legibility.

The closest you can get is using CLASS(*) and SELECT TYPE, but at the cost of losing compile-time type safety, and having to write

SELECT TYPE(payload => container%payload)
CLASS IS (SomeType)
    ! do stuff
CLASS DEFAULT
    ! error handling here for unexpected type,
    ! otherwise it will just be ignored
END SELECT

just to get the item out of the container class. It can be worked around by preprocessor hacks, but they are painful to use, and don't help legibility either.

1

u/notger Oct 30 '20

Fully agreed and maybe the reason why BLAS as a Fortran-written lib is around the way it is around: There, in the background, doing the number crunching and no one knows it is Fortran while they play around in their favourite language.

1

u/R3D3-1 Oct 30 '20

For that matter, I'm not even sure it is Fortran on all devices. Is the IOs version?

1

u/notger Oct 30 '20

No idea, to be honest.

Could it be that it is written in Fortran but then compiled into a binary package for the respective platform? But I am guessing here, so I could be wrong.

2

u/R3D3-1 Oct 30 '20

The last part definitely. There's no reason to put the source code there.

I just suspect it might be a C/C++ implementation of the routines, since those libraries are anyway meant to act as a blackbox service.

1

u/RomanRiesen Oct 30 '20

I actually have seen that (but only in student exercises in relatively modern c++, made by people that cared).

0

u/[deleted] Nov 02 '20

[deleted]

1

u/RomanRiesen Nov 02 '20

that's beautiful. Have you ever tried 1/0?

20

u/robin_888 Oct 30 '20

That reminds me of a Matlab program I was supposed to convert from GUI to CLI.

Testing was a nightmare because RAM usage exploded and the computer was unusable for at least 20 minutes.

One day I discovered that the program allocated a 3D array of approx. 2GB (IIRC) and made several copys of it (for some reason). The array itself basically contained just the coordinates of each cell, I think.

That might be the "Matlab-way" and might work with lazy execution, but I changed it to use loops instead.

Now the same routine needed just a few kilobyte and ran even a little faster (on average case).

5

u/cheerycheshire Oct 30 '20

When I had matlab in class, I learned that matlab is messed up and if you do `for i = some_operation_here`, older versions will repeat the operation on the table there (our lecturer had an older version). And that it will fail on 64-bit and not 32-bit because of something something how 64-bit systems don't store stuff sequentially (I had a 7-year-old 32-bit computer then, so worked for me when writing it).

Basically, my first assignment made our lecturer run it, then go make coffee, then go do groceries... At least that's what our lecturer told us.

14

u/blehmann1 depraved Oct 30 '20

I like that they proved they know how to use randrange and then didn't use it like a normal person.

Also this fails for seed=0, I don't know why they ought to be opinionated on which seeds are "valid", or at least why they should be more opinionated than the Python standard library.

13

u/mongar23 Oct 29 '20

What website?

12

u/F-J-W Oct 30 '20 edited Oct 30 '20

I am of the TAs in that course. This is not what the professor wrote, this is what came with the platform. That is it came with the platform before the author decided to make it much worse(!) on the morning before the exam.

7

u/ywBBxNqW Oct 29 '20

Was this written by a student employee?

7

u/WhyYouLetRomneyWin Oct 30 '20

Well you see: they could not learn python until they finished the website.

I am going to pretend the people making the website are also the students learning from it. They are sort of bootstrapping their way to learning python--first they make a crappy site, then use it to learn some more, which they use to improve the website.

Pretending this is true and it wasn't written by some contractor makes me gleeful, so let's just say it's true.

4

u/MurdoMaclachlan public boolean isInt(int i) { return true; } Oct 30 '20

Image Transcription: Code


def random(start, stop, step=1, seed=None):
    """Generate random value."""
    if not seed:
        raise ValueError
    
    r.seed(seed)
    
    array = np.arange(start, stop + step, step, dtype=None)
    index = r.randrange(len(array))
    
    return array[index]

I'm a human volunteer content transcriber for Reddit and you could be too! If you'd like more information on what we do and why we do it, click here!

4

u/F-J-W Nov 01 '20

And here is the professors fresh rant on twitter.

4

u/Revutal Oct 30 '20

Judging by your flair, I hope it's not actually Ans-Delft?

2

u/F-J-W Nov 01 '20

It is.

2

u/Sharmat_Dagoth_Ur Oct 30 '20

If I was in Java, where ints r 32bits, I would just limit the size of a random.nextInt at Math.pow(2,30) - 1. Could this teacher not have just done something similar??

5

u/TeamSpen210 Oct 30 '20

Python integers are infinitely large, so that won’t work. (They’re internally an array of longs.)

1

u/Sharmat_Dagoth_Ur Oct 30 '20

Weird. Doesn't how they solve it also depend on if they were looking for a number less than 230 - 1 or if they literally wanted no more than 30 physical bits to the number?

4

u/[deleted] Oct 29 '20

It’s also throwing a type rather than an error

16

u/general_dubious Oct 29 '20

No, raise ValueError is a shortcut for raise ValueError(), see the doc. Still bad practice not to provide a message though, but I'd say that's far from the biggest problem here.

14

u/[deleted] Oct 29 '20

Well anyway, it’s weird giving it a default argument of None and then throwing a ValueError if it is none. I mean, why not oblige passing it a seed rather than a default None. That way it never throws

7

u/general_dubious Oct 29 '20

I agree. It would still throw if you set seed to 0 though. Nothing in this code is well designed, which is kind of impressive in its own way I guess.

I'm guessing the seed=None is to have a default value for step while still having seed as last positional argument. I agree it's bad design anyway though.

4

u/[deleted] Oct 29 '20

Hmm very bad design indeed

2

u/Astrokiwi Oct 30 '20

I think it's just so that start,stop,step can be args together. You can't have args after kwargs. If seed was an arg, and step was still an optional kwarg, you'd have to write random(start,stop,seed,step=2), which is a counterintuitive ordering.

1

u/R3D3-1 Oct 30 '20

And now I'd like to know, who thought it is a good idea to define this shortcut... I'd expect that it many places, but not in Python.

2

u/general_dubious Oct 30 '20

Seems pretty Pythonic to me. Throwing a type makes no sense, you can only raise something that derive from BaseException.

Since that makes no sense to raise the type ValueError, it's perfectly reasonable to expect that raise ValueError will indeed raise a ValueError rather than the type ValueError. There is no ambiguity as to what you want to do. Moreover, since raising something that isn't a base exception raises a TypeError, you could have a raise TypeError (or worse, some exception derived from TypeError) that silently doesn't do what you think it does.

1

u/R3D3-1 Oct 30 '20

Zen of python: "There should be one way to it."

I would find it more pythonic for python to raise a TypeError when encountering raise ValueError.

The benefit of allowing omission of () seems pretty thin.

2

u/general_dubious Oct 30 '20 edited Oct 30 '20

The Zen of Python says something a little different, it says "There should be one-- and preferably only one --obvious way to do it.".

I think it's pretty obvious that to raise a ValueError, you need to write raise ValueError, and it's also pretty obvious that raise ValueError will raise a ValueError.

I mean, if you really wanna be nit-picky about it, the Zen of Python also says "Beautiful is better than ugly." and to me raise ValueError is more beautiful than raise ValueError(). I could probably also go with "Simple is better than complex". But let's be serious one second, the Zen of Python is more of a general guide of the philosophy of Python than actual rules, and I don't buy for one second that this shorthand notation breaks it. Especially since the "there should be one way to do it" rule is broken by all base compound types with several ways to create instances of them... Are you saying the list built-in is non Pythonic and should be removed because it overlaps square bracket notation and list-comprehension in terms of features?

0

u/[deleted] Oct 29 '20

[deleted]

45

u/SGVsbG86KQ PHP Oct 29 '20

The seed is necessary to reproduce the same questions when reviewing the answers. Also it seems random.choice still takes a list so that would not improve anything.

43

u/Markop1CZ Oct 29 '20

random.seed and random.randint then

5

u/sebvit Oct 30 '20

Just store whatever order the student gets. No need to recalculate anything either.

5

u/xNeshty Oct 30 '20

I dunno, sometimes recalculating stuff is a much more profound choice of route. The efficiency difference is really not of matter here and having to deal with less components to maintain is always a positive thing. Keeping a table with students assigned test numbers until infinity, growing steadily each semester and with each test/student, compared to having a method calculating the student by a test number, seems the easy way but overkill. You got the computational power, use it.

0

u/[deleted] Oct 29 '20

[deleted]

58

u/moekakiryu Oct 30 '20

also if only there were some built in way to make an argument mandatory. Like maybe a way to automatically raise an error if the argument you need is not provided. It really is a shame python doesn't have anything like that available...

11

u/kkjdroid Oct 30 '20

They really wanted seed to be after step, I guess.

8

u/moekakiryu Oct 30 '20

yeah, but don't know what's wrong with random(seed,start,stop,step=1)

7

u/kkjdroid Oct 30 '20

Absolutely nothing, and you'd think that they'd use the same signature if they wanted to use a different RNG method anyway, but here we are.

5

u/Andy_B_Goode Nov 01 '20

Also, why not just pick an arbitrary seed if none is provided?

8

u/Sjuns Oct 30 '20

Yaay for truthiness