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
tef
May 30, 2004

-> some l-system crap ->
I assume listEntry is some sort of object?

You are adding the same object over and over to the list in ranges. Something like this is what you want to do :

code:
for line in file:
     listEntry = NewSomeKindOfObject()
     listEntry.name = line[ searchPos_a + 9 : searchPos_b ]
     ranges.append(listEntry)

Here is another example for you:

Here we are chaning the contents of the list in each loop, and adding that list to
the output:
code:
>>> a = [0]; o = []
>>> for x in range(1,10):
...     a[0] = x
...     o.append(a)
... 
>>> o
[[9], [9], [9], [9], [9], [9], [9], [9], [9]]
Here we are creating a *new* list and adding that to the output:
code:
>>> for x in range(1,10):
...     a = [x] 
...     o.append(a)
... 
>>> o
[[1], [2], [3], [4], [5], [6], [7], [8], [9]]
>>>

Adbot
ADBOT LOVES YOU

pankus
Jul 30, 2003
Yeah, listEntry was an object and I had it outside the for loop. Thanks for the help.

Scaevolus
Apr 16, 2007

darknife posted:

Works!

Thanks!

code:
def isright(x1,y1,x2,y2,x3,y3):
	a = ((x2-x1)**2 + (y2-y1)**2)**.5
	b = ((x3-x2)**2 + (y3-y2)**2)**.5
	c = ((x1-x3)**2 + (y1-y3)**2)**.5
	#sort smallest to largest thanks wrok
	mysortedlist = sorted([a,b,c])
	smallest = mysortedlist[0]
	next = mysortedlist[1]
	biggest = mysortedlist[2]
	#calculate 
	if (smallest**2 + next**2) == biggest**2:
		print "Yes, it is a right triangle."
	else: print " No it is not a right triangle."

	
>>> isright(-2,2,-1,6,3,5)
Yes, it is a right triangle.
Janky function but works for what I need it to do.
You want to be careful when you compare floats for equality-- it's really easy to run into precision errors.
code:
>>> 2.4999999999==2.5
False
You need to check whether the difference is smaller than some arbitrarily small number (1e-9, perhaps?).

Or even better, you can avoid the sqrt altogether, meaning no floating-point calculations if the inputs are integers. Argument unpacking can help make your code more concise as well.
code:
def isright(x1, y1, x2, y2, x3, y3):
    a = ((x2 - x1) ** 2 + (y2 - y1) ** 2 ) ** .5
    b = ((x3 - x2) ** 2 + (y3 - y2) ** 2 ) ** .5
    c = ((x1 - x3) ** 2 + (y1 - y3) ** 2 ) ** .5
    a, b, c = sorted([a, b, c])
    if a + b == c:		
        print "Yes, it is a right triangle."
    else: 
        print "No, it is not a right triangle."

>>> isright(-2, 2, -1, 6, 3, 5)
Yes, it is a right triangle.

Scaevolus fucked around with this message at 08:02 on Feb 27, 2009

pankus
Jul 30, 2003
So I have come across another problem with lists and references it would seem.

The problem happens here:

code:
ranges[listIndex].rowFlag = True
ranges[listIndex].numData.append( [] )
This is causing [] to be appended to numData in all the objects in the ranges list, not just the index that I want. rowFlag is correctly updated for the index and none of the other list objects.

Pooball
Sep 21, 2005
Warm and squishy.

pankus posted:

So I have come across another problem with lists and references it would seem.

The problem happens here:

code:
ranges[listIndex].rowFlag = True
ranges[listIndex].numData.append( [] )
This is causing [] to be appended to numData in all the objects in the ranges list, not just the index that I want. rowFlag is correctly updated for the index and none of the other list objects.

How are you creating the numData lists? Sounds like all the numData members are referencing the same object. For example,

code:
>>> a=b=[]
>>> a.append(1)
>>> b
[1]
>>> a,b
([1], [1])
Using instead "a=[]; b=[]" would create two separate lists.

Benji the Blade
Jun 22, 2004
Plate of shrimp.
Edit:: ^^ This ^^

