« first day (2851 days earlier)      last day (2096 days later) » 
01:00 - 22:0022:00 - 00:00

1:15 AM
cabbage
 
1:40 AM
cabbage
 
def mxdiflg(a1, a2):
mx,mn=lamda a:len(max(a,key=len)),lamda a:len(min(a,key=len))
return max(mx(a1)-mn(a2),mx(a2)-mn(a1)) if len(a1) and len(a2) else -1
Traceback (most recent call last):
File "main.py", line 1, in <module>
from solution import *
File "/home/codewarrior/solution.py", line 2
mx,mn=lamda a:len(max(a,key=len)),lamda a:len(min(a,key=len))
^
SyntaxError: invalid syntax
WHY?
 
First of all, I'd recommend checking out the room rules, second of all, from what you've posted, looks like an indentation issue.
 
DSM
lambda has a "b". Before trying to cram everything into one line, let's get the syntax right. ;-)
 
@user3483203 I copy pasted it wrong it isnt...
@DSM can u point me to what "b" means? ty
 
DSM
(brief cabbage for all)
@MasterM: "b" is the second letter of the Latin alphabet.
 
1:46 AM
@DSM hahaha what u meant with "b" there
 
DSM
...
 
@DSM or just write how it should look xD
 
DSM
I did.
 
@DSM lol i noticed it now
@DSM ty xD
 
@shad0w_wa1k3r Yes, it's a level with a special type of boss...
 
1:50 AM
I seem to remember someone once said that the mature version of a lamda is a muttonda
8
 
@coldspeed im not a native english speaker so i had to google muttonda... nice joke u got me
 
recabbage
 
2:28 AM
cabbage to you
 
Potato?
 
 
4 hours later…
6:58 AM
Cabbage :-)
@coldspeed That joke would have made a big laughter among Indian developers for sure :D
 
7:13 AM
cbg-ning
 
7:30 AM
@PM2Ring I want to run an alarm app in which my script will read alarm time from file and once it meet up it ring for a specified duration, I setted up alarm ring once the time condition meets, but I need to run this method in a background service,how i can do?
 
8:23 AM
@smci haha, good one!
 
 
2 hours later…
10:02 AM
@coldspeed can't find it in the transcript for the life of me but I know it was here
 
hello, how do I specify typechecking (`Typing` library) of list of lists of size 2 each?

`List[List[str, str]]` throws error and `List[Tuple[str, str]]` does not. Any way of doing that just with Lists? `List[List[str]]` works but then it accepts lists of any size. How can I specify the size restriction with just `List`?
 
Apr 12 at 14:21, by toonarmycaptain
@wim A more mature version of lambda in python should properly be caalled muttona.
 
10:45 AM
Thanks. I new it was punctuation
 
11:37 AM
AAAAAAAA s/new/knew/
 
cbg
 
12:14 PM
How do I write good programs? Like, morally good.
If dark patterns exist, then conversely light patterns must also exist
 
cbg
 
@Kevin You use the same tricks to make the user do what you think is good then it's morally ok
A friend recommended me a book with such a philosophy ._.
 
@paul, backticks don't work on multiline messages. Consult sopython.com/wiki/… for more information.
TLDR: try ctrl-k
 
def get_item_detail(...)
def get_item_detail_by_city_name(...)
def get_item_detail_by_zip_code(...)

results = get_item_detail(address)
if len(results) == 0:
    results = get_item_detail_by_city_name(address)
    if len(results) == 0:
        results = get_item_detail_by_zip_code(address)
        if len(results) == 0:
            return {'status': 'no results'}
thx @Kevin
How can I improve this piece of code?
 
Perhaps you could do something like:
funcs = [
    get_item_detail,
    get_item_detail_by_city_name,
    get_item_detail_by_zip_code
]

for f in funcs:
    results = f(address)
    if results:
        break
if not results:
    return {'status': 'no results'}
 
12:25 PM
looks much better, thanks
 
cbg all
 
That last if not results: could be replaced with else: but I'm wary of using for-else unless I know the reader is familiar with it
 
Almost 1mil questions tagged [python] ...
 
Oh, really? I noticed the number on my front page was close to a million, but I thought that was for python questions not counting questions with all my ignored tags. I assumed that Python-without-ignored-tags had already passed a million.
Like, I'm ignoring pandas, and I assume there are thousands and thousands of those
 
Oh I didn't know that was how it worked
Guess I'm just not that good with these things :(
 
12:29 PM
I don't know one way or the other.
There's no reason to favor my theory over yours :-)
 
@Kevin well you are Kevin and I'm not, that's a reason :D
 
The fact that both of our front pages have similar numbers, despite (most likely) having different ignored tags, suggests that the number counts ignored questions anyway
 
