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
Lonely Wolf
Jan 20, 2003

Will hawk false idols for heaps and heaps of dough.
code:
def parse_duration(value):
    t = re.search()#same but with <names> changed to those in d & timedelta
    d = {"hours":0, "minutes":0, "seconds":0, "milliseconds":0}
    if t:
        d.update(t.groupdict())
    return datetime.timedelta(**d)
think you can alternately pass d to groupdict, but the documentation wasn't entirely clear and I didn't feel like testing it

Adbot
ADBOT LOVES YOU

tripwire
Nov 19, 2004

        ghost flow

Spime Wrangler posted:

Heh, guess I haven't updated for some time now. Its working fine at home under 2.6.6 so nvm I guess.

It's numpy. If you have an different version of numpy installed than the one matplotlib was coded against it blows the hell up on windows xp. It took me a while to figure out why as well.

bobthecheese
Jun 7, 2006
Although I've never met Martha Stewart, I'll probably never birth her child.
OK guys, I'm trying to access a number of HTTP APIs that are sitting behind HTTP authentication using httplib.HTTPConnection

I tried to format the URL to pass the auth information through (bad practice, probably, but I'm just trying to get this thing to work - it's a proof of concept anyway), but it's still sending the HTTP challenge back. I have something like this:

code:
    def call(self, api=None, vars=None):
        """ Does a call to the API """
        if (self.server and self.username and self.password and api):
            call_url = self.username+":"+self.password+"@"+self.server+":"+str(self.port)
            request_url = '/path/to/api.cgi?name='+api
            
            if vars != None:
                for k,v in vars.list():
                    request_url += '&'+k+'='+v
            
            if self.https:
                conn = httplib.HTTPSConnection(call_url,timeout=10)
            else :
                conn = httplib.HTTPConnection(call_url,timeout=10)
            
            conn.request('GET',request_url)
            
            res = conn.getresponse()
When I actually run that, everything... goes quiet because httplib doesn't actually appear to return the auth challenges (the reason why I know that they happen is because I re-wrote it with urllib briefly to see what was going on)

Anyway, I need to know how to pass the auth details through correctly.

I'm on Python 2.6, if that helps

deimos
Nov 30, 2006

Forget it man this bat is whack, it's got poobrain!

bobthecheese posted:

OK guys, I'm trying to access a number of HTTP APIs that are sitting behind HTTP authentication using httplib.HTTPConnection

I tried to format the URL to pass the auth information through (bad practice, probably, but I'm just trying to get this thing to work - it's a proof of concept anyway), but it's still sending the HTTP challenge back. I have something like this:

code:
:code snipped by the clamps for brevity:
When I actually run that, everything... goes quiet because httplib doesn't actually appear to return the auth challenges (the reason why I know that they happen is because I re-wrote it with urllib briefly to see what was going on)

Anyway, I need to know how to pass the auth details through correctly.

I'm on Python 2.6, if that helps

AFAIK httplib does not do authentication.

Check out httplib2: http://code.google.com/p/httplib2/
And here's your code (with anal retentive changes included).
code:
    def call(self, api=None, vars=None):
        """ Does a call to the API """
        if (self.server and self.username and self.password and api):
            request_url = "{proto}://{self.server}:{self.port}{request_path}"
            request_path = '/path/to/api.cgi?name='+api
            if vars:
                request_path += ''.join('&'+k+'='+urllib.quote(unicode(v)) for k,v in vars.list())
            h = httplib2.Http()
            h.add_credentials(self.username, self.password)
            if self.https:
                proto = "https"
            else :
                proto = "http"
            request_url = request_url.format(self=self, 
                                             proto=proto, 
                                             request_path=request_path)
            resp, content = h.request(request_url)
Also as an aside but somewhat related, if using TLS(SSL) basic auth is "good enough" (definitely better than anything else without TLS). Now a days that kind of URL is not actually passed as-is silly nilly but instead is just a convenience method for basic auth. Regardless, TLS would protect the string since the secure connection is established before the URL gets passed, since in essence TLS becomes the transport for http.

