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
Space Kablooey
May 6, 2009


Pollyanna posted:

The URL I'm sending arguments to is /get?username=asdf&password=asdf. I just get a 400 when I do this. What am I doing wrong?

You said you moved on, but what's causing the problem is (probably) that you are using GET. Notice how your data is being sent in the URL (BTW, Passing a password in the url is always a big no-no), not in a JSON. You should use POST instead. And you probably have to fiddle with the Content-Type somewhere.

Pollyanna posted:

Now I just wish SQLAlchemy stuff was more easily serializable.

I hear ya. :sigh:

Adbot
ADBOT LOVES YOU

Space Kablooey
May 6, 2009


I don't have python on this machine, but

code:
addr = '115 Berry Lane, Plano, TX 24134'
splitted = str.split(addr, ',') # not sure if addr.split(',') works too

street = splitted[0]
city = splitted[1]

we = str.split(splitted[2]) # will split at the space (' ') character

state = we[0]
zip = we[1]
might be what you are looking for.

Edit: person below me knows what's up.

Space Kablooey fucked around with this message at 20:32 on May 10, 2014

Space Kablooey
May 6, 2009


For every item ("_", in this case) in the iterable (s.split(',')), call method .strip() of that item and put that item in a tuple.

Utimately, it results in a tuple like this: ("115 Berry Lane", "Plano", "TX 24134")

For more explanation: https://docs.python.org/2/tutorial/datastructures.html#list-comprehensions

Space Kablooey
May 6, 2009


Cultural Imperial posted:

What do you guys use for templating? Jinja2?

I use Jinja2, but I'm using flask, so.

Space Kablooey
May 6, 2009



How is dogs.append(first) not throwing a NameError in your print method?

By the way, in addition to the __str__ magic method, you can do someting like this:

Python code:
class Dog:
    # (...)
   
    @staticmethod 
    def print_dogs(list_of_dogs): 
        for dog in list_of_dogs:
            print dog
	
dogs = []                                 #empty dog list in which to store objects
if __name__ == "__main__":
    while True:
        name = input("Name: ")
        breed = input("Breed: ")
        dogs.append(Dog(name, breed))  # No need to store a new instance of Dog into a variable, just add it to the list 
        Dog.print_dogs(dogs)  # (*)
(*): Since print_dogs is a static method (the @staticmethod bit), you don't need a instance of a Dog to execute the method. You just pass in the list of all dogs and let the method handle it however.

I suggest you also look into a bit called @classmethod, and see how it differs from @staticmethods and regular methods.
Anything not clear, please ask!

Space Kablooey fucked around with this message at 04:46 on Jun 11, 2014

Space Kablooey
May 6, 2009


hlfrk414 posted:

I would not suggest giving a new python programmer decorator methods either; just define a function outside the class. It's the simplest to understand and a good habit to build first. Functions that don't act on the class object or the instance can be plain functions. Not harpin' on you for helping though.

Fair enough. I don't know decorators methods myself as well as I should, and I really should brush up on that.

What I wanted to say with that, is that he should look up static classes/methods, but in the general OOP context. That it was implemented via a decorator method just muddled things up.

Space Kablooey
May 6, 2009


the posted:

...Go on...

