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
ArcticZombie
Sep 15, 2010
EDIT: I've just realized that I don't even need the De Casteljau algorithm so this post is pretty pointless now...

Thermopyle posted:

For one thing, follow the Coding Horrors thread.

I've got a coding horror for you right here.

I'm trying to implement De Casteljau's algorithm. It gives the wrong results though and I don't know why. Here's the code:

Python code:
def de_casteljau(points, t):
    points_x = []
    points_y = []
    for point in points:
        points_x.append(point[0])
        points_y.append(point[1])

    num_points = len(points)

    coords_x = []
    coords_y = []

    for i in range(num_points):
        n = num_points - i
        x = (((1-t)**(n-i))*(t**i))*(points_x[i])
        y = (((1-t)**(n-i))*(t**i))*(points_y[i])
        coords_x.append(x)
        coords_y.append(y)

    print(sum(coords_x), sum(coords_y))
Where points is a list of points and those points being:

code:
A = (1300, 300)
B = (1080, 1100)
C = (600, -400)
D = (320, 540)
And t being 0.4, I get 476.8888888888889, 229.28. I'm pretty sure it should be 722.5600000000001, 279.84 (obtained by doing it (1-t)**3 * A[0] ...).

What's wrong with my De Casteljau implementation?

ArcticZombie fucked around with this message at 14:54 on Mar 16, 2013

Adbot
ADBOT LOVES YOU

My Rhythmic Crotch
Jan 13, 2011

Hmm, I just tried it. Pseudo code taken from here: http://www.cs.mtu.edu/~shene/COURSES/cs3621/NOTES/spline/Bezier/de-casteljau.html
Python code:
def de_casteljau(P, u):
	n = len(P)
	Q = list(P)
	for k in range(1,n):
		for i in range(0,n-k):
			Q[i] = ((1.0-u)*Q[i][0]+u*Q[i+1][0],(1.0-u)*Q[i][1]+u*Q[i+1][1])
	return Q[0]
	
def main():
	points = []
	points.append((1300, 300))
	points.append((1080, 1100))
	points.append((600, -400))
	points.append((320, 540))
	u = 0.4
	print de_casteljau(points, u)

if __name__ == "__main__":
	main()
Produces (940.6400000000001, 459.36). I'm sure it's not even close to right.

the
Jul 18, 2004

by Cowcaster
Two questions:

1. How can I automatically save the PNG file from a pylab plot? I want to save a bunch and animate them.

2. Also, why doesn't this work:

Python code:
pylab.title('Fields on the x-axis at t= ',timer,'s')

Modern Pragmatist
Aug 20, 2008

the posted:

Two questions:

1. How can I automatically save the PNG file from a pylab plot? I want to save a bunch and animate them.

You just specify the path to the output PNG as the first argument to savefig. http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.savefig

the posted:

2. Also, why doesn't this work:
Python code:
pylab.title('Fields on the x-axis at t= ',timer,'s')

Where did you look that made you think that would work? The documentation doesn't say anything about concatenating additional inputs. Try something like:

Python code:
pylab.title('Fields on the x-axis at t= %d s' % timer)

the
Jul 18, 2004

by Cowcaster
Can you explain to me what you're doing in that last line? Thanks.

edit:

I'm using the savefig command, but having some issues. I'm having an integer N that goes from 1 to 20, and I want to save files 1 thru 20. I don't think the savefig command likes the integer I'm using, so I tried converting it to a string, but it's still not working:

Python code:
        #Plot#
        half = numpy.around(x.size/1.9999)-1
        estore = numpy.sqrt(e0)*ey[:,half,half]
        bstore = bz[:,half,half]/numpy.sqrt(mu0)
        pylab.figure(1)
        pylab.title('Fields on the x-axis at t=s')
        pylab.ylabel('Fields')
        pylab.xlabel('x')
        pylab.plot(x,estore,'b.-',x,bstore,'r.-')
        str(N)
        pylab.savefig(N)