I have no ignored tags and for python -> 999,899
 
I have many ignored tags and I also see 999,899. So that settles that.
 
The 1 000 000th python question will be "why is my code not working : IndentationError: expected an indented block"
 
12:35 PM
I kind of want it to be a zero-effort do-my-homework Q, and everyone is so excited about the milestone that we go ahead and answer it anyway. You want the needful? You're about to drown in needfuls buddy
 
@paul Another option is to use or short-circuiting.
return (get_item_detail(address) or
get_item_detail_by_city_name(address) or
get_item_detail_by_zip_code(address) or
{'status': 'no results'})
 
Ooh, nice. Added bonus: not using a dispatch list means that the function calls can have different arguments.
foo(a) or bar(b,c) or baz(d,e,f) or qux(g,h,i,j) or "oops not found" is not easily replicated with a loop
 
thanks guys!
 
@Kevin Thanks! I often use that trick. Some may dislike the multiline statement, but I think it's readable enough, although I guess the extra lines could do with an extra level of indentation. But I'm on my phone, so it's a bit painful to post multiline code as it is. :)
I'm betting that the millionth question is either Pandas or Django. Or possibly a machine learning question.
 
My fingers are crossed for a question involving only the standard libs. Fun for the whole family.
 
12:59 PM
Good day :)
 
DSM
Holiday cabbage for all.
Unfortunately it's way too hot plus it's supposed to rain. :-/
 
@DSM where do you spend your holiday?
 
DSM
No, today is the holiday. I haven't even gotten out of bed yet.
 
oh, I got it
 
DSM
But I'm not going anyplace exciting. Most of today is going to be spent indoors where it's air conditioned..
 
1:09 PM
The staycation has many attractive points, such as "zero travel time" and "you already know how to work the shower and thermostat"
 
DSM
@Kevin: unfortunately‌​..
 
How does one work the thermostat that does not work? What is the sound of one hand clapping? Truly, these are mysteries.
user image
3
 
Mindblow -> one hand clapping is possible
 
lol
 
Why do zen masters* ask "what is the sound of one hand clapping?" as if it is a great mystery, when it's entirely possible with a reasonable amount of dexterity? Truly, it is a mystery.
(* or rather, stereotypes of zen masters as depicted in popular culture)
 
1:17 PM
@davidism: thanks for that edit.
 
And why do I never have heard this question before?
Well, to answer your question, it makes us come with more and more question over time, maybe that's the trick
 
Does this mean you'll bring me to the grocery store?
Christmas time
 
Apparently my footnote was unnecessary because it's an actual real koan and not, as I previously assumed, something made up in the 1900s by American screenplay writers as a way of evoking a "Far East" aesthetic without actually having to do any research
 
Hm, "killing the buddha" two lines below
One day I'll need to cultivate myself about buddism. I don't know anything more than what I guess is the common misconception. Thanks.
 
1:30 PM
@Kevin I tried a few koans but they are not easy
tough, would I say
 
Presumably koans that are easily solvable don't survive long enough to get put on a Wikipedia page. Zen masters will only keep using ones that keep everyone else occupied long enough for them to slip unnoticed down to the pub for a quick round
 
@Kevin +1 the words of a zen master
 
DSM
To avoid a lot of arguments about the "real" millionth question, are we just going to accept "the first new question at the top of the tag list when the tag counter shows 1M"?
 
That's the criteria I was going to use, yeah
 
1:47 PM
cbg
 
@DSM Sounds good to me. Of course, if we included Python questions that have a version-specific tag but not the generic one, we passed the million mark ages ago. And I guess there are plenty of Python questions that don't have any Python tag, just a framework tag.
 
What would be the debate ?
 
DSM
@PM2Ring: yeah, there are ~10k which are tagged pandas but not python (because they have python-2.7 or whatever or because they have none), and that's just one..
 
Ok, let's account for the 10k pandas-not-python questions that should count but aren't, and let's also account for the 10k "what programming language should I use to do X?" questions that shouldn't count but are ;-)
Hmm, stackoverflow.com/q/51708268/953482 was interesting enough to make me try to install Selenium, but I guess I did it wrong since the code snippet in Selenium's "getting started" documentation crashes on my machine with "Unable to find a matching set of capabilities". Oh well.
If anyone already has Selenium installed, that question might be low-hanging fruit, if you can replicate the problem
The object returned by Browser() should support the full keyword, if github.com/cobrateam/splinter/blob/master/splinter/driver/… is to be believed.
 
2:03 PM
@MartijnPieters No problem. I feel like I'm changing every other answer nowadays.
 
2:28 PM
I wonder how many (if any) users have a question already written, and are just waiting for the counter to hit 999,999 before they submit it. I predict a flurry of activity will occur.
 
