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
JetsGuy
Sep 17, 2003

science + hockey
=
LASER SKATES

the posted:

I have both plots working now, but I'm having a problem where I can't do them at the same time.

I'm not putting them on the same plot. I just need two plot windows to show up.

What happens is I run the program, it calculates the plot for r versus p, and the plot pops up. The system halts until I close the plot. Then after that it continues and calculates r versus t and then shows that plot.

How can I make it pop up two windows of plots? Or better yet, how can I have two plot windows side by side?

I'm reading it may have something to do with subplot, but I'm not sure.

Here is what I have so far:

http://pastebin.com/DUzyyJjU

edit: I figured it out :) thanks for the help, though. everyone

Oh goddamnit. I probably should have read the edit before I actually spent the time to re-write the code. :doh:

I'm an idiot. I'm going to explain the answer anyway, since this is a common mistake people new to matplotlib run into.

Here's the code, I've just commented out the lines that "the" had originally in.

code:
##This is made to help "the" in the Python thread.

#pylab - because its what "the" uses
import pylab

#User Defined Parameters
r0 = int(10e15)
p0 = 1.7e-14
r = r0
rfinal = int(r*10000)

#functions

def p(r):
	return p0*pow(r/r0, -3)

def t(r):
	return t0*pow(r/r0, -2)

x = list()
y = list()

while (r < rfinal):
	x.append(r)
	y.append(p(r))
	r = r+10e15
	print len(x)

##MAKE DEM PLOTS

#pylab.plot(x,y)
#pylab.xlim([10e15,10e17])
#pylab.ylim([0,10e-19])
#pylab.show()

fig1 = pylab.figure(1, figsize = (8,8) )
ax1_1 = fig1.add_subplot(111)
ax1_1.plot(x,y, color="red")
ax1_1.set_xlim([1e16, 1e18])
ax1_1.set_ylim([0, 1e-19])

t0 = int(10e7)
r = r0


w = list()
z = list()

while (r < rfinal):
	w.append(r)
	z.append(t(r))
	r = r+10e15
	print len(w)

#pylab.plot(w,z)
#pylab.xlim([10e15,10e17])
#pylab.ylim([0,10e7])
#pylab.show()

fig2 = pylab.figure(2, figsize = (8,8))
ax2_1 = fig2.add_subplot(111)
ax2_1.plot(w,z, color="blue")
ax2_1.set_xlim([1e16, 1e17])
ax2_1.set_ylim([0, 1e8])

pylab.show()
The problem occurs because matplotlib literally stops your code when you call show(). So if you want to display multiple figures, you should call it after you have "made" the plots you want displayed.

Now, you do *not* have to use subplots to display multiple figures. However, I find that using the subplot space makes life about a million times easier. Yeah, you may not always need to make multiple plots. In fact, for me, I generally do not. However, one horror you'll run into is that the parameters for subplots end up being different for those in "figure space" for lack of a better term. For example, look at the limit commands. If I was just passing it to the figure, I'd use fig1.xlim(), but in subplot space, I use set_xlim. So basically, since I *sometimes* use subplots, I just always use it so that I always just have the syntax in my head and don't have to flip back and forth. It's a simple matter to tell matplotlib your subplot is the entire figure, that's what add_subplot(111) does.

By the way, I want to take this time to reiterate that you shouldn't use pylab. I would have imported matplotlib.pyplot, and then called the plotting commands from that module.

Even the people who make matplotlib say don't use pylab.
http://matplotlib.sourceforge.net/faq/usage_faq.html

EDIT:
I also am so obsessive about comments, that you can see that I even comment other people's code. (In this case, poorly, I was just making notes in case it took time).

Adbot
ADBOT LOVES YOU

JetsGuy
Sep 17, 2003

science + hockey
=
LASER SKATES
Using subplots in matplotlib literally changes your world and you will never go back to using what I was calling "figure space".

how!!
Nov 19, 2011

