Register a SA Forums Account here!
JOINING THE SA FORUMS WILL REMOVE THIS BIG AD, THE ANNOYING UNDERLINED ADS, AND STUPID INTERSTITIAL ADS!!!

You can: log in, read the tech support FAQ, or request your lost password. This dumb message (and those ads) will appear on every screen until you register! Get rid of this crap by registering your own SA Forums Account and joining roughly 150,000 Goons, for the one-time price of $9.95! We charge money because it costs us money per month for bills, and since we don't believe in showing ads to our users, we try to make the money back through forum registrations.
 
  • Locked thread
Lurchington
Jan 2, 2003

Forums Dragoon
I came to a web programming company after doing nothing but hobbyist python programming for several years. I had no background in javascript or HTML at all, but that didn't matter since we did a lot of server-side stuff using pylons and cherrypy that really just writing regular python, no need to be a networking expert. We mostly setup secure communications / internal websites for banks / financial companies.

an example of a common problem I was assigned early on, was how to efficiently traverse a multi-KB blob of JSON (essentially just a python dictionary) and shove the important bits into a postgres database using SQLAlchemy. That's pretty much just leveraging your knowledge of python data structures and the absolutely barest of knowledge about SQLA's object relational mapper

That's my "how I got a real job (TM) writing python" story

Lurchington fucked around with this message at 21:16 on Mar 30, 2012

Adbot
ADBOT LOVES YOU

Cabbages and VHS
Aug 25, 2004

Listen, I've been around a bit, you know, and I thought I'd seen some creepy things go on in the movie business, but I really have to say this is the most disgusting thing that's ever happened to me.
I'm struggling with something pretty basic. I have an XML file that looks like this:
code:
?xml version="1.0" encoding="iso-8859-1"?>
<dcst:ServiceRequests xmlns:dcst="http://dc.gov/dcstat/types/1.0/">
    <dcst:ServiceRequest xmlns:dcst="http://dc.gov/dcstat/types/1.0/">
        <dcst:inspectiondate><![CDATA[2009-01-06T23:41:00-05:00]]></dcst:inspectiondate>
        <dcst:resolution><![CDATA[Complete]]></dcst:resolution>
        <dcst:resolutiondate><![CDATA[2009-01-06T23:41:00-05:00]]></dcst:resolutiondate>
        <dcst:serviceduedate><![CDATA[2009-01-05T01:56:00-05:00]]></dcst:serviceduedate>
        <dcst:servicenotes><![CDATA[Close Ticket.]]></dcst:servicenotes>
        <dcst:parentservicerequestid><![CDATA[]]></dcst:parentservicerequestid>
        <dcst:adddate><![CDATA[2009-01-01T00:00:00-05:00]]></dcst:adddate>
        <dcst:lastmodifieddate><![CDATA[2009-12-31T00:00:00-05:00]]></dcst:lastmodifieddate>
        <dcst:siteaddress><![CDATA[5312 NORTH CAPITOL STREET NW]]></dcst:siteaddress>
     </ServiceRequest>
   <dcst:ServiceRequest xmlns:dcst="http://dc.gov/dcstat/types/1.0/">
         <dcst:inspectiondate><![CDATA[2009-01-01T06:40:00-05:00]]></dcst:inspectiondate>
        <dcst:resolution><![CDATA[Complete]]></dcst:resolution>
        <dcst:resolutiondate><![CDATA[2009-01-01T06:40:00-05:00]]></dcst:resolutiondate>
        <dcst:serviceduedate><![CDATA[2009-01-01T07:11:00-05:00]]></dcst:serviceduedate>
        <dcst:servicenotes><![CDATA[]]></dcst:servicenotes>
        <dcst:parentservicerequestid><![CDATA[]]></dcst:parentservicerequestid>
        <dcst:adddate><![CDATA[2009-01-01T00:00:00-05:00]]></dcst:adddate>
        <dcst:lastmodifieddate><![CDATA[2009-12-31T00:00:00-05:00]]></dcst:lastmodifieddate>
        <dcst:siteaddress><![CDATA[]]></dcst:siteaddress>
        <geo:lat xmlns:geo="http://www.w3.org/2003/01/geo/wgs84_pos#">0</geo:lat>
        <geo:long xmlns:geo="http://www.w3.org/2003/01/geo/wgs84_pos#">0</geo:long>
    </ServiceRequest>
