« first day (3132 days earlier)      last day (1816 days later) » 

12:47 AM
cbg
 
 
1 hour later…
2:09 AM
recbg
 
2:30 AM
@Kevin no
@Kevin json is standards-compliant with only allow_nan=False
 
wim
2:53 AM
@AnttiHaapala no it ain't ..
@Aran-Fey which is the majority of the stdlib and mostly every Python class written ever :P
 
wim
3:17 AM
What to do with this answer? There's nothing actually incorrect in it, that's just really dated and doesn't work in Python 3. It can't really be edited into shape to contribute anything useful.
PEP Explorer <-- neat
 
rbrb
 
3:51 AM
Traceback (most recent call last):
  File "run_test.py", line 20, in <module>
    parser.add_argument('--unittest-conf', action=argparse.FileType('rb'), required=True)
  File "/usr/lib/python2.7/argparse.py", line 1294, in add_argument
    action = action_class(**kwargs)
TypeError: __call__() got an unexpected keyword argument 'dest'
am I being stupid or what?
ya I know it is Python 2...
action, type...
nvm
@wim let's rephrase: there are greater chances that a successful json.dumps will result in conforming JSON output when allow_nan=False
>>> json.dumps(1e309, allow_nan=False)
ValueError: Out of range float values are not JSON compliant
The RFC prohibits adding a byte order mark (BOM) to the start of a JSON text, and this module’s serializer does not add a BOM to its output. The RFC permits, but does not require, JSON deserializers to ignore an initial BOM in their input. This module’s deserializer raises a ValueError when an initial BOM is present.
@wim I can't see any other deviation than the possibility of having a strange dict subclass that has duplicate string keys
 
wim
4:29 AM
@AnttiHaapala better :)
thanks for an excuse to DV that
 
4:56 AM
Hey folks, anybody here?
 
wim
@MisterMiyagi I had an inkling that pushing OrderedDict in front of MultiValueDict would alleviate matters. But I hadn't actually tried it (seems not to work)
class MyMeta(type):
    def mro(cls):
        return [cls, QueryDict, OrderedDict, MultiValueDict, dict, object]
 
@George occasionally yes, but if you want to ask a question just ask and wait
 
wim
5:17 AM
now I'm not sure if even this can be made to work without adapters :( please also adjust your answer to use code from this tag because some of the explanations aren't quite correct ...
in fact I don't even know where you found that implementation of lists, the Django releases I'm looking at do not use a super there.
 
 
2 hours later…
7:14 AM
I didn't know that liking Flying Circus helps with Python ;-)
 
7:47 AM
@wim I think the problem is that MultiValueDict expects self methods to conform to MultiValueDict, but super() methods to conform to dict
so if OrderedDict is in the MRO before MultiValueDict, the lists/items works but __getitem__ breaks
in general, I think this pattern is a sure sign that LSP is violated
class Foo(Bar):
    def a(self):
        super().b()
 
cbg
 
it basically means that Foo knows that self.b does not provide the expected behaviour
 
8:20 AM
Hi folks.. I have a little bit of a problem with my flask-restplus. In short, I can access the /swaggerui folder locally, but I can't access it through my nginx server...
I'm guessing it's a nginx-config issue, but I'm not sure. does anyone know if I have to do something special in nginx to enable the swaggerui?
I have already tried adding this config, but it doesn't seem to help...
location /swaggerui {
           proxy_pass localhost:8000/swaggerui;
}
I'm not quite sure why that would be needed though.. I already have a / route in the config, and it works for other flask stuff.
 
8:38 AM
One strange thing is that if I navigate to a faulty address (like /swaggerui/swagger-ui-bundle.as) I get the flask page not found page, but when I navigate to the correct address (...bundle.js) then I get a nginx served 404
 
8:58 AM
I have a strange problem with some sockets. I have a sender and receiver and the sender before sending X bytes sends a message with 16bytes that has included in it how many bytes the next message will be. Now somehow the receiver receives 'File000000000000' instead of a number. But I'm unsure how this is even possible given this code snippet:
def send_size(s, size):
    size_to_send = str(size)
    fixed_length_size = "0"*(16-len(size_to_send))
    fixed_length_size = fixed_length_size + size_to_send
    s.send(fixed_length_size.encode())
    return