by angerbot
So I wrote a python package, and I uploaded it to pypi. It installs fine via python setup.py install, but won't install via pip install [package_name]. What am I missing? The package is here: http://pypi.python.org/pypi/django-easydump

Suspicious Dish
Sep 24, 2011

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

how!! posted:

So I wrote a python package, and I uploaded it to pypi. It installs fine via python setup.py install, but won't install via pip install [package_name]. What am I missing? The package is here: http://pypi.python.org/pypi/django-easydump

What error are you getting when trying to install it?

how!!
Nov 19, 2011

by angerbot

Suspicious Dish posted:

What error are you getting when trying to install it?

code:
(test)chris@amnesia:~$ pip install easydump 
Downloading/unpacking easydump 
  Could not find any downloads that satisfy the requirement easydump 
No distributions at all found for easydump 
Storing complete log in /Users/chris/.pip/pip.log 
(test)chris@amnesia:~$ pip install django-easydump 
Downloading/unpacking django-easydump 
  Could not find any downloads that satisfy the requirement django-easydump 
No distributions at all found for django-easydump 
Storing complete log in /Users/chris/.pip/pip.log 
(text)chris@amnesia:~$ 

Thermopyle
Jul 1, 2003

...the stupid are cocksure while the intelligent are full of doubt. —Bertrand Russell

I'm trying to figure out how to scrape the "XXXXX HAVE YOU IN CIRCLES" number from a Google+ profile page. (My page, just because I'm curious to plot trends about number of people following me and how that relates to things like posting frequency, day of the week, etc)

Before G+ redesigned this week, it was a simple matter of a regex (gasp, I know...parsing HTML with a regex). They've gone and hosed that up, and I can't quite figure out how to get that number reliably. If I search the source for "have you in circles" the text doesn't even appear, and if I search with the current actual number as shown on the web page, it shows up in a couple of places that I don't get how to parse out programmatically. It's embedded in what looks like some sort of JSON structure or something...

This may better belong to the general questions thread or somewhere, but I guess I'll start here since I'm doing it in Python.

Here's my profile: https://plus.google.com/117177689300294532641/posts

Anyone have a clue how to do this?

Suspicious Dish
Sep 24, 2011

2020 is the year of linux on the desktop, bro
Fun Shoe
You never uploaded any package. Use python setup.py sdist upload. See the documentation about PyPI for more details.

king salmon
Oct 30, 2011

by Cowcaster

Thermopyle posted:

I'm trying to figure out how to scrape the "XXXXX HAVE YOU IN CIRCLES" number from a Google+ profile page. (My page, just because I'm curious to plot trends about number of people following me and how that relates to things like posting frequency, day of the week, etc)

Before G+ redesigned this week, it was a simple matter of a regex (gasp, I know...parsing HTML with a regex). They've gone and hosed that up, and I can't quite figure out how to get that number reliably. If I search the source for "have you in circles" the text doesn't even appear, and if I search with the current actual number as shown on the web page, it shows up in a couple of places that I don't get how to parse out programmatically. It's embedded in what looks like some sort of JSON structure or something...

This may better belong to the general questions thread or somewhere, but I guess I'll start here since I'm doing it in Python.

Here's my profile: https://plus.google.com/117177689300294532641/posts

Anyone have a clue how to do this?

The correct way to do it is to use the API google provides (for free I think). If it's being generated by a script there's obviously no way to get it from parsing the HTML.

Suspicious Dish
Sep 24, 2011

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

Acallapani posted:

The correct way to do it is to use the API google provides (for free I think). If it's being generated by a script there's obviously no way to get it from parsing the HTML.

There is no official Google+ Circles API. There is an unofficial one, though.

Thermopyle
Jul 1, 2003

...the stupid are cocksure while the intelligent are full of doubt. —Bertrand Russell

Acallapani posted:

The correct way to do it is to use the API google provides (for free I think). If it's being generated by a script there's obviously no way to get it from parsing the HTML.

There isn't one that gets this information.

Suspicious Dish posted:

There is no official Google+ Circles API. There is an unofficial one, though.