DSM
Ten to go! (I have a script pulling the list. Nothing's getting past me!)
 
If so, this increases the chance that the question will actually be good, since it won't be fired from the hip
 
I bet the millionth' will be closed as off topic or primarly opinion based.
(I changed my mind)
 
DSM
If I had to bet, I'd bet that it should be closed as a dupe, mostly because most things should be..
 
Data analysis challenge: find all tags that already have a million questions, and determine which percentage of them have a closed millionth question.
 
2:32 PM
Was my first bet with "indentationerror" but Kevin made me change my mind if some are actually waiting the 999 999 counter to post.
 
DSM
That would be pretty lame. It's kind of fun to watch it, but no fun to rig it.
(whew) We narrowly missed it being a question about type hinting. :sweat:
 
To confuse matters, I was looking a 999,995 and a new question rolled in but I didn't see the counter change
 
yes it changed 10 sec after dunno why
 
It's the second one on my list, while the counter reads 1,000,001. So... I guess so
 
DSM
Let me have a look at my saved output..
 
2:38 PM
This looks like the millionth on my phone:
0
Q: Find all lowercase words in a sentence

FrankI have to to find all lowercase words in a sentence using Python. I've thought about using regular expression as follows: import re re.findall(r'\b[^A-Z()\s\d]+\b', 'A word, TWO words') It works except for the case in which I have, for instance, Aword. How can I solve it? In general, the rege...

 
Yep.
 
DSM
My code agrees.
 
blah!
 
Next time
 
2,000,000 is no fun! Would have to be 1,000,000,000
 
2:46 PM
Well
2,000,000 would be in 10 years if the question number progression is linear
 
1,048,576 is the real next milestone
 
So it's still something
 
DSM
If SO is still around for 1 B questions I'll be very surprised. If Python is still being used I think I'll be a little disappointed in the development of programming languages.
 
where does coding go from here?
 
"Do What I Mean" programming, where the concept of a "programming language" as distinct from regular conversational language, ceases to exist
 
2:49 PM
We already train hard for this kind of programming
 
Alexa, make Madden 2050. It should have twice as many polygons as the last one.
 
Lots and lots of developpers talk to their computer when the code doesn't do what they expected
 
Well back to my regularly scheduled programming set_cbg('opacity', 0.5)
 
DSM
I can see growth in declarative constraint-based programming. Some of what I do requires me to think hard about equations, but some of it is pretty rote. A framework which basically supported automatic fuzzing/hypothesis-style testing, which automatically brought up corner cases, would help for a lot of that.
@piRSquared: cheers, piRS!
 
I wouldn't be surprised to see a gradual decline in the release of truly novel languages, and an increasing tendency of existing languages to borrow features from one another until they're largely interchangeable. Maybe not a combining into a single collective, but into a limited number of siloes: C-like, Java-like, Lisp-like.
Compare to the situation today where it's more or less understood what someone means when they say they want to program in "assembly" even though technically there are many different varieties of assembly
The "x86" is implied
 
2:58 PM
I'm tempted to write an answer for the millionth question that uses translate to delete non-lower chars... I wonder how fast it'd be compared to Ajax's regex...
 
Same, except with str.replace and functools.reduce iterating over all ANSI characters
 
DSM
Wouldn't you make things contiguous that shouldn't be?
 
cabbage
 
@DSM True. So I'll translate to space and then do a .split
Guess I better turn on my computer. ;)
 
Hmm, does the string module not have an "all ascii characters" attribute? I thought there was one.
I guess I can do without it, but then I may as well not even use reduce... Where's the fun in that?
 
3:06 PM
Are you looking for string.printable?
 
result = "".join(c if c.isalpha() and c.islower() else " " for c in s).split()
Yawn
@user3483203 The thing I'm looking for would have a len of 256, so printable falls a bit short.
 
3:19 PM
@Kevin You can do bytes(range(256))
To get all ASCII you can do bytes(range(128)).decode(), or bytes(range(128)).decode('ASCII')
 
DSM
Maybe I'm missing the fun part we're seeking, but wouldn't it be easier just to check the ord if this is what we were after?
 
Nice. And bytes(range(256)).decode("ANSI") gets me the 256-length string I originally wanted (but probably don't need, since the input the OP is operating on almost certainly doesn't use the back half)
"no accents" means I don't need any of "ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖ×ØÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿ"
@DSM Pretty much.
Pursuing weird approaches long past the point where it was proven to be suboptimal is a hobby of mine
 