In so far as APIs go, two-legged OAuth is becoming the standard protocol for API security, it's fairly straightforward and can accomodate varied deployments, including federation.

deimos fucked around with this message at 09:16 on Nov 5, 2010

Zombywuf
Mar 29, 2008

So the DBAPI is pissing me off. I'm using PyODBC to write to an SQL Server DB through a stored procedure. The PyODBC driver does not support callproc, so the only way to call the proc is via cursor.execute("EXEC write_to_db ?, ?, ...", (arg1, arg2, ...). This causes the following to occur on the db:
  • sp_preparestmt is called on the server with the string passed to execute.
  • The handle is executed with the bound parameters.
  • The statement handle is disposed of.
This is sloooooooooooooooooooooooooooooooow. Ideally I want to re-use the prepared statement with multiple sets of bound parameters. However executemany is not a good solution as I want to write data to the DB as soon as it is available and then wait for more data. Also, the fact that there are a range of statements fact that PyODBC caches the last statement is not much use.

Any ideas anyone?

Lurchington
Jan 2, 2003

Forums Dragoon

deimos posted:

AFAIK httplib does not do authentication.

I guess it depends on what you mean for authentication but you do have an HTTPSConnection that can use certificates:
http://docs.python.org/library/httplib.html#httplib.HTTPSConnection

The trick is that there's no validation of the server's certificate, which may or may not be a big deal depending on your needs.

Haystack
Jan 23, 2005





Some interesting news from the web framework front: Repoze.bfg has become Pyramid, part of the Pylons Project

Pyramid info and documentation

Highlights:
  • Feature development of Pylons will stop in favor of Pyramid. Pylons will get legacy support indefinitely.
  • Documentation and testing are at BFG standards, meaning 100% test coverage and that every feature gets up to date narrative and API documentation. For reference, BFG's documentation is about 500 pages long, printed.
  • Pyramid is pretty much BFG with a handful of features thrown in to make pylons developers more comfortable. Everything BFG had, Pyramid has.
  • Built in support for Mako templates (yay!).
  • Built in support for sessions.

deimos
Nov 30, 2006

Forget it man this bat is whack, it's got poobrain!

Lurchington posted:

I guess it depends on what you mean for authentication but you do have an HTTPSConnection that can use certificates:
http://docs.python.org/library/httplib.html#httplib.HTTPSConnection

The trick is that there's no validation of the server's certificate, which may or may not be a big deal depending on your needs.

Authentication is authentication. If there's no validation of the server cert then there's no authentication. What he's trying to do is Basic Auth (part of the http standard) and uses the Authentication headers (which I guess he could build manually).

Lurchington
Jan 2, 2003

Forums Dragoon

deimos posted:

Authentication is authentication. If there's no validation of the server cert then there's no authentication. What he's trying to do is Basic Auth (part of the http standard) and uses the Authentication headers (which I guess he could build manually).

The example was talking about passing a username and password over an HTTPConnection as well as an HTTPS, so I think the tautology is a bit misplaced.

Anyway, here's a reasonable looking subclassed-HTTPSConnection for the server cert validation.

Lurchington fucked around with this message at 03:57 on Nov 6, 2010

Radio Allergy
Nov 2, 2010
All right, I have a beginner question.
I want to fill a 200x200 bitmap using Tkinter but I am kind of struggling using the "put" method in PhotoImage; they recommend building a list of colors and positions for each row so that you can call the put method only once.
So, I guess my question is how can I create the lists correctly?

Here's my code:
code:
from Tkinter import *
from random import randrange

root = Tk()
c = Canvas(root, width = 200, height = 200); c.pack()
img = PhotoImage(width = 200, height = 200)
clrs = []
positions = []

for i in range(40000):
    temp = [randrange(256) for j in range(3)]
    clrs.append('#%02x%02x%02x' % tuple(temp))

for i in range(200):
    for j in range(200):
        positions.append((j, i))

img.put(clrs, positions)
c.create_image(0, 0, anchor = NW, image = img)
root.mainloop()