numData is almost certainly a reference to the same list in every item in ranges. You don't include the code where you assign numData, but make sure you're constructing a new object for each entry in ranges if you want each numData to be different.

Again, variables in Python are just labels that point to data somewhere in memory. The equals operator doesn't copy anything but references (at least usually).

pankus
Jul 30, 2003
Thanks again.
In my object definition I was setting numData=[] as the default value in the __init__ which was the problem.

Vexed Morgan
Dec 22, 2008

Please ignore me I am illiterate

Vexed Morgan fucked around with this message at 05:39 on Feb 28, 2009

yippee cahier
Mar 28, 2005

I feel like a moron. How do I modify the original string references so the changes I make are visible outside of this loop?
code:
#null terminate our strings
for tag in [make,model,software,time,uniquecameramodel,copyright]:
    tag.ljust(len(tag) + 1 + len(tag)%2, '\0')  #dng_validate complains if we have an odd string length
Use a dict instead?

such a nice boy
Mar 22, 2002

sund posted:

I feel like a moron. How do I modify the original string references so the changes I make are visible outside of this loop?
code:
#null terminate our strings
for tag in [make,model,software,time,uniquecameramodel,copyright]:
    tag.ljust(len(tag) + 1 + len(tag)%2, '\0')  #dng_validate complains if we have an odd string length
Use a dict instead?

ljust returns a new string.

tag = tag.ljust(len(tag) + 1 + len(tag)%2, '\0')

Benji the Blade
Jun 22, 2004
Plate of shrimp.

such a nice boy posted:

ljust returns a new string.

tag = tag.ljust(len(tag) + 1 + len(tag)%2, '\0')

That won't do anything, because you assign the left justified returned string to tag, which is then overwritten at the top of the for loop by whatever's next in the list.

Instead, you'll want to build a new list:

code:
def adjust_strs(str_list):
    return [tag.ljust(len(tag) + 1 + len(tag) % 2, '\0') for tag in str_list]

adjusted_strs = adjust_strs([make, model, software, time, uniquecameramodel, copyright])
If it's really important to do it in place, you could do this instead:

code:
def adjust_strs_inplace(str_list):
    for i in range(len(str_list)):
        str_list[i] = str_list[i].ljust(len(tag) + 1 + len(tag) % 2, '\0')

adjusted_strs = [make, model, software, time, uniquecameramodel, copyright]
adjust_strs_inplace(adjusted_strs)
But that's a little more verbose and may not actually be any faster, depending on the data. In this case, you're still not altering the strings in place, you're just not creating a new list, but instead replacing all the items in your first list.

Benji the Blade fucked around with this message at 19:10 on Feb 28, 2009

tayl0r
Oct 3, 2002
This post brought to you by SOE
I'm using Django with Google App Engine and I can't seem to figure out how to display a specific element from a list, when the element index is contained in another variable.

I have a list called contentType. It's a simple list with elements 0 through 4.
I have a variable (I guess a dict?) called adventure. It's from my datamodel and has a property called contentType, so adventure.contentType is the integer of the index I want to display.

I basically want this: contentType[adventure.contentType]
But that doesn't work. I can't figure what does.

I tried {{ contentType|splice:"3:"|first }}
This works and gives me back the 4th element.
When I changed it to {{ contentType|splice:"adventure.contentType:"|first }} it just gives me back the 1st element.

I can also do {{ contentType.3 }}, which gives me back the 4th element. How can I use a variable there instead of hard coding the number?

I guess I could just do this little bit of logic in the python and pass that variable into the template but it seems like there should be a way to do it here, in the template.

uncleTomOfFinland
May 25, 2008

tayl0r posted:

I'm using Django with Google App Engine and I can't seem to figure out how to display a specific element from a list, when the element index is contained in another variable.

I have a list called contentType. It's a simple list with elements 0 through 4.
I have a variable (I guess a dict?) called adventure. It's from my datamodel and has a property called contentType, so adventure.contentType is the integer of the index I want to display.

I basically want this: contentType[adventure.contentType]
But that doesn't work. I can't figure what does.

