« first day (2037 days earlier)      last day (2916 days later) » 

5:00 AM
then your code won't
 
value = 42
role = 'ADMIN'

def requires_role(func):
	def forty_two(*args, **kwargs):
		print(42)
	def check_role():
		if role == 'ADMIN':
			print('admin is correct')
			func()
		else:
			print('you are not authorized')
	return check_role

@requires_role
def set_value():
    global value
    value = 12
    print('hello. set_value here')

def user_has_valid_role(*roles):
    if role not in roles:
        print('Role {!r} not in required roles {!r}'.format(role, roles))
        return False
    else:
you mean like this
value = 42
role = 'ADMIN'

def requires_role(func):
	def forty_two(*args, **kwargs):
		print(42)
	def check_role():
		if role == 'ADMIN':
			print('admin is correct')
			func()
		else:
			print('you are not authorized')
	return check_role

@requires_role
def set_value():
    global value
    value = 12
    print('hello. set_value here')

@requires_role
def update_widget(setting):
    widget = setting
    print(widget, ' User has valid role of ADMIN')
 
(you can remove forty_two, we're done with that ;) )
unrelated to this... but apparently this happened reddit.com/r/Python/comments/4ivd2k/…
 
lol..
 
apparently at my school theres someone named st. elmo
 
I cant figure out whats wrong
value = 42
role = 'ADMIN'

def requires_role(func):
	def check_role():
		if role == 'ADMIN':
			print('admin is correct')
			func()
		else:
			print('you are not authorized')
	return check_role

@requires_role
def set_value():
    global value
    value = 12
    print('hello. set_value here')

@requires_role
def update_widget(setting):
    widget = setting
    print(widget, ' User has valid role of ADMIN')

set_value()
update_widget()
 
5:08 AM
Please use external sites to post long snippets of code. sopython.com/chatroom
 
got it. sry.
 
That looks like about a dozen lines -_-
@Ming Pay attention to your stack trace. What does it tell you?
 
tells TypeError: check_role() takes 0 positional arguments but 1 was given
oh wait. it says this
TypeError: update_widget() missing 1 required positional argument: 'setting'
update_widget = requires_role(update_widget)
but update_widget() requires 1 positional argument. but check_role takes none
 
so, if you notice - check_role is our wrapper function. It doesn't take any arguments, and it's not calling func with any, either
which works for set_valuecause it doesn't need them
Have you come across *args, **kwargs?
 
yes
allows to have 0 or more args
for *args.
**kwargs keywords args. those are like dicts??
 
5:16 AM
yeah, it is
 
sry meant 1 or more args for *args?
 
it turns keyword args into dictionaries
or a dict, rather
you were right - zero or more
positional, and keyword arguments
you can also use tuple unpacking/keyword expansion when calling a function
so in our case, that means def check_role(*args, **kwargs):
and then we can do return func(*args, **kwargs)
and that will always do the right thing
 
so always put *args, **kwargs to be safe?
 
if you're curious to see what's passed and when, you can add print(*args, **kwargs)
 
in our case, there is no need for **kwargs right?
 
5:19 AM
for a decorator, yes, always put them both. There's no need, but there could be
leave off kwargs and call update_widget(42) then update_widget(setting='hello')
what happens?
 
dosn't allow because
TypeError: check_role() got an unexpected keyword argument 'setting'
is this correct? hastebin.com/memokiqaxi.py
def requires_role(func):
	def check_role(*args, **kwargs):
		if role == 'ADMIN':
			print('admin is correct')
			print(*args, ' this is args')
			func(*args, **kwargs)
		else:
			print('you are not authorized')
	return check_role

@requires_role
def update_widget(setting):
    widget = setting
    print(widget, ' User has valid role of ADMIN')
 
looks right to me. Runs well?
 
yeah it runs.
i just have 1 more thing that i'm confused in this example
def requires_role(func):
	def check_role():
		if role == 'ADMIN':
			print('admin is correct')
			func(*args, **kwargs)
		else:
			print('you are not authorized')
	return check_role
why this doesn't work?
 
where are args and kwargs defined?
 
my update_widget(42) i'm passing 42 to func() right?
 
5:26 AM
you're passing 42 to check_role
 
oh....
you mean. i'm passing the arguent to the return value of the decorator function?
 
(that's the tricky bit of decorators. You usually think that you're passing values to the function, but you're actually passing values to the wrapper functions)
bingo
because a decorator rebinds the name of the decorated function to the return value of the decorator
 
must all decorator function have a wrapper function?
must all decorator functions return functions?
 
remember:

@foo
def bar():
    ...

is the equivalent of

bar = foo(bar)
no, not necessarily. Only if you ever want to call the decorated function ;)
a decorator really just needs to return a callable
anything that you can put a () on the end of
 
def deco():
	def randomFunc(a):
		return a * 10
	return randomFunc

@deco()
def decorated(b):
	return b

decorated(10)
I'm trying to figure it out.
 
5:31 AM
remove the () on @deco
 
TypeError: deco() takes 0 positional arguments but 1 was given
 
and def deco(func) needs to take an argument (yours doesn't)
 
def deco():
	def randomFunc(a):
		return a * 10
	return randomFunc

@deco
def decorated(b):
	return b
oh
 
(you can use () on the end of decorators, and I plan to show you the examples, but I want to make sure you grok the more basic case, first)
 
i still trying to figure out the deco()
 
5:35 AM
def deco(f):
    print('decorator was called')
    def random_func(a):
        print('wrapper function was called')
        return a * 10
    print('returning random func')
    return random_func

@deco
def decorated(b):
    print('decorated was called')
    return b


print('calling decorated function')
decorated(42)
 
i see. ok. it wasnt taking in anyting for deco()
 
You should read:

decorator was called
returning random func
calling decorated function
wrapper function was called
decorated was called will never show up because it's never called
if you add f() anywhere in your deco function, it'll be called
depending on where you place it when it will be called will change ;)
 
yes. but i will also need to put in *args right
 
cbg
well, you'll have to pass it an argument
you can use *args, **kwargs or you could hard code the value
*, ** is more general and useful
 
5:40 AM
def deco(f):
	def randomFunc(a):
		f(*args)
		return a * 10
	return randomFunc

@deco
def decorated(b):
	print('decorated was called')
	return b

print(decorated(10))
i did this. but still. cannot.
 
wat
@Ming your random func takes wrong arguments
 
i know its similar problem earlier. i just didnt get it yet.
 
understand? or get it to run?
ah, right
args is not defined
 
and it isn't a "random func", it is a wrapper
 
a is
 
5:41 AM
that is why it is usually called wrapper
 
yeah, Ming is pretty new to this :P
 
so instead of calling f, you're calling the wrapper, right
then the wrapper needs to behave exactly as if it was f
it needs to accept the same number of arguments, and keyword arguments, otherwise it wouldn't work the same way outside
 
but where to call args?
def deco(f):
	def randomWrapper(*args):
		f(*args)
		return a * 10
	return randomWrapper

@deco
def decorated(b):
	print('decorated was called')
	return b

print(decorated(10))
 
@Ming ok lets put it this way: what should your decorator do
 
deco takes a function(f)
@WayneWerner told me earlier . decorated = deco(decorated)
deco takes function (f). call f within the randomWrapper
 
5:44 AM
yes, but how should your decorator change the behaviour of the decorated function
 
hmm
 
hmmmm indeed
 
the decorator is the one passing in args?
 
I think Ming is still working out the relationship between functions and names ;)
 