Rohaq
Aug 11, 2006
So I need to use SciPy, but I'm running Python 2.7 under Windows, and the SciPy installer complains that it can't find 2.6. Can anybody offer me any tips on getting it working with my setup?

hink
Feb 19, 2006
>>> help(PhotoImage.put)
Help on method put in module Tkinter:

put(self, data, to=None) unbound Tkinter.PhotoImage method
Put row formated colors to image starting from
position TO, e.g. image.put("{red green} {blue yellow}", to=(4,6))

BeefofAges
Jun 5, 2004

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

Rohaq posted:

So I need to use SciPy, but I'm running Python 2.7 under Windows, and the SciPy installer complains that it can't find 2.6. Can anybody offer me any tips on getting it working with my setup?

Install 2.6?

Rohaq
Aug 11, 2006

BeefofAges posted:

Install 2.6?
drat, is there really no way to build SciPy to work with 2.7? Only reason I ask is because I'm using argparse to handle my input arguments, which is new in 2.7, and it'd be a minor pain to recode my argument handling.

EDIT:- Never mind, found this, and going to give it a go:
http://www.lfd.uci.edu/~gohlke/pythonlibs/

Rohaq fucked around with this message at 16:23 on Nov 7, 2010

bobthecheese
Jun 7, 2006
Although I've never met Martha Stewart, I'll probably never birth her child.
I ended up (after much more googling, and mashing several different tutorials together) with this:

code:
    def call(self, api=None, vars=None):
        """ Does a call to the API """
        if (self.server and self.username and self.password and api):
            # Build the authentication headers
            auth = base64.encodestring("%s:%s" % (self.username, self.password))[:-1]
            headers = {"Authorization" : "Basic %s" % auth}
            
            # Get the call and request URLs
            call_url = self.server
            request_url = '/path/to/api.cgi'
            
            # Add any variables
            if vars == None:
                vars = {}
            
            # API to call
            vars['name']=api
            
            params = urllib.urlencode(vars)
            
            # Build the connection
            if self.https:
                conn = httplib.HTTPSConnection(call_url,self.port,timeout=10)
            else :
                conn = httplib.HTTPConnection(call_url,self.port,timeout=10)
            
            # Do the connection
            conn.request('POST',request_url,body=params,headers=headers)
            res = conn.getresponse()
            
            # return whatever we get
            return res.read()

posting smiling
Jun 22, 2008

Stabby McDamage posted:

2. Is there any way to ask for the old print statement in python 3? I'd never use it in code, but it might be nice on the command line. Unfortunately, it doesn't look like there's a "__past__" module.

This was already answered, but I wanted to mention that ipython does pretty much exactly this, but for all functions.
code:
In [3]: min 1, 2, 3
------> min(1, 2, 3)
Out[3]: 1

echinopsis
Apr 13, 2004

by Fluffdaddy
I'm pretty amateur when it comes to coding, I'm trying to make a program with evolutionary principles. Anyway, I'm running into problems which make no sense to me. I'm trying to make a class, but it's spitting the dummy,

code:
def genefromgenome(genome):
    genecount = genome.count('a')
    return genome.split('a')[1:]

class plant(object):
    def init(genome):
        genes=[]
        #gonna strip out all the genes from the genome
        for eachchromosome in genome:
            genes.append(genefromgenome(eachchromosome))
        return genes
    
    
genome=['abertzactrezahtzabhiue','abertzactrezahtzabhiue']

myplant = plant()
print myplant.init(genome)
That's all that's relevant at the moment. It's telling me that the plant.init method is being passed 2 arguments not 1, but I'm only passing it genome (aren't I?)
If I hack it so that plant.init is meant to take 2 arguments I get around that problem but now it's telling me that the for loop in the class has a "TypeError: 'plant' object is not iterable"
I don't understand, I'm not trying to iterate the object, just through my genome list.


This probably seems like the most retarded questions to you pros but..

Lonely Wolf
Jan 20, 2003

Will hawk false idols for heaps and heaps of dough.
You are passing it two and it only accepts one. The first parameter of a method is the object so a.b() is the same as b(a) so a.b(c) is b(a, c).

So you need to change your method to take (self, genome).

also it's __init__ not init so it should be __init__(self, genome)

echinopsis
Apr 13, 2004

by Fluffdaddy
Thanks man, that was really confusing the hell out of me :)