I tried {{ contentType|splice:"3:"|first }}
This works and gives me back the 4th element.
When I changed it to {{ contentType|splice:"adventure.contentType:"|first }} it just gives me back the 1st element.

I can also do {{ contentType.3 }}, which gives me back the 4th element. How can I use a variable there instead of hard coding the number?

I guess I could just do this little bit of logic in the python and pass that variable into the template but it seems like there should be a way to do it here, in the template.

That's more of a Django question than a Python question, try this thread.

EDIT: Could'nt you just use contentType[adventure.contentType] as a template argument?

uncleTomOfFinland fucked around with this message at 12:31 on Mar 1, 2009

tayl0r
Oct 3, 2002
This post brought to you by SOE
Yeah, doing that little 1 liner in python and just passing it into the template would work just fine. I still think there has to be a way to do it in Django though.

hitze
Aug 28, 2007
Give me a dollar. No, the twenty. This is gonna blow your mind...

Is there a way to run pngcrush in a script? I'm trying to figure out how to crush the pngs after I make them with PIL.
code:
import os, sys
import Image

infile = "flight-of-the-conchords.jpg"
outfile = "flight-of-the-conchords-(album)-100.png"

im = Image.open(infile)
im = im.resize((100, 100), Image.ANTIALIAS)
im = im.save(outfile, "PNG")
I've got that right now, but I can't seem to find anything dealing with running pngcrush in python.

Modern Pragmatist
Aug 20, 2008

hitze posted:

Is there a way to run pngcrush in a script? I'm trying to figure out how to crush the pngs after I make them with PIL.
code:
import os, sys
import Image

infile = "flight-of-the-conchords.jpg"
outfile = "flight-of-the-conchords-(album)-100.png"

im = Image.open(infile)
im = im.resize((100, 100), Image.ANTIALIAS)
im = im.save(outfile, "PNG")
I've got that right now, but I can't seem to find anything dealing with running pngcrush in python.

couldn't you use os.system to run pngcrush from the command line?

Habnabit
Dec 30, 2007

lift your skinny fists like
antennas in germany.

Modern Pragmatist posted:

couldn't you use subprocess.call to run pngcrush from the command line?

Fixed.

Thermopyle
Jul 1, 2003

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

Two related questions:

1. Can someone please compile MySQLdb for Python 2.6 on Windows? On sourceforge a couple of random people have attempted it, but neither of their packages work for me:

code:
Traceback (most recent call last):
  File "<pyshell#0>", line 1, in <module>
    import MySQLdb
  File "C:\Python26\lib\site-packages\mysql_python-1.2.2-py2.5-win32.egg\MySQLdb\__init__.py", line 19, in <module>
  File "C:\Python26\lib\site-packages\mysql_python-1.2.2-py2.5-win32.egg\_mysql.py", line 7, in <module>
  File "C:\Python26\lib\site-packages\mysql_python-1.2.2-py2.5-win32.egg\_mysql.py", line 6, in __bootstrap__
ImportError: DLL load failed: The specified module could not be found.
2. How come Python doesn't come with a MySQL module? It seems like this would be a pretty important feature...

Thermopyle fucked around with this message at 20:03 on Mar 1, 2009

NotShadowStar
Sep 20, 2000
Okay I've been looking to beef up my Python besides just the basics. Best way to do that is to do some of the more mundane problems that I come up with, cleaning data files, data matching and so forth.

First, is there something like CPAN or better Rubygems for Python? It's liberating to use something that will install libraries for you without having to do the work manually.

Then, is there the 'go to' ORM library for Python, like ActiveRecord for Ruby or Hibernate for Java?

This is going to be weird after doing mostly Ruby for about 4 years to a language that discourages metaprogramming.

m0nk3yz
Mar 13, 2002

Behold the power of cheese!

NotShadowStar posted:

Okay I've been looking to beef up my Python besides just the basics. Best way to do that is to do some of the more mundane problems that I come up with, cleaning data files, data matching and so forth.

First, is there something like CPAN or better Rubygems for Python? It's liberating to use something that will install libraries for you without having to do the work manually.