Spits out:

quote:

Traceback (most recent call last):
File "C:\Users\gronke\Dropbox\physics\em4.py", line 114, in <module>
pylab.savefig(N)
File "C:\Python27\lib\site-packages\matplotlib\pyplot.py", line 471, in savefig
return fig.savefig(*args, **kwargs)
File "C:\Python27\lib\site-packages\matplotlib\figure.py", line 1172, in savefig
self.canvas.print_figure(*args, **kwargs)
File "C:\Python27\lib\site-packages\matplotlib\backends\backend_wxagg.py", line 100, in print_figure
FigureCanvasAgg.print_figure(self, filename, *args, **kwargs)
File "C:\Python27\lib\site-packages\matplotlib\backend_bases.py", line 2017, in print_figure
**kwargs)
File "C:\Python27\lib\site-packages\matplotlib\backends\backend_agg.py", line 453, in print_png
filename_or_obj, self.figure.dpi)
TypeError: Object does not appear to be a 8-bit string path or a Python file-like object


edit: I changed it to:

Python code:
pylab.savefig(str(N))
And it worked! :)

the fucked around with this message at 22:20 on Mar 18, 2013

evensevenone
May 12, 2001
Glass is a solid.
str(N) is a function that takes N as an argument, and returns a string.
If you just do
code:
str(N)
, you aren't telling it to do anything with what it returned, so it's just going to get rid of it.

If you do
code:
savefig(str(N))
, you're saying "take N, make a string with N, and use that string as the filename for savefig.

If you wanted to do what you were trying originally, you'd want something like
code:
filename = str(N)
pylab.savefig(filename)
That might actually be something worth doing, so if you come back to the code later and don't remember what the arguments of pylab.savefig() are, it'll be easy to see what you were doing.

az jan jananam
Sep 6, 2011
HI, I'M HARDCORE SAX HERE TO DROP A NICE JUICY TURD OF A POST FROM UP ON HIGH
Are there any resources with interesting/challenging python exercises for someone with novice-intermediate Python skills?

Emacs Headroom
Aug 2, 2003

az jan jananam posted:

Are there any resources with interesting/challenging python exercises for someone with novice-intermediate Python skills?

Python Challenge!

Lysidas
Jul 26, 2002

John Diefenbaker is a madman who thinks he's John Diefenbaker.
Pillbug
Rosalind is a platform for learning bioinformatics through problem solving.

The problems are quite neat; my only gripe with the site is that they recommend installing Python 2 instead of 3.

Nippashish
Nov 2, 2005

Let me see you dance!

Lysidas posted:

The problems are quite neat; my only gripe with the site is that they recommend installing Python 2 instead of 3.

Probably because the scientific python world still lives in 2.7.

JetsGuy
Sep 17, 2003

science + hockey
=
LASER SKATES

the posted:

Can you explain to me what you're doing in that last line? Thanks.

edit:

I'm using the savefig command, but having some issues. I'm having an integer N that goes from 1 to 20, and I want to save files 1 thru 20. I don't think the savefig command likes the integer I'm using, so I tried converting it to a string, but it's still not working:

Python code:
        #Plot#
        half = numpy.around(x.size/1.9999)-1
        estore = numpy.sqrt(e0)*ey[:,half,half]
        bstore = bz[:,half,half]/numpy.sqrt(mu0)
        pylab.figure(1)
        pylab.title('Fields on the x-axis at t=s')
        pylab.ylabel('Fields')
        pylab.xlabel('x')
        pylab.plot(x,estore,'b.-',x,bstore,'r.-')
        str(N)
        pylab.savefig(N)
Spits out:



edit: I changed it to:

Python code:
pylab.savefig(str(N))
And it worked! :)

The, I use matplotlib virtually every day, and I have to recommend against using pylab. It's really a big mistake, and even the matplotlib documentation recommends against it. Pylab, as I remember it, is numpy and pyplot in the same namespace. This is rather wreckless and also doesn't hammer home which functions are in numpy and which are in pyplot. Generally, this isn't a huge deal, but I definitely prefer it. Pylab could be (slightly) better if you were making a program in which you wanted to interact with your graph, but even then, the only difference that I can think of would be simply one of convenience.