On the receiver side I get:
ValueError: invalid literal for int() with base 10: 'File000000000000'
But I dont get how this can be, I mean I would understand it if File would be att the send of the string, which would mean I passed "File" to the send_size function, but at the beginning makes no sense, since fixed_length_size has "0"*(16-len(size_to_send)) at the beginning, which can never be something else than zeros
receiver does this:
def receive_string(s):
    string_size = int(s.recv(16).decode())
    string = s.recv(string_size).decode()
    return string
*end of the string
 
9:22 AM
did you send anything else over the connection?
by the way, note that you can store an integer as raw bytes, instead of an ASCII byte string
 
Yeah I'm rereading the pytho socket howto
I think this is my problem
"One complication to be aware of: if your conversational protocol allows multiple messages to be sent back to back (without some kind of reply), and you pass recv an arbitrary chunk size, you may end up reading the start of a following message. You’ll need to put that aside and hold onto it, until it’s needed.
And despite having read this, you will eventually get bit by it!"
Looks like the File comes from the previous message, the previous message is "File"
althought I dont recv with arbitrary chunk sizes, I always use s.recv(16|lenght that I just got in the previous message)
 
do you check that you actually read as much data as expected?
sockets will return at most as much data as you ask from it
depending on your message size, you must repeatedly read to get the entire buffer
 
Yeah I think this is somehow my problem, that the previous recv gets too little and the next recv wich should get the size of the next message actually reads the content of the old one
Hmm stupid, I though when I do s.recv(16) it reads exactly 16 bytes
 
9:39 AM
might be of interest: code.activestate.com/recipes/…
 
Oh I think I know what happens, the sender tries to send "File" and the receiver instead of getting the string size with fixed length 16bytes only reads 10 or so, which are all 0, which makes the next recv read 0bytes, and then when the next recv wants to get the size of the next message it reads File
 
cbg
 
Man I cant believe this is an issue, when I send I file I do it in a loop and check that I receive everything, but I didn't assume I need to do the same for measly 16bytes or short file names
 
@Hakaishin lol
 
user7437554
Any idea how to count how many times each number of a list appears in a list?
 
9:45 AM
google
 
a for loop and another list?
or dict
 
google knows best
 
user7437554
googling
 
@santimirandarp The first result: stackoverflow.com/questions/2600191/…
 
user7437554
the first is not
 
user7437554
9:47 AM
but the second :)
 
You probably did the wrong search, this is mine:
 
user7437554
but I need Count
 
user7437554
not count
 
Ya mean collections.Counter?
anyways, what are we taliking about, you got it already lol :-)
 
result order can vary by what google has saved on your preferences so far too, leading to some reordering.
 
9:50 AM
@ParitoshSingh Exactly, if you got that result before on a similar search, it would make the first link a little lower...
 
I love the small message below google that say you have clicked on this link before. Makes me furious, like I know and I didnt get it the first time :D or it was irrelevant before
 
@Hakaishin Lol, exactly, and the number of times.... when it gets big... and get's to 100... lol :-)
 
10:07 AM
*laughs in duckduckgo*
 
Aran too uses duckduckgo
Meanwhile, I got too much of 'super' from yesterday's conversation to keep me occupied for 2 days !
 
I use both ddg and google. Sometimes ddg alone just doesn't cut it, sadly
 
ddg is kinda meta-search, hence it falls behind
 
i never used that...
@lmao My first impression was that ddg is google...
 
Do I get this right, that python sockets connect call like this: s.connect((host, int(port))) specifies the remote host and port, but choses a random port for the local one?
 
10:17 AM
@U9-Forward: Give it a try!
However, people used to google don't appear to adjust to it
 
I gave it a try a while ago but it didn't convince me
but I use it to look up health stuff, but then again, all websites have google tracking in them anyways and dont care about the browser sending dont track me
 
For some reason, when I am posting an answer, Are you a human captcha is popping up on SO, what might be the reason for it ?
 