oh
 
5:45 AM
:D
 
return randomWrapper(*args) ??
no
 
anybody here ever heard of diffusion mapping or renormalization groups?
 
@Skyler no
:D
 
I may have heard of diffusion mapping
but I couldn't tell you anything about it
 
I still haven't heard anything about it, but now at least I know what it is related to :d
 
5:47 AM
i really cant get it
 
@DSM I have a mongo ebook somewhere. When we're next on chat together I can ping-and-delete the Dropbox link.
 
btw, im curious guys, what do you guys do with python personally
 
@Skyler personally on our personal time, or personally like individually?
cause those are different :D
 
@WayneWerner well as in what do you frequently use python for
job or personal
 
my job - moving money around, and reporting where that money came from and went to
 
5:49 AM
i mean i suspect people on the Python chat fancy the language
 
currently working on a project management software, a social media analysis system and an embedded device
 
personally, anything that tickles my fancy or makes my life better
 
just got it.
@WayneWerner like this
def deco(f):
	def randomWrapper(*args):
		return f(*args)
		print('this is never called')
		# return a * 10
	return randomWrapper

@deco
def decorated(b):
	print('decorated was called')
	return b

print(decorated(10))
 
and you @Ffisegydd?
 
@Ming bingo
ffisegydd used to do ffisegydd-things on python
 