It has a ton of other nodes that I don't care about. All I want to do is parse this into some useful, simple data structure such that I end up with a list of associated inspectiondates, siteaddresses and resolutions. I've been playing with xml.dom.minidom.parse, and have not come up with anything helpful:
code:
import xml.dom.minidom
from xml.dom.minidom import Node
doc = xml.dom.minidom.parse("src.xml")
mapping = {}
i = 0 
for node in doc.getElementsByTagName("dcst:ServiceRequest"):
	address = node.getAttribute("dcst:siteaddress")
	mapping[i] = address
	i+=1
That gets me an object that has the same length as the number of elements I'm after, but nothing useful. Basically, I don't know what the gently caress I'm doing, but I think if someone gave me a snippet that returned something useful to me I could figure out how it's working and extend it to whatever I need. Can someone throw me a bone?

What I say "some useful data object", I don't really care what it looks like as long as I can easily extract an address along with it's associated resolution, and resolutionDate. This is also something I'm doing completely for fun that has nothing to do with my job, etc, so I'm not asking anyone to do my job-work for me.

OnceIWasAnOstrich
Jul 22, 2006

spengler posted:

It has a ton of other nodes that I don't care about. All I want to do is parse this into some useful, simple data structure such that I end up with a list of associated inspectiondates, siteaddresses and resolutions. I've been playing with xml.dom.minidom.parse, and have not come up with anything helpful:

That gets me an object that has the same length as the number of elements I'm after, but nothing useful. Basically, I don't know what the gently caress I'm doing, but I think if someone gave me a snippet that returned something useful to me I could figure out how it's working and extend it to whatever I need. Can someone throw me a bone?

What I say "some useful data object", I don't really care what it looks like as long as I can easily extract an address along with it's associated resolution, and resolutionDate. This is also something I'm doing completely for fun that has nothing to do with my job, etc, so I'm not asking anyone to do my job-work for me.

I recommend using 'from xml.etree.ElementTree import ElementTree' over the minidom if you don't immediately understand DOM, I know I certainly don't.

Something like

code:
from xml.etree.ElementTree import ElementTree
tree = ElementTree()
tree.parse(xmlstring)
Then you just have a giant tree structure. I don't have a computer right now to play around with what the data will actually look like in the tree, but it has all sorts of fun methods like tree.getroot() and everything has a tag dictionary.

Cabbages and VHS
Aug 25, 2004

Listen, I've been around a bit, you know, and I thought I'd seen some creepy things go on in the movie business, but I really have to say this is the most disgusting thing that's ever happened to me.
I was mucking with ElementTree and got discouraged before I found a tutorial based on minidom that I got equally discouraged by, but if you think it's simpler then I will give it another go tomorrow.

My goal here is to use city supplied data to make a google map that shows that over-privileged white people are more likely to bitch about how dirty their neighbors lawns are; I got the gmaps stuff figured out lickity-split but am struggling with basic XML parsing, which amuses me because going into this I assumed it would be the other way around.

ButtWolf
Dec 30, 2004

by Jeffrey of YOSPOS
EDIT: BEGINNER STUFF NM


I'm going through Learning Python using 2.3, IDLE i'm using is 3.2.2
Should I throw this book away? Has too much syntax been changed?

ButtWolf fucked around with this message at 01:44 on Apr 2, 2012

JetsGuy
Sep 17, 2003

science + hockey
=
LASER SKATES

jimcunningham posted:

EDIT: BEGINNER STUFF NM


I'm going through Learning Python using 2.3, IDLE i'm using is 3.2.2
Should I throw this book away? Has too much syntax been changed?

I wouldn't throw it away, but Py 2 is a *lot* different from Py 3. I've never used Py 3, and many libraries don't yet support Py 3. See a few pages back for our discussion on who used what.

I use Py 2.7 and have no desire to move towards Py 3. Most of that is because I can't, because my entire field uses 2.6/2.7.

I'd hold onto your 2.3 manual though, because you'll probably find Py 2 code for which you'll be glad you kept a reference. Alternatively, everyone loves "learning python the hard way".

FAKE EDIT: :psyduck: What the poo poo, didn't that thing used to just be a free website?

Plorkyeran
Mar 22, 2007