Are you a robot?
 
I am not I think
 
Uh-oh
 
10:19 AM
@Aran-Fey lol....
 
I think I've experienced captchas like that when I logged in from a new PC
 
@DeveshKumarSingh that happens to me only when i do short answers. i still don't think i am a robot...
 
Aah okay, how short are we talking, maybe code only? without text
 
Google not only remembers your preferences, but also explores your other tabs as well, continuously gathering data about you...hence it excels in reading up your mind
 
10:22 AM
i have had that pop up once when i answered too quickly. Ofcourse, i am incapable of answering quickly so i was confused. Turns out the question was vote closed, and reopened in the duration i was writing up an answer for it, and i had managed to give an answer within a few seconds of it opening. strange timing that.
 
it has happened to me multiple times in the past few weeks!
 
maybe you are a robot that doesn't realise it.
Sounds like some interesting plot for some sci fi novel, that probably already exists.
 
en mass
 
haha yes
that's your Try This phase?
Or This should work phase?
 
10:26 AM
@U9-Forward that's a very nice needlessly complicated version of the top answer
I like how you call enumerate then don't use the value at all
you should have thrown in a nested comprehension loop to make it even more convoluted :P
 
Assuming I have this code
readables, writables, exceptionals = select.select([s], [], [], 60)
if self.run:
    for readable in readables:
        client, addr = readable.accept()  # Establish connection with client.
        t = threading.Thread(group=None, target=on_new_client, args=(self, client, addr))
        threads.append(t)
        t.start()
    if not readables:  # pragma: no cover
        log.debug("Timed out select")
 
how's [''.join(c for c in s[idx:idx+2]) for idx,val in enumerate(s) if idx%2 == 0]?
 
and the threads close connections when they are done, I'm not accumulating additional socket connections right?
 
hm, curious. jw, if i only need indexes, is there an official preference on iterating on enumerate vs iterating on range(len()) ?
 
@ParitoshSingh why would you use enumarate?!
 
10:29 AM
@AndrasDeak So should i use:
 
I need grilled cheese. Solution: I order five pizzas and scrape off the cheese then throw away the rest.
@U9-Forward you should use the top voted answer if you want to follow that approach
 
print([s[idx:idx+2] for idx in range(len(s)) if idx%2 == 0])
 
yes, that's a worse version of the top answer
 
@AndrasDeak Geez, wha can i do?
 
looping N times and throwing away every other is much worse than looping N/2 times in the first place
@U9-Forward you can do whatever you like
one thing you can do is not answer 6 years late with a redundant and worse solution
But I don't want to raise the bar too high ;)
 
10:33 AM
@AndrasDeak Hey, can i do:
>>> s = '1234567890'
>>> [x+y for x,y in zip(s[::2],s[1::2])]
['12', '34', '56', '78', '90']
>>>
 
oh hey there was another answer from two years before with basically your original solution
@U9-Forward already has a downvote and a delvote stackoverflow.com/a/46824738/5067311
well, almost, I guess, yours works
 
@AndrasDeak Shall i edit?
 
6 mins ago, by Andras Deak
@U9-Forward you can do whatever you like
I wouldn't edit
 
damn.. i dunno what to do.
 
Hello everyone
I have this chunk of code
```
original_img = cv2.imread('./0_00002.png', cv2.IMREAD_GRAYSCALE)

original_shape = original_img.shape

cv2.imshow("bg", original_img)
if cv2.waitKey() == 27:
cv2.destroyAllWindows()

# Trying to ravel and to reshape
original_img = np.ravel(original_img)
np.reshape(original_img, original_shape)

# Show the mesh points
cv2.imshow("bg", original_img)
if cv2.waitKey() == 27:
cv2.destroyAllWindows()
```
 
10:49 AM
@francescop And?
 
the secon image show does not work, can anyone explaing me why? It seems that:
1. loading and image and show it <---- it works
2. ravel + reshape
3 reshow <----it does not show the image
basically I want to ravel the image to be able to change the pixels with an indexing which ranges between [0, img_height*img_width]
LOL
I FORGOT to save the result of reshape
thanks anyway hahaha
 