wim
>>> class MyType(types.ModuleType):
...     def __getattr__(self, name):
...         if name == 'spam':
...             return 123
...         raise AttributeError
...
...     def __getitem__(self, name):
...         if name == 'spam':
...             return 456
...         raise KeyError
...
>>> mymodule = MyType('mymodule')
>>> mymodule.spam
123
>>> mymodule['spam']
456
>>> eval('spam', {'__builtins__': mymodule})
@Kevin guess the output
I was curious after seeing your math / sin thing
 
My guess is "456" but I'm bracing myself to be surprised
Ok, I ran it, and I'm more surprised than I braced myself for
 
wim
yeah I got no idea what going on here
even debug prints in __getattribute__ not telling anything
 
3:36 PM
There is dark magic afoot
 
cbg
 
I don't think there's anything in the name resolution code that would imply this behavior, so my money's on "the f_builtins attribute doesn't point directly to the mymodule object. Instead, it is some kind of proxy that invisibly handles getitem calls in an atypical fashion"
i.e. it doesn't just delegate straight to __getitem__
 
rb folks
 
does anybody know how websites like repl.it use to run code (e.g. python) in browser
the code to run can be sent via HTTP , but is there any standard to run untrusted code in an isolated environment ?
 
3:52 PM
@harveyslash Do they use a transpiler like this github.com/QQuick/Transcrypt and just run it client side?
 
I suspect virtual machines are involved
 
I would hope they're spinning up containers, similar to how test services like Travis work.
 
so something like docker ?
 
Yeah some sort of VM seems likely
 
There is no way to safely run untrusted code without controlling the environment around it, which is outside of Python's scope.
 
3:54 PM
Fairly certain REPLIT uses docker: repl.it/repls/SquigglyConfusedNaturaldocs
 
for each new url they spin up a new docker container ?
@user3483203 that was pretty cool, thanks !
 
I'm vaguely troubled by the fact that the code running in the sandbox can tell that it's inside a sandbox
Yet I can't come up with an argument for "a virtual machine should try to trick its inhabitants into thinking they're operating within a perfectly normal environment" that isn't isomorphic to security by obscurity
 
i have a series of 8 bit numbers in a python program, where i want to output each number to 8 pins of a raspberry pi if an input pin is high (clock of an FPGA). reading, it doesn't seem there's any way to "wait until [condition]" in python, but is there a feature i'm missing?
 
Not natively, although plenty of libraries that communicate with an outside resource have some kind of "block until whatever" capability
 
Maybe there's some way of either using a callback, or if this is embedded an ISR to trigger it
 
wim
4:05 PM
@Kevin Dolores? Is that you?
 
@Kevin hmm...might RPi.GPIO?
(library that handles raspberry pi pins in python)
 
There's always while not thing_you_want: time.sleep(some_amount) but that kind of busy-waiting is typically not the best approach
Especially since you might miss the event if it happens faster than some_amount
 
@Kevin the clock on the FPGA is very quick - 50 megahertz or so, I think, and it can go faster. thus i want this program to be a speedy as possible because it's effectively setting up the input for the FPGA to run.
 
Something something event loop
 
@heather Let's see. How about GPIO.wait_for_edge?
 
4:10 PM
@heather can you use an interrupt to trigger what you need?
 
sourceforge.net/p/raspberry-gpio-python/wiki/Inputs discusses a number of ways to look at inputs, and their pros/cons
 
@DSM Like this?
"".join([c if 97 <= ord(c) <= 122 else " " for c in s]).split()
 
@Kevin ooh, that might be perfect
 
Does that block though?
 
Yes, if you don't provide a timeout parameter
Looks like you use event_detected() if you want something really asynchronous
 
4:15 PM
I just wonder if there's a way to do this with an interrupt service routine so that we don't block
 
Or, maybe add_event_callback()? Heck, I don't know
 
Does anyone else have suggestions for the "Find all lowercase" challenge? My timeit results look like this:
find_lower_pm2r      : 0.060880, 0.061017, 0.061169
find_lower_ajax      : 0.163527, 0.163972, 0.170531
find_lower_dsm       : 0.602145, 0.653777, 0.657454
find_lower_kevin     : 0.649604, 0.685652, 0.819500
 
^ link to challenge and submissions?
 
I thought about "".join(c if pre_prepared_truth_table[ord(c)] else " " for c in s]).split() but I don't know if one list lookup is faster than two int comparisons
Not even taking into account the time needed to create the table
 
nvm, up to speed. still on question with my failed attempt. scraping ego off of floor in attempt to reengage...
 
4:23 PM
Darn you, markup engine
 
@Kevin I just realised you don't need the isalpha check, and removing it gives your code a nice speedup.
 
Nice. When I was writing it, I thought "actually, what does islower() return for non-alpha characters?" but I never bothered to check
 
In [409]: '1'.islower()
Out[409]: False
I wonder how set performance compares
lwr = set(string.ascii_lowercase)
''.join([i if i in lwr else ' ' for i in s]).split()
 