Also, as another suggestion, I used to make plots using figures also, but I moved on to using subplots. Even if you are making ONE subplot, it's a decent habit to get into and many of the commands are basically the same. Most of them just require a "set_" in front of the commands you are used to. For example, your plot above may turn into:

Python code:
#Plot#
        half = numpy.around(x.size/1.9999)-1
        estore = numpy.sqrt(e0)*ey[:,half,half]
        bstore = bz[:,half,half]/numpy.sqrt(mu0)

        fig = pyplot.figure(1)
        ax1 = fig.add_subplot(111)
        ax1.set_title('Fields on the x-axis at t=s')
        ax1.set_ylabel('Fields')
        ax1.set_xlabel('x')
        ax1.plot(x,estore,'b.-',x,bstore,'r.-')
        outfile_name = str(N)
        fig.savefig(outfile_name)
This has the huge added benefit of making it very easy for you to get into putting in a second plot if you need it. For example:

Python code:
#Plot#
        half = numpy.around(x.size/1.9999)-1
        estore = numpy.sqrt(e0)*ey[:,half,half]
        bstore = bz[:,half,half]/numpy.sqrt(mu0)

        fig = pyplot.figure(1)
        ax1 = fig.add_subplot(211)   #LOOK HERE!!!!
        ax1.set_title('Fields on the x-axis at t=s')
        ax1.set_ylabel('Fields')
        ax1.set_xlabel('x')
        ax1.plot(x,estore,'b.-',x,bstore,'r.-')

        ax2 = fig.add_subplot(212)  #BEGIN SECOND PLOT UNDERNEATH!
        ax2.set_title('Hurf over Time')
        ax2.set_xlabel('Time (s)')
        ax2.set_ylabel('Hurf (MegaHurfs)')
        ax2.errorbar(time, hurf, yerr=hurf_err, ecolor='#CDCDCD',
                     elinewidth=1.0, linestyle="None")
        #End subplot I added


        title_name = str(N)
        fig.savefig(title_name)
That little three digit code is telling pyplot to use a preset grid (of equal spacing). You're saying for ax1, you want to make the plot the first plot in a 2x1 array. That is, the first digits designate the array, and the last sets what figure you're talking about.

You can also manually set how big you want the subplots to be, which I find useful if I'm plotting residuals of a fit for example.

Just a few suggestions. These are really style choices, but I really never use the figure space ever anymore.

Emacs Headroom
Aug 2, 2003
Has anyone used DiscoProject for anything serious? I just got it up and running on our lab cluster, and I'm moving some computation stuff to it (and I'm thinking about adding some functionality to automatically spool up EC2 instances and add them in to supplement when we need to). It's definitely on the immature side, but so is Hadoop I guess. Anyone got good / bad /indifferent stories on using it in the wild?

OnceIWasAnOstrich
Jul 22, 2006

Emacs Headroom posted:

Has anyone used DiscoProject for anything serious? I just got it up and running on our lab cluster, and I'm moving some computation stuff to it (and I'm thinking about adding some functionality to automatically spool up EC2 instances and add them in to supplement when we need to). It's definitely on the immature side, but so is Hadoop I guess. Anyone got good / bad /indifferent stories on using it in the wild?

I don't know about Disco but for all your Python automated EC2 needs everything is already there in StarCluster.

Dominoes
Sep 20, 2007

I'm new to Python and programming. Which GUI do you recommend? There's lots of info on the internet, with conflicting opinions, much of which may be out of date. The most popular seem to be TKinter and wxPython. I've heard each is easier to use from different sources, and wxPython looks better/more native for every OS. I've also heard reverences to gtk and qt. Which do you prefer, and why?

Any tips for getting notepad++ to run Python code through IDLE?