Also not that you probably don't have to ravel before reshaping. I'd expect opencv yo give you a C-ordered array.
also you don't have to reshape to use linear indices: original_img.flat[linear_indices] = new_val will work
even arr.ravel()[linear_indices] = new_val will work if your original array is contiguous and C-ordered
>>> M = np.random.rand(3,3)
... M.ravel()[4] = -1
... print(M)
...
... N = np.random.rand(6,6)[::2,::2]
... N.ravel()[4] = -1
... print(N)
[[ 0.795051721  0.217004401  0.196437375]
 [ 0.985124677 -1.           0.192941719]
 [ 0.708134398  0.728364852  0.212657228]]
[[0.049547592 0.019303911 0.441090061]
 [0.619125278 0.827906936 0.183268869]
 [0.487236352 0.660910717 0.789724683]]
indexing into .flat is probably better for this reason
@AndrasDeak *note, *you
 
ok thank you I try flat
thank you @AndrasDeak it works! :)
 
no problem
 
rbrb
 
11:04 AM
rbrb
 
How are your experiences with ZeroMQ guys?
 
@AndrasDeak the only argument would be if it is considered more "pythonic" way to access indexes. ive seen that as a standalone statement with the range(len()) being called an antipattern, but to be fair, im pretty sure in that case both indexes and values were needed. Wondering if that is the case or no for accessing indexes on their own
 
enumerate works with all iterables
len only works with sequences/containers
 
ooh, thats a good point too
 
@MisterMiyagi yeah, sure, but do we really need to enumerate a string?
 
11:11 AM
in most cases, I'd say indexing is an XY problem anyways
if you need indices of a string, by all means use enumerate
 
yeah no, i think in this case its no doubt. More so wondering about a general case where we need indexes
 
but consider why you need indices in the first place
 
here, you need to skip iteration steps, and in that case, you never really should be accessing the extra values
 
or you need to slice ahead using indices
 
Slicing is a valid and common enough usecase that requires indices.
think that justifies indices
 
11:14 AM
yeah, the need for slicing I understand
indexing can be useful, but I've rarely seen such cases outside of numpy and friends
 
on a tangent, now this convo makes me wonder how slicing would work with something like generators or some other iterable.
 
like islice?
 
aye, but add sliding window requirement, and skipping elements on top, and it becomes messy. the islice is consuming the generator
 
there's no general solution for a non-reiterable
unless you use something like tee that keeps track of consumed items under the hood
@MisterMiyagi but with numpy range(len()) usually is an antipattern
there are almost always better ways to do things when that comes up
 
with numpy iteration itself is considered antipattern
 
11:32 AM
Is there any update from Kenneth Reitzs side to the allegation?
 
so where would you folks use indexing?
I don't really do it outside of low-level stuff in Cython
 
@MisterMiyagi I don't understand the question
 
im quite sure ive written enumerate a fair few times, but i end up drawing a blank when it comes to something notable about the scenario where i used em.
just.. i guess when you need indexes, you just need indexes? (not really helpful sorry :P )
 
no, I wholeheartedly agree
 
@AndrasDeak when would you use indices over, say, iteration or maps?
 
11:36 AM
ah. Okay, one case i can point out, is mutation of the container
 
whenever I need incides :P
 
if i need to replace specific elements based on a condition of the value
i can either replicate the entire container with the change, or just mutate the original if i had indices
 
if there are specific elements, then why is your container a list?
lists imply that the number and thus position of items is meaningless
sorry, just something that has me pondering since the last "indexing should start at 0" discussion
 
that's not a good mindset to start any discussion from
 
11:38 AM
no no, all good. but why would list imply that?
sure, the actual indexes might be pointless, but the order may very well be critical
 
Hmm interesting follow up post. How do people from the community stand on this?
Ofc indexes should start from 0, there are enough good answers on SO explaining why
 
@MisterMiyagi You might want to change negative values wherever they are, etc. I don't think navel-gazing sessions on abstract grounds are particularly helpful here.
 
@AndrasDeak was this somehow directed to my question or comment? I dont really understand the sentence
 