Then, is there the 'go to' ORM library for Python, like ActiveRecord for Ruby or Hibernate for Java?

This is going to be weird after doing mostly Ruby for about 4 years to a language that discourages metaprogramming.

You want to look at easy_install http://peak.telecommunity.com/DevCenter/EasyInstall, or pip http://pypi.python.org/pypi/pip (I prefer pip). There is nothing like cpan "baked right into python" as it is commonly felt that external tools can perform the tasks better than something built in. Note that these do build on distutils (the baked in packaging system). So, try out pip.

As for ORM's - it depends. Django has it's own, but I think sqlalchemy http://www.sqlalchemy.org/ is the really popular one.

Xenos
Jun 17, 2005

edit: ^^ :argh:

NotShadowStar posted:

First, is there something like CPAN or better Rubygems for Python? It's liberating to use something that will install libraries for you without having to do the work manually.

The Python Package Index used with EasyInstall, which belongs to the setuptools package, will let you do this sort of thing. If you want to install simplejson, all you have to do is type this:

code:
$ easy_install simplejson
Some people really hate setuptools, though.

quote:

Then, is there the 'go to' ORM library for Python, like ActiveRecord for Ruby or Hibernate for Java?

I love SQLAlchemy, mostly because it doesn't force you to use the ActiveRecord model design. There's also the Django ORM, which is ActiveRecord based, but you have to install the whole Django framework to get it. Some people like SQLObject, too.

m0nk3yz
Mar 13, 2002

Behold the power of cheese!

Xenos posted:

Some people really hate setuptools, though.

Because it's barely maintained, riddled with bugs/etc. Use pip, you'll thank me.

Xenos
Jun 17, 2005

m0nk3yz posted:

Because it's barely maintained, riddled with bugs/etc. Use pip, you'll thank me.

I'll definitely look into it. I've seen somebody mention it on the TurboGears mailing list, but they didn't really talk about why pip is better.

hey mom its 420
May 12, 2007

This is a good post about it.

NotShadowStar
Sep 20, 2000

Bonus posted:

This is a good post about it.

Good to know. Although I don't get where he thinks gem gets it wrong, because he describes how pip works and that's pretty much how rubygems works, though pip took some of the Rails extensions to gem like freezing and such.

Xenos
Jun 17, 2005

Bonus posted:

This is a good post about it.

Thanks for the link, the responses from Ian Bicking were also good reading. The changes made with pip really do make a lot of sense, like how all the required packages are downloaded before being installed. Seriously, why would you want to install packages any other way? This easy_install "feature" gave me a lot of headaches last summer.

I really like the idea of a bundle option. I think that having this option would've made deploying last year's TurboGears 2 alpha to OSX Server a little less painful.

Allie
Jan 17, 2004

setuptools is definitely annoying. I've run into a lot of headaches with it maintaining one particular Python-based application:

1. Customizing distutils commands can cause problems if setuptools comes into the mix. setuptools monkeypatches some things, but not others, so you can run into issues where subclassed commands don't behave properly because you aren't subclassing the setuptools versions.

2. Importing setuptools means you're effectively forcing users to install with setuptools. If they have it installed, it's used. If you remove this import later, subsequent distutils-based installs will never become effective due to how setuptools uses pth files. This can be confusing when people upgrade to a new version of your application and wonder why it still reports being an older version.

3. setuptools provides no way of installing man pages, or any other sort of shared data. easy_install even goes out of its way to "sandbox" the script, preventing it from writing outside of the egg directory.

4. And now my latest issue with setuptools: it seems to completely ignore build subcommands I've added. I have a build_mo subcommand that builds localization files, but with setuptools the command is never run. I still haven't figured out the issue, but suffice to say I loving hate setuptools.

I think part of the problem is how distutils itself is designed, but I haven't fully crystallized my thoughts on it yet.

I've used pip. It seems okay. One thing that annoys me is that it leaves an empty build directory wherever I run it, which seems incredibly sloppy to me. The fact that there isn't a dedicated forum for it (he says to use the virtualenv Google group), and the very spartan Trac instance that presents you with a blank page by default also seem sloppy. It also doesn't have its own site, instead just using its PyPI page.