To Escape The Shackles Of The Old Forums, We Must Reject The Tribal Negativity He Endorsed
The HTML version still is free.

JetsGuy
Sep 17, 2003

science + hockey
=
LASER SKATES

Plorkyeran posted:

The HTML version still is free.

:doh:
http://learnpythonthehardway.org/book/

duck monster
Dec 15, 2004

I still think the way he teaches OO is abysmal. His "gogoths are getting classy" is terrible. If the first thing you learn about a class is that it can be a abused as a faux dictionary, your just going to end up more confused about OO than you started.

duck monster fucked around with this message at 14:24 on Apr 3, 2012

Captain Capacitor
Jan 21, 2008

The code you say?
I just finished setting this up at work where we have a flaky Internet connection, but for those of you that redownload the same packages over and over again, take a look at Localshop.

Computer viking
May 30, 2011
Now with less breakage.

duck monster posted:

I still think the way he teaches OO is abysmal. His "gogoths are getting classy" is terrible. If the first thing you learn about a class is that it can be a abused as a faux dictionary, your just going to end up more confused about OO than you started.
I don't really agree - seeing an object as a container of data sounds like a reasonable first step? Add on "and relevant functions" as the next step, and then move on to interfaces and eventually class hierarchies.

Admittedly, I view OO in what might be an overly prosaic (and imperative) way. And I should perhaps read what you're talking about before answering...

Computer viking fucked around with this message at 17:34 on Apr 3, 2012

Munkeymon
Aug 14, 2003

Motherfucker's got an
armor-piercing crowbar! Rigoddamndicu𝜆ous.



spengler posted:

I'm struggling with something pretty basic. I have an XML file that looks like this:
code:
?xml version="1.0" encoding="iso-8859-1"?>
<dcst:ServiceRequests xmlns:dcst="http://dc.gov/dcstat/types/1.0/">
    <dcst:ServiceRequest xmlns:dcst="http://dc.gov/dcstat/types/1.0/">
        <dcst:inspectiondate><![CDATA[2009-01-06T23:41:00-05:00]]></dcst:inspectiondate>
        <dcst:resolution><![CDATA[Complete]]></dcst:resolution>
        <dcst:resolutiondate><![CDATA[2009-01-06T23:41:00-05:00]]></dcst:resolutiondate>
        <dcst:serviceduedate><![CDATA[2009-01-05T01:56:00-05:00]]></dcst:serviceduedate>
        <dcst:servicenotes><![CDATA[Close Ticket.]]></dcst:servicenotes>
        <dcst:parentservicerequestid><![CDATA[]]></dcst:parentservicerequestid>
        <dcst:adddate><![CDATA[2009-01-01T00:00:00-05:00]]></dcst:adddate>
        <dcst:lastmodifieddate><![CDATA[2009-12-31T00:00:00-05:00]]></dcst:lastmodifieddate>
        <dcst:siteaddress><![CDATA[5312 NORTH CAPITOL STREET NW]]></dcst:siteaddress>
     </ServiceRequest>
   <dcst:ServiceRequest xmlns:dcst="http://dc.gov/dcstat/types/1.0/">
         <dcst:inspectiondate><![CDATA[2009-01-01T06:40:00-05:00]]></dcst:inspectiondate>
        <dcst:resolution><![CDATA[Complete]]></dcst:resolution>
        <dcst:resolutiondate><![CDATA[2009-01-01T06:40:00-05:00]]></dcst:resolutiondate>
        <dcst:serviceduedate><![CDATA[2009-01-01T07:11:00-05:00]]></dcst:serviceduedate>
        <dcst:servicenotes><![CDATA[]]></dcst:servicenotes>
        <dcst:parentservicerequestid><![CDATA[]]></dcst:parentservicerequestid>
        <dcst:adddate><![CDATA[2009-01-01T00:00:00-05:00]]></dcst:adddate>
        <dcst:lastmodifieddate><![CDATA[2009-12-31T00:00:00-05:00]]></dcst:lastmodifieddate>
        <dcst:siteaddress><![CDATA[]]></dcst:siteaddress>
        <geo:lat xmlns:geo="http://www.w3.org/2003/01/geo/wgs84_pos#">0</geo:lat>
        <geo:long xmlns:geo="http://www.w3.org/2003/01/geo/wgs84_pos#">0</geo:long>
    </ServiceRequest>
