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
Thermopyle
Jul 1, 2003

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

Cirian posted:

Just in case anyone is interested, I work with the original Pyglet developer in a fairly large game dev company, and he is releasing a successor to it after many years of non-involvement. He doesn't have an account here, but I know it's still fairly popular in the Python world, so I thought at least one of you guys might be interested in looking at his new project.

The URL is here: http://pypi.python.org/pypi/bacon/

I'll pass on any suggestions to him directly :)

I haven't looked at it yet, but just a couple weeks ago we were complaining about the sad state of Python gaming frameworks. I hope this begins to alleviate that!

edit: Oh. No Linux support. :( (Like people write games for linux.)

Adbot
ADBOT LOVES YOU

Dominoes
Sep 20, 2007

Was there a change in how post requests work in new ewer versions of Requests? Upgrading from Requests 1.1.0 to 1.2.3 broke post for me. Get requests work. Post now returns:



Example code causing this:
Python code:
auth = requests_oauthlib.OAuth1(my_auth.client_key, my_auth.client_secret, my_auth.resource_owner_key,
                                my_auth.resource_owner_secret, signature_type = 'auth_header')
url = 'https://api.tradeking.com/v1/market/ext/quotes.json'
payload = {'symbols': 'GOOG', 'fids': 'last'}
r = requests.post(url, data=payload, auth=auth)
print(r.text)
The key bit is probably "Duplicate Content-Length header". This code worked in Requests 1.1.0. Get requests still work in 1.2.3. Any ideas? Changelog doesn't seem to mention a change to post functionality, and the code above is in line with the quickstart guide.

Cirian
Nov 7, 2002
Fun Shoe

Thermopyle posted:

I haven't looked at it yet, but just a couple weeks ago we were complaining about the sad state of Python gaming frameworks. I hope this begins to alleviate that!

edit: Oh. No Linux support. :( (Like people write games for linux.)

He's not really a Linux guy :) One of the alpha testers (another programmer here) can't get enough Linux though, maybe he (or someone else) will want to write a port. Most of the code that does the heavy lifting is written in C++, so it may not be ... super trivial to do so.

I'd give more of a comparative introduction to it (vs Pyglet) if I had ever used the precursor to it, so forgive my vagueness!

Thermopyle
Jul 1, 2003

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

Dominoes posted:

Was there a change in how post requests work in new ewer versions of Requests? Upgrading from Requests 1.1.0 to 1.2.3 broke post for me. Get requests work. Post now returns:



Example code causing this:
Python code:
auth = requests_oauthlib.OAuth1(my_auth.client_key, my_auth.client_secret, my_auth.resource_owner_key,
                                my_auth.resource_owner_secret, signature_type = 'auth_header')
url = 'https://api.tradeking.com/v1/market/ext/quotes.json'
payload = {'symbols': 'GOOG', 'fids': 'last'}
r = requests.post(url, data=payload, auth=auth)
print(r.text)
The key bit is probably "Duplicate Content-Length header". This code worked in Requests 1.1.0. Get requests still work in 1.2.3. Any ideas? Changelog doesn't seem to mention a change to post functionality, and the code above is in line with the quickstart guide.

Turn on output of requests logging. As it uses the logging module, something like this should work:

Python code:
logging.basicConfig() 
logging.getLogger().setLevel(logging.DEBUG)
requests_log = logging.getLogger("requests.packages.urllib3")
requests_log.setLevel(logging.DEBUG)
requests_log.propagate = True

the
Jul 18, 2004

by Cowcaster
So let's say I have a 2d array of zeros.

I want to add to one dimension of them depending on a random number that I get.

The first element is [0,0], what I don't know is how I'd make the next element [1,0], then [1,1], then [1,2], etc. I don't know the correct code to say "check the previous element in that dimension and add one onto it." I'm sure it's really simple. Thanks.

Thermopyle
Jul 1, 2003

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

My last post made me think of something I've meant to post before when beginners were asking questions, and since we've currently got some beginners participating in the thread:

Learn the logging module. You'll think "bah, I'll just put some print statements in here", or you'll look up a code snippet and cut/paste it from some web site, but you'll do well to learn how to use it, because once you get how it works, it's pretty powerful and amazingly useful.

Here's a couple links that help explain it:
http://eric.themoritzfamily.com/learning-python-logging.html
http://www.shutupandship.com/2012/02/how-python-logging-module-works.html

deimos
Nov 30, 2006

Forget it man this bat is whack, it's got poobrain!
Regarding Requests, are you using Python3? https://github.com/kennethreitz/requests/issues/1335

TURTLE SLUT
Dec 12, 2005

I'm making a deployment script that runs a bunch of stuff on Node.js through Python. The Node script accesses and compresses a bunch of .js files.

The weird thing is, if I try to call node with subprocess.call I get a "OSError: [Errno 2] No such file or directory" error. If I use os.system instead, it works pretty much like I would expect it to. Does anyone know what's the key difference between the two? I would like to use subprocess because of how some surrounding code works.

Also I wish we had an inline code block in BBcode.

deimos
Nov 30, 2006

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

JOHN SKELETON posted:

I'm making a deployment script that runs a bunch of stuff on Node.js through Python. The Node script accesses and compresses a bunch of .js files.

The weird thing is, if I try to call node with subprocess.call I get a "OSError: [Errno 2] No such file or directory" error. If I use os.system instead, it works pretty much like I would expect it to. Does anyone know what's the key difference between the two? I would like to use subprocess because of how some surrounding code works.

os.system opens a subshell and subprocess.call doesn't. Check that your PATHs match.

quote:

Also I wish we had an inline code block in BBcode.

we do in SA (and some other implementations)

TURTLE SLUT
Dec 12, 2005

Hmm, okay, thanks.

deimos posted:

we do in SA (and some other implementations)
The more you know!

JingleCreb
May 3, 2007

print('B', end = "")
while True: print('a', end = "")
I'm a beginner and have been toying with the idea of making a share data analysis program to help me learn about building/storing/analysing data structures, and working with GUIs. I've had a go, but wanted to see what people think about a few choices I've found myself having to make.

1. Is it best to write the back-end functions (that will download, store, manipulate, analyse the data) first, testing them from the command line, and then build the GUI around that? Or should I write the GUI first to make working with the data stuff easier as I'm developing it?

2. I've read that JSON or XML is the way to go for data files, rather than pickle. But (for JSON at least) this seems to rule out storing and loading arbitrary objects. I find it a bit more intuitive to write my own classes rather than work with dicts, so is it best to use my own classes in the program and convert them to/from dicts when saving and loading JSON files, or does that seem like unnecessary work?

3. I'm thinking of doing the GUI in Pyside but the official tutorial has quite a steep learning curve after the first couple of lessons and I can't find much else. Any recommendations?

Dominoes
Sep 20, 2007

Thermopyle posted:

Turn on output of requests logging. As it uses the logging module, something like this should work:

Python code:
logging.basicConfig() 
logging.getLogger().setLevel(logging.DEBUG)
requests_log = logging.getLogger("requests.packages.urllib3")
requests_log.setLevel(logging.DEBUG)
requests_log.propagate = True

No idea.

JingleCreb posted:

2. I've read that JSON or XML is the way to go for data files, rather than pickle. But (for JSON at least) this seems to rule out storing and loading arbitrary objects. I find it a bit more intuitive to write my own classes rather than work with dicts, so is it best to use my own classes in the program and convert them to/from dicts when saving and loading JSON files, or does that seem like unnecessary work?

3. I'm thinking of doing the GUI in Pyside but the official tutorial has quite a steep learning curve after the first couple of lessons and I can't find much else. Any recommendations?
2 - YAML is a format similar to JSON that can store objects. It's much slower though, so isn't a good option if you're storing large amounts of data. pip install pyyaml

3 - I haven't found a good tutorial for PySide/PyQt, and many examples online are outdated. Learning it was relatively painful compared to Python itself. Post if you have specific questions. Qt Designer is awesome.

Here's an example PyQt template that demonstrates the basics. PySide code should look similar. Exceptions being use QtCore.Signal() instead of QtCore.pyqtSignal(), import QtCore from PySide instead of from PyQt etc.

Python code:
import sys

from PyQt5 import QtCore, QtWidgets

#from module_gui import Ui_Main  #For QT designer files
#from another_window_gui import Ui_Another

class Main(QtWidgets.QMainWindow):
    def __init__(self, parent=None):
        QtWidgets.QWidget.__init__(self, parent)
        self.btn_another = QtWidgets.QPushButton('another', self)
        self.btn_another.setGeometry(QtCore.QRect(20, 30, 75, 23))
        self.btn_another.clicked.connect(self.another_window)
        self.lbl_1 = QtWidgets.QLabel("Here's a label", self)
        self.lbl_1.setGeometry(QtCore.QRect(40, 50, 75, 23))
        self.mySignal.connect(lambda string, integer: function2(string, integer))
    mySignal = QtCore.pyqtSignal(str, int)

    def another_window(self):
        self.w = AnotherWindow()
        self.w.show()


class AnotherWindow(QtWidgets.QWidget):
    def __init__(self, parent = None):
        QtWidgets.QWidget.__init__(self, parent)
        self.ui = Ui_Another()
        self.ui.setupUi(self)


def function():
    main.mySignal.emit("hi", 5)

def function2(string, integer):
    print(string, integer)
    main.lbl_1.setText("MOOO!")

if __name__ == "__main__":
    app = QtWidgets.QApplication(sys.argv)
    main = Main()
    main.show()
    sys.exit(app.exec_())

Dominoes fucked around with this message at 00:30 on Sep 7, 2013

Thermopyle
Jul 1, 2003

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


deimos posted:

Regarding Requests, are you using Python3? https://github.com/kennethreitz/requests/issues/1335

Dren
Jan 5, 2001

Pillbug
You can overload the python json library to do custom serialize/deserialize for your objects. I have done it, it wasn't hard. If you can't figure it out from this documentation http://docs.python.org/2/library/json.html#encoders-and-decoders I will post an example for you.

I think you should go with json over xml. json's types cleanly map to the standard python types (they both have lists, dictionaries, ints, strings, etc). With xml you'd have to come up with a schema (at least informally) and the parsing code is harder to write and ugh... xml is terrible.

JingleCreb
May 3, 2007

print('B', end = "")
while True: print('a', end = "")

Dominoes posted:

2 - YAML is a format similar to JSON that can store objects. It's much slower though, so isn't a good option if you're storing large amounts of data. pip install pyyaml

Hmm, not come across YAML before. I'll skip it for now in favour of JSON given what you say about performance. Might also do me good to experiment with subclassing as suggested below.

Dominoes posted:

3 - I haven't found a good tutorial for PySide/PyQt, and many examples online are outdated. Learning it was relatively painful compared to Python itself. Post if you have specific questions. Qt Designer is awesome.

Here's an example PyQt template that demonstrates the basics. PySide code should look similar. Exceptions being use QtCore.Signal() instead of QtCore.pyqtSignal(), import QtCore from PySide instead of from PyQt etc.

Thanks very much - that's handy. Shame there's not much out there. Maybe if I get to grips with it I'll try writing a beginners' guide.

Dren posted:

You can overload the python json library to do custom serialize/deserialize for your objects. I have done it, it wasn't hard. If you can't figure it out from this documentation http://docs.python.org/2/library/json.html#encoders-and-decoders I will post an example for you.

Ha, thanks, that hadn't occurred to me. Sounds just like what I'm looking for. Presumably you have to write a new method for each new class you want to be able to serialize?

quote:

I think you should go with json over xml. json's types cleanly map to the standard python types (they both have lists, dictionaries, ints, strings, etc). With xml you'd have to come up with a schema (at least informally) and the parsing code is harder to write and ugh... xml is terrible.

That's good: I was leaning towards JSON anyway. Don't really know much about XML but came across it once and... didn't have a good time.

Dren
Jan 5, 2001

Pillbug

JingleCreb posted:

Ha, thanks, that hadn't occurred to me. Sounds just like what I'm looking for. Presumably you have to write a new method for each new class you want to be able to serialize?

You can write one method that knows how to deal with all of your classes. Use 'if instanceof(...)'

ahmeni
May 1, 2005

It's one continuous form where hardware and software function in perfect unison, creating a new generation of iPhone that's better by any measure.
Grimey Drawer

Cirian posted:

Just in case anyone is interested, I work with the original Pyglet developer in a fairly large game dev company, and he is releasing a successor to it after many years of non-involvement. He doesn't have an account here, but I know it's still fairly popular in the Python world, so I thought at least one of you guys might be interested in looking at his new project.

The URL is here: http://pypi.python.org/pypi/bacon/

I'll pass on any suggestions to him directly :)

From a quick gloss over with my phone it's basically pyglet with some more OpenGL stuff baked in so there's less of your own stuff to roll like glTranslate stacks and shaders. That's super cool to see progress and that definitely makes things easier to handle for newer developers. Do you guys use it in production there or is it just his own project?

It's really a pity nobody has hit the multi-platform target with Python like C# has with Unity3D and Xamarin/MonoGame. I think the closest we have right now is that things you develop in Python Cocos2D are easily translatable to the iPhone, C++ and C# versions.

Thermopyle
Jul 1, 2003

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

Oh, I forgot to mention that you should bring up Bacon in the game development megathread.

Cirian
Nov 7, 2002
Fun Shoe

ahmeni posted:

From a quick gloss over with my phone it's basically pyglet with some more OpenGL stuff baked in so there's less of your own stuff to roll like glTranslate stacks and shaders. That's super cool to see progress and that definitely makes things easier to handle for newer developers. Do you guys use it in production there or is it just his own project?

It's his own project he did in preparation for Pyweek (he's done the game called "Monthly Visitor"). We make fairly big 3D iOS/Android games for our day jobs.

I'm pretty sure Bacon also includes some shader stuff that would have been a pain in Pyglet, such as shader uniform/state management and also possibly automatic sprite batching for things that share texture atlasses/shader state.

ahmeni posted:

It's really a pity nobody has hit the multi-platform target with Python like C# has with Unity3D and Xamarin/MonoGame. I think the closest we have right now is that things you develop in Python Cocos2D are easily translatable to the iPhone, C++ and C# versions.

Multi-platforming these things is pretty hard, especially with mobile devices which have such annoying requirements in terms of what code can actually run on them. I seem to remember Alex talking about wanting to make an iOS version of Bacon. I think the solution he went for (using Google's Angle) to abstract away the graphics API to OpenGLES was a good idea. Not that I would do that, as I'm a dyed-in-the-wool D3D person :)

Thermopyle posted:

Oh, I forgot to mention that you should bring up Bacon in the game development megathread.

I'll crosspost it there, seems sensible now that his Pyweek submission is done as well (as an example game).

Dominoes
Sep 20, 2007

deimos posted:

Regarding Requests, are you using Python3? https://github.com/kennethreitz/requests/issues/1335
Are they saying that it's still a WIP? I edited the text of models.py and utils.py per pull 1338, but it's still producing the duplicate content-length header problem. I tried going to the "master" section, and replaced my whole requests folder with it, but that has the same problem as well. The discussions are from 4 months ago.

Dominoes fucked around with this message at 18:15 on Sep 8, 2013

Thermopyle
Jul 1, 2003

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

Dominoes posted:

Are they saying that it's still a WIP? I edited the text of models.py and utils.py per pull 1338, but it's still producing the duplicate content-length header problem. I tried going to the "master" section, and replaced my whole requests folder with it, but that has the same problem as well. The discussions are from 4 months ago.

Yes, it's a WIP. #1338 was merged into 2.0, so you'd have to pull the 2.0 branch instead of master. It looks like 2.0 didn't pass their last Travis CI build, but I'm not sure how bad of a break it is.

Basically, you'll have to pull the 2.0 branch, see if its working in its current state, if not, then fix it (submit your fixes back to github!).

Dominoes
Sep 20, 2007

Thermopyle posted:

Yes, it's a WIP. #1338 was merged into 2.0, so you'd have to pull the 2.0 branch instead of master. It looks like 2.0 didn't pass their last Travis CI build, but I'm not sure how bad of a break it is.

Basically, you'll have to pull the 2.0 branch, see if its working in its current state, if not, then fix it (submit your fixes back to github!).
Same issue with the content header on 2.0. I'm wondering if it has to do with the the requests_oauthlib module rather than requests itself - I think I upgraded both at the same time, and reverting to Requests 1.1.0 doesn't help. I tried sending (unauthenticated) post requests to http://www.posttestserver.com/, and they work. requests_oauthlib is a separate module that works with requests, so I'll see if I can find the version I had and and track down the problem... Although authenticated get requests work.

edit: Narrowed it down. The problem is not with Requests itself... it's with requests_oauthlib. Requests_oauthlib 0.3.0 works correctly (including with Requests 1.2.3, the current version), version 0.3.1 glitches out, with TypeError('startswith first arg must be bytes or a tuple of bytes, not str'), and v0.3.2 and v0.3.3 (the current version) produce the double header error. I'll try to fix the bug.

edit2: I was able to make requests_oauthlib v0.3.3 (current on PYPI) work by altering three lines in core.py:

Replaced return string.decode('utf-8') with return string on line 17
Removed decoding='utf-8' from line 32
Removed decoding=decoding from line 41

I'm pretty sure this decoding stuff is there for a reason - and specifically Python 3, but it's currently breaking the module.

Dominoes fucked around with this message at 22:30 on Sep 8, 2013

QuarkJets
Sep 8, 2008

the posted:

So let's say I have a 2d array of zeros.

I want to add to one dimension of them depending on a random number that I get.

The first element is [0,0], what I don't know is how I'd make the next element [1,0], then [1,1], then [1,2], etc. I don't know the correct code to say "check the previous element in that dimension and add one onto it." I'm sure it's really simple. Thanks.

I'm not totally sure what your question is. Can you create an example? For a 5x5 matrix of zeros and a random number of 2,what do you want as output?

deimos
Nov 30, 2006

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

Dominoes posted:

Same issue with the content header on 2.0. I'm wondering if it has to do with the the requests_oauthlib module rather than requests itself - I think I upgraded both at the same time, and reverting to Requests 1.1.0 doesn't help. I tried sending (unauthenticated) post requests to http://www.posttestserver.com/, and they work. requests_oauthlib is a separate module that works with requests, so I'll see if I can find the version I had and and track down the problem... Although authenticated get requests work.

edit: Narrowed it down. The problem is not with Requests itself... it's with requests_oauthlib. Requests_oauthlib 0.3.0 works correctly (including with Requests 1.2.3, the current version), version 0.3.1 glitches out, with TypeError('startswith first arg must be bytes or a tuple of bytes, not str'), and v0.3.2 and v0.3.3 (the current version) produce the double header error. I'll try to fix the bug.

edit2: I was able to make requests_oauthlib v0.3.3 (current on PYPI) work by altering three lines in core.py:

Replaced return string.decode('utf-8') with return string on line 17
Removed decoding='utf-8' from line 32
Removed decoding=decoding from line 41

I'm pretty sure this decoding stuff is there for a reason - and specifically Python 3, but it's currently breaking the module.

Sounds like you should file a bug report.

Also that decoding stuff is what breaks it for 3 but would be necessary for 2, the change that broke requests is that it handles headers as bytes instead of string, in P3 str.encode returns bytes, bytes.decode returns a string.

In Python2 there's no such thing as bytes, they are handled with str, which causes it's own headaches, when using encode and decode for example.

deimos fucked around with this message at 19:11 on Sep 9, 2013

Megaman
May 8, 2004
I didn't read the thread BUT...
Ok Python gods, I need your help, don't fail me now.

I'm trying to tag all aws instances created by my boto script upon creation.

Basically this is what I have:

import boto
import boto.ec2
conn = boto.ec2.connect_to_region("us-west-2")

conn.run_instances(
'ami-bf1d8a8f',
key_name='foo',
instance_type='t1.micro',
security_groups=['foo'],

reservations = conn.get_all_instances()
instances = [i for r in reservations for i in r.instances]
for i in instances:
running_ids = i.__dict__['id'] , i.__dict__['_state']
print running_ids

The result is this:
(u'i-d32918e7', terminated(48))
(u'i-2aee091d', terminated(48))
(u'i-d4ef08e3', terminated(48))
(u'i-d1ef08e6', terminated(48))
(u'i-2fee0918', terminated(48))
(u'i-830a8db7', terminated(48))
(u'i-630a8d57', terminated(48))
(u'i-190ef12e', pending(0))
(u'i-22c1cb16', running(16))
(u'i-73c0ca47', terminated(48))
(u'i-78c0ca4c', terminated(48))
(u'i-18c0ca2c', terminated(48))
(u'i-d7e272e3', terminated(48))
(u'i-dce272e8', terminated(48))
(u'i-229ddc16', running(16))
(u'i-9ae272ae', terminated(48))
(u'i-1f0df228', terminated(48))
(u'i-720df245', terminated(48))
(u'i-840ef1b3', terminated(48))
(u'i-9b0ef1ac', terminated(48))
(u'i-be2ec689', terminated(48))
(u'i-a2ee0995', pending(0))
(u'i-cfcb6afb', terminated(48))
(u'i-209adb14', running(16))

I want to exclude all lists with value x in them and print the result, so for example I want to exclude 'terminated', I'd get:
(u'i-190ef12e', pending(0))
(u'i-22c1cb16', running(16))
(u'i-229ddc16', running(16))
(u'i-a2ee0995', pending(0))
(u'i-209adb14', running(16))

So then I could re-extract the IDs and assign them tags. How do I exclude these lists, which is the equivalent of grep -v in bash?

spankweasel
Jan 4, 2006

use that list comprehension:

code:

reservations = conn.get_all_instances()
instances = [i for r in reservations for i in r.instances if i.__dict__['_state] != 'terminated']
for i in instances:
    running_ids = i.__dict__['id'] , i.__dict__['_state']
    print running_ids 

Megaman
May 8, 2004
I didn't read the thread BUT...

spankweasel posted:

use that list comprehension:

code:

reservations = conn.get_all_instances()
instances = [i for r in reservations for i in r.instances if i.__dict__['_state] != 'terminated']
for i in instances:
    running_ids = i.__dict__['id'] , i.__dict__['_state']
    print running_ids 


I'm not sure why but it doesn't work, and it's not because you forgot a single quote. Any ideas?

Kumquat
Oct 8, 2010

Megaman posted:

I'm not sure why but it doesn't work, and it's not because you forgot a single quote. Any ideas?

Did you actually change !='terminated' to !='terminated(48)'? != checks for equivalency, not whether a string contains another.

Megaman
May 8, 2004
I didn't read the thread BUT...

Kumquat posted:

Did you actually change !='terminated' to !='terminated(48)'? != checks for equivalency, not whether a string contains another.

I did, same result

spankweasel
Jan 4, 2006

What if you use the optional filters arg to get_all_instances()?

http://boto.readthedocs.org/en/latest/ref/ec2.html#boto.ec2.connection.EC2Connection.get_all_instances

quote:

filters (dict) – Optional filters that can be used to limit the results returned. Filters are provided in the form of a dictionary consisting of filter names as the key and filter values as the value. The set of allowable filter names/values is dependent on the request being performed. Check the EC2 API guide for details.

Also, please don't use single letter variable names. It makes it a total bitch to debug poo poo.

You could also try using pdb and step through the code one line at a time.

import pdb; pdb.set_trace()

Stick that line right after your get_all_instances() call and you'll enter the pdb shell. You can see everything one line at a time and you have a limited python subshell to execute things in.

edit:

http://docs.aws.amazon.com/AWSEC2/latest/APIReference/ApiReference-query-DescribeInstances.html

link to EC2 API reference

spankweasel fucked around with this message at 03:18 on Sep 10, 2013

Dominoes
Sep 20, 2007

deimos posted:

Sounds like you should file a bug report.

Also that decoding stuff is what breaks it for 3 but would be necessary for 2, the change that broke requests is that it handles headers as bytes instead of string, in P3 str.encode returns bytes, bytes.decode returns a string.

In Python2 there's no such thing as bytes, they are handled with str, which causes it's own headaches, when using encode and decode for example.

Bug submitted. The string.decode line is in part of an explicit version checking statement, and the python2 fork is actually what works:

Python code:
if sys.version > "3":
    unicode = str

    def to_native_str(string):
        return string.decode('utf-8')
else:
    def to_native_str(string):
        return string

deimos
Nov 30, 2006

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

Dominoes posted:

Bug submitted. The string.decode line is in part of an explicit version checking statement, and the python2 fork is actually what works:

Python code:
if sys.version > "3":
    unicode = str

    def to_native_str(string):
        return string.decode('utf-8')
else:
    def to_native_str(string):
        return string

And already fixed in git, OSS works.

Dominoes
Sep 20, 2007

deimos posted:

And already fixed in git, OSS works.
Awesome. Lundren's fix works.

the
Jul 18, 2004

by Cowcaster
Getting an "int is not callable" on the second to last line, but I don't understand why because none of those are ints.

Python code:
nsteps = numpy.linspace(100,1000,10)
nstores = numpy.zeros(nsteps.size)
for i in range (0, nsteps.size):
    rvalues = numpy.zeros(40)
    for j in range (0,rvalues.size):
        randomx = numpy.zeros(10**6)
        randomy = numpy.zeros(10**6)
        for k in range(1,randomx.size):
            rvalue = numpy.random.randint(1,4)
            if rvalue == 1:
                randomx[k] = randomx[k-1]-1
                randomy[k] = randomy[k-1] 
            if rvalue == 2:
                randomx[k] = randomx[k-1]+1
                randomy[k] = randomy[k-1]  
            if rvalue == 3:
                randomx[k] = randomx[k-1]
                randomy[k] = randomy[k-1]-1
            if rvalue == 4:
                randomx[k] = randomx[k-1]
                randomy[k] = randomy[k-1]+1
        rvalues[j] = numpy.sqrt((randomx[-1])**2 (randomy[-1])**2)
    nstores[i] = (numpy.sum(rvalues))/40.

Crosscontaminant
Jan 18, 2007

There's an operator missing.

code:
rvalues[j] = numpy.sqrt((randomx[-1])**2 ? (randomy[-1])**2)
Without the operator it parses as trying to call the integer 2.

the
Jul 18, 2004

by Cowcaster
Thanks. I stared at that line for like 20 minutes and it was just missing a plus sign. Whew.

The Witness
Jul 2, 2012
I am a beginner trying to make a tic tac toe program in python but I am having major difficulty writing a function that randomly selects a position on the grid and prints an O after an X has been placed. I imagine the function would look look something like this:

if CheckKey[K_1] == True:
DISPLAYSURF.blit(textSurfaceObj1b, textRectObj1)
DISPLAYSURF.blit(textSurfaceObjX150, (166, 69))

random.choice(K_2, K_3, K_4, K_5, K_6, K_7, K_8, K_9)

I get the feeling that this is an abomination of a solution. I'd appreciate any suggestions about how to improve my code. To be honest, the solution I tried to come up with feels like a complete mess.

The Witness fucked around with this message at 03:04 on Sep 11, 2013

Hammerite
Mar 9, 2007

And you don't remember what I said here, either, but it was pompous and stupid.
Jade Ear Joe

The Witness posted:

I am a beginner trying to make a tic tac toe program in python but I am having major difficulty writing a function that randomly selects a position on the grid and prints an O after an X has been placed. I imagine the function would look look something like this:

if CheckKey[K_1] == True:
DISPLAYSURF.blit(textSurfaceObj1b, textRectObj1)
DISPLAYSURF.blit(textSurfaceObjX150, (166, 69))

random.choice(K_2, K_3, K_4, K_5, K_6, K_7, K_8, K_9)

I get the feeling that this is an abomination of a solution. I'd appreciate any suggestions about how to improve my code. To be honest, the solution I tried to come up with feels like a complete mess.

You probably have a data structure keeping track of what the status of each cell is (or you should do). Suppose for the sake of argument that this data structure is a tuple of row-data tuples, so it might look something like

Python code:
row_data = ((None, None, 'X'), (None, 'O', 'X'), ('O', None, 'O'))
which would represent this grid:

 | |X
-+-+-
 |O|X
-+-+-
O| |O


Then to choose a random cell, you might do this:

Python code:
choice = random.choice([(i, j) for i in range(3) for j in range(3) if row_data[i][j] is None])

Lunar Suite
Jun 5, 2011

If you love a flower which happens to be on a star, it is sweet at night to gaze at the sky. All the stars are a riot of flowers.
My nice fresh installation of twisted shits itself in its web module, by trying to from collections import and then either Sequence in errors.py or MutableMapping in http_headers.py
errors.py I could manually screw around with by just replacing relevant lines with import collections and collections.Sequence but that doesn't fly with MutableMapping.

It worked on a machine I'd borrowed over the summer, but here the fresh install doesn't work.

Adbot
ADBOT LOVES YOU

Pollyanna
Mar 5, 2005

Milk's on them.


How do you extract stuff from nested dictionaries? Like, I have a dictionary of dictionaries, which is basically a set of keys associated with a dictionary, which has its own set of keys and values. Is there a way of saying dictionary[all]['requested key'] or something?

edit: got it :cool: for loop did it

edit 2 wait no I need help again.

When I take dictionary.keys(), it returns the keys out of order. Like, it'd return:

code:
'2013-09-09',
 '2013-04-18',
 '2013-07-05',
 '2013-04-11',
 '2013-04-10',
 '2013-09-03',
 '2013-04-12',
 '2013-09-05',
 '2013-09-04',
 '2013-04-17',
 '2013-09-06',
etc
You can see that the calendar dates are all jumbled up. What gives? It's not like that in the original dictionary. :confused: Why does this happen?

Pollyanna fucked around with this message at 21:07 on Sep 12, 2013

  • Locked thread