I'm very skeptical of Ian Bicking in general, having used many of his older projects and being amazed at how over-designed and poorly implemented they were. I've wasted a lot of my time with things like SQLObject, FormEncode, and Paste.

Grinnblade
Sep 24, 2007
So, I'm making an edit to a Pyborg so that it responds to any sentence whatsoever that starts with its name. I'm thinking the best way to go would be to edit this code here:

code:
		if body.lower().find(self.settings.myname.lower() ) != -1:
			replyrate = replyrate * 2
However, the one version I tried, this:

code:
		if (body.lower.left(self.settings.myname.length()) == self.settings.myname.lower()):
			replyrate = 100
made PyBorg vomit on itself. Any ideas?

Also, I'd like it to respond if a specific abbreviation (MQ) of its nickname is used at the start of a sentence, but this code:

code:
		if body[0:1] == "MQ" or body[0:2] == " MQ":
			replyrate = 100
doesn't work. It doesn't break the bot, but it doesn't work.

bitprophet
Jul 22, 2004
Taco Defender

Grinnblade posted:

if (body.lower.left(self.settings.myname.length()) == self.settings.myname.lower()):
replyrate = 100

missing parens.

wrt your last example, you are slicing incorrectly. "mystring"[0:1] will result in "m"; the right index is exclusive. so "the first 2 chars" would be [:2] (note: zero is not necessary, which is why that example right there will work; nor is end-of-string, you can just do e.g. mystr[5:] to get from the 5th char to end of string)

Habnabit
Dec 30, 2007

lift your skinny fists like
antennas in germany.

Grinnblade posted:

code:
		if body.lower().startswith(self.settings.myname.lower()):
			replyrate = 100
code:
		if body.startswith(("MQ", " MQ")):
			replyrate = 100

If you haven't read a tutorial already, now is probably a good time!

MetaKnyght
May 18, 2004
My name is Jeff, not to be confused with the legendary eBay meta-scammer MyNameIsJeff
I need to learn a GUI framework for Python, so I was wondering which one is most preferred. Is there any reason not to use PyQt4 for application and GUI development? Or is one of the other standard tool-kits (GTK, wxPython, Tkinter) more commonly used and accepted? My current shop uses Qt3 and 4 in C/C++, so I figured Qt in Python might be a good place for me to start. Any suggestions? Thanks.

AzraelNewtype
Nov 9, 2004

「ブレストバーン!!」
If you already know Qt, using it in Python is by far your best move. If you're good with Qt Designer, you can convert its ui files into usable python with a single command and then just run from there. It's all very familiar.

MetaKnyght
May 18, 2004
My name is Jeff, not to be confused with the legendary eBay meta-scammer MyNameIsJeff

AzraelNewtype posted:

If you already know Qt, using it in Python is by far your best move. If you're good with Qt Designer, you can convert its ui files into usable python with a single command and then just run from there. It's all very familiar.

Sorry, I should have clarified. I, personally, don't know Qt yet, or any other toolkit. Just getting started with GUI work in general. Most of my work has been limited to the console or very, very basic Tkinter.

AzraelNewtype
Nov 9, 2004

「ブレストバーン!!」
It's really not that hard to pick up, and the rest of your shop should have no trouble reading it and helping out as it's a pretty literal conversion from C++ to Python for most of the stuff. It's probably not necessarily any better or easier than wxPython (which I think is the common choice) but there's definitely something to be said for having living resources. Outside of some very, very limited AWT experience, Qt was the first GUI toolkit I really looked at and I really quite liked it. The python wrapper does nothing to hurt the positive aspects of it, and it removes some of the dumber bits (extensive preprocessor magic).

NotShadowStar
Sep 20, 2000
Another thing... my two dead tree references for Ruby are The Ruby Programming Language and The Ruby Cookbook. Combined they're all I need. I use a similar set for Perl except I used the unholy trinity of The Llama, The Camel and The Cookbook. What's the combination for Python that's similar?