It has a ton of other nodes that I don't care about. All I want to do is parse this into some useful, simple data structure such that I end up with a list of associated inspectiondates, siteaddresses and resolutions. I've been playing with xml.dom.minidom.parse, and have not come up with anything helpful:
code:
import xml.dom.minidom
from xml.dom.minidom import Node
doc = xml.dom.minidom.parse("src.xml")
mapping = {}
i = 0 
for node in doc.getElementsByTagName("dcst:ServiceRequest"):
	address = node.getAttribute("dcst:siteaddress")
	mapping[i] = address
	i+=1
That gets me an object that has the same length as the number of elements I'm after, but nothing useful. Basically, I don't know what the gently caress I'm doing, but I think if someone gave me a snippet that returned something useful to me I could figure out how it's working and extend it to whatever I need. Can someone throw me a bone?

What I say "some useful data object", I don't really care what it looks like as long as I can easily extract an address along with it's associated resolution, and resolutionDate. This is also something I'm doing completely for fun that has nothing to do with my job, etc, so I'm not asking anyone to do my job-work for me.

"dcst:siteaddress" is also a tag name, fyi.

The minidom DOM is, by Python standards pretty obtuse. Try this stuff:
code:
def _get_text(nodelist):
   return ''.join([n.data for n in nodelist if n.nodeType == n.CDATA_SECTION_NODE])

def get_addresses(from_file):
   import xml.dom.minidom
   doc = xml.dom.minidom.parse(from_file)
   for req in doc.getElementsByTagName('dcst:ServiceRequest'):
      yield (_get_text(req.getElementsByTagName('dcst:resolution')[0].childNodes),
            _get_text(req.getElementsByTagName('dcst:siteaddress')[0].childNodes),
            _get_text(req.getElementsByTagName('dcst:resolutiondate')[0].childNodes))
(Tested - should work)

And if that's not quite what you want, hopefully you can figure out how to modify it.

JetsGuy
Sep 17, 2003

science + hockey
=
LASER SKATES
I'm having a bit of an issue with managing UI. This is going to basically just be me using this, but given that I'm prone to keystroke errors often, I like to keep my code smart enough to tell me to gently caress myself if I'm going to screw my data. Here's what I wrote, but it is not doing what I want:

code:
while True:
            fine_bin_size = raw_input("What fine bin size do you want? (in ms, <12)  ")
            try:
                fine_bin_size = float(fine_bin_size)
                if fine_bin_size%2==1:
                    sys.stdout.write("Unacceptable. Must be divisible by 2 ms.\n")
                
                if 2.>fine_bin_size or fine_bin_size>12.:
                    sys.stdout.write("Unacceptable.  Too fine/coarse binning.\n")
                else:
                    sys.stdout.write("Okay.\n")
                    break
                
            except(ValueError):
                sys.stdout.write("That's not a number.\n")
