« first day (3530 days earlier)      last day (1401 days later) » 
01:00 - 19:0019:00 - 00:00

user13682510
1:48 AM
@AndrasDeak I see. Noted!
 
user13682510
@MisterMiyagi Me too.
 
user13682510
@MisterMiyagi You said it!
 
user13682510
@ExoticBirdsMerchant G'night.
 
4:08 AM
I've got a popup tk.Frame widget that displays an image with a save as button, which delegates to a file save as dialogue...any way I can remove/disable the x in the corner of the original Frame widget? My app freezes/hangs when it is pressed, waiting (I assume) for input that isn't coming.
 
5:02 AM
stackoverflow.com/questions/62369661/… essentially a duplicate of multithreading/multiprocessing but OP does not seem to understand what they are asking
 
How would I easily get the inverse of: [{"name": "bob", "pets": ["dog", "cat"], "name": alice, "pets": ["dog", "fish]} so that I end up with [{"pets": "dog", name: ["bob", "alice"]}, {"pets": "cat", "name": ["bob"]}, {"pets": "fish", "name": ["alice"]}]
 
You can't have a dict with multiple keys of the same value - both "pets" and "name" showed up twice in the dict inside the first list.
 
ah sorry, let me fix it
[{"name": "bob", "pets": ["dog", "cat"]}, {"name": alice, "pets": ["dog", "fish]}]
 
Still failing syntax check when pasting it into the interactive interpreter.
 
apologies: [{"name": "bob", "pets": ["dog", "cat"]}, {"name": "alice", "pets": ["dog", "fish"]}]
 
5:17 AM
all I am seeing is that you are flattening the dicts into individual elements in the output, I am not sure where the inversing comes from.
>>> value = [{"name": "bob", "pets": ["dog", "cat"]}, {"name": "alice", "pets": ["dog", "fish"]}]
>>> [{'name': [i['name']], 'pets': pet} for i in value for pet in i['pets']]
[{'name': ['bob'], 'pets': 'dog'}, {'name': ['bob'], 'pets': 'cat'}, {'name': ['alice'], 'pets': 'dog'}, {'name': ['alice'], 'pets': 'fish'}]
 
pets: dog should have bob and alice
are you sure about that?
I'm trying to inverse the 1-to-many relationship
 
Sorry, it's really hard to tell when your initial answers don't actually syntax check
 
5:46 AM
anyway, trying this again, what I did was essentially flattening everything, but you can use defaultdict with a list value to group everything back up
>>> from collections import defaultdict
>>> value = [{"name": "bob", "pets": ["dog", "cat"]}, {"name": "alice", "pets": ["dog", "fish"]}]
>>> flattened = [(pet, i['name']) for i in value for pet in i['pets']]>>> result = defaultdict(list)
>>> for pet, name in flattened:
...     result[pet].append(name)
...
>>> print(result)
defaultdict(<class 'list'>, {'dog': ['bob', 'alice'], 'cat': ['bob'], 'fish': ['alice']})
to bring it back to the individualized mapping, just do another list comprehension
>>> [{'pet': pet, 'name': names} for pet, names in result.items()]
[{'pet': 'dog', 'name': ['bob', 'alice']}, {'pet': 'cat', 'name': ['bob']}, {'pet': 'fish', 'name': ['alice']}]
@jigglypuff also "inversing" is not the correct term - as there could be the case of multiple relationships (e.g. between name, pet, and fruit) and thus "grouping" would be a more accurate description of what you are trying to do
To be more clear, the following is more copy/paste friendly (this text box sometimes merges multiple lines together and I don't know why)
from collections import defaultdict
value = [{"name": "bob", "pets": ["dog", "cat"]}, {"name": "alice", "pets": ["dog", "fish"]}]
flattened = [(pet, i['name']) for i in value for pet in i['pets']]
pet_names = defaultdict(list)
for pet, name in flattened:
    pet_names[pet].append(name)
result = [{'pet': pet, 'name': names} for pet, names in pet_names.items()]
print(result)
 
 
2 hours later…
7:52 AM
@metatoaster great, thanks, I'll have a look. I came up with something but yours looks shorter
 
 
2 hours later…
9:48 AM
@toonarmycaptain How are you displaying that Frame? I assume it's in a Toplevel window. You could remove the Title bar of that window, there's some info about that here: stackoverflow.com/q/44969674/4014959 Alternatively, you can intercept window close events, see stackoverflow.com/q/111155/4014959
 
 
3 hours later…
12:20 PM
Guys is it allowed to paste my stackoverflow question link here?
 
only if it's older than 48 hours
 
Thank you. It isn't.
 
12:34 PM
@CDoc thanks. For details you can find the rules at sopython.com/chatroom
 
12:47 PM
Hello everyone, I was working on this Leetcode problem and wondered if my solution can be made more elegant / Pythonic. Here it is:
from collections import deque
class Solution:
    def findCheapestPrice(self, n: int, flights: List[List[int]], src: int, dst: int, K: int) -> int:
        graph = [[] for _ in range(n)]
        for s, d, price in flights:
            graph[s].append((d, price))
        seen = [float('inf')] * n
        seen[src] = 0
        q = deque([(src, -1, 0)])
        while q:
            node, stops, node_cost = q.popleft()
            if node == dst or stops == K:
                continue
            for nei, price in graph[node]:
 
Cbg
 
1:03 PM
@PM2Ring Yeah I create a root, instantiate a tk.frame and run it's mainloop, so I think that's toplevel? It's the only thing that appears, a convenience on top of a CLI (currently, it'll be in a browser at some point). I'll look at those links when I work on it later, thankyou :)
 
@SamChats That looks pretty good, I only have 2 minor suggestions: 1) Don't do too many things in a single line (i.e. break the def findCheapestPrice, if (nei_cost := ..., and return ... lines) and 2) No single-letter variable names (n and k might be alright, if they're also referred to as such in the task, but use a lower case k)
oh, and the top half of the code would benefit from some whitespace/empty lines
 
And isn't that asspression gratuitous?
 
A comment or two is always good, especially when presenting code to others. I would second the suggestion to drop the := usage here. It buries the assignment inside the if - general advice in this room would be to avoid := when an explicit assignment is an easy replacement.
:= is the new lambda
 
(f:=(lambda: print('what do you mean?')))()
(Sorry, can't test right now)
 
Am I the only that got completely trashed by the asspression setting a value for use when the if does not trigger?
 
1:13 PM
@AndrasDeak I can, but refuse to taint my interpreter with a walrus
 
Partially disagree with "avoid := when an explicit assignment is an easy replacement". 90% of the asspressions I use are inside conditionals. That said, I usually only use them when I want to store the value of the entire condition, e.g. if m := re.match(a,b):
 
@MisterMiyagi trashed?
 
If I need to add parentheses to make sure the walrus operator has the correct precedence, I think very hard about whether it's worth using
 
I mean I did notice that. No idea how confusing that is in context.
 
@AndrasDeak Didn't figure out the control flow until I reread it, oh, the fourth time. My head parsed that as nei_cost being available only inside the if body.
 
1:15 PM
@MisterMiyagi do you need a scoping tutorial?
 
@Kevin If that statement is part of an if/elif/elif/... chain of tests, then an explicit assignment is not an easy replacement. That is one of the appropriate usages.
 
You'd be surprised but ifs don't have their own scope :P
 
@AndrasDeak a hot chocolate and the red-hot pokers, please :P
@Kevin I just avoid regular expressions. Both problems solved.
 
I know enough languages where ifs do have their own scope that my initial reaction is persuaded in that direction even when looking at Python
 
@AndrasDeak I vaguely remember reading about that recently... :P
 
1:18 PM
@MisterMiyagi Extra hot mrlovenstein.com/comic/758
 
Amended: If that statement is part of an if/elif/elif/... chain of tests where the assigned value is used in the body of the condition (such as when testing against a series of regular expressions), then an explicit assignment is not an easy replacement. That is one of the appropriate usages.
In the posted code, the assigned value is not used in the body of the 'if' block, but is used later. So double-demerits for not really needing the := since the assigned value isn't needed in the body of the 'if' block, plus obscuring the assignment of the value that is used later when the if condition evaluates to False.
 
if cond: continue is a bit of an antipattern regardless, and could be replaced with its negation:
if (nei_cost := node_cost+price) < seen[nei]:
    seen[nei] = nei_cost
    q.append((nei, stops+1, nei_cost))
This at least quells concerns about nei_cost being used outside of its "intuitive" scope
 
Really? I use if cond: continue to avoid deeper code nesting.
 
same
 
Me too, sometimes, but I'm not feeling it here
 
1:34 PM
@AndrasDeak I have been trained to look for hover texts... sadness...
 
@Kevin Still feels gratuitous (that word popped into my head too when I first saw it), since it is easily made into its own separate assignment with no other change in the code structure. := here saves one line of code, but buries the variable assignment inside a parenthesized if condition.
 
I think we both agree that it's important to find a balance between brevity and readability, but we fall on slightly different parts of that gradient
 
I see zero value in not pre-assigning and using if nei_cost < seen[nei]
And not just because it's an asspression :P
 
I won't argue that there's substantial value in doing it one way over the other. I knew from the beginning we were bikeshedding :^)
 
Bikeshedding is pointless. There's nothing pointless about purging asspressions from otherwise decent code :P
 
1:47 PM
Seems like confusion over byte strings that have characters that fall into ASCII ranges not showing up as \x## is more common than I thought, got another one of these stackoverflow.com/questions/62389324/…
 
We can't decide whether asspressions make code less decent and need to be purged until we agree on a color for this bikeshed. I think white, as it reflects sunlight which will keep the interior cooler. Anyone that proposes a color that won't show grime is simply lazy and trying to get out of washing the shed.
 
@metatoaster it's really a problem for people to grasp that what their terminal displays is just a representation of data, isn't it?
 
apparently it is
 
anyways, I also had a situation a few days back where seeing ASCII instead of just hex sequences was really distracting.
 
yeah, I am actually annoyed that the default repr doesn't just simply escape all to the \x sequence
 
1:51 PM
I'm somewhat 50/50 whether bytes-as-ASCII is a good idea or not.
 
I had a very hard time with the data/representation distinction the other month when I tried to answer "given a string of length 1, how do I determine whether it will be printed with a single glyph, or an escape sequence?"
 
there is __str__, that could have the current rendering
 
@metatoaster I can certainly understand that confusion
 
@Kevin can that even be answered without knowing, like, everything about the environment?
 
1:52 PM
__repr__ should escape to \x, I mean I do have quite a lot sympathy for the issue.
 
Conclusion: there's no way to find out from Python, because how characters are printed is dependent on the underlying C environment and/or the shell
 
@metatoaster so __str__ as hex+ASCII, and __repr__ as just hex? I like that
 
I don't believe __repr__ worked for the particular input I was testing on. I'll see if I can replicate the problem
 
yes, exactly that.
 
To be clear, it was a unicode string, not a bytes
 
1:56 PM
unicode has its share of funny issues too, most notably with whitespace characters
 
@Kevin I'm decently sure that there are situations in which Python cannot know everything about its viewing terminal. Remote sessions come to mind, especially cross platform.
 
the repr version will leave double-width spaces as \uXXXX encoded when repr
 
2:12 PM
@MisterMiyagi Always this too:
list(b'sldkfj')
[115, 108, 100, 107, 102, 106]
 
I can't replicate my original problem, which is that a character was printing itself as an actual \\x escape sequence. But here's a similar problem. In my shell, x = chr(65536), aka LINEAR B SYLLABLE B008 A is printed as two question marks in boxes: ��. len(x) is 1. len(str(x)) is 1. len(repr(x)) is 3. There's no apparent way to get the string's "width".
 
Could someone please advise how to properly read from two CSV files and to find the identical data that has the same unique ID values, for example? As a result, parse the output into the third CSV file. I'd appreciate if you can share the reference link
 
@Eugene_S have you read a python tutorial?
This is not a trivial task so looking for an existing solution might be too optimistic
 
@AndrasDeak Yes, I've managed to write into the file at the moment - github.com/eugenesheyko/csv_write/blob/master/csv_write.py
 
2:21 PM
Effectively it's the shell's responsibility to decide how many glyphs a character needs, and the process that's making the print calls doesn't get a say, or even any insight into which decision was made
 
@Kevin I wonder if you could steal a copy of the output tee style
 
@Kevin normalization itself means you cannot know the length of the output, since the viewer may decide to normalize or not.
 
@Eugene_S I'm pretty sure you don't have to skip over line 0 when using DictReader, since the DictReader has to read that line to get the dict keys to be created.
 
I think the best you can do is peek at the text cursor's position using winapi calls, before and after printing
 
tell me more about this winapi thing, mortal
 
2:25 PM
actually, with emojis this effectively becomes impossible
there is no meaninful glyph vs number of bytes vs length vs character count anymore
 
@Eugene_S It is not a very well-known package, but I wrote a pip-installable package for simple import and manipulation of CSV file data called littletable. Reading in 2 CSV's and then doing a "join" on a common field would be pretty simple stuff, with minimal overhead.
 
@MisterMiyagi I have no practical experience with this particular call, but I believe GetConsoleScreenBufferInfo returns a struct with a dwCursorPosition property. Naturally, you're on your own if you're not using Windows.
 
or not using the standard windows terminal, I would assume
 
Yeah.
 
Thanks @PaulMcG
 
2:37 PM
Third party library colorama uses GetConsoleScreenBufferInfo and accomplices in order to hijack the terminal into recognizing ANSI color codes. So I know that in principle this kind of terminal interaction is possible.
 
@PaulMcG neat
 
hi can someone here help me with my question that I posted a while back. I still havent been able to figure out.
 
import colorama
colorama.init()
x = chr(65536)
start = colorama.ansitowin32.winterm.get_position(colorama.win32.STDOUT)
print(x, end="")
end = colorama.ansitowin32.winterm.get_position(colorama.win32.STDOUT)
print(f"\nWidth: {end.X - start.X}")

#output:
#��
#width: 2
Hard mode: find the width without printing the character
Credit will be given for instantiating an invisible terminal and printing to that
 
2:52 PM
@Aran-Fey Thanks a lot. I cannot break the function signature as that's used by Leetcode's online judge, but I agree that breaking the if statement with walrus will help in improving readability!
 
@SamChats does leetcode allow having auxiliary methods/functions?
you could easily separate this into parts
e.g. building the graph, then finding the cheapest path
 
Even if the global namespace can contain exactly and only one function definition, you could still define functions inside that function
 
@SamChats I guess you might need to keep the uppercase K, but you don't have to write all function parameters on the same line. When you have too many, aligning them vertically is more readable
def findCheapestPrice(self,
                      n: int,
                      flights: List[List[int]],
                      ...  # and so on
 
@jaylas inviting people to random chatrooms is not nice. And the question in the linked room is 6 hours old. Please read our rules
 
sorry im new
 
3:07 PM
It's alright. You can learn.
 
3:30 PM
"width" of a character is actually meaningless - fonts can be made to render that to be equal width with every other character
so yes, in other words, the width of chr(65536) is highly dependent on how it is rendered
now on the otherhand, if what you are after is some formal definition, you will have to look at what was actually defined for that specific unicode codepoint
that isn't something built into Python IIRC
codepoints.net/U+10000 noted that codepoint has width defined as Neutral East Asian Width
that's the formal definition - how it gets rendered is highly dependent on the implementation, so in effect it is impossible to answer and thus platform specific
 
3:45 PM
I'm having a serious brain fart here. What is @blahblah called in Python, like before a function def.
decorator...
 
@Code-Apprentice our work here is done
 
4:27 PM
@toonarmycaptain Oh, ok. A Toplevel widget is a window. It's pretty similar to a root window. A Tkinter program can only have 1 root window, any additional windows must be Toplevels. The reason for that is that when you open a root window it also starts a Tcl interpreter that actually handles all the Tcl stuff. You don't want more than 1 Tcl interpreter running!
@toonarmycaptain Since your Frame is in the root window, then it's probably a bad idea to get rid of its Title bar. So use the 2nd option I mentioned and intercept the window's Close event instead.
 
Can someone explain to me what the following code is doing?
 
Hiding the X button feels like a bit of a bandaid solution to the problem of "my program hangs if the window closes"
 
bits = bin(bytes[0])[2:].zfill(8)[::-1] + bin(bytes[1])[2:].zfill(8)[::-1]
I know that bin converts an integer to a binary string prefixed with "0b" but I don't know what the parts 2:].zfill(8)[::-1] do?
 
@MyWrathAcademia bytes[0] gets the first element of bytes. bin converts it into a string containing the number's binary representation, e.g. 7 becomes "0b111". [2:] chops off the "0b". zfill pads the string with zeroes. [::-1] reverses the string.
 
this looks suspiciously like manual little-endian'ing.
 
4:41 PM
@Kevin thanks a lot.
The code I posted above converts two bytes to 16-bit binary representation.
 
In my experience, bin is almost never the right tool for converting values. Getting a zero padded binary-looking string could be done more concisely with string formatting, for example.
>>> foobar = 7
>>> f"{foobar:08b}"
'00000111'
 
@Kevin Agreed. OTOH, it's not unusual to have dialog boxes that don't have a X close button. But the main window definitely should have a close button, otherwise that will annoy / confuse / frustrate users.
 
In any case strings are a poor choice for storing intermediary calculations of binary operations. You can almost always use perfectly ordinary integers for that
bitwise and, or, xor are all available for ints
 
@MisterMiyagi more like a failed attempt at it. Endianness is about the order of the bytes, not bits
 
Yeah. bin & hex are relics of Ancient Times, IMHO. There's rarely a good reason to use them these days.
 
4:45 PM
@MisterMiyagi Or the opposite?
@Kevin Is the point of reversing the string to convert from little endian to big endian?
 
I will be honest. I have never understood endianness.
The instant that "endian" appears before my eyes in a requirements document, I'm already navigating to docs.python.org/3/library/struct.html in the hopes that it can do the hard parts for me
 
@Kevin Big endian is basically the same order as numbers in the decimal numeral system, i.e. most significant is the leftmost digit, where as least significant digit is the rightmost digit. For example the decimal number 1000 is big endian. Does this make sense?
 
@Aran-Fey I have literally no idea whether it is correct. I've just spent long enough on SO to get triggered on byte-wise bit-reversal.
 
@PM2Ring I'm even beginning to find decimal a little passé.
 
@MyWrathAcademia That seems to contradict how Aran-Fey described it
 
4:50 PM
@Kevin Can you link to where he describes it?
 
@MyWrathAcademia Computer memory doesn't exist in a physical space. Endianness is about whether the least or most significant byte is stored at the lowest memory address.
 
5 mins ago, by Aran-Fey
@MisterMiyagi more like a failed attempt at it. Endianness is about the order of the bytes, not bits
 
>>> struct.pack('<H', 260)
b'\x04\x01'
>>> struct.pack('>H', 260)
b'\x01\x04'
bytes, not bits
 
Wow. It's over 4 years since I switched to Python 3. All this talk of hex etc reminded me of that hexdump function that uses f-strings that I posted here: chat.stackoverflow.com/transcript/message/30542743#30542743
 
@Kevin Thanks. I'm also talking about byte order, not bit order.
 
4:51 PM
Perhaps I'm misunderstanding what is meant by "digit" here. If you think of each byte in memory as a single base-256 digit, then endianness does map neatly to the order of digits.
I think we're all on the same page now. To answer the question, reversing the string is an incorrect way of converting between endiannesses, because you're flipping the bits, not the bytes
 
@Kevin correct.
Converting it to a list of hex-digit pairs might give a workable and equally inelegant solution :-)
 
German wikipedia claims everything makes sense when you think about endian'ness as startian'ness. Seems legit.
 
"lowest memory address" always trips me up because I visualize memory as a vertical stack of cells, with 0x0000 at the top, and 0xFFFF at the bottom
 
yet 0x0000 is smaller than 0xFFFF
 
Spatially speaking, 0xFFFF is the lowest address. But computer scientists almost always mean 0x0000 when they refer to the lowest.
 
4:56 PM
everything's upside-down in IT. Memory, trees, Y coordinates, you name it
 
I can get it right if I think about it for more than three seconds, but it's an expensive cache miss
 
Endianness is mostly important when designing systems that must operate across heterogeneous architectures. In networking terms the layer that takes care of this (the presentation layer) offers an architecture-specific interface to clients, using the normalised network data from the session layer.
 
I think of memory as horizontal, with the lowest address on the left. That's not so useful when people talk about stacks growing upwards or downwards. ;)
 
And if you live on the southern hemisphere, you have to flip all the directions again, it's just a mess
 
Yeah, hence my comment to @MyWrathAcademia - it can be unhelpful ...
 
4:59 PM
May 26 at 11:46, by Andras Deak
I always thought that the "end" refers to the end of the stream. Which would swap the meaning of little and big endian. Because the subject is not confusing enough already.
So I approve of wikipädia
 
Gotta love mnemonics that have multiple plausible interpretations and are thus useless
 
@AndrasDeak And in serial communications you also have to consider whether the first bit that arrives is most or least significant. I once had to write software that did exactly that, for a serial communications multiplexer (it handled IBM BiSync protocols at 2400 bps over up to 128 channels)..
 
At least in this case it's probably more satire than mnemonic
@holdenweb byte, not bit, right?
 
No, bit. He's talking about a serial protocol.
 
@Kevin I see, thanks. I got that code from this function. That function implements a custom float that has a 10 bit mantissa (i.e. significand) and 6 bit exponent. I don't know python but it's readable enough for me to use to implement the same solution in C Sharp.
 
5:03 PM
For the record, I'd probably flip a 16-bit integer's endianness with:
 
It can't be least significant bit if bytes get swapped. Can it?
 
>>> struct.unpack(">H", struct.pack("<H", 260))
(1025,)
 
@AndrasDeak you can have both bit and byte ordered separately
 
Ugggh
 
yeah
 
5:04 PM
And what is that if not endianness?
 
@Kevin If [2:] chops off the "0b" then does exponent = bits[10:] chop off the first 10 characters of the string?
 
@MyWrathAcademia try and see
And then read a tutorial
 
@AndrasDeak the start of even more confusion? Or was it the end...
 
When I do binary arithmetic in Conway's life using streams of gliders to represent bit strings, the least significant bit is at the front of the stream. That makes it easier to handle arbitrary precision.
 
@PM2Ring but that's not endianness, is it? This is confusing enough on its own...
 
5:07 PM
bit numbering / bit endianness is the bitwise version of endianness, apparently
 
@Kevin Thanks
 
@AndrasDeak I don't have an IDE that runs Python. How can I use Python's REPL from the command line?
 
> This article may require cleanup to meet Wikipedia's quality standards. The specific problem is: The article is full of inaccuracies and mixes endianness with bit numbering. The article also implies that bit numbering is a property of the CPU; it is not. Mixes least significant byte with least significant bit, which have the same TLA.
:|
@MyWrathAcademia just type python3 in your shell. Or py on windows.
 
@AndrasDeak Correct. Endianness is about byte ordering, not bit ordering. But holdenweb was talking about serial protocols, where you do have to worry about bit ordering. It can also be an issue in bitmap graphics data formats.
 
@PM2Ring I see
@MyWrathAcademia so how are you working with python?
 
5:10 PM
Sounds like he's porting this Python function to C#, without necessarily having a Python environment set up
 
Aah...
 
@AndrasDeak string[10:] does chop off the first 10 characters of the string.
@AndrasDeak Come again?
 
@MyWrathAcademia Indeed! And other sequences too.
 
I've never had to do bit numbering reversal in C# before, but Google tells me that the BitConverter class has a number of functions that may come in handy
 
I would have had to create a whole class in C Sharp (or Java) just to test that little code.
 
5:13 PM
@MyWrathAcademia I presumed you have access to a python interpreter, asking about python code
 
I'm still relatively confident that you can do almost all of this math with integer types
 
@MyWrathAcademia Is there a reason why you are using this custom format? There usually is a half-precision float type (also supported by Python's struct), but it has a bit reserved for the sign.
 
Some wild stuff going on in Is there a built-in function to reverse bit order... (b * 0x0202020202 & 0x010884422010) % 1023???
Whoops, I used the wrong endianness while formatting that link :-P
 
Ok so I might be confusing things (sorry, jumping off and on because my wife is doing all-day PD). Essentially what I do is (skipping set root.title and sizing):
root = tk.Tk() # ImageDisplay inherits from tk.Frame, and displays an image with a 'save as' button.
image_display = ImageDisplay(image_path, master=root)
image_display.mainloop() #Should only be able to get rid of the window by clicking button.
root.destroy()
 
@Kevin Reminds me of that fast sqrt trick...
 
5:17 PM
Same :-)
 
@AndrasDeak Yeah, Python is automatically installed on my operating system.
 
user13682510
@holdenweb Congratulations! Welcome to the club!
 
@toonarmycaptain On my machine, if I try to call destroy() after mainloop finishes executing, I get _tkinter.TclError: can't invoke "destroy" command: application has been destroyed
In other words, clicking the X destroys the window without you having to do it in the code
 
user13682510
@AndrasDeak I want to know the trick! :D
 
It doesn't explain why the application is freezing, though. It should be a nice clean stack trace and exit.
Fast inverse square root, sometimes referred to as Fast InvSqrt() or by the hexadecimal constant 0x5F3759DF, is an algorithm that estimates ​1⁄√x, the reciprocal (or multiplicative inverse) of the square root of a 32-bit floating-point number x in IEEE 754 floating-point format. This operation is used in digital signal processing to normalize a vector, i.e., scale it to length 1. For example, computer graphics programs use inverse square roots to compute angles of incidence and reflection for lighting and shading. The algorithm is best known for its implementation in 1999 in the source code of...
 
5:21 PM
@MisterMiyagi I rather not implement a custom float as my understanding of float representation in binary is not that good but I'm reading bytes from a file and those bytes must be converted to a float with no sign, 10 bit mantissa, and 6 bit exponent, so I have to implement a custom float.
 
user13682510
@Kevin Wow! But there's too many words, please elaborate!
 
@username you need to click and read them all
 
user13682510
Aww...
 
The road to knowledge is set in pain mild discomfort
 
Summary: Quake III Arena could only run quickly by making use of a "fast inverse square root" algorithm that calculates the result using seemingly arbitrary mathematical operations. None of the game's developers could remember how it was created, adding to the function's mystique.
 
user13682510
5:24 PM
@AndrasDeak Wow! how did you scratch that word?
 
@Kevin I use BitConverter but it only converts bytes to/from pre-existing data types. I can't use it to convert two bytes to a custom float like I want to do here.
 
@username I could tell you but you'd have to read
 
user13682510
i will ;)
 
user13682510
rbrb, i'll be reading!
 
5:26 PM
Good luck
 
@MyWrathAcademia I thought that might be the case. Basically I'm proposing that you use BitConverter to do the initial bit order reversal that is currently done by bits = bin(bytes[0])[2:].zfill(8)[::-1] + bin(bytes[1])[2:].zfill(8)[::-1], and then use bit-shifting and regular arithmetic to complete the rest of the logic.
In principle, it's easy to test whether your C# implementation is correct, because you can run it and the Python implementation on all 65,536 possible inputs to see if they match.
 
I don't see an error in the CLI/terminal, it just hangs (I presumed because the window is destroyed without returning something, but that could be wrong). I'm not wrapping anything in a try-except, so.
I was mistaken in how I'd set it up though. The 'save as' button just calls self.quit (so you see the image, and then click the save as button), and my next line calls a function that instantiates another tk.root to do a native save as dialogue, which is probably not efficient or normal, but saved me some complexity, since I wasn't trying to do a full GUI.
 
In practice it might be tricky to cross-reference them because there's no guarantee that Python prints floats in the same format that C# does.
 
@Kevin thanks, but I looked through BitConverter and it does do a bit reversal but not without also converting to a data type such as UInt32 etc.
 
Hmm, troublesome. I wish I was more acquainted with bit-specific types in C#. I just use int for everything in my day job :-P
 
5:42 PM
rbrb, thanks for the help, I'm tag teaming. I think rerouting what the 'X' does might work (have it call self.quit like the save as button?). If I remove the manual root.destroy, the window displaying the image hangs around after the user clicks 'save as', which is not what I want. If have one hidden tk.root for the whole app, then I had to worry about passing that around, which I wasn't wanting to manage, but if have to I can, I guess.
 
user13682510
cbg!
 
@Kevin to be honest I've only done byte shifting using the << bit shift operator. I have not shifted individual bits.
 
I wonder if it would help to call asksaveasfilename before you call self.quit...
I'm poking around in the dark here since I don't have any good idea of what could cause the behavior you're seeing
@MyWrathAcademia It's easy. x >> 8 shifts right by one byte, and x >> 1 shifts right by one bit.
 
@Kevin I see.
@Kevin Of course!
 
brb, conference call time
 
5:46 PM
@Kevin Thanks, now I can achieve the following in C Sharp:
bits = bin(bytes[0])[2:].zfill(8)[::-1] + bin(bytes[1])[2:].zfill(8)[::-1]
I don't get why you would want to reverse a single byte. If you reverse a sequence of bytes you change the endianness, but if you reverse a single byte what exactly are you changing?
 
well... the value of the byte
 
@Aran-Fey Yeah, this caught my eye just now. What exactly is that line of code gaining by reversing the bit order?
 
That's impossible to say without knowing how the input data was generated and what the output data should look like
 
@toonarmycaptain You normally do root.mainloop(). It seems a bit odd to call the .mainloop on a Frame (or a widget that inherits from Frame). Ok, so that ImageDisplay widget has a 'save as' button, and the window closes when the user press that button. What if the user doesn't want to save the image? Should they hit the X close button in the title bar?
 
user13682510
6:00 PM
@PM2Ring According to my understanding of the message, no.
 
@toonarmycaptain If you do want to intercept close events, you can install a handler function by doing root.protocol("WM_DELETE_WINDOW", handler). See the SO link I gave earlier or this page for some info: effbot.org/tkinterbook/tkinter-events-and-bindings.htm
 
wim
iirc the magic number 0x5F3759DF is somehow related to the sqrt of 2**127
but I played around with struct.pack and couldn't figure it out
 
user13682510
@wim I'm sorry, I can't help you with that... maybe next time?
 
wim
maybe I am breaking the egg on the wrong end..
 
user13682510
@wim Maybe.
 
6:05 PM
try a wheel instead :P
It's funny because of those words are related to code distribution. My sense of humor is magnificent.
 
user13682510
@Aran-Fey XDXDXDXDXD Yeah, mine too!
 
@wim wikipedia says " 0x5F3759DF, which is a floating point representation of an approximation of √(2^127)", so yeah. something like that
 
That's just 2^63.5...
 
wim
aha, I think I got it
 
@toonarmycaptain I think it's safe to create a new root window if the previous one is destroyed. It sounds like your program is mostly a CLI program, and just pops up a GUI window every now & again.
 
6:16 PM
@Aran-Fey The next part of the code is this:
# get mantissa and exponent
        mantissa = bits[:10]
        exponent = bits[10:]
I understand that the above code means:
# get mantissa and exponent
// first 10 bits is the mantissa
mantissa = bits[:10]

// last 6 bits is the exponent
exponent = bits[10:]
 
Ok, but what's the input data? Why are those bits in the order they are in?
 
@MyWrathAcademia I assume that the oddball float format has the bit order reversed for some oddball reason. ;) BTW, whoever wrote that code has done some odd stuff. Like shadowing the built-in bytes type.
 
@Aran-Fey the repo says it's for some raw tomography data. it's probably just a dump of what the hardware does.
 
However, the way mantissa and èxponent` are calculated suggests that the string variable bits always has a length of 16 characters. But how can this be the case when bin(...) can give you strings of different length which is then padded with 8 zeros?
 
It's padded to 8 digits.
 
6:25 PM
@Aran-Fey The input data is two bytes from a larger array of bytes that represent image data.
 
knew that I've seen that one before...
 
Hmm. Image data doesn't care about bit order, I don't think
 
@MisterMiyagi which was MWA's first confusing question here
 
@Aran-Fey I have no explanation for the second part.
@PM2Ring Shadowing?
 
@AndrasDeak I wasn't aware we were still on that topic, TBH.
@MyWrathAcademia bytes by default refers to the builtin bytes type. Shadowing means to re-use a name from an outer scope (in this case, bytes from builtins) for something else.
 
6:28 PM
@MisterMiyagi From bitbucket.org/uocte/uocte/wiki/Heidelberg%20File%20Format "Because no specification of this file format was available for the development of uocte, the file format was reverse engineered for interoperability. The information on this page therefore is incomplete and may be incorrect. It only serves to document which parts of the data are interpreted by uocte and which assumptions it makes concerning interpretation." Eek!
 
@Aran-Fey What? @Kevin said it's padded with zeroes:
2 hours ago, by Kevin
@MyWrathAcademia bytes[0] gets the first element of bytes. bin converts it into a string containing the number's binary representation, e.g. 7 becomes "0b111". [2:] chops off the "0b". zfill pads the string with zeroes. [::-1] reverses the string.
 
@PM2Ring Yeah, I've found tons of German resources which practically say the same.
 
@Aran-Fey Is it padded to 8 digits, or padded with 8 zeros?
 
@MyWrathAcademia Yes, but it's padded to a certain length, not by a certain number of zeroes.
 
Still, for medical data that's actually more information than I'm used to.
 
6:29 PM
@MyWrathAcademia He uses bytes as a parameter name for his function. That's like using list or str as a variable name.
 
@MyWrathAcademia it's padded with zeros to 8 digits (which are either 1 or 0)
 
When you work with an unfamiliar language, you must stop making assumptions and instead start reading the docs of all the functions you see.
 
@MisterMiyagi Really, I'm surprised Python lets you do that. In C Sharp you can only use a keyword as an identifier if you prefix it with the @ symbol.
 
builtins are not keywords
 
@MisterMiyagi :) Getting data out of hardware manufacturers is difficult, and the difficulty scales with the cost of the hardware.
 
6:33 PM
@PM2Ring I can fully understand that for business purposes. But I've had to deal with medical data in a scientific context, where not having direct access to data is... questionable.
 
@Aran-Fey I see, so .zfill(8) pads the string with zeros until there are 8 characters in the string. That explains this then:
16 mins ago, by MyWrathAcademia
# get mantissa and exponent
// first 10 bits is the mantissa
mantissa = bits[:10]

// last 6 bits is the exponent
exponent = bits[10:]
 
@MisterMiyagi I fully agree with both of those points.
 
@Aran-Fey Why wouldn't image data care about bit order? If changing the bit order changes the value of the byte then shouldn't the image data that byte represents also be affected?
 
Because images work with numbers. They don't care how the hardware represents those numbers. They work on a byte level
 
@Aran-Fey Good point. Python is quite readable so I guess it sometimes lulls you into a false sense of security.
@PM2Ring They want you to pay for that data?
 
6:39 PM
I don't suppose anyone has an env.py file for Alembic that works with Flask but does not rely on flask-sqlalchemy? I've spent hour upon hour trying to get migrations to work without flask-migrate and flask-sqlalchemy and I've just thrown the towel in; there isn't a single guide that doesn't rely on those last 2 libraries to push me in the right direction
 
@MyWrathAcademia They might not even want to give you the data even if you offer to pay for it.
 
@PM2Ring but we're here saving lives. That's not acceptable.
 
wim
@roganjosh why don't you just write it yourself
 
@MyWrathAcademia Hey, I'm a strong believer in open source, etc. But there are plenty of proprietary data formats & hardware protocols out there. That's one reason why Linux has a hard time supplying drivers for hardware. People often have to reverse-engineer the protocol. And the hardware manufacturer may have a contract with Microsoft that forbids them to make that information available to 3rd parties.
 
wim
I just write env.py by hand it's generally only ~20 lines
 
6:44 PM
@wim I have jumped back to doing that in between my intermittent searches but that's 2 libraries to go through to try find what's actually pertinent in picking up all models
 
wim
not following - don't you have a base model?
then it's just context.configure(connection=connection, target_metadata=Base.metadata)
 
@wim this is with an app factory and a separate database.py file?
Ok, but connection here comes from current_app.config?
 
wim
the connection is what you get when engine.connect() is entered context
and the engine is, you guessed it, what sqlalchemy.create_engine returns
then on the context instance you begin a transaction and run migrations
 
@Aran-Fey Yes, but different bit orderings mean different values. Even if you work on the byte level and avoid dealing with the number representations of a byte, the byte is still different once it has been reversed, right?
 
Sure, but knowing that the input is image data doesn't give us any valuable insight into why anyone would want to reverse it
 
6:53 PM
@wim ok, and this works with blueprints as well? Most of my frustration is not being able to pinpoint what I'm doing incorrectly and so I'm not sure that model imports into routes within blueprints are all resolved correctly (without importing the models into __init__.py for the main app)
That's just a word salad :/ Tied myself up in knots, sorry
 
01:00 - 19:0019:00 - 00:00

« first day (3530 days earlier)      last day (1401 days later) »