The government has been hiding lowercase 1 from us for years because they fear its power
9
I'd expect set membership testing to be slower than 97 <= ord(c) <= 122, but I'm not sure where I'd place it among the other results
 
I found it close to that if you don't include setup costs, I'll look at the other ones
 
4:41 PM
cabbage
 
cbg
@Kevin XD
 
@user3483203 Pretty good, actually.
 
@PM2Ring Did you end up writing the translate solution?
 
Trying to decide whether we can reasonably expect set(string.ascii_lowercase) to have individual buckets for each individual character. Are single-character strings interned even if they don't appear in a literal in your program?
I guess it doesn't matter. I assumed that the hashes of consecutive characters would also be consecutive, but that's not the case. I guess only small integers do that.
 
4:55 PM
Is it an implementation detail or are the hashes of all consecutive integers also consecutive in Python?
 
I think it's an implementation detail.
 
@user3483203 Yes. And I did 2 versions of DSM's. Actually, I did 3 versions, but one I modified so much that I decided to "adopt" it. :)
def find_lower_pm2r_byte(s):
    return bytes(b if 97 <= b <= 122 else 32 for b in s.encode()).decode().split()
Here's my main solution:
# Create a translation table that maps all ASCII chars
# except lowercase letters to space
bad = bytes(set(range(128)) - set(ascii_lowercase.encode()))
table = dict.fromkeys(bad, ' ')
def find_lower_pm2r(s, table=table):
    return s.translate(table).split()
 
docs.python.org/3/reference/datamodel.html#object.__hash__ indicates that hashes of strings are intentionally salted, and by implication you might assume that the hashes of ints are not salted, but it doesn't say that explicitly
 
Here are some typical timeit results for strings containing random "words" of 8 chars, with len words per string.
 
Incidentally, that section says "Changing hash values affects the iteration order of dicts, sets and other mappings. Python has never made guarantees about this ordering (and it typically varies between 32-bit and 64-bit builds)". I wonder if that wording ought to be changed now that dicts are ordered.
 
5:01 PM
loops 512 len 64 True
find_lower_pm2r      : 0.027083, 0.027194, 0.027215
find_lower_ajax      : 0.069744, 0.069850, 0.086880
find_lower_3483203   : 0.127333, 0.127370, 0.128956
find_lower_kevin     : 0.213148, 0.214116, 0.215894
find_lower_pm2r_byte : 0.222670, 0.223349, 0.224171
find_lower_dsm_byte  : 0.247014, 0.248227, 0.248874
find_lower_dsm_char  : 0.309891, 0.311903, 0.311922
Does anyone have any objections if I post my code as an answer? Of course I'm happy to accept any amendments / improvements after I post the code.
 
No I think they are good. I might most a community wiki with all the timings and the graph, unless you want it as part of your answer
 
Oops. I just noticed that DSM isn't here to object. Oh well. I'll put links to your profiles in my answer.
 
DSM
Hey, I asked one offhand question. Don't make me responsible for the two slowest solutions. ;-)
 
@user3483203 There's no graph, just raw timeit output, for len ranging from 32 to 1024.
 
I release my portion of this conversation into the public domain.
 
5:07 PM
@DSM Ok. How about you have the fastest variation on that theme, the one currently named find_lower_pm2r_byte? I'm happy to keep your name off it, if you prefer.
 
DSM
Since I haven't actually written a line of code, fast or otherwise, I think that's only reasonable. :-P ;-)
 
@Kevin Does that mean you prefer if I don't link your profile?
@DSM Rightio.
@user3483203 Do you want to post your own answer separately before I post the timeit answer?
 
Please cite my function as find_lower_kevin_first_of_his_name_lord_of_stars_heir_apparent_of_house_pyhton_‌​and_protector_of_small_white_triangles
(but don't actually)
 
@PM2Ring No, it's fine, you can just add it to yours
 
DSM
It's so hot here that my root beer became warm within minutes. Time to flee the house, I guess.
 
5:40 PM
Ok, I've posted my answer.
Thanks guys. I appreciate the votes, but I didn't do this to score points. I did it to show that regex isn't always the best way. And to have an answer on the millionth question. :)
 
def find_lower_pirs(s):
    word = []
    words = []
    for b in (s + ' ').encode():
        if 97 <= b <= 122:
            word.append(b)
        elif word:
            words.append(bytes(word).decode())
            word = []
    return words
which can be cythonized
 
@piRSquared I think cythonizing is cheating for this. :) And without cython, that version takes about twice as long as find_lower_pm2r_byte.
 
If you're not cheating, you're not trying... So I've heard. Twice as long as find_lower_pm2r_byte is still pretty fast (-: I was trying to get around the formation of the string and subsequent split. Oh well.
 