5:50 AM
Currently my personal project is/was syncing my camera photos to my computer
 
@AnttiHaapala ah. great.
 
apparently my USB ports are shot, and I have no SD card reader on it either
 
@Ming though your function does not work on keyword arguments anymore
decorated(b=10)
try it
 
@WayneWerner your camera has built in internet?
 
What am I answering?
 
5:51 AM
ah yes - I pointed that out earlier ;)
(about the kwargs thing)
 
@Ffisegydd what do you do with python personally
 
@AnttiHaapala yeah ur right.
 
job or personalally
 
got to add **kwargs
 
personal*
 
5:52 AM
just got an 88¢ usb OTG card reader so I can plug it into my tablet. I'm learning all kinds of atrocious things about HTTP/Android/Kivy so I can copy my dang files over
@Skyler no built-in net, yet, sadly.
 
@WayneWerner @AnttiHaapala thanks very very much for the guidance and help. appreciate it. my brain is almost dead now.
need to process it through :)
@WayneWerner appreciate spending the time to help me. :)
 
@Ming Sleep on it and play some more. Decorators can be fun. And we didn't get to the @deco('stuff', 'can go here') style yet :D
 
@WayneWerner wouldn't it be easier to just plug the device in directly?
when you say camera are you referring to a dslr or phone camera, just saw android in the last comment
but you said no internet
 
@WayneWerner any good reference books you can recommend? is the best way to learn practice challenges, or go through tutorials in books?
 
so not phone...
 
5:54 AM
DSLR - tablet is android
 
@Skyler those were all false rumours and slander! I'll sue anyone who mentions them! I didn't know it was a real snake!
 
my computer has shot USB ports, at least when it comes to storage
 
@WayneWerner eg: Codewars, is it useful?
 
it can mount HIDs all day long - tablet, mouse, whatever
 
5:56 AM
but it won't read my camera. I have a different PC, but I think it must be like USB 1, because it's slooooooow to transfer
 
so now I have a flask app that I can fire up on my main machine, and a kivy app on my tablet. I can plug in my SD card to my tablet and copy over all the pics to my main computer. But holy crap, internet/android, do you even copy, bro?
 
@Ffisegydd so what would you go on the record saying you do
 
Turns out that Android <5 doesn't support multiple file upload in the browser, because reasons
 
@WayneWerner wait, android is on v5?
 
5:58 AM
Yeah, Lollipop?
 
@Ming automate boring stuff with python; dive into python 3 for example
 
my tablet is not a nexus device, so it's on 4.4
 
@Ming stay away from learn python the hard way
 
@WayneWerner whats the highest 4.x?
 
@Skyler everything. Data science, scripting, websites, restful apis, automation, testing.
 
6:00 AM
4.4 afaik. 4.4.3?
 
ah which reminds me
 
@Ffisegydd i peeked on your page and it mentioned data visualization, in what way?
 
I need to answer 1 coding task to try to win oculus rift
 
@WayneWerner man, my phone is 4.0.4
or maybe 4.0.1
 
Any way. Mostly matplotlib but also use D3.js in javascript
 
6:00 AM
@Skyler that seriously limits the apps that Google Play has for you, lol.
@Ming the official Python tutorial is pretty good
 
@WayneWerner i guess i never really took time to figure out where the update feature is on my phone
 