insidius
Jul 21, 2009

What a guy!
I have only just started with python and I am not very good but I have a question if someone could assist or if its really bad someone can just tell me to go right away.

Ive been working on a small thing just to get the hang of it take that takes a series of inputs including time and then is used to calculate my TOIL from work. Oddly I was able to get that to all work first go and it calculates it and what not and multiplies it correctly and then writes it to file, well after I figured out that you cant write a float to the file so I had to convert it all to strings first.

I am now at the point however where I want to be able to do one of two things based on the users input which I know I would use a series of if statements for which I already did earlier in the code to decide how to multiply a variable I had based on their input.

I dont know how to do the same though to decide how to execute a different action based on the choice. As I said I am not very good but I would assume that I need to "mark/define" my sections of code and then call that "section" based on the answer?

Sorry if I am being rather simple with this all but I am trying to get as much done myself without having to bug people.

good jovi
Dec 11, 2000

'm pro-dickgirl, and I VOTE!

insidius posted:

I have only just started with python and I am not very good but I have a question if someone could assist or if its really bad someone can just tell me to go right away.

Ive been working on a small thing just to get the hang of it take that takes a series of inputs including time and then is used to calculate my TOIL from work. Oddly I was able to get that to all work first go and it calculates it and what not and multiplies it correctly and then writes it to file, well after I figured out that you cant write a float to the file so I had to convert it all to strings first.

I am now at the point however where I want to be able to do one of two things based on the users input which I know I would use a series of if statements for which I already did earlier in the code to decide how to multiply a variable I had based on their input.

I dont know how to do the same though to decide how to execute a different action based on the choice. As I said I am not very good but I would assume that I need to "mark/define" my sections of code and then call that "section" based on the answer?

Sorry if I am being rather simple with this all but I am trying to get as much done myself without having to bug people.

I'm not entirely sure what you mean by "mark/define", but it sounds like you're asking how to use functions. Have you done any programming before? The python tutorial is pretty solid, but I'm not sure how useful it is for someone with no programming experience at all.

insidius
Jul 21, 2009

What a guy!

Sailor_Spoon posted:

I'm not entirely sure what you mean by "mark/define", but it sounds like you're asking how to use functions. Have you done any programming before? The python tutorial is pretty solid, but I'm not sure how useful it is for someone with no programming experience at all.