Vote please on this horrible pandas=numpy tag synonym stackoverflow.com/tags/pandas/synonyms thanks
 
that made me panic
 
5:52 PM
I wonder how ["".join(v) for k,v in itertools.groupby(s, str.islower) if k] ranks against the rest, since it doesn't use split.
 
^ doh, why didn't I think of groupby
 
DSM
@Kevin: I actually tried that.. slower than all the others in PM2R's test.
 
I thought that might be the case. str.split might have C-level juice that groupby can't use.
I was hoping I'd make up for it by being able to immediately discard bad characters, rather than replacing them with spaces or whatever, but I guess that's not enough
 
groupby is great, but it's built for comfort, not for speed.
 
Sometimes O(N) time and O(1) extra space just doesn't cut it
 
DSM
5:58 PM
♫ ain't got no diamonds ♫ ain't got no gold ♫
 
I wonder if it's worthwhile hitting the C libs via ctypes, or whether the conversion from Python types to C types and back would chew up any speed gains. Assuming of course that it can be done with C calls. stptok maybe?
 
DSM
6:11 PM
(For non-blues fans: "Built for Comfort" is a classic by Willie Dixon. Most famous version by Howlin' Wolf.)
 
Wow! My mental model of who/what @DSM is has been updated significantly.
 
@PM2Ring feel free to ignore if you don't like it, I added in a plotting section to your file: gist.github.com/user3483203/e37990716ac6b1b01c3de461baee1004
 
i have a list of numbers that goes [-1, -1, 1, 1, -1, -1, 1, 1, ....]. my function that's converting these to two's complement is giving me [1, 1, 1, 1, 1, ...]. this is incorrect, right?
there needs to be a way to distinguish -1 and 1, and this isn't, so i assume it's wrong.
 
Maybe it is or isnt ... Is it a value sign/unsigned thing so it does distinguish it but then it gets dumped into a variable that just drops the signs?
 
The internet tells me that the two's complement of -1 is 11111111, so yeah your output doesn't look right
 
6:22 PM
@user3483203 Thanks. I'll link to your code, and paste the graph in.
 
okay. this'll be interesting =)
 
Hmm, but this other site says that the two's complement of -1 is 0000 0001. So I don't know what to think.
I could probably solve this mystery by actually reading the text and not just looking at charts and pressing buttons
 
@DSM thanks ;)
 
6:41 PM
@heather If you want to convert signed numbers to two's complement you need to choose a bitlength for the result. In C and similar languages that's easy to do because the language gives you a bunch of different sized integers. In Python, it's slightly tricky because our integers grow as big as they need to be. So how big do you want these numbers to be?
 
8 bits
 
@heather Ok. Give me a minute or two to find my two's complement code. :)
@heather Check out this answer for some more info: stackoverflow.com/a/40365873/4014959 But here's code that does 8 bit two's complement:
for n in range(-128, 128):
    print('{:+4}: {:08b}'.format(n, n & 0xff))
 
recbg
@heather did you try printing the two's complement representation?
 
@Code-Apprentice that is the two's complement representation - each item in the second list is the two's complement of the item in the first list (or it's supposed to be, anyway)
@PM2Ring i'm a little confused here on what the input is
 
6:57 PM
@heather oic...you aren't printing any leading zeros. Note that it is common practice to do so, to show how many bits you are using. So the two's complement of 1 can be printed as 00000001. The two's complement of -1 should be 11111111.
You can even put a space between each set of four bits to help make it easier to read.
 
@Code-Apprentice oh that makes sense
 
@heather n is the input, n & 0xff is the output.
So my code prints the two's complement representation of all numbers from -128 to 127.
 
Hmm, does struct.unpack("B", struct.pack("b", x))[0] give the twos complement of x? It worked for the handful of test cases I tried but I'm not wholly confident in it.
 
so what i really need to do is keep my function but switch from using bin() to format().
though @PM2Ring's code looks a lot cleaner than mine.
 
This print command might be helpful: print('{0:+4}: {1:08b} {1}'.format(n, n & 0xff)). Now we see the output in binary and decimal.
Positive numbers stay the same, but negative numbers get 256 added to them.
@heather Yeah, don't use bin. That's old-school. :) And you have to slice off the stuff you don't want. The format functions are faster, and give you control over the length. And of course you can also do it with f-strings.
Eg, f'{n:+4}: {n & 0xff:08b}'. Or if you just want the bitstring, f'{n & 0xff:08b}'
You could write 0xff as 255, but I think it's a good idea to use hex when you're twiddling bits.
@Kevin Yes, that works. But it takes two function calls and a tuple indexing, so it's going to be a lot slower than an f-string.
 