If you enjoy game programming the L line which says nothing about python on the cover is pretty good
 
@Ffisegydd what types of data?
 
@Skyler if you have AT&T it's usually right behind the big "F-U never" button.
 
@WayneWerner and if its motorola i still shouldnt update the device?
 
6:03 AM
No, I mean they don't roll out updates
because for some reason they feel that if you don't have their branded version of Android that you'll I don't even know, maybe go off to their competitor or something? I don't know
but... yeah, you should update if you can
 
"Update Motorola Software"?
 
A A
@AnttiHaapala Can you just put a reason before the link of the question and after the tag when you're doing [cv-pls]. It really helps in the [LQPHQ](http://chat.meta.stackexchange.com/rooms/773/low-quality-posts-hq) when a reason is there. You can just do it even in short form:
[cv-pls] TB <link>
 
and wth is PRL
 
some of those older versions have some bugs
 
@WayneWerner ironically when i loaded that page it started showing me error messages for a second
 
6:07 AM
looks like 4.4.4
 
@AA I am using the cv-pls extension, let me see
 
A A
@AnttiHaapala What you're doing is also correct, just that it would be a bit more helpful if you would put a reason after the tag and before the link. Like this
 
@Skyler all types
 
@Ffisegydd anything cool in recent times?
 
Yes
 
6:22 AM
example?
 
No
 
=(
 
I got me a new tilt-shift lens Thursday. Makes it fun to artistic the mess out of shots :D
(copying pictures like that to my computer is one of those things I do with Python)
 
@WayneWerner nice. I have always wanted to try a tilt shift
I do a lot of landscape and want to make it look macroey
 
6:35 AM
This one is a lensbaby spark duo kit - got it for a little under $70. It's ridiculously fun
I find myself either loving the pics with this look or thinking they're garbage, little in between. I've got a 35mm f/2.8 that has been my go-to lens for anything that I could physically get near.
 
7:22 AM
Oh yeah I've looked into lensbaby
 
Cabbage
@WayneWerner: It was fun reading your decorators tute session with Ming, but maybe next time you could create a room to do that sort of thing so as not to clutter up the main room. OTOH, it's not like there was a lot of other traffic at the time. :)
 
Yeah I didn't read it, but from having to scroll through it, I admire your dedication.
:p
 
@AnttiHaapala I also use a cv-pls extension; but the one I use just adds the [tag:cv-pls] you have to add the link manually (AFAIK), so it's easy to add a close reason. FWIW, the SOCVR people also monitor [tag:cv-pls] and appreciate it when a reason is given; in the SOCVR room itself it's mandatory to provide a reason. But as A A said an abbreviation is acceptable, eg POB for Primarily Opinion Based.
 
0
Q: When Implimenting The Flask Web server in my Python code it stops Executing

Kurt I have this scenario: A code which every 1 Second check the distance from the Sensor (div CheckLen()) I have another div which Check the distance using IF statements for example [if len>20:). These divs are then called in a while loop (infinite) one after each other (first check lenght then che...

Lollerskates
div? def? Function? — Antti Haapala 18 secs ago
 
7:40 AM
@AnttiHaapala "I put this thing in that thing and now it doesn't do the right thing. What thing should I do instead?"
 
this guy is writing def myfunc
then 2 seconds later, "was it so that html had <def class="foo"></def> and python had div myfunc, hmm so it was"
 
To be fair, it can be confusing when you're switching back & forth between 2 or more languages, even when you're not a newbie.
But mixing up div and def is daft. :)
 
I spent more time than I'd care to admit confused why my function definition using function foo was failing
 
Hi
 
Too much JS
 
7:48 AM
I got this literal '\t\x00' while reading a file in binary mode. What does this literal represent?
 
whenever I've posted a question to stackoverflow
it took like ages because I was checking and rechecking everything...
 
@MoonOwl22 \t is a tab char, ASCII 9, so that's the same as \x09\x00.
 
Yeah. I've thrown away way more questions than I've written because I found my solution during preparing it
 
@PM2Ring Thank you!
 
@Ffisegydd If only more question-askers did that...
 
7:52 AM
Well I only do it due to knowing the pain of answering bad questions
 
@MoonOwl22 No worries. What sort of data is in that binary file? Python might have more efficient ways of processing it than what you're currently attempting.
 
It's a data file my lecturer sent for me to read the message and follow the instructions. I've read it. It's string that instructs me to extract the image and send it to him
 
morning
 
@MoonOwl22 Ok. You may find some of the functions in binascii helpful... if you're allowed to use them. :) Also see docs.python.org/3/library/struct.html#module-struct
Greetings, Dr Snape.
 
Sup Snapey
 
8:05 AM
Sounds like a fun challenge to find the message and extract an image. Good luck!
Not a lot Fizzy. Killing a bit of time before kids to karate run.
On phone, so expect typos
 
On my way to a conference in Bristol
 
Ah, is that tge open data gig?
I recall using an open data project to find pubs in bristol, jI think via one of your links.
Open data thus showing it truly is a Force for Good.
 
Truly the best use of open data - beer.
 
Great minds :)
Next up, gin joints in the Cotswolds....
 