Nice. I didn't want to get in to this, so glad to see someone else did it.

BigRedDot
Mar 6, 2008

Spime Wrangler posted:

Enthought's Traits + Chaco caught my eye recently because I've literally never done GUI work before and needed to get something off the ground quick. I have to say that while I'm still a bit confused on how to properly go about getting some of the traits magic to work, and while there's almost no guides on the internet, the stuff is growing on me.

Have any of you used it at all extensively? I'm probably in too deep to make it worth switching to something else, but I'm just not finding much 3rd-party info to help smooth the learning curve.
I used to work at Enthought, so sure, I've used Traits quite a bit in the past. And I contributed some parts of Chaco. I think they've both changed somewhat in the four or five years since I've used them extensively, but I might be able to answer some questions. Maybe you've seen this, but here is a tutorial session from pycon a few years ago:

http://python.mirocommunity.org/video/1690/pycon-2010-introduction-to-tra

And here's a short tutorial on traits/chaco integration:

http://drliddle.com/index.php?option=com_content&view=article&id=14:quicktuttraits&catid=3:tutorials&Itemid=6

king salmon
Oct 30, 2011

by Cowcaster
I'm using Sax to parse an XML file, and I'd like the program to stop after it finds n entries. Is there a better way to do this than to raise an error? Ideally one that doesn't require Python to stop completely.

code:
import xml.sax
from xml.sax.handler import *
    
def parse_XML(xml_filename, do_stuff, n):
    
    class QuotationHandler(ContentHandler):
        def __init__(self):
            self.title = ''
            self.in_title = 0
            self.text = ''
            self.in_text = 0
            self.c = 0
                
        def startElement(self, name, attrs):
            if name == 'title':
                self.in_title = 1
                self.c += 1
            if name == 'text':
                self.in_text = 1
                
        def endElement(self, name):

            if name == 'title':
                self.in_title = 0
                
            if name == 'text':
                
                do_stuff(self.title, self.text)

                if n != 'oo':
                    if self.c > n:
                        raise StopSaxError

                self.text = ''
                self.in_text = 0
                
                self.title = ''
                
        def characters(self, ch):
            if self.in_title:
                 self.title = self.title + ch
            if self.in_text:
                self.text = self.text + ch

    parser = xml.sax.make_parser()
    handler = QuotationHandler()
    parser.setContentHandler(handler)
    parser.parse(xml_filename)

Chimp_On_Stilts
Aug 31, 2004
Holy Hell.
I'm working on a simple script to keep track of the number of tasks someone has completed. For some reason, it gives me a syntax error on line 36. I cannot figure out why.

Let me know if you see the problem: http://pastebin.com/JZgmY7iX