no, I was talking to Miyagi
(there, edited)
 
naval-gazing, what a funny word
 
11:41 AM
naval-gazing sure is funny :D
gazes at his navel
all the stuff I could come up with does not need indizes
 
re 0 vs 1 indexing, use whatever really, just dont break consistency. python is rock solid about consistency when it comes to 0 indexing. (and i'll resist the temptation to add that 0 indexing is better off. oh wait.. oops)
 
e.g. ordering and removal of invalid values is preserved by map/filter/Iter and friends
 
for a more concrete example of the list mutation thing, there's a piece of code that read up a file by newlines, and mutated lines that matched a certain condition
now, you could argue for regex matching each line and replacing using read, but i dont really see why that would be easier or more readable. using readlines, you avoid having to deal with the delimiter yourself. the file is small enough to be read in memory, and the list has meaning in the order. The list is passed around pretty ruthlessly and goes through a lot of work.
but it is critical the line counts* dont change and all mutations are contained within a line
Sorry if that still isnt convincing enough, but im sure there's other cases where mutation of some specific container items makes sense
 
but then the indices are magic numbers, aren't they?
 
no? could you elaborate?
 
11:49 AM
if you want to work with specific lines because they have meaning, say month = data[2], then the index is a placeholder for some unspecified meaning
 
Like, it doesnt matter to the code which line passes a "check". but if it passes that check, it needs to be altered. The alteration is done there and then. The code does not wish to create a new copy (although you can, to the same effect. that's where map could come into the picture)
 
e.g. 2 == march
 
ah. well, think preprocessing instead. actual text files of unclean data.
i wouldnt want to give away more specifics here though :P
the condition is not where the index is used
the index is only needed because you need to mutate the element.
 
yeah I also dont see how you could mutate items in a list without indexes. And why that should be a bad thing
 
user7437554
x.append(element) and x=x+[element]
 
user7437554
11:53 AM
I know the difference but can't understand why the second is faster
 
12:04 PM
try with a big list
 
x = x + [element] means "allocate a brand new list containing one element. Then allocate a brand new list whose length is one larger than x. Move every element from x into the new list, and move every element from [element] into the new list". x.append(element) means "allocate one new slot on the existing list x and put element into it"
If x is ten million elements long, x = x + [element] will allocate a new list of ten million and one elements, which is something like 100 megabytes. x.append(element) will allocate space for one new item, which is something like 10 bytes.
Allocating 100 megabytes is pretty slow. Moving ten million elements from x into the new list is very slow. Adding one element to the end of x is fast.
 
cabbage
 
pretty well explained. The x+[element] will only appear fast for small lists, try it with a big list and you'll see the difference in performance.
cbg
 
I know the difference but can't understand why the first** one is faster
 
Even if your x is not ten million elements long and it never will be ten million elements long, you might still notice a performance bottleneck if you're doing a lot of concatenations. Doing an O(N) operation N times is O(N^2) after all.
 
12:16 PM
o/
 
user7437554
But why it appears faster?
 
x = x + [element] doesn't appear faster to me. On my machine, append is faster.
import timeit
def concatenate():
    x = []
    for i in range(10):
        x = x + [i]

def append():
    x = []
    for i in range(10):
        x.append(i)

print(timeit.timeit(concatenate, number=100000))
#result: 0.747927292
print(timeit.timeit(append, number=100000))
#result: 0.541342821
And the difference only widens if I increase the range
When I reduce the range to 1, sometimes x = x + [i] wins, but the margin is small and .append wins by just as much when I re-run the program, so it's basically a coin flip
 
12:33 PM
timeit('x+[4]', setup='x=[1]', number=1000000)
0.10681252900394611
timeit('x.append(4)', setup='x=[1]', number=1000000)
0.12687978300527902
timeit('x+[4]', setup='x=[1]*10000', number=1000000)
42.355247837003844
timeit('x.append(4)', setup='x=[1]*10000', number=1000000)
0.13128727699950105
 
One might argue that concatenation can win over append when the list is very small because append requires an attribute lookup and concatenation does not. Certainly, name lookup takes more than zero seconds to evaluate:
>>> timeit.timeit("x.append(0)",setup="x=[]", number=100000)
0.03178576200000549
>>> timeit.timeit("f(0)",setup="x=[]; f=x.append", number=100000)
0.02310624799999772
 
and if the list is small you'll get several reallocations during append
 
But the takeaway of this isn't "so I should use concatenation when my list is zero elements long and I want to add one element to it". If you know your list is zero elements, why concatenate at all? Surely x = [element] beats x = x + [element] in that case.
 
I don't know how that matters
 
Reallocation is asymptotically O(N) so at least you don't have to worry about it killing your complexity
I don't know how much clock time it consumes compared to adding an element into an already-allocated-yet-currently-unused slot
 
user7437554
12:44 PM
@Kevin thank u :)
 
user7437554
s='one two three four five six seven eight nine'
namelist=list(s.split())
numToname={}

for i in range(1,10):
  numToname[namelist[i-1]]=i
print(numToname)
 
@santimirandarp s.split() is already a list
 
user7437554
I've written a short example to start learning about dicts
 
user7437554
oups
 
user7437554
haha. you're faster than append XD
 
12:49 PM
Looks complicated, I'd rather just do num_to_name=dict(enumerate(s.split(), 1))
 
and this might be subjective but I prefer range(9) with ... = i+1 on the right-hand side, so you see what the indices are
 
user7437554
Is there a shorter way to write that code? 4 example with list comprehensions or something?
 
and what Kevin said
 
My crystal ball needs tuning, it's not supposed to let me answer questions before they get asked ;-)
 
user7437554
haha. Thanks both
 
12:49 PM
If they end up not asking the question, I get the worst headache
 
maybe the crystal ball is just doing its job too well. I'd say leave it be
 
I kind of threw like three new concepts at you there, what with enumerate and calling dict with a weird argument etc. So it may be instructive to see a version of the code halfway between yours and mine:
s='one two three four five six seven eight nine'
namelist=list(s.split())
numToname={}
for i, name in enumerate(namelist, 1):
    numToname[name] = i
print(numToname)
 
user7437554
yes I was reading what enumerate is haha
 
user7437554
and as @AndrasDeak said list is not needed isnt it? @Kevin
 
user7437554
second line
 
12:56 PM
You can often reap benefits from looking at code that calls range() and thinking about whether you really need it
@santimirandarp Yeah. I left it in because I usually compose instructive examples by making the minimum possible changes to the querent's original code.
list is completely superfluous there, but it doesn't change the result, so I left it in
 
user7437554
I see
 
Which date format is this? 1557837049.5097163
Number of seconds from a date?
 
Could be a Unix epoch timestamp.
>>> import datetime
>>> datetime.datetime.fromtimestamp(1557837049.5097163)
datetime.datetime(2019, 5, 14, 8, 30, 49, 509716)
 
If you interpret it as such it corresponds to thirty minutes ago. That's a good sign.
If you try to interpret a number as a timestamp when it isn't a timestamp, you typically get something way in the future or way in the past
 
user7437554
1:04 PM
weird
 
@Kevin actually, it's 15:05 now
 
uhm, actually... :P
 
Yes but I'm sitting in a spaceship that's going very fast, so thirty minutes ago is simultaneously six hours and thirty minutes ago.
 
(for the record the result from fromtimestamp is timezone-dependent)
 
You'll have to speak up, your text is quite red shifted
 
1:08 PM
or, just turn your ship the other way :P
 
red shift as in going far away?
 
(this joke doesn't work because my spaceship must be maintaining a roughly constant distance from earth, or else my responses would have significant delay. So signals I receive from earth wouldn't be shifted in either direction)
You don't necessarily have to be far away from something for it to redshift from your perspective. But if something close to you is redshifted, you're probably going to incinerate it with your thrusters.
 
Unless there's a huge gravitational gradient. Then again that has issues of its own.
 
so long suckers! i rev up my Alcubierre drive and create a huge gravitational gradient. When the bubble dissipates im lying completely spaghettified on the pavement
 
hey all, I am struggling to count the frequency of values in a pandas Dataframe column. I am trying df.groupby(col).count() but the output is wierd
 
1:15 PM
MCVE and output?
 
@Kevin im not quite sure if that calls for a celebration or not.
 
"The output is weird", "it doesn't work", "there is an error" is never sufficient information. How is the output weird? When it doesn't work, is there an error? Does it produce nothing or something wrong instead? What is the error message? What is the expected output? Put together a minimal example if necessary. That makes it easier for others to help you.
7
 
On one hand, if mankind gets access to my Alcubierre drive, it will usher in a golden age of space colonization, which calls for celebration. On the other hand, I'll be dead, which does not call for celebration.
If I die while sucesfully testing some completely revolutionary tech, I grant permission for everyone to party afterwards as long as someone pours out a 40 for me
 
Based on a few discussions these past few days I've decided to pin an MCVE message
 
You tell em Andras
 
1:18 PM
@AndrasDeak ye sorry was just copying some code and then deleted it off my clipboard accidentally
 
Alcubierre drive - That's something real, just searched it.
 
data_list = []

df = pd.DataFrame({'col1': [1, 2,1], 'col2': [0.1, 0.2,0.1]}, index=['a', 'b','c'])
 
Morning all o/
 
output of df.groupby('col1').count() is:

col2
col1
1 2
2 1
 
It's about as real as the orbital satellite I own in my mind
 
1:20 PM
@lmao yep. Kevin doing kevin stuff.
 
argh cant copy output properly, sorry
 
Is there a "proper" way to dump a full dictionary into a text file so one can import it into a different program i.e. LabView?
 
see the other pinned message for formatting multiline code in chat :P
 
@AndrasDeak ok sorry ><
 
@biggi_ first step is figuring out what format labview will accept
 
1:20 PM
@ParitoshSingh - So kevin a physicist too?
 
@biggi_ json is pretty popular for serializing data in a format that can be read by other languages. I have no idea if LabView specifically can read json though.
 
@AndrasDeak any sort of byte array or string with a delimiter works awesome. I do tons of LabView
 
@biggi_ traditionally, you can dump a dictionary out as json if you wish to send info to some other program
 
I haven't done any sort of json before, I'm electrical engineer gone weirdo program stuff for work haha
 
"string with a delimiter" may indicate that csv is worth looking into as well
 
1:22 PM
Right
 
its just like a dictionary, slightly stricter rules.
 
But for some reason I can't seem to get it to export. I've tried pickling it and when I open the text file it's all wingdings
 
csv and json are both built-in modules that do 95% of the work for you, if that wasn't clear. You don't need to write your own serializer.
 
pickle is something for the python ecosystem.
 
pickle is supposed to look like windings. It trades human-readability for compactness.
 
1:23 PM
@Andy your example is pretty bad because you can't distinguish values from counts
 
afaik, its meant for python to consume
not humans :P
 
Gotcha. Would it help if I made a gist and popped it here?
 
@ParitoshSingh Yeah.
 
>>> df = pd.DataFrame({'col1': [-3, 4, -3], 'col2': [0.1, 0.2, 0.3]}, index=['a', 'b','c'])
>>> df.groupby('col1').count()
      col2
col1
-3       2
 4       1
this indicates that the counts and values are correct, it's just the column name that's weird
 
@biggi_ If you want.
 
1:24 PM
it seems to use 'col1' as an index, probably due to the groupby
 
Let me get it setup. I don't mind, nothing proprietary on there at all
 
quick google search says labview will behave nicely with excel/csvs
 
perhaps you're looking for Series.value_counts:
>>> df.col1.value_counts()
-3    2
 4    1
Name: col1, dtype: int64
 
json might be tricker.
 
That's what I like to hear. If I had a nickel for every "I can't share any example data or even describe the layout of my data structure :3"...
I'd have like seventeen nickels
 
1:25 PM
i'd rather have taken quatloos
 
business idea: a website that lets you look at puppy daycare videos, called lab view
 
As the central quatloo authority, I possess effectively infinite quatloos, so having seventeen more isn't very useful to me.
 
i literally just typed why "lab" view? and then it hit me.
and by "it", i mean the meaning. not an actual labrador. that might have been painful.
 
@ParitoshSingh I do lots o LabView, and yes it does play very nice
 
all dogs are good dogs but it's hard to beat a lab pup in cuteness as far as puppies go
 
1:27 PM
So look at StartScan() on PyG4Edit. It tosses out a generator distdict. I'm putting that into a "master" variable that will let me keep track of all the angles (this is running a YDLIDAR)
Essentially I want to get x_master[angle] out into a csv or something. Bonus points for being able to do x_master[angle]:y_master[angle], x_master[angle1]:y_master[angle1], etc
 
Not directly related to your question, but style tip: distdict.update({i:0}) is more idiomatically written as distdict[i] = 0
 
I literally pulled this off Git. It's meant for the X4 and I changed a few of the COM settings for the G4
Just for reference, this is what I'm playing with: robotshop.com/en/ydlidar-g4-360-laser-scanner.html
 
@AndrasDeak ye my whole code attempt was a failure. Thanks for the comments. Will be taking a look on what you suggested
and will improve mcve next time
 
@biggi_ Is it possible for you to print out x_master and put the output in a gist as well? I would run your program myself and inspect the data on my machine, but I don't own a LIDAR laser scanner.
 
It's blank
Let me double check
Actually getting an error: "A bytes-like object is required, not 'str'
OH, I was tryign to cast to string
sec
 
1:36 PM
If you're saying "I can't print the dict because it doesn't like it when I do print(str(x_master))", print() can print objects of any type, no casting required
 
watch out with how you "cast" things
 
I can print it, I can't write it to a text/csv file
 
(terminology pedantry: Python does not have casting in the way that e.g. c++ has casting)
 
Ok so
I fixed it, I think
 
@AndrasDeak ye Series.value_counts was what i was looking for. Thanks!
 
1:39 PM
If I want to transmit 10kb does it even make sense to make the recv call chunked let's say in 2048? Since I anyway have to track how many bytes have been sent I could also do recv(10000). But I wonder what is more efficient to let the network and recv internals chop up my packets or to package them myself into some 2^n bytes
 
@Kevin added file to the gist with the output gist.github.com/biggidvs/fe285fa0f1d48637163dfccca92f4b1f
 
Progress!
 
@Andy no problem
 
So this works. Now, is there a good way to get it so when I write it I can do like xmaster[0]:ymaster[0], xmaster[1]:ymaster[1], etc instead of just xmaster0, xmaster1, etc?
 
That's not too hard.
 
1:42 PM
So I actually used the write statement that's above (the gist has been updated)
so how would I do that? I'm new to Python (I love being thrown into the fire)
 
I know I said to use a serialization library, but if the data is just a flat list of floats, then it's not too hard to compose the output yourself. Example:
x_master = [1447.0, 1469.25, 1500.75, 508.0, 1137.25]
y_master = [1514.5, 498.25, 739.25, 1465.75, 1453.0]
pairs = []
for x,y in zip(x_master, y_master):
    pairs.append("{}:{}".format(x,y))   #or use f strings if your version supports it
text = ", ".join(pairs)
with open("output.txt", "w") as file:
    file.write(text)
Now output.txt will contain the text 1447.0:1514.5, 1469.25:498.25, 1500.75:739.25, 508.0:1465.75, 1137.25:1453.0
 
O.o
That did the trick. So that'll get us going at least. Next is time to look at the PyG4Edit and take out the rounding parts so it prints out all the data. Typically you can get 3 or 4 readings per degree instead of 1, but I'll dig into that later
I appreciate the help, that would have taken me way to long to figure out on my own...if anyone needs hardware or labview help hit me up :)
 
No problem. Python has a bunch of fun list and/or string manipulation methods that can make tasks like this quick and simple... If you know ahead of time what methods you need to use.
format and join are constantly useful and zip is frequently useful
@Hakaishin I wonder this myself whenever I'm sending big data over a socket. I usually just send/recv the whole thing in one call, but it makes me nervous. Nervous about what, I don't know. It's an unknown unknown.
 

« first day (3132 days earlier)      last day (1816 days later) »