Lily-Gins. Best gin bar in Cheltenham.
 
8:13 AM
@Ffisegydd why didn't you make a self-answered q
 
Lazy.
 
Anonymous
9:12 AM
Hello, all. I have a question. Aside for the obvious reasons of maintainability, modularizing, DRY etc.., Does using OOP in Python provide much more benefits?
 
Anonymous
I have refactored my old, ugly, spaghetti code to use functions which I call using import and so, far I am satisfied.
 
Anonymous
Not sure, if I need to use OOP, just for the sake of using OOP.
 
9:47 AM
@samayo In a sense, you're always using OOP in Python, because everything is an object. But if you mean should you wrap everything up in classes as if you were writing Java, then no you don't need to do that. OTOH, that may make it easier to extend and re-use your code in the future.
 
Anonymous
Yeah, that's what I was looking for.
 
Anonymous
My code is so far the cleanest it has ever been, I can simple go the file > line I need to make adjustment in a matter of seconds, so I don't see it as a must-do to rewrite everything in OOP.
 
Anonymous
I have a conn, and helper class that I made with OOP, just to learn it, and these classes feel like they should be encapsulated, but that's just about it.
 
10:13 AM
cabbage
 
cbg @Bhargav
 
cbg @jon
Awaiting results of my non-technical paper today. Hoping that it'll be accepted.
 
@Bhargav did you bribe them with sufficient amounts of scooby snacks to make sure? :p
 
Unfortunately they were humans, So I sent them some salad
 
Whatever works :)
 
10:22 AM
Yep, :P
Tbh, I am quite skeptical that it'll be accepted. I spent some 3 months on it.
 
What's the one obvious way to get the current UNIX epoch time in Python as a string?

>>> str(int(time.time()))
'1463220694'

or

>>> str(time.time()).split('.')[0]
'1463220698'
I'm Dutch but I don't know about this one
 
str(int(time.time())) seems more intuitive to me.
 
Okay thanks :)
 
Or even: format(time.time(), '.0f')
 
Now how does that work?
 
10:31 AM
>>> "%d"%(time.time())
'1463221864'
 
I've never seen it before (but I'm quite new)
 
I'll check it out.
 
Also avoid using % which I showed, That's just for fun
 
Thanks again
 
10:43 AM
cbg
lol... pycharm crashed... again
@grooveplex these are slightly different
int() will cut the fractional part
 
hi
 
>>> format(0.6, '.0f'), str(int(0.6))
('1', '0')
 
@AnttiHaapala cbg
@AnttiHaapala That's what he wants :/
@Prakhar hi
 
@BhargavRao I think Antti is showing that they differ in case of rounding :)
 
Ah, Understood that.
 
10:49 AM
@JonClements you think correctly
 
>>> format(0.6, '.0f'), str(int(0.6)), "%d"%(0.6),  str(0.6).split('.')[0]
('1', '0', '0', '0')
Find the odd 1 out
 