Edit: Good gravy, it was simply a matter of closing some parenthesis. I spent like 45 minutes hunting for the problem =(

Chimp_On_Stilts fucked around with this message at 02:06 on Apr 16, 2012

redleader
Aug 18, 2005

Engage according to operational parameters
Count your parentheses!

The Gripper
Sep 14, 2004
i am winner

Acallapani posted:

I'm using Sax to parse an XML file, and I'd like the program to stop after it finds n entries. Is there a better way to do this than to raise an error? Ideally one that doesn't require Python to stop completely.
Is there any reason you can't just put a return where you want processing to stop?[edit; checked and yeah that just makes it go to the next start tag] Putting it in a try: except: block might be the better solution (without causing python to exit).
code:
class FakeError(Exception):
   def __init__(self, value): 
      self.value = value
   def __str__(self):
      return repr(self.value)

...
raise FakeError
...

try:
   parser.parse(xml_filename)
except FakeError:
   pass
If doing that makes sax crap out and terminate then keeping with StopSaxError and changing the except to except StopSaxError: might work better (but you then run the risk of having a legitimate StopSaxError occur, and you continuing with busted up data).

The Gripper fucked around with this message at 10:03 on Apr 16, 2012

how!!
Nov 19, 2011

by angerbot

Suspicious Dish posted:

You never uploaded any package. Use python setup.py sdist upload. See the documentation about PyPI for more details.

Ah, thanks. The problem I'm having now is the README and VERSION files (in the same folder as the setup.py file) is not being included in the package. here is my setup.py file:

https://github.com/priestc/django-easydump/blob/master/setup.py

When I run setup.py straight from from the git repo, it works, but installing from the sdist package tels me the VERSION and/or README file is not found. Did I do the package_data dict right?

Hanpan
Dec 5, 2004

I'm attempting to figure out how to load and store settings for my project. I have a settings.json file (reason for JSON is that the same file is also used in Node) and I want to create an importable "singleton" that stores a reference to each setting defined in this file. For example, I want to do something like this:

code:
import settings
print settings.SOME_SETTING
Obviously though, each time I import the JSON file I'll need to re-import and re-parse which is obviously undesirable. I had a look at the Django source code as I know they handle settings in a similar fashion but it doesn't seem to be very clear how exactly they are keeping state across the entire project.

Is there any way to do this without resorting to memcache or pickle?

TOO SCSI FOR MY CAT
Oct 12, 2008

this is what happens when you take UI design away from engineers and give it to a bunch of hipster art student "designers"
create a settings.py with a global variable to store the parsed settings. The global should be an instance of a type with overridden __getattr__ to read them.

code:
# myproject/settings.py
import json

PATH_TO_YOUR_CONFIG = "/path/to/your/config.json"

class _Settings(object):
  def __init__(self):
      self._d = None

  def _load(self):
      with open(PATH_TO_YOUR_CONFIG, "rb") as fp:
          self._d = json.load(fp)

  def __getattr__(self, name):
      if self._d is None:
          self._load()
      return self._d[name]

settings = _Settings()
code:
# myproject/main.py
from myproject.settings import settings

print settings.SOME_SETTING

Suspicious Dish
Sep 24, 2011

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

how!! posted:

Ah, thanks. The problem I'm having now is the README and VERSION files (in the same folder as the setup.py file) is not being included in the package. here is my setup.py file:

https://github.com/priestc/django-easydump/blob/master/setup.py

When I run setup.py straight from from the git repo, it works, but installing from the sdist package tels me the VERSION and/or README file is not found. Did I do the package_data dict right?

You're using setuptools. Don't do that.

Also, the way distutils constructs the distribution package is by something called a MANIFEST file. You need to look into that.

Suspicious Dish
Sep 24, 2011

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

Hanpan posted:

code:
import settings
print settings.SOME_SETTING
Obviously though, each time I import the JSON file I'll need to re-import and re-parse which is obviously undesirable.

What? So, first of all, don't use module global attributes

code:
# settings.py
settings = None
def init_settings(filename):
    settings = json.loads(filename)
code:
# app main/init
import settings
def init(self):
    settings.init_settings('settings.json')
code:
# settings using code
from settings import settings
settings['SOME_SETTING']
This should require one parse, which is at app init time. The settings module doesn't have to be kept separate, but it may be easier to that to prevent circular imports.

quaunaut
Sep 15, 2007

WHOOSH
Okay, I'm feeling extremely dumb at the moment and Google isn't exactly helping.

How exactly, does the following for loop work?

code:
for k, v in values:
I can't figure out what place the v has there. Assume the values variable is a dictionary.

Suspicious Dish
Sep 24, 2011

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

quaunaut posted:

Okay, I'm feeling extremely dumb at the moment and Google isn't exactly helping.

How exactly, does the following for loop work?

It doesn't. It would have to be

code:
for k, v in values.iteritems():

quaunaut
Sep 15, 2007

WHOOSH

Suspicious Dish posted:

It doesn't. It would have to be

code:
for k, v in values.iteritems():

Well, how would it work there, exactly? Is it simply a way of saying, "go through each key and value pair of the dictionary" until done, effectively being little more than "for i in thing"?


Edit: Thanks, both of you <3

quaunaut fucked around with this message at 03:40 on Apr 17, 2012

TOO SCSI FOR MY CAT
Oct 12, 2008

this is what happens when you take UI design away from engineers and give it to a bunch of hipster art student "designers"
there's three separate features interacting, there.

the first is that iterating over a dictionary yields its keys, in arbitrary order:

code:
>>> d = {1: "a", 2: "b", 3: "c"}
>>> for k in d:
...    print k
2
1
3
the second is that tuples are indicated with commas. the parens are largely stylistic:

code:
>>> x = 1, 2
>>> print x
(1, 2)
the third is that for loops (and also variable assignment) will automatically unpack tuples:

code:
>>> tups = [(1, "a"), (2, "b"), (3, "c")]
>>> for k, v in tups:
...    print k, v
1 a
2 b
3 c
put that together, and you can use that first code sample to iterate over a dictionary with 2-item tuples as keys.

Additionally, with the definition of 'dict.iteritems', you can get a for loop that'll iterate over all the key-value pairs in a dictionary.

Suspicious Dish
Sep 24, 2011

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

Janin posted:

the third is that for loops (and also variable assignment) will automatically unpack tuples:

code:
>>> tups = [(1, "a"), (2, "b"), (3, "c")]
>>> for k, v in tups:
...    print k, v
1 a
2 b
3 c

I just want to note that this sort of unpacking works for any iterable, not just tuples:

code:
>>> thing = [1, 2, 3]
>>> a, b, c = thing

>>> def gen():
...   for i in xrange(5):
...     yield randrange(0, 25)
>>> a, b, c, d, e = gen()
You can also do some fancy stuff like:

code:
>>> thing = [[1, 2], [3, 4]]
>>> ((a, b), (c, d)) = thing
Note that the syntax is always parens, even when we're unpacking a list. In Python 3, you can even do variable-length unpacking:

code:
>>> iters = [1, 2, 3, 4, 5, 6]
>>> a, *b, c = iters
>>> a
1
>>> b
[2, 3, 4, 5]
>>> c
6

Janin posted:

Additionally, with the definition of 'dict.iteritems', you can get a for loop that'll iterate over all the key-value pairs in a dictionary.

dict.iteritems is simply an optimization for dict.items, similar to how xrange is an optimization for range:


>>> range(10)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> xrange(10)
<xrange object>

>>> D = dict(A=1, B=2) # shorthand for {'A': 1, 'B': 2}
>>> D.items()
[('A', 1), ('B', 2)]
>>> D.iteritems()
<dictionary-itemiterator object>
>>> next(_) # '_' is a special variable for the last result in the Python REPL
('A', 1)

TOO SCSI FOR MY CAT
Oct 12, 2008

this is what happens when you take UI design away from engineers and give it to a bunch of hipster art student "designers"

Suspicious Dish posted:

I just want to note that this sort of unpacking works for any iterable, not just tuples:

code:
>>> thing = [1, 2, 3]
>>> a, b, c = thing

>>> def gen():
...   for i in xrange(5):
...     yield randrange(0, 25)
>>> a, b, c, d, e = gen()
This is possible, but ewwww, please don't do it! It violates the semantics of the types and will make anyone who reads the code hate you.

Suspicious Dish
Sep 24, 2011

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

Janin posted:

This is possible, but ewwww, please don't do it! It violates the semantics of the types and will make anyone who reads the code hate you.

Well, yeah, I wouldn't ever do that, except in cases where the length of the generated sequence is explicitly specified, like islice. Rather than miss the point I'm trying to make completely by using something like that, I'd rather write something that shows the semantics I'm talking about, and attempt to make it blatantly obvious that this was just for demonstration purposes.

... I think I failed on that last part, there.

Spime Wrangler
Feb 23, 2003

Because we can.

BigRedDot posted:

I used to work at Enthought, so sure, I've used Traits quite a bit in the past. And I contributed some parts of Chaco. I think they've both changed somewhat in the four or five years since I've used them extensively, but I might be able to answer some questions. Maybe you've seen this, but here is a tutorial session from pycon a few years ago:

http://python.mirocommunity.org/video/1690/pycon-2010-introduction-to-tra

And here's a short tutorial on traits/chaco integration:

http://drliddle.com/index.php?option=com_content&view=article&id=14:quicktuttraits&catid=3:tutorials&Itemid=6

Thanks! I actually found the second one not long after I posted that, and I've got prototypes working of the basic traits + interactive chaco stuff I'll need. Once I got the hang of the basics with that and picking apart the draggable polygon example its gone very smoothly.

I'm watching the video now, its been helpful so far.

Exergy
Jul 21, 2011

What is the best module/library for scientific data visualization? I have python 3.2 if it matters.

vikingstrike
Sep 23, 2007

whats happening, captain
Might be a stupid follow-up but are you looking for plotting libraries or data manipulation type libraries? Or neither and I will leave this to an expert. :)