(I don't know what you mean by join in your query)

You are probably firing two or more of those:

One may be:

SELECT id_butt, whatever1 FROM butts

And the other may be:

SELECT id_fart, id_butt, whatever2 FROM farts


The result is that you have now two separated sets of data that are logically related. Modern databases are handy in that relational databases are all the rage for quite some time now. Instead of having two sets of separated but related data, you can have only one set of related data, saving you the hassle of JOINing them yourself. The database excels in that already. Something like this:

SELECT b.id_butt, b.whatever1, f.id_fart, f.whatever2 FROM butts b, farts f WHERE f.id_butt = b.id_butt;

My SQL is quite rusty, so that may not be quite right (sqlalchemy :allears:), so I'll just leave you a link to the CoC SQL megathread. Sorry for not being more helpful.

Space Kablooey
May 6, 2009


theguyoncouch posted:

Said friend here. This is how mine ended up. first time with python but i tried to cover all my bases. probably not the best

code:
def cif(words): 							#shifting cipher
	result, new_char = "", "" 					#declaring what I can
	for char in words:						#looping per each character in phrase
		cap = char.isupper()					#Checks if letter is captilized. Saves this in cap.
		ltr = ord(char.lower()) + shift 			#converts to lower-case as well as shifting the ascii number
		if ltr > 122: ltr -= 26  				#if it goes above the range of lower-case letters it loops it back
		elif ltr < 97: ltr += 26 				#if it goes above the range of lower-case letters it loops it back
		if char.isalpha(): 					#checks to see if char is an alphabetical letter
			if cap == True: ltr -= 32			#reverts ltr back to it's capitalized state
			new_char = chr(ltr)      			#assigns ltr in to char after reverting to character
		else: new_char = char					#if it is not an alphabetical letter it prints as is
		result += new_char					#joining characters back into string
	return result							#completes and returns string

Don't use tabs. Use spaces, preferably 4.

Space Kablooey
May 6, 2009


Thermopyle posted:

You also need some blank lines for readability. I can't think of the studies right now to quote, but something like this:

Python code:
def cipher(words):                                    
    new_phrase = []

    for char in words:                                  
        uppercase_check = char.isupper()

        letter = ord(char.lower())
        letter += shift

        if letter > 122:                    #Preventing ASCII from over 'z'
            letter -= 26                   
        elif letter < 97:                   #Preventing ASCII from under 'a'
            letter += 26      
            
        if char.isalpha():
            if uppercase_check is True: 
                letter -= 32
    
            new_phrase.append(chr(letter))
        else: 
            new_phrase.append(char)                          

    return ''.join(new_phrase)
It's an issue with theguyoncouch's code, but shift isn't being defined in this function, it really should be a parameter.



qntm posted:

Set your tab size to a single space, then indent using four tabs.

The best option, IMO, is to set tabs to convert to four spaces.

Space Kablooey
May 6, 2009


GET requests can time out, but they shouldn’t time out because you took a long time between two of them.

This is working:

Python code:
# coding: UTF-8
import requests


for i in range(1001):
    print i
    response = requests.get('http://www.ratebeer.com/json/bi.asp?k=tTmwRTWT-W7tpBhtL&b=' + str(i))
    print response.ok
    try:
        print response.json()
    except ValueError:
        pass
I'm really not sure what's going on on your end.

Space Kablooey
May 6, 2009


e: disregard

Space Kablooey
May 6, 2009


code:
Python 2.7.6 (default, Mar 22 2014, 22:59:56) 
[GCC 4.8.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> from datetime import datetime
>>> date = datetime(2013, 8, 26, 17, 21, 53)
>>> date
datetime.datetime(2013, 8, 26, 17, 21, 53)
>>> today = datetime.now()
>>> today
datetime.datetime(2014, 7, 18, 14, 45, 55, 374920)
>>> date >= today
False
>>> date == today
False
>>> date <= today
True
>>> date != today
True
>>> 
fake edit: beaten

Space Kablooey
May 6, 2009


I need to parse ISO 8601 dates and I found the dateutil module (https://pypi.python.org/pypi/python-dateutil/1.5). However, the latest version for python 2.X is 1.5, which is 4 years old by now. Is there any recommendations against it?

Space Kablooey
May 6, 2009


I thought the author just picked all those versions as a catch-all. Thanks. :)

Space Kablooey
May 6, 2009


Looks very interesting. Will take a look as soon as possible. Thanks.

Space Kablooey
May 6, 2009


the posted:

I have a technical interview for a Python position today at 4:30.

:ohdear:

Well, good luck! :v:

Space Kablooey
May 6, 2009


ShadowHawk posted:

Python code:
#!/usr/bin/env python3
import itertools
print("\n".join(("".join(fizzbuzz) or str(number) for number, fizzbuzz in itertools.islice(enumerate(zip(itertools.cycle(("fizz","","")), itertools.cycle(("buzz","","","","")))), 1, 101))))
Do I get the job?

You crashed my computer, so yes. :v:

EDIT: Changed zip to itertools.izip and it worked in python 2.7

Space Kablooey fucked around with this message at 20:21 on Aug 11, 2014

Space Kablooey
May 6, 2009


Crosscontaminant posted:

Your computer symlinks python3 to a Python 2 instance? That's a bit dubious. I'd do something about that, like installing Python 3.

Nah, it was my own fault, am I'm used to writing just "python" in the command line: "Oh, this is Python 3 code, I just have to import print function and it will work. What can go wrong? :downs:"

Space Kablooey
May 6, 2009


map is a function that is always available for every script, so you can't have anything that is called "map"

https://docs.python.org/2/library/functions.html

https://docs.python.org/3.4/library/functions.html

__getitem__ is what the "array[i]" actually calls down in the guts of python:

https://docs.python.org/2/library/operator.html#operator.__getitem__

Space Kablooey fucked around with this message at 05:06 on Aug 14, 2014

Space Kablooey
May 6, 2009


KICK BAMA KICK posted:

So either you mistyped map in place of something else (like fov_map perhaps?) or you need to incorporate the code that defines map. In the unlikely event that this code does redefine a very basic and useful built-in function rather than simply coming up with a unique name, consider learning from another source because that's a huge red flag.

Also this again, for effect.

Space Kablooey
May 6, 2009


QuarkJets posted:

This seems like a reasonable path to take. Feel free to ask any questions in here

There are several ways to be able to find modules inside of a sub-directory:
<snip>

What you posted isn't what virtualenv sets out to do?

Space Kablooey
May 6, 2009


Poison Mushroom posted:

A class is a sort of blueprint for making an object or a function, something you'll need to do a lot. Classes are to functions as constants are to magic numbers. If I wanted to create a lot of gamemaps, then it would behoove me to make a Class for them, something to repeat the map-making code over and over. Something like Floor or Level.

So I'd put my map-generation code into that class under def __init__, and every time something from the code calls to create something from the Floor class, it'd run all the mapmaking code right then, with room to also include in the class possible variations on the formula? (Larger rooms, fewer rooms, a different tunnel generation process, etc?)

In a nutshell, yes, that is pretty much it.

Space Kablooey
May 6, 2009


Dominoes posted:

Looking for help parsing XML files. I have long files - I want to pull some of the information into database entries.
*snip*

I used https://pypi.python.org/pypi/xmltodict some time ago and it worked well. Not sure about its performance on large files.

EDIT:

Murodese posted:

Really, really bad. I was using xmltodict to read 300kb-1.5mb XML files and changing it to use XPath resulted in a speedup of something like 15,000%.

Ouch

Space Kablooey fucked around with this message at 15:31 on Sep 2, 2014

Space Kablooey
May 6, 2009


There's probably a better way, but

Python code:
for row in rows[1:]:
	if row[2] == 'some_eid': # I'm guessing this is the eid column that you want
	# or you could use something like
	# if row[2] in list_of_eids_to_update:
		row[3] = str(datetime.datetime.now()) # Or whatever column you want to update
	writer.writerow(row)

Space Kablooey
May 6, 2009


See if this works:

Python code:
# main.py

from module import function

obj_list = [obj1, ...]

function(obj_list, x)
Python code:
# module.py

function(obj_list, x):
    for obj in obj_list:
        if obj.x == a:
            return True
    return False
However, it sounds to me that you should wrap the obj_list and the functions with a class.

Space Kablooey
May 6, 2009


Python code:
# main.py
from module import function


class Foo:
    x = 1

obj_list = [Foo(), Foo()]

x = 2

print function(obj_list, x)

Python code:
# module.py

def function(obj_list, x):
    for obj in obj_list:
        if obj.x == x:
            return True
    return False

Space Kablooey
May 6, 2009


Hughmoris posted:

code:
#this script will iterate through a CSV with multiple rows and three columns. The filepath is in column 0.
import csv 
r = csv.reader(open('C:/projects/python/test_data.csv')) #read in CSV as CSV object
for row in r: #iterates over each row in CSV. So for this, row[0] is file name
	f = open(row[0]).read() #read in the file path
	f = f.replace('OIS=1234', 'OIS=9999')
	new_file = open(row[0], 'w')
	new_file.write(f)
	new_file.close()

Is it working on your end? Isn't opening two file pointers to the same file wrong?


EDIT: Stupid bold tags don't work inside code.

Space Kablooey fucked around with this message at 14:22 on Sep 26, 2014

Space Kablooey
May 6, 2009


e: nevermind

Space Kablooey fucked around with this message at 20:52 on Oct 6, 2014

Space Kablooey
May 6, 2009


lotor9530 posted:

Damnit. I feel like an idiot now.

Thanks for the quick reply! One of these days I'll stop sucking at python.

One way to deal with SyntaxErrors is to take a break for a little while and then come back. :)

Space Kablooey
May 6, 2009


I'm unclear on what you actually want, but maybe this?


Python code:
Python 2.7.6 (default, Mar 22 2014, 22:59:56) 
[GCC 4.8.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> x = {}
>>> x['somekey'] = []
>>> x['somekey'].append({'foo': 1})
>>> x['somekey'].append({'foo': 2})
>>> x['somekey'].append({'foo': 3})
>>> x
{'somekey': [{'foo': 1}, {'foo': 2}, {'foo': 3}]}
>>> 
Or this:

Python code:
>>> y = {}
>>> 
>>> y['key1'] = {'foo': 1}
>>> y['key2'] = {'foo': 2}
>>> y['key3'] = {'foo': 3}
>>> y
{'key3': {'foo': 3}, 'key2': {'foo': 2}, 'key1': {'foo': 1}}
>>> 

Space Kablooey fucked around with this message at 18:43 on Oct 20, 2014

Space Kablooey
May 6, 2009


Begall posted:

I do have control over the schema, but I've been making changes to it quite rapidly through a web admin tool, so it seemed easier to just reflect it rather than go through and update the code each time. address_data is simply the name of the table, and represents the table so that I can do things like:

Python code:
self.db_session.query(address_data).filter_by(addressref = self.addressref).first()
Address is then implementing some application logic, which also includes calls to the address_data table. Does that make sense?

You should look at alembic. It generates migrations for your database (creating tables/fields, altering them, etc.) based on your SQLAlchemy models.

Space Kablooey
May 6, 2009



Mocking is something like this:

Python code:
import requests
from unittest import mock

class MockResponse():
    content = 'xyz'

# EXAMPLE OVER-SIMPLIFIED CODE
@mock.patch('requests.get')
def parse(url, mock_get):
    mock_get.return_value = MockResponse()
    r = requests.get(url)  # HTML is delivered in r.content
    return some_parsed_value(r.content)  # lxml or whatever extracts some value

def some_parsed_value(value):
    return value

# EXAMPLE TEST
def test_parsed(url):
    # assume something that maps a url to a local HTML file for content
    print(parse(url) == 'xyz')

test_parsed('url')
As long you do import requests in the modules that you want to test, that of mocking will most certainly work.

The tricky part of mocking is that you mock where the imported function being used, not where it was declared. For example:

Python code:
#main_module.py

from unittest import mock

from another_module import another_thing


@mock.patch('another_module.thing')
def mocked(mock_thing):
    mock_thing.return_value = 'yep'
    print(another_thing() == 'yep')

mocked()

#submodule.py
def thing():
    return 'nope'

#another_module.py
from submodule import thing


def another_thing():
    return thing()

Space Kablooey
May 6, 2009


Gothmog1065 posted:

Hey guys, I'm relearning python, and doing it via code academy. I'm trying to be dumb and do things a step above, and I suppose make it.. different? Dunno, trying things, but I can't remember if I can do a for loop like this:

I seem to recall a way to set the variable names within the for loop, so instead of item_weighted = foo, it actually comes out as homework_weighted = foo. Am I dumb and this can't be done?

Do you mean this?

Python code:
things = ["homework", "quizzes", "tests"]
weights = [.1, .3, .6]
for thing, weight in zip(things, weights):
    print thing, weight
it prints

code:
homework 0.1
quizzes 0.3
tests 0.6
EDIT: As SurgicalOntologist said below, it's better to use a dictionary. I completely forgot. :eng99:

Space Kablooey fucked around with this message at 17:10 on Feb 18, 2015

Space Kablooey
May 6, 2009


I started with the mega-tutorial.

I'm also working with it for almost two years now, if you hit a snag I can probably help you.

Space Kablooey
May 6, 2009


Instead of executemany, try using execute.

Also, you should use the row own id instead of a counter to put in the WHERE clause.

Also, if you really want to use a counter (you shouldn't in this case), you should take a look at the enumerate built in.

edit:

:gonk: don't do that.

Space Kablooey
May 6, 2009


Your each_patient variable should contain information about the row that you are iterating on. If I had to guess, it returns a dictionary mapping each column to a key; You would then access the id value by doing each_patient['Id'] and then you would pass that to execute. For example

Python code:
for each_patient in pts:
    insurance = random.choice(insurance_carriers)
    c.execute("UPDATE patients SET ins_carrier = ? WHERE Id = ?", (insurance, each_patient['Id']))


I'm still not convinced that the executemany wasn't the culprit. See: https://docs.python.org/2/library/sqlite3.html#sqlite3.Cursor.executemany

What happens when you print each_patient?

Space Kablooey fucked around with this message at 05:09 on Mar 29, 2015

Space Kablooey
May 6, 2009


outlier posted:

It's been a few years since I did anything with Django but: it is that easy to just put Django in front of an arbitrary database and use it as the ORM for the site? I seem to recall Django being a bit pernicky about how db's were laid out. Of course, it depends on how complex the object are that you are pulling out and how polluted my memory is by all those frameworks that are really strict about database structure ("must be named foo_id and must be an integer ...")

Django is not just a ORM, though, it a really complete web framework that happens to be somewhat opinionated about the structure of your code. Not that it is a completely bad thing, because if you are just starting with web dev, it is easy to pick it up and let it run. Your business logic shouldn't be constrained by your web framework of all things.

If you don't like Django's opinions, then there are alternatives like Flask, where it has very little say on how you should do things and it is very extensible, but it is easier to make a mess of your code.

Space Kablooey
May 6, 2009


I can't tell whats wrong, but it's this line:

Python code:
{% if a | match 'github' %}
As for doing differently, I would pass a list of tuples, (url, text), like this:

code:
<ul>
{% for url, text in repos %}
   <li><A HREF="{{ url }}">{{ text }}</A></li>
{% endfor %}
</ul>
The problem with this is when you have a lot of these, but that can be easily generated.

Space Kablooey
May 6, 2009


Rocko Bonaparte posted:

Is there some peculiar reason why somebody might want to explicitly pass self into an instance method rather than call it from self directly? I can't imagine what's going on. I'm reading some code from somebody I initially was giving a lot of slack since he was generally doing decent software engineering conceptually. However, bells started to go off when I saw some Systems Hungarian Notation.

:raise:

You mean as an other argument other than the standard self?

Python code:
class Butt():
	def __init__(self, whatever):
		self.whatever = whatever
		self.fart(self)

	def fart(self, self2):
		print self2.whatever
	
If it is like this above then you should nip it before it gets worse.

Adbot
ADBOT LOVES YOU

Space Kablooey
May 6, 2009


To me it looks like you have to load your station objects on a dictionary that is a member of the class TemperatureData.

Your get_data should be simple enough when you get to that, and if you are stumped on get_stations, you can call a function called dir on that dictionary, and that should give you some ideas. :)

  • Locked thread