Yes, I know I just angered the coding Gods by using a while True loop... :(

Anyway, it works fine if I do something dumb like enter in a number and a letter or a letter. However, if I try an odd number, it decides it's fine and continues on its way.

Is there a cleaner way to do this? As I write this, it occurs to me I could make an array of possible answers and refuse to leave the loop if the answer isn't in there...

code:
 while True:
            fine_bin_size = raw_input("What fine bin size do you want? (in ms, <= 12)  ")
            if fine_bin_size in ["2","4","6","8","10","12"]:
                sys.stdout("Okay.")
                fine_bin_size = float(fine_bin_size)
                break
            else:
                sys.stdout.write("Unacceptable answer. Divisible by 2, <= 12 ms.")
My problem with this solution is that if I ever want to make this a much bigger set, it's going to become a pain in the rear end. I know there's a way to change the data type for numpy arrays, but would that work?

Suspicious Dish
Sep 24, 2011

2020 is the year of linux on the desktop, bro
Fun Shoe

JetsGuy posted:

code:
while True:
            fine_bin_size = raw_input("What fine bin size do you want? (in ms, <12)  ")
            try:
                fine_bin_size = float(fine_bin_size)
                if fine_bin_size%2==1:
                    sys.stdout.write("Unacceptable. Must be divisible by 2 ms.\n")
                
                if 2.>fine_bin_size or fine_bin_size>12.:
                    sys.stdout.write("Unacceptable.  Too fine/coarse binning.\n")
                else:
                    sys.stdout.write("Okay.\n")
                    break
                
            except(ValueError):
                sys.stdout.write("That's not a number.\n")

This seems fine to me. Three suggestions: use an integer, not a float, put this in its own function so that the loop is encapsulated easily, and use smart range expressions:

code:
def grab_fine_bin_size():
    while True:
        bin_size_str = raw_input("What fine bin size do you want? (in ms, <12) ")
        try:
            bin_size = int(bin_size_str)
        except ValueError:
            print "That's not a number."
            continue

        if 2 <= bin_size < 12:
            print "Okay."
            return bin_size
        else:
            print "Unacceptable."

JetsGuy
Sep 17, 2003

science + hockey
=
LASER SKATES

Suspicious Dish posted:

This seems fine to me. Three suggestions: use an integer, not a float, put this in its own function so that the loop is encapsulated easily, and use smart range expressions:

code:
def grab_fine_bin_size():
    while True:
        bin_size_str = raw_input("What fine bin size do you want? (in ms, <12) ")
        try:
            bin_size = int(bin_size_str)
        except ValueError:
            print "That's not a number."
            continue

        if 2 <= bin_size < 12:
            print "Okay."
            return bin_size
        else:
            print "Unacceptable."

:doh: How'd I forget about continue?? Thanks man.

Also, yeah, I don't know why I didn't use a better range exception. This is for a snippet that I needed to just quickly edit data sets for myself. The whole "program" is only 80 lines, and the bulk of it is catching idiotic entries.

V:shobon:V

Not My Leg
Nov 6, 2002

AYN RAND AKBAR!

Computer viking posted:

I don't really agree - seeing an object as a container of data sounds like a reasonable first step? Add on "and relevant functions" as the next step, and then move on to interfaces and eventually class hierarchies.

Admittedly, I view OO in what might be an overly prosaic (and imperative) way. And I should perhaps read what you're talking about before answering...

I actually found LPTHW pretty useless for learning OO programming. I mean, it's fine for learning the syntax of classes and how they work, but it really doesn't do much for how or why you would want to use them.

His first example of a class is "let's see what that game we made would look like if we used classes." Then he makes a 'game' class and throws the entire program into it. My reaction on seeing that was that classes were either pointless, or this was a terrible example of how to use a class.

German Joey
Dec 18, 2004
Is there any way to check if a method is decorated? (and decorated with what?)

ComptimusPrime
Jan 23, 2006
Computer Transformer

Not My Leg posted:

I actually found LPTHW pretty useless for learning OO programming. I mean, it's fine for learning the syntax of classes and how they work, but it really doesn't do much for how or why you would want to use them.

His first example of a class is "let's see what that game we made would look like if we used classes." Then he makes a 'game' class and throws the entire program into it. My reaction on seeing that was that classes were either pointless, or this was a terrible example of how to use a class.

I would argue that this is a failing of all language specific programming books. At least those that I have read. None of them cover why you would use OO or how to truly use it effectively.

Simply covering what a class is and what an object is, is insufficient for learning object oriented design.

Hughlander
May 11, 2005

German Joey posted:

Is there any way to check if a method is decorated? (and decorated with what?)

http://schinckel.net/2012/01/20/get-decorators-wrapping-a-function/ talks about it...

Suspicious Dish
Sep 24, 2011

2020 is the year of linux on the desktop, bro
Fun Shoe

German Joey posted:

Is there any way to check if a method is decorated? (and decorated with what?)

Why would you ever need to do this?

Not My Leg
Nov 6, 2002

AYN RAND AKBAR!

ComptimusPrime posted:

I would argue that this is a failing of all language specific programming books. At least those that I have read. None of them cover why you would use OO or how to truly use it effectively.

Simply covering what a class is and what an object is, is insufficient for learning object oriented design.

I would agree, and I don't know how much I actually mean that to be a criticism of LPTHW (even though it did come out that way). Since we're on the subject, anyone have a good resource for learning object oriented design?

tef
May 30, 2004

-> some l-system crap ->

German Joey posted:

Is there any way to check if a method is decorated? (and decorated with what?)

Yes. What are you trying to do from the outset ?

ComptimusPrime
Jan 23, 2006
Computer Transformer

Not My Leg posted:

I would agree, and I don't know how much I actually mean that to be a criticism of LPTHW (even though it did come out that way). Since we're on the subject, anyone have a good resource for learning object oriented design?

The only book I can ever recommend is The Object-Oriented Thought Process by Weisfeld. It is not perfect, but it is good. And it is only 200 pages, which I feel is pretty adequate.

Sockser
Jun 28, 2007

This world only remembers the results!




Tried googling this. Probably wasn't using the right terms... combined OSX/Python question.

Working on a project for my machine learning course (Written in Python). Group member designed it to run paralleled so it's spawning 1-5 processes at once. Cool. On my friend's Windows machine, this eats up 100% of his CPU and blazes through the work it has to do. On my Quad core mac, with Chrome, Safari, Mail, Pages, Spotify, iTunes, and Steam running in addition to it, I'm running at around 35% CPU, though each Python process says 100%?

His windows machine of comparable specs is knocking out roughly three times as much data processing as mine, and the entire goal of this part of the project is to run the learning algorithm with different parameters and compare them... so I kinda want this poo poo to run fast.

So my question is uhhhh... is there a way to force CPU priority on python in general (or in Python when I create the process)? Each new process spawned by our app has a unique pid so I can't just sit here and call nice on it every five seconds.

ComptimusPrime
Jan 23, 2006
Computer Transformer
You have 8 virtual cores. 4 cores * 2 due to hyper threading. You will need to up the process count.

raymond
Mar 20, 2004

German Joey posted:

Is there any way to check if a method is decorated? (and decorated with what?)

Suspicious Dish posted:

Why would you ever need to do this?

I'll sort of answer both.

I'm building a framework and want to allow people to define functions as normal ones (return something) or asynchronous ones that pass the result into a callback function.

I wanted to determine if a function was decorated with http://www.tornadoweb.org/documentation/_modules/tornado/gen.html#engine

This is what I did. I welcome suggestions for improvement because it's pretty weird.
code:
def is_engine(func):
    return func.func_code is engine_func_code
engine_func_code = tornado.gen.engine(object).func_code

class FormButton(object):

    def __init__(self, action_func):
        self._generator = is_engine(action_func)
        self._action_func = action_func

    @tornado.gen.engine
    def __call__(self, form, callback=None):
        if self._generator:
            result = yield tornado.gen.Task(self._action_func, form)
        else:
            result = self._action_func(form)
        callback(result)

raymond fucked around with this message at 10:18 on Apr 5, 2012

Sockser
Jun 28, 2007

This world only remembers the results!




ComptimusPrime posted:

You have 8 virtual cores. 4 cores * 2 due to hyper threading. You will need to up the process count.

Thing is, the data I'm mining runs the same algorithm five times per generation, so five is kinda the max I can spawn...

Is that the only way to speed it up?

ComptimusPrime
Jan 23, 2006
Computer Transformer
I am not familiar with the problem. So I have no idea. Process two generations at the same time?

Captain Capacitor
Jan 21, 2008

The code you say?
The second reply here might give you a way to set a nice limit for the processes.

Sockser
Jun 28, 2007

This world only remembers the results!




ComptimusPrime posted:

I am not familiar with the problem. So I have no idea. Process two generations at the same time?

Teaching a computer to play checkers. Each generation starts with 15 'solutions', they're mutated into 15 more, and mine plays each of the 30 against a random 5. 15 best of the 30 move on to the next generation. So, processing more than one at a time doesn't really make sense.

^^^this thread looks like it might work! Trying to un-limit the processes, not limit them, but, I'll give it a go tomorrow.

ComptimusPrime
Jan 23, 2006
Computer Transformer
Well you could restate the solution. Run 2 generations at the same time, combine the results by taking the set of 30 all the way through. At each step the ai agent could gain information from each distinct generation.

Of course I do not really know much about chess, so this solution may be pointless.

ynohtna
Feb 16, 2007

backwoods compatible
Illegal Hen
Running parallel simulations and interbreeding the survivors between them is also a highly effective way of rapidly evolving optimal solutions. (GAs are funny like that: fundamentally simple but all the magic happens in the system tweaking and nurturing.)

German Joey
Dec 18, 2004

raymond posted:

I'll sort of answer both.

I'm building a framework and want to allow people to define functions as normal ones (return something) or asynchronous ones that pass the result into a callback function.

I wanted to determine if a function was decorated with http://www.tornadoweb.org/documentation/_modules/tornado/gen.html#engine

This is what I did. I welcome suggestions for improvement because it's pretty weird.
code:
def is_engine(func):
    return func.func_code is engine_func_code
engine_func_code = tornado.gen.engine(object).func_code

class FormButton(object):

    def __init__(self, action_func):
        self._generator = is_engine(action_func)
        self._action_func = action_func

    @tornado.gen.engine
    def __call__(self, form, callback=None):
        if self._generator:
            result = yield tornado.gen.Task(self._action_func, form)
        else:
            result = self._action_func(form)
        callback(result)

This sounds actually pretty similar to what I'm trying to do as well! In my case, users interface with a processing engine by subclassing a base "Component" class and redefining a method called "simulate." The engine is supposed to take care of finding and pre-processing data, but has no real way of knowing the minimum amount of data required, as it can vary by both quantity, quality, and condition from component to component. In the cases of a complex condition, I can have advanced users define a "simCondition" method to be called by the engine that can check to see if the input is adequate. However, most components will be simple, requiring only that all input-slots have *something* in them or that all input slots have a minimum quantity of *something* in them (e.g. like 10s worth of data in each slot). The easiest interface for that is to define a decorator on the simulate method such as "@combinational" in the first case or "@runTime(10)" in the second.

Thanks for all the help, from both you and Hughlander!

Suspicious Dish
Sep 24, 2011

2020 is the year of linux on the desktop, bro
Fun Shoe
If you want a decorator to act as a flat, what about :

code:
def combinatorial(f):
    f.is_combinatorial = True
    return f
and then when you want to check:

code:
if getattr(f, "is_combinatorial", False):
     do_combinatorial_things(f)
You can adapt this to runTime as well:

code:
def runTime(sec):
    def inner(f):
        f.run_time = sec
        return f
    return inner

# ...

def do_a_thing(f):
    run_time = getattr(f, "run_time", 0)
    if run_time > 0:
        do_run_timey_things(f, run_time)
    else:
        do_non_run_timey_things(f)

JetsGuy
Sep 17, 2003

science + hockey
=
LASER SKATES
I had to reinstall python completely today. gently caress macports forever. That poo poo is an insidious disease that really fucks your system.

:downs: -m32? gently caress YOU, I KNOW BETTER

:downs: NO REFUSE TO PAY ATTENTION TO ANY OTHER BUILDS! EVERYTHING MUST BE IN THE OPT FOLDER OR IT DOESN'T EXIST!

Seriously, I had a compiler issue with perl because for whatever reason, heasoft was using the macports perl (which is poo poo, perl is poo poo).

So I had enough of macports being a bitch, and uninstalled the whole thing. This meant having to install python and ipython (etc etc) again, but it was remarkably pleasant how easy it was this time around.

I'm not looking forward to doing it when I get home on the Lion machine.

FoiledAgain
May 6, 2007

Not sure if this belongs here or the scientific computing thread, but I think this is more of a Python question. I'm trying use the facecolors argument in matplotlib's plot_surface() and I'm getting this error back:

code:
surf = ax.plot_surface(X,Y,Z,facecolors=cm.jet(N),linewidth=0, antialiased=False)

>>> 
Traceback (most recent call last):
  File "C:\Python27\heat_plots01.py", line 217, in <module>
    plotstuff()
  File "C:\Python27\heat_plots01.py", line 199, in plotstuff
    linewidth=0, antialiased=False)
  File "C:\Python27\lib\site-packages\mpl_toolkits\mplot3d\axes3d.py", line 733, in plot_surface
    colset = self._shade_colors(colset, normals)
  File "C:\Python27\lib\site-packages\mpl_toolkits\mplot3d\axes3d.py", line 792, in _shade_colors
    for c, v in zip(color, shade)]
  File "C:\Python27\lib\site-packages\matplotlib\colors.py", line 353, in to_rgba
    raise ValueError('to_rgba: Invalid rgba arg "%s"\n%s' % (str(arg), exc))