Exergy
Jul 21, 2011

vikingstrike posted:

Might be a stupid follow-up but are you looking for plotting libraries or data manipulation type libraries? Or neither and I will leave this to an expert. :)

I have numpy and scipy installed. Now looking for plotting library. Basically I am trying to replicate Matlab with Python...

FoiledAgain
May 6, 2007

Tovarisch posted:

I have numpy and scipy installed. Now looking for plotting library. Basically I am trying to replicate Matlab with Python...

You want matplotlib.

OnceIWasAnOstrich
Jul 22, 2006

Tovarisch posted:

I have numpy and scipy installed. Now looking for plotting library. Basically I am trying to replicate Matlab with Python...

edit: gotta start refreshing this page before applying, matplotlab is indeed your answer

Exergy
Jul 21, 2011

Thanks, took a while to find matplotlib for 3.2 (no link on official page) but finally installed it and examples work fine.

Anyone has experience with iPython? I am trying to find an alternative to default python shell on windows, again to build something similar to matlab.

vikingstrike
Sep 23, 2007

whats happening, captain
I really enjoy iPython and at times find myself using it over the bash shell to get work done. (I can think in Python easier than bash on the fly.)

I would recommend checking out the docs because there are some pretty cool features that you can use within it.

Suspicious Dish
Sep 24, 2011