Ahh yes that makes sense :(

Move my current code into two sets of functions then call the one I need. Why do I fail at things that are so simple even after I re-read through the function page.

Thank you good sir for pointing out my obvious failure.

RobotEmpire
Dec 8, 2007

echinopsis posted:

I'm pretty amateur when it comes to coding, I'm trying to make a program with evolutionary principles. Anyway, I'm running into problems which make no sense to me. I'm trying to make a class, but it's spitting the dummy,

Quick question, why are you making a class here? Seems like an unnecessary level of complexity unless you're going to be working with a bunch of different kinds of plants who use completely different ways of stripping out gene sequences from genomes. Anyway, something to think about.

code:
def stripgenome(genome):
    #gonna strip out all the genes from the genome
    genes = []
    for eachchromosome in genome:
        genes.append(genefromgenome(eachchromosome))
    return genes
   
def genefromgenome(genome):
#   genecount = genome.count('a') # not sure what this is supposed to do, you don't return the variable ??
    gene_list = []
    for i in genome:
        gene_list.append(i.split('a'))
#    return genome.split('a')[1:] # Read about string manipulation, particularly slices. Lists don't have a split method, you might want list.pop(),/
     but I dunno. This is just all wrong
    return gene_list # I think this is more of what you're trying to do, but test it out at the command line first
    
genome=['abertzactrezahtzabhiue','abertzactrezahtzabhiue']

print stripgenome(genome)
Ditch the class definition and get your core logic working before worrying about that poo poo imo. Totally unnecesary.

RobotEmpire fucked around with this message at 06:05 on Nov 10, 2010

MaberMK
Feb 1, 2008

BFFs

RobotEmpire posted:

Quick question, why are you making a class here? Seems like an unnecessary level of complexity unless you're going to be working with a bunch of different kinds of plants who use completely different ways of stripping out gene sequences from genomes. Anyway, something to think about.

code:
def stripgenome(genome):
    #gonna strip out all the genes from the genome
    genes = []
    for eachchromosome in genome:
        genes.append(genefromgenome(eachchromosome))
    return genes
   
def genefromgenome(genome):
#   genecount = genome.count('a') # not sure what this is supposed to do, you don't return the variable ??
    gene_list = []
    for i in genome:
        gene_list.append(i.split('a'))
#    return genome.split('a')[1:] # Read about string manipulation, particularly slices. Lists don't have a split method, you might want list.pop(),/
     but I dunno. This is just all wrong
    return gene_list # I think this is more of what you're trying to do, but test it out at the command line first
    
genome=['abertzactrezahtzabhiue','abertzactrezahtzabhiue']

print stripgenome(genome)
Ditch the class definition and get your core logic working before worrying about that poo poo imo. Totally unnecesary.

This is precisely how 99% of scientific software becomes total garbage. If you're going to the trouble of writing software to solve a problem, build a good foundation of software development skills and code it right. It'll be more maintainable and thereby more useful to other scientists down the road, and you'll have learned a valuable skill. Without even bothering to speculate whether an object-oriented approach is suitable for this problem, I can say that "getting the core logic working before worrying about [anything else" is the wrong attitude.

echinopsis
Apr 13, 2004

by Fluffdaddy

RobotEmpire posted:

Quick question, why are you making a class here? Seems like an unnecessary level of complexity unless you're going to be working with a bunch of different kinds of plants who use completely different ways of stripping out gene sequences from genomes. Anyway, something to think about.
Ditch the class definition and get your core logic working before worrying about that poo poo imo. Totally unnecesary.

Thanks for the tips. I've changed it a bit since then. Reading "how-tos" in coding doesn't tell you much about theory, like don't repeat yourself etc.
Yeah that plant class is going to be used many many times, it's going to simulate plants growing, in my mind a instance of the class for each plant seems the easiest way to maintain it.

Should only the things that absolutely necessary be in an class be in one? Should everything else just be functions?

MaberMK posted:

This is precisely how 99% of scientific software becomes total garbage. If you're going to the trouble of writing software to solve a problem, build a good foundation of software development skills and code it right. It'll be more maintainable and thereby more useful to other scientists down the road, and you'll have learned a valuable skill.

Well this isn't really scientific software or anything, it's me loving around on my holidays based on an idea of trying to make entities evolve towards an ecosystem, incorporating an emerging system of families/species etc

Part of this is to also learn how to learn fundamentals anyway, I have little background in coding.

quote:

Without even bothering to speculate whether an object-oriented approach is suitable for this problem, I can say that "getting the core logic working before worrying about [anything else" is the wrong attitude.

Interesting, that is exactly what I am doing.. What's a better approach (generally)?

o.m. 94
Nov 23, 2009

Nitpicky question, but which is the preferred way to comment? The PEP guide wasn't clear on this....

code:
if discriminant == 0:
    roots[0] = -(b / (2 * a))
else:
    if discriminant > 0:
        root = math.sqrt(discriminant)

    # If discriminant is negative, then we need to use the cmath sqrt since the roots will be complex numbers.

    else: 
        root = cmath.sqrt(discriminant)
or

code:
if discriminant == 0:
    roots[0] = -(b / (2 * a))
else:
    if discriminant > 0:
        root = math.sqrt(discriminant)

    # If discriminant is negative, then we need to use the cmath sqrt since the roots will be complex numbers.
    else: 
        root = cmath.sqrt(discriminant)
or

code:
if discriminant == 0:
    roots[0] = -(b / (2 * a))
else:
    if discriminant > 0:
        root = math.sqrt(discriminant)
    # If discriminant is negative, then we need to use the cmath sqrt since the roots will be complex numbers.
    else: 
        root = cmath.sqrt(discriminant)
The first one seems the most readable, but I get the feeling that having newlines between an if / else statement isn't good practice?

RobotEmpire
Dec 8, 2007

MaberMK posted:

This is precisely how 99% of scientific software becomes total garbage. If you're going to the trouble of writing software to solve a problem, build a good foundation of software development skills and code it right. It'll be more maintainable and thereby more useful to other scientists down the road, and you'll have learned a valuable skill. Without even bothering to speculate whether an object-oriented approach is suitable for this problem, I can say that "getting the core logic working before worrying about [anything else" is the wrong attitude.

Right I totally get this 100%, but this is a dude's hobby project, and dude has zero background programming. From a motivational perspective -- speaking from first-hand experience -- there's nothing that will make you say "gently caress it" more than not being able to get a single thing working.

RobotEmpire
Dec 8, 2007

echinopsis posted:

Thanks for the tips. I've changed it a bit since then. Reading "how-tos" in coding doesn't tell you much about theory, like don't repeat yourself etc.
Yeah that plant class is going to be used many many times, it's going to simulate plants growing, in my mind a instance of the class for each plant seems the easiest way to maintain it.

Should only the things that absolutely necessary be in an class be in one? Should everything else just be functions?

Well, I dunno about all that.

But have you read Dive Into Python? It's an excellent resource. For just an introduction to classes:

http://www.freenetpages.co.uk/hp/alan.gauld/tutclass.htm

A A 2 3 5 8 K
Nov 24, 2003
Illiteracy... what does that word even mean?

oiseaux morts 1994 posted:

Nitpicky question, but which is the preferred way to comment? The PEP guide wasn't clear on this....

The first one seems the most readable, but I get the feeling that having newlines between an if / else statement isn't good practice?

Do what you like best, there's no single right way and there's no reason to follow a guideline from PEP8 if you have an alternative that's reasonable.

Scaevolus
Apr 16, 2007

oiseaux morts 1994 posted:

code:
if discriminant == 0:
    roots[0] = -(b / (2 * a))
else:
    if discriminant > 0:
        root = math.sqrt(discriminant)

    # If discriminant is negative, then we need to use the cmath sqrt since the roots will be complex numbers.
    else: 
        root = cmath.sqrt(discriminant)
I prefer this one.

tripwire
Nov 19, 2004

        ghost flow

RobotEmpire posted:

Well, I dunno about all that.

But have you read Dive Into Python?

NO


NO

DO NOT DO THIS

Lurchington
Jan 2, 2003

Forums Dragoon

tripwire posted:

NO


NO

DO NOT DO THIS

In fairness, DIP is still prominently featured on the first post, so it's not surprising we're seeing these still.

For a bit more content, since PEP8 was mentioned, I have determined where I personally deviate from it: I got tired of staying at 79 character lines for exception/assert raising output. Especially with assertions being a statement instead of a function. Seriously, nothing more annoying than seeing the stacktrace only show the last 1/3 of the statement and having to physically go to the line and see what the hell you were asserting on. Yes, the text should be descriptive, but it's a kick in the teeth to break a nice grammatically-correct sentence over 5 lines and be rewarded with slightly less output.

Lurchington fucked around with this message at 15:48 on Nov 10, 2010

MaberMK
Feb 1, 2008

BFFs

RobotEmpire posted:

Right I totally get this 100%, but this is a dude's hobby project, and dude has zero background programming. From a motivational perspective -- speaking from first-hand experience -- there's nothing that will make you say "gently caress it" more than not being able to get a single thing working.

I suppose I kinda jumped before I really thought carefully about his situation. I will most certainly agree that fundamentals come before higher-level design principles. (I work with the abominations scientists produce every day so I'm a little sensitive to "how I do program" and "<insert scientific principle or problem>" appearing in the same statement)


Lurchington posted:

In fairness, DIP is still prominently featured on the first post, so it's not surprising we're seeing these still.

For a bit more content, since PEP8 was mentioned, I have determined where I personally deviate from it: I got tired of staying at 79 character lines for exception/assert raising output. Especially with assertions being a statement instead of a function. Seriously, nothing more annoying than seeing the stacktrace only show the last 1/3 of the statement and having to physically go to the line and see what the hell you were asserting on. Yes, the text should be descriptive, but it's a kick in the teeth to break a nice grammatically-correct sentence over 5 lines and be rewarded with slightly less output.

Use a line span and you can stay under the 79 character limit and get the whole string.

code:
>>> assert False, 'asdfasdfasfasdfasdfasdffasdfasdfasdfasdf' \
...               'asdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdf'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AssertionError: asdfasdfasfasdfasdfasdffasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdf
Don't get me wrong, I'm not completely averse to breaking the 79 character limit. For example, it's pretty much impossible to stay under and be able to read the code when you're setting up mappings in SQLAlchemy.

qntm
Jun 17, 2009

tripwire posted:

NO


NO

DO NOT DO THIS

What's wrong with Dive Into Python?

o.m. 94
Nov 23, 2009

qntm posted:

What's wrong with Dive Into Python?

http://oppugn.us/posts/1272050135.html

MaberMK
Feb 1, 2008

BFFs

oiseaux morts 1994 posted:

http://oppugn.us/posts/1272050135.html

I had never read Dive Into Python before. I read your link followed by the first chapter of the book.... wow. I had no idea.

Ahernia
Feb 9, 2005
I'm trying to use Tkinter's Canvas to produce a vector map of Great Britain :britain: that you can pan around in, and zoom into.

It's working great so far, using .move and .scale from the Canvas class for the panning and zooming, respectively. These methods actually directly manipulate the coordinates of each object on the canvas, so you aren't moving the 'viewport', you're just moving everything around on the canvas to simulate that effect.

This is all well and good until I want to draw something new, like a line from London to Manchester.

I essentially need a function that will get my old coordinates to the 'new' coordinates. If I only implemented panning and forgot zooming, this would be easy since I can update a variable with every panning transformation and then run that against any 'old' coordinate to get it into the right place e.g.

code:
x = x - a
Where I have a value I can use for 'a' that has been updated with every movement of the canvas.

The canvas.scale method is this (for x and y but shown only for x):

code:
x = ((x - a) * b) + a
Where 'a' is the x coordinate the zoom function was performed at, so you scale away from that point, and 'b' is the scaling factor. What would be the equivalent functions that update the value of 'a' and 'b', such that I can transform an old coordinate to a new coordinate?

I don't even know what mathematics this involves, or the name of it, so even that would be helpful. I posted this question in here in the hopes that maybe somebody has had to do the same thing, as it seems to be a byproduct of the tkinter canvas not having a viewport.

good jovi
Dec 11, 2000

'm pro-dickgirl, and I VOTE!

MaberMK posted:

Use a line span and you can stay under the 79 character limit and get the whole string.

code:
>>> assert False, 'asdfasdfasfasdfasdfasdffasdfasdfasdfasdf' \
...               'asdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdf'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AssertionError: asdfasdfasfasdfasdfasdffasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdf
Don't get me wrong, I'm not completely averse to breaking the 79 character limit. For example, it's pretty much impossible to stay under and be able to read the code when you're setting up mappings in SQLAlchemy.

Breaking a string inside parentheses is preferred. Like so:

code:
In [1]: assert False, ('hey '
   ...:                'whats up?')
---------------------------------------------------------------------------
AssertionError                            Traceback (most recent call last)

/Users/user/<ipython console> in <module>()

AssertionError: hey whats up?
I think backslashes for line continuation are really ugly, and if you're not cool enough to have an editor that highlights trailing whitespace, they're another way to introduce some hard to spot errors.

Lurchington
Jan 2, 2003

Forums Dragoon

MaberMK posted:

Use a line span and you can stay under the 79 character limit and get the whole string.

<code>

Don't get me wrong, I'm not completely averse to breaking the 79 character limit. For example, it's pretty much impossible to stay under and be able to read the code when you're setting up mappings in SQLAlchemy.

Well, your answer caused me to think about it a bit more:

here's all 1 string and not broken up:
pre:
def wrap(num):
    assert num<10, 'asdfsadfsadfsadfasdfa<snip for tables>ffffffffffffffff'
    return wrap(num+1)

yields

Traceback (most recent call last):
  File "assert_test.py", line 19, in <module>
    wrap(10)
  File "assert_test.py", line 2, in wrap
    assert num<10, 'asdfsadfsadfsadfasdfa<snip for tables>ffffffffffffffff''
AssertionError: asdfsadfsadfsadfasdfa<snip for tables>ffffffffffffffff

notice how the trace shows the entire line (assert num<10 and the message)

compare to:

pre:
def wrap1(num):
    assert num<10, ('asdfsadfsadfsadfasdfasdfasdfasdfasdfasdfasdfasdffffffffff'+
                   'ffffffffffffffffffffffffffffffffffffffffasdfsadfsadfsadfa'+
                   'sdfasdfasdfasdfasdfasdfasdfasdfffffffffffffffffffffffffff'+
                   'fffffffffffffffffffffff')
    return wrap1(num+1)

yields:

Traceback (most recent call last):
  File "assert_test.py", line 19, in <module>
    wrap1(10)
  File "assert_test.py", line 9, in wrap1
    'fffffffffffffffffffffff')
AssertionError: <omitted, it's all the same everytime>
notice the bolded part; we've cutout the original assertion

pre:
def wrap2(num):
    assert num<10, ('asdfsadfsadfsadfasdfasdfasdfasdfasdfasdfasdfasdffffffffff'\
                   'ffffffffffffffffffffffffffffffffffffffffasdfsadfsadfsadfa'\
                   'sdfasdfasdfasdfasdfasdfasdfasdfffffffffffffffffffffffffff'\
                   'fffffffffffffffffffffff')
    return wrap2(num+1)   

yields

Traceback (most recent call last):
  File "assert_test.py", line 26, in <module>
    wrap2(10)
  File "assert_test.py", line 13, in wrap2
    assert num<10, ('asdfsadfsadfsadfasdfasdfasdfasdfasdfasdfasdfasdffffffffff'\ 
AssertionError:  <snip>
we have everything until the first continuation, which seems reasonable I suppose. Better than the + in my opinion

and based on sailor_spoon's suggestion:
pre:
def wrap3(num):
    assert num<10, ('asdfsadfsadfsadfasdfasdfasdfasdfasdfasdfasdfasdffffffffff'
                   'ffffffffffffffffffffffffffffffffffffffffasdfsadfsadfsadfa'
                   'sdfasdfasdfasdfasdfasdfasdfasdfffffffffffffffffffffffffff'
                   'fffffffffffffffffffffff')
    return wrap3(num+1)

yields:

Traceback (most recent call last):
  File "assert_test.py", line 26, in <module>
    wrap3(10)
  File "assert_test.py", line 20, in wrap3
    assert num<10, ('asdfsadfsadfsadfasdfasdfasdfasdfasdfasdfasdfasdffffffffff'
AssertionError: <again, the same>
basically the same as continuation.

All these assertion commands produce the same output, but in the first one, the stacktrace gave me a little extra information on the one liner, and I appreciate that as long as I don't go too far over 79.

Lurchington fucked around with this message at 19:50 on Nov 10, 2010

Adbot
ADBOT LOVES YOU

echinopsis
Apr 13, 2004

by Fluffdaddy

RobotEmpire posted:

Well, I dunno about all that.

I did read this book called "head first into programming" or something, it's not a learn to python book but python was the language it taught. It's cheesy as gently caress, but I guess it does help some things stick, but it was also more about how to write code than, learn these tools and dive in.
I can recognise when my code is poo poo, I just don't know how to improve it.

  • Locked thread