I've been experimenting with handling binary data in Python 3. I guess it'll take me a little while to get used to it... Here's a comparison of my old & new hexdump functions. Old:
def hexdump(data):
    width = 16
    ww = 3 * width - 1
    loc, hic = '\x20\x7e'
    for count, row in enumerate(izip_longest(*[iter(data)] * width)):
        h = ' '.join([c.encode('hex') for c in row if c]).ljust(ww)
        a = ''.join([c if loc <= c <= hic else '.' for c in row if c])
        print '%08x  %s %s  |%s|' % (count * width, h[:24], h[24:], a)
    print '%08x' % len(data)
New:
def hexdump(data):
    width = 16
    ww = 3 * width - 1
    lo, hi = 0x20, 0x7e
    for count, row in enumerate(zip_longest(*[iter(data)] * width)):
        #print(row)
        hexstr = ' '.join([format(u, '02x') for u in row if u is not None]).ljust(ww)
        ascstr = ''.join([chr(u) if lo <= u <= hi else '.' for u in row if u is not None])
        print('{:08x}  {} {}  |{}|'.format(count * width, hexstr[:24], hexstr[24:], ascstr))
    print('{:08x}'.format(len(data)))
 
bbiab
 
The new version seems messier to me...
 
@BhargavRao Im working on a python app that needs to connect to websocket concurrently and it reads the socket every sec and does the work it needs to, im using threads atm, do you think gevent will be better for this
?
 
10:55 AM
@Prakhar Ask questions in general (w/o @mentioning). Just coz if others know an answer to your question, they might be able to help you. :)
 
ok, thanx
can anyone help me please ?
 
11:10 AM
Rhubarb
 
rbrb
 
11:22 AM
Hey guys, I've taken on a hubspot theme that uses the jinja2 templating system. Inside the css file I have syntax like this

{% macro transition(value) -%}
-webkit-transition: {{ value }};
{%- endmacro %}
I've never used python let alone the jinja2 templating system. I've come from wordpress and I'm used to using scss and gulp. Piping this css file through the gulp-scss module throws errors. Is there a gulp module I can use to keep this syntax and use sass or am I going to have to use some other preprocessor and gulp module. If so any recommendations?
 
11:42 AM
@UzumakiDev is that actually in a CSS file?
 
yup
in a file called hubtheme.css
if it's being preprocess somehow I don't know where it would be, I haven't used jinja2 before so I'm not familiar with workflows.
here's a link with the a similar file designers.hubspot.com/docs/tools/boilerplate-css
maybe there has to be something processing that css file, right?
 
12:04 PM
pycharm crashed
 
Anonymous
I have this script sort of that I use to generate 90K .svg images every day, I'm running the script on a 512GB VPS, and memory maxes out often. Is there any way to improve the performance of that script?
 
Anonymous
by any means?
 
12:22 PM
@samayo are you stopping the script...
@samayo 90K only?
 
Anonymous
@AnttiHaapala I'm not stopping it, 90K is only for creating those .svg images, there are other tasks running, but problem and swap notification arrive as soon as that script runs.
 
anyone using gevent/celery here ?
 
12:49 PM
Just ask your question :)
 
alright
 
Me
 
so, im working on a app which gets all the tokens from db and uses them to connect to slack websocket for teams and reads the socket every 1 sec and processes it, so as of now i just get all the rows from db and start a new thread for them , what i want to ask is , is there a better way to do this ? with celery or gevent (im not very much familiar with them, yet)
any idea ?
import time
from slackclient import SlackClient

token = "xoxp-28192348123947234198234"# found at api.slack.com/web#authentication
sc = SlackClient(token)
if sc.rtm_connect():
    while True:
        print sc.rtm_read()
        time.sleep(1)
else:
    print "Connection Failed, invalid token?"
this is the basic stuff, which needs to run concurrently for different tokens
is there a better way then thread per token ?
 
hello
 
hi bro :)
 
12:58 PM
hello, can i ask you anything general programming?
@p
@Prakhar
 
sure, i'll try to answer it
 
@samayo was trying to ask whether or not you run that script as a continuous process or oneshot
 

« first day (2037 days earlier)      last day (2916 days later) »