Dominoes fucked around with this message at 15:52 on Mar 20, 2013

Emacs Headroom
Aug 2, 2003
I've used wxWidgets for a small project, and if I was doing it over I would use QT instead. wxWidgets has problems being actually good at cross-platform (especially on OSX), and the style is not good. Using the MVC pattern in QT will be better, as it's a more modern (and sane) way to organize GUIs and other systems use that kind of pattern.

aeverous
Nov 13, 2009

Dominoes posted:

I'm new to Python and programming. Which GUI do you recommend? There's lots of info on the internet, with conflicting opinions, much of which may be out of date. The most popular seem to be TKinter and wxPython. I've heard each is easier to use from different sources, and wxPython looks better/more native for every OS. I've also heard reverences to gtk and qt. Which do you prefer, and why?

Any tips for getting notepad++ to run Python code through IDLE?

I dunno why you want it through IDLE but try using the PyNPP plugin for Notepad++ and bind a key to run scripts.

evensevenone
May 12, 2001
Glass is a solid.
I've been learning Qt and loving it, much more so than tkinter and wx. The only downside is that a lot of the documentation is for C++.

It also has great cross platform support, as good as anything else or better.

accipter
Sep 12, 2003

evensevenone posted:

I've been learning Qt and loving it, much more so than tkinter and wx. The only downside is that a lot of the documentation is for C++.

It also has great cross platform support, as good as anything else or better.

I would have to second Qt via Pyside. Just look at this documentation!

JetsGuy
Sep 17, 2003

science + hockey
=
LASER SKATES

Emacs Headroom posted:

I've used wxWidgets for a small project, and if I was doing it over I would use QT instead. wxWidgets has problems being actually good at cross-platform (especially on OSX), and the style is not good. Using the MVC pattern in QT will be better, as it's a more modern (and sane) way to organize GUIs and other systems use that kind of pattern.

WxPython seemed like a great idea over Christmas break when I tried to do a GUI program. I quickly learned how awful it is with OSX. There's a lot of times where the commands simply don't work on OSX systems. You'll go mad because it's the right command, but it won't work right because WxPython just simply is intended for Windows. Period.

I should look at QT, though.

QuarkJets
Sep 8, 2008

I have used Qt and wxPython on Redhat and Windows. I couldn't say that one was necessarily better than the other, so if wxPython has Mac problems then you may as well go to Qt

Thermopyle
Jul 1, 2003

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

accipter posted:

I would have to second Qt via Pyside. Just look at this documentation!

PySide is pretty great.

Posting Principle
Dec 10, 2011

by Ralp
If you guys like PySide you should contribute to it :)

Development is mostly dead, and the mailing list is a real sad place to be these days.

DARPA
Apr 24, 2005
We know what happens to people who stay in the middle of the road. They get run over.

Dominoes posted:

I'm new to Python and programming. Which GUI do you recommend? There's lots of info on the internet, with conflicting opinions, much of which may be out of date. The most popular seem to be TKinter and wxPython. I've heard each is easier to use from different sources, and wxPython looks better/more native for every OS. I've also heard reverences to gtk and qt. Which do you prefer, and why?

Any tips for getting notepad++ to run Python code through IDLE?

If you're new to both python and programming I recommend Tkinter. It's incredibly easy to learn, handles data binding simply, and comes bundled with the standard python installation. Using the widgets from ttk makes things look nicer than Tk's reputation let's on. Just make sure the python ttk package is installed and imported. Then all it takes is changing your widget definitions like Button(...) to ttk.Button(...) and you'll get a better themed look.

wx and Qt are great, but they're also a lot to take in for very little gain when you're just learning and want to make something that adds two numbers.

QuarkJets
Sep 8, 2008

DARPA posted:

If you're new to both python and programming I recommend Tkinter. It's incredibly easy to learn, handles data binding simply, and comes bundled with the standard python installation. Using the widgets from ttk makes things look nicer than Tk's reputation let's on. Just make sure the python ttk package is installed and imported. Then all it takes is changing your widget definitions like Button(...) to ttk.Button(...) and you'll get a better themed look.