ValueError: to_rgba: Invalid rgba arg "0.0"
to_rgb: Invalid rgb arg "0.0"
cannot convert argument to rgb sequence
The N in facecolors=cm.jet(N) is a list of floats in [0,1], which I think is the appropriate thing to give to facecolors. Any suggestions?


Edit: forgot to make clear the real problem. There are no values of 0.0 in the N that I supply. This value only shows up in a new list returned by cm.jet.

FoiledAgain fucked around with this message at 22:23 on Apr 6, 2012

JetsGuy
Sep 17, 2003

science + hockey
=
LASER SKATES

FoiledAgain posted:

Not sure if this belongs here or the scientific computing thread, but I think this is more of a Python question. I'm trying use the facecolors argument in matplotlib's plot_surface() and I'm getting this error back:

code:
surf = ax.plot_surface(X,Y,Z,facecolors=cm.jet(N),linewidth=0, antialiased=False)

>>> 
Traceback (most recent call last):
  File "C:\Python27\heat_plots01.py", line 217, in <module>
    plotstuff()
  File "C:\Python27\heat_plots01.py", line 199, in plotstuff
    linewidth=0, antialiased=False)
  File "C:\Python27\lib\site-packages\mpl_toolkits\mplot3d\axes3d.py", line 733, in plot_surface
    colset = self._shade_colors(colset, normals)
  File "C:\Python27\lib\site-packages\mpl_toolkits\mplot3d\axes3d.py", line 792, in _shade_colors
    for c, v in zip(color, shade)]
  File "C:\Python27\lib\site-packages\matplotlib\colors.py", line 353, in to_rgba
    raise ValueError('to_rgba: Invalid rgba arg "%s"\n%s' % (str(arg), exc))