7:10 PM
Have we determined what we need two's complement for, to begin with? If the use-case is "I need to serialize this smallish signed integer into a bytes of length one, and then turn it back later", then I'd promote my struct idea from "fun thought experiment" to "serious recommendation"
Although if we're doing round-trip serialization you're probably not going to pack with mode "b" and unpack with mode "B"
 
@PM2Ring Is that the technical term? "twiddling"?
 
@Code-Apprentice Definitely!
Bit Twiddling Hacks from cs.stanford.edu.
From https://en.wikipedia.org/wiki/Bit_manipulation#Terminology Bit twiddling and bit bashing are often used interchangeably with bit manipulation, but sometimes exclusively refer to clever or non-obvious ways or uses of bit manipulation, or tedious or challenging low-level device control data manipulation tasks.

The term bit twiddling dates from early computing hardware, where computer operators would make adjustments by tweaking or twiddling computer controls. As computer programming languages evolved, programmers adopted the term to mean any handling of data that involved bit-level comp
@Kevin Good point. We may be in XY land. ;)
The struct pack & unpack functions are great when you have a lot of data to work with. But yeah, we need to determine whether heather really needs strings of bits, or actual integers.
FWIW, I've been doing a lot of 32 bit unsigned arithmetic lately, experimenting with various hashing functions, so my code's been littered with & 0xffffffff
 
Am I late to the 1 million questions under the python tag party?
 
@TemporalWolf No. :)
 
tsk tsk, you should eliminate that magic value by replacing it with a F8 constant :-P
 
7:26 PM
@Kevin When you're doing that sort of thing with thousands of iterations in nested loops, you don't mind magic numbers literals if they give a slight speed improvement.
 
Looks like it passed 1m about 4 hours ago
 
@TemporalWolf It did. Here's the question: stackoverflow.com/questions/51710087/…
 
tsk tsk, you should write your own variant of Python that supports compile-time macros so you can write F8 while still enjoying the benefits of embedded int literals
 
TBH, I do occasionally do stuff like mask = 0xffffffff and
def u32(n):
    ''' Constrain int n to unsigned 32 bit '''
    return n & 0xffffffff
 
Alternate solution: implement a static code analyzer that determines that the value of F8 will never change, and optimizes the byte code accordingly
And I don't want to hear excuses involving the Halting Problem
 
7:33 PM
But these hash functions are full of inscrutable magic numbers. Simple bitmasks like F8 are the familiar friends in a sea of mystery. Eg, here's the final mixing phase from the 32 bit version of the popular Murmur3 algorithm:
def murmur3_final32(n):
    n ^= n >> 16
    n = (n * 0x85ebca6b) & 0xffffffff
    n ^= n >> 13
    n = (n * 0xc2b2ae35) & 0xffffffff
    n ^= n >> 16
    return n
 
Reminiscent of Quake's "Fast inverse square root" method, which contains the line: i = 0x5f3759df - ( i >> 1 ); // what the f---?
 
Or another example, the xxhash algorithm cut down to hash a 32 bit number:
def xxhash_num(n, seed=0):
    n = (374761397 + seed + n * 3266489917) & 0xffffffff
    n = ((n << 17 | n >> 15) * 668265263) & 0xffffffff
    n ^= n >> 15
    n = (n * 2246822519) & 0xffffffff
    n ^= n >> 13
    n = (n * 3266489917) & 0xffffffff
    return n ^ (n >> 16)
@Kevin Well, that is a weird magic number. It depends on quirks of floating-point representation. And IIRC, the algorithm starts to fail around 40k or so. I was just re-reading about it on SO a few days ago.
 
I suspect code of this nature has a very high sleepless-nights-to-size ratio
 
@Kevin :) Sort of. It involves a lot of brute searching for big prime numbers that are good at mixing bits up.
 
Ah, so not so much "crying in front of five full whiteboards" and more like swordfights while waiting for the mainframe to finish churning
Or, if it was in an academic context, the compromise position of "crying over your half-finished research grant applications, which you must fill out whenever you're not actively coding"
 
7:49 PM
Yep. But there's also an element of coming with likely families of primes that may behave as desired. Eg, primes that have lots of 101010... alternation in them seem to work well. But there's no simple way (as far as I know) to predict which good primes will work well in combination with each other.
Fortunately, we've got a way of testing these things: the avalanche effect
 
Meanwhile, in python, hash(1) is just 1
Ah, it's just as you said:
Jul 27 at 8:06, by PM 2Ring
The Python hash function is ok for hashing long strings, but it doesn't work so well when you want to randomize small integers. Of course, if you just pass it a small integer it just returns that integer, but you can pass it a tuple to get a random-looking result. However, it has terrible avalanching.
 