wx and Qt are great, but they're also a lot to take in for very little gain when you're just learning and want to make something that adds two numbers.

That said, all of the Tkinter examples that I've seen look like poo poo, so think of it as a good educational tool only

yippee cahier
Mar 28, 2005

Here's an interface I'm currently working on using ttk on Windows 7:


It's written in Tcl/Tk, but you could make something identical in Python quite easily. For some software that logs some data when you hit a button, it doesn't look like garbage, does it? I've chopped padding down and compressed things to use up less real estate. Don't discount Tkinter for quick and basic UIs.

That being said, we're right at the point where we're laying the groundwork to switch to Qt, but we already have a prototype and can wait a little bit to do something "properly".

BeefofAges
Jun 5, 2004

Cry 'Havoc!', and let slip the cows of war.

That looks fine to me. When I think of bad user interfaces, I think of those horrible bundled utilities from video card and motherboard manufacturers.

Jewel
May 2, 2009

sund posted:

Here's an interface I'm currently working on using ttk on Windows 7:


It's written in Tcl/Tk, but you could make something identical in Python quite easily. For some software that logs some data when you hit a button, it doesn't look like garbage, does it? I've chopped padding down and compressed things to use up less real estate. Don't discount Tkinter for quick and basic UIs.

That being said, we're right at the point where we're laying the groundwork to switch to Qt, but we already have a prototype and can wait a little bit to do something "properly".

One quick thing you could do to free up a little room is probably color "Timing Valid" and "Vertical Sync" green or red themselves rather than having to place a "yes"/"no" next to it. Still pretty easy to gather what it means and uses up less space.

Foiltha
Jun 12, 2008
What's the most Pythonic way of checking if all elements in a list are also present in another list?

I know I could probably do something like:

code:
all(element in second_list for element in first_list)
But is there a more clever way?

Edit: I also realized that this approach is O(n*m) which isn't exactly great.

Civil Twilight
Apr 2, 2011

how about
Python code:
set(first_list).issubset(second_list)

Suspicious Dish
Sep 24, 2011

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

Civil Twilight posted:

how about
Python code:
set(first_list).issubset(second_list)

This requires that all elements are hashable.

BeefofAges
Jun 5, 2004

Cry 'Havoc!', and let slip the cows of war.

Is there a module out there that could help me set up NFS, CIFS, and AFP network shares in Linux via Python? I'm doing it via subprocess right now and it's not really my favorite way to handle these things.

Dominoes
Sep 20, 2007

Thanks for the GUI advice dudes - I'm going to use QT.

aeverous posted:

I dunno why you want it through IDLE but try using the PyNPP plugin for Notepad++ and bind a key to run scripts.
IDLE is the only program I know of that runs uncompiled python scripts, other than a command line. What do you recommend instead? I'll try PyNPP.

Is there a trick to getting the pyPdf module to work? I've been able to get several other modules to install and work, including Pip, Py2exe, requests and Rauth.

If I run 'pip install pypdf', it appears to install, and populates pypdf and pypdf.... egg-info folders in python27/lib/site-packages. However, I get a crash at import module, both with 'import pypdf' and import 'pypdf2'. If I try to 'pip install pypdf2', pip can't find the package. I downloaded pypdf manually from here. Running the setup script from command prompt (setup build / setup intstall), I get an error about not finding the pypdf2 directory to install things with. If I edit the script and change the directory to the precise path, it installs a PyPDF2-1.15-py2.7.egg-info file in site-packages, but no folders, and the import command still bugs out.

Dominoes fucked around with this message at 22:32 on Mar 21, 2013

accipter
Sep 12, 2003

I think you might want to try to install pypdf2, since pypdf stopped being developed 3 years ago.

Dominoes
Sep 20, 2007

accipter posted:

I think you might want to try to install pypdf2, since pypdf stopped being developed 3 years ago.
I think that's what I'm trying to install.

aeverous
Nov 13, 2009

Dominoes posted:

IDLE is the only program I know of that runs uncompiled python scripts, other than a command line. What do you recommend instead? I'll try PyNPP.

PyNPP will basically run the script in command line for you as a shortcut, alongside other features.

OnceIWasAnOstrich
Jul 22, 2006

IPython also will run scripts from the command line or using "IPython Magic" (which does many other really cool things, like RPy2 integration) in the interpreter itself, as well as give you tab-completion, shell access, and more goodies.

fake edit: Reading comprehension failed me so I didn't realize you were talking about editor integration.

the
Jul 18, 2004

by Cowcaster
Have any of you guys used VPython? If I wanted to make a short animation of, say, a few "molecules" (basically connected spheres) moving around, could that be easily accomplished in VPython?

edit: Follow up question, how do I see my output? I installed the package from Vpython.org. I open up VIDLE and run one of their demo programs. It just ... runs... but no 3D output pops up. It looks like I need something called "Visual?"

edit: No, looks like Visual is just the module that I'm supposed to import, which I am. What the heck is going on here? Why am I not getting any windows of 3D images popping up?

final edit: Looks like VIDLE was the problem. I can run it in IPython. Bleh.

the fucked around with this message at 01:55 on Mar 22, 2013

Dominoes
Sep 20, 2007

Can anyone help me with a Python 2 to 3 conversion problem? I'm switching to Python 3, and one of the functions in a project I'm working on won't convert well. I'm looping through a website's possible urls for files until I find a valid one with URLLIB. I'm using urlopen, and verifying that the file size is a reasonable size. However, now in Python 3, I get a crash with HTTP errors when I present an invalid URL, instead of passing a bogus file, realizing it's bogus and continuing the loop.

Python 2 working code:
code:
from urllib import urlopen

def find_version():
    #Determines latest FAA procedure version by checking downloaded file size for descending dates
    print "Determining latest procedure version..."
    i = ((date.today().year + 1) % 100) * 100 + 12    
    while i > (date.today().year % 100) * 100:
        url = 'http://aeronav.faa.gov/d-tpp/%s/%s.PDF' % (str(i), all_plates[0].file_name)
        web_file = urlopen(url)
        if int(web_file.info()['Content-Length']) > 10000:
            return str(i)
        i -= 1
        if i % 100 == 0:
            i -= 88
Python 3 broken code.
code:
from urllib.request import urlopen

def find_version():
    #Determines latest FAA procedure version by checking downloaded file size for descending dates
    print ("Determining latest procedure version...")
    i = ((date.today().year + 1) % 100) * 100 + 12    
    while i > (date.today().year % 100) * 100:
        url = ('http://aeronav.faa.gov/d-tpp/%s/%s.PDF' % (i, all_plates[0].file_name))
        web_file = urlopen(url)
        if int(web_file.info()['Content-Length']) > 10000:
            return str(i)
        i -= 1
        if i % 100 == 0:
            i -= 88
Thhe code 'web_file = urlopen(url)' crashes the program if presented with an invalid URL. Passing invalid URLs to it is the point of this function, and it worked as intended before.

Error:


I've spent lots of time Googling this, and haven't found a solution.

accipter
Sep 12, 2003

Dominoes posted:

urllib in Python 3

Why don't you just surround the urlopen in a try/catch statement on urllib.error.HTTPError?

Adbot
ADBOT LOVES YOU

DoggesAndCattes
Aug 2, 2007

I made a post in here about two weeks ago asking about a cryptography assignment that I was having some major problems with. Now I've come to an assignment that's due in four hours, and I don't know what I'm doing. I don't even know how to go about it. AT ALL. I think I need to buy some beer and read the provided online book all weekend until I figure it out. Maybe I can submit it for partial credit before Monday.

http://www.openbookproject.net/thinkcs/python/english2e/index.html

  • Locked thread