ValueError: to_rgba: Invalid rgba arg "0.0"
to_rgb: Invalid rgb arg "0.0"
cannot convert argument to rgb sequence
The N in facecolors=cm.jet(N) is a list of floats in [0,1], which I think is the appropriate thing to give to facecolors. Any suggestions?


Edit: forgot to make clear the real problem. There are no values of 0.0 in the N that I supply. This value only shows up in a new list returned by cm.jet.

Can you give the place where you explicitly define N? I suspect you unwittingly are adding in a 0 and not knowing it. Happened to me a bunch of times.

Also, there's a scientific computing thread?

vikingstrike
Sep 23, 2007

whats happening, captain

JetsGuy posted:

I had to reinstall python completely today. gently caress macports forever. That poo poo is an insidious disease that really fucks your system.

:downs: -m32? gently caress YOU, I KNOW BETTER

:downs: NO REFUSE TO PAY ATTENTION TO ANY OTHER BUILDS! EVERYTHING MUST BE IN THE OPT FOLDER OR IT DOESN'T EXIST!

Seriously, I had a compiler issue with perl because for whatever reason, heasoft was using the macports perl (which is poo poo, perl is poo poo).

So I had enough of macports being a bitch, and uninstalled the whole thing. This meant having to install python and ipython (etc etc) again, but it was remarkably pleasant how easy it was this time around.