@Kevin Yeah. Not much good when you actually need a random hash from your integers. You can do stuff like hash((n,)), or hash((n, n * 2654435761)), but the avalanching is pretty ordinary.
 
Lesson: don't assume all hash functions are cryptographic hash functions
 
Python's hash isn't much better than one or two iterations of a simple linear congruential RNG. It's designed to work with Python's hash tables, and to be fast.
 
A sensible priority, as long as cryptography researchers make up less than 99.999% of Python's user base.
 
8:10 PM
Well, there are non-cryptographic uses for hashes that need better avalanching than what hash provides, eg Bloom filters. And while Python's dict & set are ok with contiguous integer keys they don't really perform well with large numbers of contiguous integers because of the poor avalanching. I've tweaked my avalanching colour scheme slightly, to give a little more difference of colour in the middle range. It now looks like this:
And this is the avalanche diagram of hash((n,)) & 0xffffffff
As I said the other day "The value grid[y][x] is a measure of the probability that flipping bit y in the input bitstring causes bit x to be flipped in the output bitstring." The LSB of the input bitstring is at the top, and the LSB of the output is at the left. I do it like that to be consistent with usual matrix notation, i.e. lambda x: x would give the identity matrix, a red diagonal from top left to bottom right, on a sea of blue.
 
I have a project with a server (Python) and a front-end, which I recently divided into two directories. I've put all Python related code in the server directory but now when Travis runs it looks for requirements.txt in the root, where it of course doesn't find it. Should requirements.txt live in the root, even though I have this full-stack application, or should I try to make Travis look inside of server?
 
Travis doesn't look for requirements.txt at all, that's something your configuration is doing. Fix your configuration.
Hmm, maybe it does? I've just never used the default. Specify your own install command in the config that does pip install -r path/to/requirements.txt.
 
Thanks, what I was looking for was if Python has some weird standard to have the requirements.txt in the root no matter what. I thought that was weird so I just had to ask, and now I know :)
 
The requirements.txt file isn't even a standard, let alone its location. It's just a common thing that people use with pip when they don't want to use setup.py.
 
8:25 PM
And here's a fairly simple multiply & shift hash in comparison.
def simple_hash(n):
    n = (42331 * n) & 0xffffffff
    return n ^ n >> 16
That's still not fantastic, but it's a big improvement in many ways over hash.
Anyway, I better stop cluttering up the room with diagrams. :)
 
is that your new identicon?
 
8:40 PM
Ah, no. :) It's not that hard to make a hash function that gives a nice mostly green diagram. The trick is to do it in the smallest number of operations for maximum speed.
Strictly speaking, these functions that only operate on a single 32 bit number are called mixing functions, but they're an important component of a full hash function that takes any number of bytes.
 
8:52 PM
@Kevin the python program is to set up the input for an FPGA program which performs the trapezoidal integration method. i want to be able to handle signed numbers and i've heard two's complement is the best way to do that. also, i think verilog automatically handles signed numbers as two's complement.
 
@heather What are you integrating? How come you only need inputs that are integers in range(-128, 128)?
 
@PM2Ring well, i'm testing the fpga, so right now i'm just integrating a square wave.
the size is limited only by the number of I/O pins on the FPGA, and I could go a little bigger (maybe up to 10 bit numbers?), but for testing purposes I'm sticking with 8 bit numbers.
because i'm not delivering the data serially, so i need 8 pins for input of one thing, 8 pins for input of another thing, 8 pins for output, 8 pins for another input...
and i'm not delivering the data serially because it's faster.
 
Oh, ok. I guess the FPGA has pretty limited precision for arithmetic. And that you have to use integer arithmetic.
Still, trapezoidal is pretty crude. Simpson's rule is only slightly more complicated but almost always gives better results.
Of course, it won't make a difference on a square wave, but I assume your actual data will be a little more complicated. ;)
 
9:12 PM
the time step will also be very small, and trapezoidal is fairly accurate over small time steps.
 
and here I thought we were bit twiddling for twiddling's sake. I missed the beginning of the conversation that shows what this is being used for.
or is this a continuation of a conversation from a previous day?
 
@Code-Apprentice well this is the first time i've mentioned what it's being used for, i think
 
okay...no wonder I was unaware of the FPGA part
 
i think i mentioned the FPGA at one point, but not the full context.
 
5 hours ago, by heather
i have a series of 8 bit numbers in a python program, where i want to output each number to 8 pins of a raspberry pi if an input pin is high (clock of an FPGA). reading, it doesn't seem there's any way to "wait until [condition]" in python, but is there a feature i'm missing?
 
01:00 - 22:0022:00 - 00:00

« first day (2851 days earlier)      last day (2096 days later) »