The Python Recipes book has a rabbit on the cover. Cute.

ahobday
Apr 19, 2007

I've looked around, and I can't find any resources for programming an ascii based tile game engine in Python. Essentially, I want to create an RPG tech demo with a fixed game world (Not randomly generated as in a Roguelike).

Imagine a top-down jRPG such as Final Fantasy 1, but with ascii tiles rather than graphical tiles. Can anyone help me out with the concepts here? I don't know how to go about both displaying a map from a text file and then dynamically updating it based on events and whatnot. Some starter advice on how to approach the problem is all I need for now.

Schatten
Jul 7, 2002

Das ist nicht meine
schnellen Rennwagen
Here's my newbie python question.

I'm writing a small script to telnet over to a particular device, run a few checks and then run a few commands. The issue - the checks. The checks will run commands, and display status/results. I need to get those results in order to continue or abandon the script depending on the status.

For example, this isn't the actual command needed, but it gives you an idea of what I'm looking for:

command - ifconfig
parsing through results to find a particular string, say... "Loopback"

If Loopback is present, I will continue, else, abandon.

p.s. - fyi, there's no grep on the remote device, nor can it be implemented. It is just a standalone device that has a limited number of device specific commands.

Schatten fucked around with this message at 21:19 on Mar 5, 2009

Animosity
Aug 8, 2004

it's penguin time.

Centipeed posted:

I've looked around, and I can't find any resources for programming an ascii based tile game engine in Python. Essentially, I want to create an RPG tech demo with a fixed game world (Not randomly generated as in a Roguelike).

Imagine a top-down jRPG such as Final Fantasy 1, but with ascii tiles rather than graphical tiles. Can anyone help me out with the concepts here? I don't know how to go about both displaying a map from a text file and then dynamically updating it based on events and whatnot. Some starter advice on how to approach the problem is all I need for now.

I think you want to check out the pycurses module

m0nk3yz
Mar 13, 2002

Behold the power of cheese!

Schatten posted:

Here's my newbie python question.

I'm writing a small script to telnet over to a particular device, run a few checks and then run a few commands. The issue - the checks. The checks will run commands, and display status/results. I need to get those results in order to continue or abandon the script depending on the status.

For example, this isn't the actual command needed, but it gives you an idea of what I'm looking for:

command - ifconfig
parsing through results to find a particular string, say... "Loopback"

If Loopback is present, I will continue, else, abandon.

p.s. - fyi, there's no grep on the remote device, nor can it be implemented. It is just a standalone device that has a limited number of device specific commands.

Check out paramiko, pexpect and the like, you're going to need to issue a command, get the output, parse and choose, and then reconnect

Adbot
ADBOT LOVES YOU

bitprophet
Jul 22, 2004
Taco Defender

Schatten posted:

I'm writing a small script to telnet over to a particular device, run a few checks and then run a few commands. The issue - the checks. The checks will run commands, and display status/results. I need to get those results in order to continue or abandon the script depending on the status.

Big, important question: is it literally telnet, or is it SSH? The following only applies to SSH. For Telnet you'd need to use Python's builtin telnet lib, I think, as I'm not aware of higher level tools that aren't SSH specific. (Condolences if you are working with a telnet-only device, I assume it's very resource constrained or very old...?)

So, assuming SSH: you could do what m0nk3yz suggests, but I think Fabric is a much better idea; having a newbie wrestle with Paramiko and Pexpect doesn't sound like the best idea IMHO.

I contributed a big overhaul of Fabric's capability last year specifically so it can do this kind of thing; no other "deploy" related tools were able to (long story; they could do e.g. run('ifconfig') but weren't able to get the result back, or do logic based on the result).

Here's an example fabfile based on your example:
code:
import sys

config.fab_hosts = ['device_hostname']
config.fab_user = ['device_username']

def do_stuff():
    if not 'Loopback' in run('ifconfig'):
        print "OMG no loopback :("
        sys.exit(1)
    
    # do more stuff here since loopback exists; we would've exited otherwise.

  • Locked thread