2020 is the year of linux on the desktop, bro
Fun Shoe
I do not like IPython. It made me run in circles for a while trying to figure out why my code was broken, until I realized that it was IPython that broke my code, and my code was fine.

I use bpython when I need a somewhat fancy interpreter. It doesn't work on Python 3, or Windows, though.

vikingstrike
Sep 23, 2007

whats happening, captain

Suspicious Dish posted:

I do not like IPython. It made me run in circles for a while trying to figure out why my code was broken, until I realized that it was IPython that broke my code, and my code was fine.

I use bpython when I need a somewhat fancy interpreter. It doesn't work on Python 3, or Windows, though.

Out of curiosity now, what was iPython doing? I usually just use it for one off things, but I'll move to something else if it's broken.

Suspicious Dish
Sep 24, 2011

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

vikingstrike posted:

Out of curiosity now, what was iPython doing? I usually just use it for one off things, but I'll move to something else if it's broken.

I don't know, and I didn't investigate why it failed on IPython, just that it did, and I didn't care at that point as I had already lost several hours to it. It was failing with a weird exception when I added a __getattr__ to my class. Removing it made it work fine in IPython.

Both versions worked fine under Python.

Catalyst-proof
May 11, 2011

better waste some time with you
ipython for me is a necessity. It's the first think I install in any virtualenv, and I've never once had a problem with it. Debugging code you input is as easy as %debug.

Adbot
ADBOT LOVES YOU

Exergy
Jul 21, 2011

What was the main motivation for all the changes in Python 3.x?

I had problems installing matplotlib for 3.2, now having problems with ipython since it wants setuptools, which in turn are not available for 3.2. Half of the examples from the book I have don't work with 3.2 and require changes... I mean there should be some strong reasons for such dramatic changes, especially if the language is well established and already has a lot of supporters.

  • Locked thread