I'm not looking forward to doing it when I get home on the Lion machine.

Not sure what all you use module wise, but look at SciPySuperpack. It's a bash script that will build numpy, scipy, matplotlib, statsmodels, pymc, pandas, and ipython against the Apple default Python and all you'll need additionally is Xcode.

Otherwise I use the python.org site to install 2.7 or use homebrew instead of macports to install it.

JetsGuy
Sep 17, 2003

science + hockey
=
LASER SKATES

vikingstrike posted:

Not sure what all you use module wise, but look at SciPySuperpack. It's a bash script that will build numpy, scipy, matplotlib, statsmodels, pymc, pandas, and ipython against the Apple default Python and all you'll need additionally is Xcode.

Otherwise I use the python.org site to install 2.7 or use homebrew instead of macports to install it.

This whole experience has soured me on macports, and I was already soured on fink and god help us, easy_install. I'm just going to install all my own poo poo from now on.

Also, :smug: of course I have Xcode, what kind of pleb do you think I am?

Adbot
ADBOT LOVES YOU

OnceIWasAnOstrich
Jul 22, 2006

JetsGuy posted:

This whole experience has soured me on macports, and I was already soured on fink and god help us, easy_install. I'm just going to install all my own poo poo from now on.

Also, :smug: of course I have Xcode, what kind of pleb do you think I am?

I am perfectly fine with easy_install (actually pip) for most non-numpy/scipy things, but fink and macports are the enemy. Homebrew for things that have a recipe, the installer for things with an installer, and pip for everything else.

  • Locked thread