content
stringlengths
85
101k
title
stringlengths
0
150
question
stringlengths
15
48k
answers
list
answers_scores
list
non_answers
list
non_answers_scores
list
tags
list
name
stringlengths
35
137
Q: Problem with Crawling Mechanism of Twitter Python Crawler Below is a small snippet of code I have for my twitter crawler mechanism: from BeautifulSoup import BeautifulSoup import re import urllib2 url = 'http://mobile.twitter.com/NYTimesKrugman' def gettweets(soup): tags = soup.findAll('div', {'class' : "li...
Problem with Crawling Mechanism of Twitter Python Crawler
Below is a small snippet of code I have for my twitter crawler mechanism: from BeautifulSoup import BeautifulSoup import re import urllib2 url = 'http://mobile.twitter.com/NYTimesKrugman' def gettweets(soup): tags = soup.findAll('div', {'class' : "list-tweet"})#to obtain tweet of a follower for tag in tags: ...
[ "Your soup.findall() is picking up an image tag in a link that matches your pattern (has an href attribute and class status-link).\nInstead of always returning on the very first link, try:\nfor time in times:\n stamp = time.renderContents()\n test_stamp = str(stamp)\n print test_stamp\n if not test_stam...
[ 1 ]
[]
[]
[ "html", "python", "twitter", "web_crawler" ]
stackoverflow_0006950113_html_python_twitter_web_crawler.txt
Q: comparing and replacing the elements of a nested list I have got a list which is: mylist = { 'a': [(-1,-1), (0.2,0.4)] 'b': [(0.3,1.0), (-1,-1)] 'c': [(-1,-1), (-1,-1)] 'd': [(0.15,0.35), (0.05,0.15)] } I have to get an output which will be like the following...
comparing and replacing the elements of a nested list
I have got a list which is: mylist = { 'a': [(-1,-1), (0.2,0.4)] 'b': [(0.3,1.0), (-1,-1)] 'c': [(-1,-1), (-1,-1)] 'd': [(0.15,0.35), (0.05,0.15)] } I have to get an output which will be like the following: mylist = { 'a': [(0.3, 0.35), (0.2,0.4)] ...
[ "def update(mylist, row, col, cmprow, cmpcol):\n lo, hi = mylist[row][col]\n low, high = mylist[cmprow][cmpcol]\n\n # always replace the current value if it's (-1, -1)\n if (lo, hi) == (-1, -1):\n mylist[row][col] = low, high\n print \"replacing empty\", row, col, \"with\", cmprow, cmpcol\...
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0006949211_python.txt
Q: How to create a dynamic array As I understand, the list type in Python is a dynamic pointer array, which will increase it's capacity when items are appended to it. And an array in NumPy uses a continuous memory area to hold all the data of the array. Are there any types that dynamically increase its capacity as a ...
How to create a dynamic array
As I understand, the list type in Python is a dynamic pointer array, which will increase it's capacity when items are appended to it. And an array in NumPy uses a continuous memory area to hold all the data of the array. Are there any types that dynamically increase its capacity as a list, and stores the value as a Num...
[ "You may be interested to know that the Python standard library also includes an array module which sounds like just what you want:\n\nThis module defines an object type which can compactly represent an\n array of basic values: characters, integers, floating point numbers.\n Arrays are sequence types and behave v...
[ 22 ]
[]
[]
[ "list", "numpy", "python" ]
stackoverflow_0006950456_list_numpy_python.txt
Q: Efficient IP address c/c++ library on unix Is there a good high level library that can be used for IP address manipulation? I need to do things like: Given a string find out if it is a valid IPv4/IPv6 address. Have functionality like ntop and pton etc I can use the low level inet_ntop() etc. But is there a bette...
Efficient IP address c/c++ library on unix
Is there a good high level library that can be used for IP address manipulation? I need to do things like: Given a string find out if it is a valid IPv4/IPv6 address. Have functionality like ntop and pton etc I can use the low level inet_ntop() etc. But is there a better library that handles these better and fast (c/...
[ "For C++, the standard high-level answer would be boost.asio. Specifically, to convert a string into an IP address it has\nip::address::from_string and to obtain a string representation of an ip address, it has to_string.\nDo check out other constructors for the ip address objects -- using raw bytes is likely to be...
[ 3, 1, 1, 0 ]
[ "I have the mind boogling ipv4 / ipv6 validating regexps around, which are quite long and non-trivial to produce. I can share if you want.\n" ]
[ -1 ]
[ "c", "c++", "freebsd", "ipv6", "python" ]
stackoverflow_0005857320_c_c++_freebsd_ipv6_python.txt
Q: Somewhat confused about how auth and sessions work in Python/Django I'm using an existing database for my latest Django project, so unless I change my Models or the Django auth code, it's going to be rather difficult to merge the two. Rather than messing with the existing auth backend, I'm planning on just writing...
Somewhat confused about how auth and sessions work in Python/Django
I'm using an existing database for my latest Django project, so unless I change my Models or the Django auth code, it's going to be rather difficult to merge the two. Rather than messing with the existing auth backend, I'm planning on just writing my own authentication app. Anyway, all of my previous authentication app...
[ "HTTP is stateless; regardless of the server used, the framework or language, there is no intrinsic way for an HTTP client to say \"this request is part of that session\". That's part of the design of HTTP. \nSo sessions are always a feature of the web application; either supported by the a web app framework or i...
[ 11 ]
[]
[]
[ "authentication", "django", "python", "session" ]
stackoverflow_0006950557_authentication_django_python_session.txt
Q: Why isn't swing calling toString() on the objects I pass to a JComboBox? I have this class to represent choices in a combobox: class Choice(object): def __init__(self, id, label): self.id = id self.label = label def toString(self): print "in Choice.toString" #for debugging ...
Why isn't swing calling toString() on the objects I pass to a JComboBox?
I have this class to represent choices in a combobox: class Choice(object): def __init__(self, id, label): self.id = id self.label = label def toString(self): print "in Choice.toString" #for debugging return self.label I have an array of Choice objects, and I want to show the l...
[ "Found it! On the back of Atrey's answer and JimN's comment, I found out that Python's equivalent to toString() is actually __repr__.\nSo my class now looks like:\nclass Choice(object):\n def __init__(self, id, label):\n self.id = id\n self.label = label\n\n def __repr__(self):\n return s...
[ 3, 2 ]
[]
[]
[ "java", "jython", "python", "swing", "tostring" ]
stackoverflow_0006950705_java_jython_python_swing_tostring.txt
Q: Interoperating with Django/Celery From Java Our company has a Python based web site and some Python based worker nodes which communicate via Django/Celery and RabbitMQ. I have a Java based application which needs to submit tasks to the Celery based workers. I can send jobs to RabbitMQ from Java just fine, but the ...
Interoperating with Django/Celery From Java
Our company has a Python based web site and some Python based worker nodes which communicate via Django/Celery and RabbitMQ. I have a Java based application which needs to submit tasks to the Celery based workers. I can send jobs to RabbitMQ from Java just fine, but the Celery based workers are never picking up the job...
[ "I found the solution. The Java library for RabbitMQ refers to exchanges/queues/routekeys. In Celery, the queue name is actually mapping to the exchange referred to in the Java library. By default, the queue for Celery is simply \"celery\". If your Django settings define a queue called \"myqueue\" using the followi...
[ 12 ]
[]
[]
[ "celery", "django", "java", "python", "rabbitmq" ]
stackoverflow_0006933833_celery_django_java_python_rabbitmq.txt
Q: "Programmatically" add stuff to a class? I'm writing a class that has a dict containing int to method mappings. However setting the values in this dict results in the dict being populated with unbound functions. class A: def meth_a: ... def meth_b: ... ... map = {1: meth_a, 2: meth_b, ...} for...
"Programmatically" add stuff to a class?
I'm writing a class that has a dict containing int to method mappings. However setting the values in this dict results in the dict being populated with unbound functions. class A: def meth_a: ... def meth_b: ... ... map = {1: meth_a, 2: meth_b, ...} for int in ...: map[int] = meth_x This d...
[ "I'm not sure exactly why you're doing what you're doing, but you certainly can do it right in the class definition; you don't need __init__.\nclass A:\n def meth_a(self): pass\n\n m = {1: meth_a}\n def foo(self, number):\n self.m[number](self)\n\na = A()\na.foo(1)\n\nAn \"unbound\" instance method ...
[ 3, 2, 2, 1 ]
[]
[]
[ "class", "dictionary", "initialization", "python", "python_3.x" ]
stackoverflow_0006950569_class_dictionary_initialization_python_python_3.x.txt
Q: Opencv error on python no matter what "CV_FOURCC" I use I get this: OpenCV Error: Unsupported format or combination of formats (Gstreamer Opencv backend doesn't support this codec acutally.) in CvVideoWriter_GStreamer::open, file /usr/src/packages/BUILD/OpenCV-2.2.0/modules/highgui/src/cap_gstreamer.cpp, ...
Opencv error on python
no matter what "CV_FOURCC" I use I get this: OpenCV Error: Unsupported format or combination of formats (Gstreamer Opencv backend doesn't support this codec acutally.) in CvVideoWriter_GStreamer::open, file /usr/src/packages/BUILD/OpenCV-2.2.0/modules/highgui/src/cap_gstreamer.cpp, line 489 writer = cv.Create...
[ "If I do this this it creates a working AVI file:\nwriter = cv.CreateVideoWriter(\n filename=file,\n fourcc=cv.CV_FOURCC('F', 'M', 'P', '4') ,\n fps=iFps,\n frame_size=(800,600),\n is_color=1)\ncv.WriteFrame(writer, cv.LoadImage(frames[i]))\ndel writer # this makes a working ...
[ 1 ]
[]
[]
[ "codec", "computer_vision", "linux", "opencv", "python" ]
stackoverflow_0006918995_codec_computer_vision_linux_opencv_python.txt
Q: How to make letters in a string lowercas, Python I want to make a function that would uncapitalize capitalized letters. I was thinking I could do if x in caps where caps is a list of all the capital letters, and I had it return the position in the list that letter is in, I could have it replace itself with the low...
How to make letters in a string lowercas, Python
I want to make a function that would uncapitalize capitalized letters. I was thinking I could do if x in caps where caps is a list of all the capital letters, and I had it return the position in the list that letter is in, I could have it replace itself with the lowercase. How would I do this? Thanks.
[ "Why not use the built in \"lower\"\na = 'aBcDeFg'\nprint a.lower() # abcdefg\n\nIf that doesn't work, you can always iterate and then use ord and chr:\n\"\".join(\n # if i is between A and Z change it to between a and z\n [chr(ord(i)+32) if 65<= ord(i) <= 90 \n # otherwise leave it as is\n else i for i in a])\...
[ 6, 1, 1, 0 ]
[]
[]
[ "list", "python" ]
stackoverflow_0006951005_list_python.txt
Q: Resuming an optimization with pyevolve I have done an optimization with Pyevolve and after a look at the results I wanted to add a few generation to have a better convergence. As an evaluation is quite long, I was wondering if I can resume my optimization to the last generation and add like 20 more generations. Ev...
Resuming an optimization with pyevolve
I have done an optimization with Pyevolve and after a look at the results I wanted to add a few generation to have a better convergence. As an evaluation is quite long, I was wondering if I can resume my optimization to the last generation and add like 20 more generations. Everything must be set in the DB I hope so he ...
[ "Hi after reviewing the documentation of Pyevolve there doesn't seem to be any way to resume an evolution base on what you stored in the database (strange behaviour).\nIf you want to implement this type of mechanism, you could look at pickling your population once and a while and implementing the whole thing in Pye...
[ 3 ]
[]
[]
[ "genetic_algorithm", "pyevolve", "python" ]
stackoverflow_0006841573_genetic_algorithm_pyevolve_python.txt
Q: Jquery XHR which results in a dom change that persists through refreshes, etc This is more of a design question than technical, but it has me completely stumped. So, I have a webpage (hosted via google app engine) that lists a number of seperate forms (each is a question/puzzle). A single puzzle has a number of t...
Jquery XHR which results in a dom change that persists through refreshes, etc
This is more of a design question than technical, but it has me completely stumped. So, I have a webpage (hosted via google app engine) that lists a number of seperate forms (each is a question/puzzle). A single puzzle has a number of text boxes to fill out, as well as a submit button. Upon hitting submit, an ajax re...
[ "I'd opt for a variant of option #1 (use Jinja2 to render the proper markup) - unless you are rendering a very large number of forms, the page should return in very short order (and if you do have a very large number of forms, making a great number of XHR requests is not going to be faster). Also, by letting Jinja ...
[ 1 ]
[]
[]
[ "ajax", "google_app_engine", "jinja2", "jquery", "python" ]
stackoverflow_0006945507_ajax_google_app_engine_jinja2_jquery_python.txt
Q: In which encoding does the shell command [mysql -e "..." -u ... > some_file.sql] store the content into some_file.sql? I wanted to export the results of a certain query into a file and therefore issued the shell command mysql -e "SELECT some, thing FROM some_where" -u my_user -p my_database > some_file.sql I shou...
In which encoding does the shell command [mysql -e "..." -u ... > some_file.sql] store the content into some_file.sql?
I wanted to export the results of a certain query into a file and therefore issued the shell command mysql -e "SELECT some, thing FROM some_where" -u my_user -p my_database > some_file.sql I should mention, that the table and the columns are stored in utf8. When trying to iterate through the lines by this python code ...
[ "mysql uses Latin-1 as the default character set unless you tell it otherwise. You can either decode from iso-8859-1 in python, or use:\nmysql --default-character-set=utf-8 -e \"SELECT some, thing FROM some_where\" -u my_user -p my_database > some_file.sql\n\n" ]
[ 1 ]
[]
[]
[ "dump", "encoding", "mysql", "python" ]
stackoverflow_0006951332_dump_encoding_mysql_python.txt
Q: How to move data across tables with django? Say I have three tables A, B, and C. A is the active table, B has a one2one relationship with A, and C is an archive table to store old A data. So in django I want to move a piece of data from A to C while being able to retain the one2one relationship with B. So how ca...
How to move data across tables with django?
Say I have three tables A, B, and C. A is the active table, B has a one2one relationship with A, and C is an archive table to store old A data. So in django I want to move a piece of data from A to C while being able to retain the one2one relationship with B. So how can I do this? Should I just copy the data to C, de...
[ "Assuming A,B,C are 3 models declared in your app, you can simply make A and C have similar fields, and then copy the data from A to C, including the fkey field to B.\nWhen you call delete in Django, it emulates the SQL constraint ON DELETE CASCADE, see https://docs.djangoproject.com/en/1.3/ref/models/querysets/#de...
[ 1 ]
[]
[]
[ "cascade", "database", "django", "python", "relational_database" ]
stackoverflow_0006951329_cascade_database_django_python_relational_database.txt
Q: Delete entry in database by datetime with mysql and django? I'm using mysql with django 1.3 and I have posts stored in a database. The posts are stored for a certain amount of time, say 7 days. How can I delete a post when the duration(7 days) is up? I'm not asking how to delete, but more how to determine when ...
Delete entry in database by datetime with mysql and django?
I'm using mysql with django 1.3 and I have posts stored in a database. The posts are stored for a certain amount of time, say 7 days. How can I delete a post when the duration(7 days) is up? I'm not asking how to delete, but more how to determine when to delete? I don't know if this is a good way of doing things, bu...
[ "Can't you mark a date of expiry on the post?\nclass Post(models.Model):\n # ...\n date_expire = models.DateField()\n\nI would then extend the save method to add 7 days to the current date and save it to that field. Then when a user is retrieving the posts,\ndef some_view(request):\n # ....\n posts = Po...
[ 0, 0, 0 ]
[]
[]
[ "database", "datetime", "django", "python", "sql" ]
stackoverflow_0006951294_database_datetime_django_python_sql.txt
Q: Problem with Python logging RotatingFileHandler in Django website I've a django powered website, and I use standard logging module to track web activity. The log is done via RotatingFileHandler which is configured with 10 log files, 1000000 byte each. The log system works, but this are the log files I get: -rw-r--...
Problem with Python logging RotatingFileHandler in Django website
I've a django powered website, and I use standard logging module to track web activity. The log is done via RotatingFileHandler which is configured with 10 log files, 1000000 byte each. The log system works, but this are the log files I get: -rw-r--r-- 1 apache apache 83 Jul 23 13:30 hr.log -rw-r--r-- 1 a...
[ "I've found this behavior when there are multiple precesses are running with your code.\nUnfortunatelly no perfect option exists.\nSome ideas, you can incorporate are:\n\nuse WatchedFileHandler (new in 2.6) and rotate with external programs as logrotate\nuse syslog or other log aggregating server\nuse python log ag...
[ 8, 6, 0 ]
[]
[]
[ "django", "logging", "python" ]
stackoverflow_0003319860_django_logging_python.txt
Q: Rapidly redrawing Tkinter window - What is a faster way? I am trying to make a microenvironmental simulator in Python, and so far I have a fractal map generator and a simple collision-detecting class of moving 'entities'. The entities worked fine when the canvas was sparse, but now that it has to redraw the map w...
Rapidly redrawing Tkinter window - What is a faster way?
I am trying to make a microenvironmental simulator in Python, and so far I have a fractal map generator and a simple collision-detecting class of moving 'entities'. The entities worked fine when the canvas was sparse, but now that it has to redraw the map with each update, it runs slowly. I am using create_rectangle'...
[ "A few things could probably be done to improve the FPS of your code:\n\nGet rid of the w.update() and use the normal event loop via mainloop()\nGet rid of the w.delete(ALL) and reuse the blocks (just move them around instead of delete and recreate them all)\nUse the help of the canvas find() method to do collision...
[ 1, 0 ]
[ "some minimal changes:\nfrom Tkinter import *\nfrom random import *\nfrom time import *\n\nroot = Tk()\n\nw = Canvas(root, width = 640, height=640, bd=0, highlightthickness=0)\nw.pack()\n\nentities = []\nrunning = True\n\n## Size of squares, in pixels\nsize = 5\n\n## Make tiles a 128x128 array\ntiles = []\nfor i in...
[ -1 ]
[ "python", "tkinter" ]
stackoverflow_0004551098_python_tkinter.txt
Q: PIL and Bitmap from WinAPI I have code that makes a screenshot of the window using winapi. Then I have to save image to disk and load it again from disk to memory PIL. Is there any way at once without saving to disk to pass this bitmap in the PIL. import win32gui, win32ui, win32con import Image win_name='Book' bm...
PIL and Bitmap from WinAPI
I have code that makes a screenshot of the window using winapi. Then I have to save image to disk and load it again from disk to memory PIL. Is there any way at once without saving to disk to pass this bitmap in the PIL. import win32gui, win32ui, win32con import Image win_name='Book' bmpfilenamename='1.bmp' hWnd = win...
[ "Comment out this line:\ndataBitMap.SaveBitmapFile(cDC, bmpfilenamename)\n\nand add this instead:\nbmpinfo = dataBitMap.GetInfo()\nbmpstr = dataBitMap.GetBitmapBits(True)\nim = Image.frombuffer(\n 'RGB',\n (bmpinfo['bmWidth'], bmpinfo['bmHeight']),\n bmpstr, 'raw', 'BGRX', 0, 1)\n\n[from another SO questio...
[ 14 ]
[ "If you are using PIL why not to use it for screenshoting?\nPIL contains ImageGrab module, which can be used like:\nimport win32gui, win32ui, win32con\nimport Image\nimport ImageGrab\n\nwin_name='Book'\nhWnd = win32gui.FindWindow(None, win_name)\nwindowcor = win32gui.GetWindowRect(hWnd)\n\nim = ImageGrab.grab(windo...
[ -1 ]
[ "python", "python_imaging_library", "screenshot", "winapi" ]
stackoverflow_0006951557_python_python_imaging_library_screenshot_winapi.txt
Q: a += b not the same as a = a + b Possible Duplicate: Why does += behave unexpectedly on lists? I found an interesting "feature" of the python language today, that gave me much grief. >>> a = [1, 2, 3] >>> b = "lol" >>> a = a + b TypeError: can only concatenate list (not "str") to list >>> a += b >>> a [1, 2, 3,...
a += b not the same as a = a + b
Possible Duplicate: Why does += behave unexpectedly on lists? I found an interesting "feature" of the python language today, that gave me much grief. >>> a = [1, 2, 3] >>> b = "lol" >>> a = a + b TypeError: can only concatenate list (not "str") to list >>> a += b >>> a [1, 2, 3, 'l', 'o', 'l'] How is that? I thoug...
[ "This is and always has been a problem with mutability in general, and operator overloading specifically. C++ is no better.\nThe expression a + b computes a new list from the objects bound to a and b, which are not modified. When you assign this back to a, you change the binding of one variable to point to the ne...
[ 42, 8 ]
[]
[]
[ "python" ]
stackoverflow_0006951792_python.txt
Q: python py2app help I tried using py2app, but I can't figure out where to put the filename of the file I want to make the standalone for. What command do I need to run? I'm extremely confused... A: In your setup.py, you want to do something like this: from distutils.core import setup import py2app setup(name="Ap...
python py2app help
I tried using py2app, but I can't figure out where to put the filename of the file I want to make the standalone for. What command do I need to run? I'm extremely confused...
[ "In your setup.py, you want to do something like this:\nfrom distutils.core import setup\nimport py2app\n\nsetup(name=\"App name\",\n version=\"App version\",\n options=opts, # see the py2app docs, could be a lot of things\n app=[main.py], # This is the standalone script\n )\n\n", "See docs - y...
[ 3, 1 ]
[]
[]
[ "py2app", "python" ]
stackoverflow_0006951731_py2app_python.txt
Q: XML DOM parsing; keeping inheritance I understand xml and minidom but I am missing something. What I want to do is be able to parse a variable size XML file and be able to build a tree of the elements. Take this example <doc> <foo> <server> <ip>10.1.1.1</ip> <service>service1</service> <n...
XML DOM parsing; keeping inheritance
I understand xml and minidom but I am missing something. What I want to do is be able to parse a variable size XML file and be able to build a tree of the elements. Take this example <doc> <foo> <server> <ip>10.1.1.1</ip> <service>service1</service> <name>somename</name> <something>some...
[ "Here's my quick code.\nI have a list of elements implementation and a list of servers implementation(+get_dict()). This should be all you need, as based on the question, afaik.\nimport lxml.etree as etree\n\nclass server(object):\n def __init__(self):\n self.ip = ''\n self.service = ''\n s...
[ 0 ]
[]
[]
[ "lxml", "python" ]
stackoverflow_0006951597_lxml_python.txt
Q: How to add dictionaries to tuple I'm new to python. I have tuple. It's have a elements /dictionaries/. I need a add new dictionaries to tuple? How to do it? I'm using python 2.7. Thank you for every help. A: As Chris Gregg said, you can't add anything to a tuple that already exists. You can add two tuples to cre...
How to add dictionaries to tuple
I'm new to python. I have tuple. It's have a elements /dictionaries/. I need a add new dictionaries to tuple? How to do it? I'm using python 2.7. Thank you for every help.
[ "As Chris Gregg said, you can't add anything to a tuple that already exists. You can add two tuples to create a new one though. \n>>> t = (1, 2, 3)\n>>> d = {'a':1, 'b':2, 'c':3}\n>>> t + (d,)\n(1, 2, 3, {'a': 1, 'c': 3, 'b': 2})\n\nThe old tuple remains the same:\n>>> t\n(1, 2, 3)\n\nYou could also do this:\nt += ...
[ 9, 2, 1 ]
[]
[]
[ "python", "tuples" ]
stackoverflow_0006950692_python_tuples.txt
Q: Logic check using any value from a list? list = ["apples", "oranges", "jerky", "tofu"] if "chew" in action and list[:] in action: print "Yum!" else: print "Ew!" How do I have a logic check where it checks for "chew" in action as well as ANY value in list? For example, I want to print "Yum!" whether actio...
Logic check using any value from a list?
list = ["apples", "oranges", "jerky", "tofu"] if "chew" in action and list[:] in action: print "Yum!" else: print "Ew!" How do I have a logic check where it checks for "chew" in action as well as ANY value in list? For example, I want to print "Yum!" whether action is "chew oranges" or "chew jerky".
[ "Why not use the builtin any() function? The following seems quite Pythonic to me:\nfoods = [\"apples\", \"oranges\", \"jerky\", \"tofu\"]\n\nif \"chew\" in action and any(f in action for f in foods):\n print \"Yum!\"\nelse:\n print \"Ew!\"\n\nOf course, just searching for simple substrings may give some weir...
[ 6, 4, 0, 0, 0 ]
[]
[]
[ "if_statement", "list", "logic", "python" ]
stackoverflow_0006951719_if_statement_list_logic_python.txt
Q: python google closure compiler Source class question This code is copy from http://code.google.com/p/closure-library/source/browse/trunk/closure/bin/build/source.py The Source class's __str __method referred self._path Is it a special property for self? Cuz, i couldn't find the place define this variable at Sourc...
python google closure compiler Source class question
This code is copy from http://code.google.com/p/closure-library/source/browse/trunk/closure/bin/build/source.py The Source class's __str __method referred self._path Is it a special property for self? Cuz, i couldn't find the place define this variable at Source Class import re _BASE_REGEX_STRING = '^\s*goog\.%s\(\s*...
[ "No, _path is just an attribute that may or me not be set on an object like any other attribute. The leading underscore simply means that the author felt it was an internal detail of the object and didn't want it regarded as part of the public interface.\nIn this particular case, unless something is setting the att...
[ 1 ]
[]
[]
[ "google_closure_compiler", "python" ]
stackoverflow_0006952954_google_closure_compiler_python.txt
Q: how to check something eg java, php, program etc installed with python? im makeing something like a check system before run so it meets the requirements with python. heres my code so far; def checksystem(): installednode = os.popen('node ' + srctocoffeecompiler + ' -v') // version 1.1.1 print installed...
how to check something eg java, php, program etc installed with python?
im makeing something like a check system before run so it meets the requirements with python. heres my code so far; def checksystem(): installednode = os.popen('node ' + srctocoffeecompiler + ' -v') // version 1.1.1 print installednode.read() i can print the version but is there a better way to check its i...
[ "I would split the version string, the comparison is pretty simple if you use lists:\n>>> vers1 = '1.0.1'.split('.')\n>>> vers2 = '1.0.0'.split('.')\n>>> vers1\n['1', '0', '1']\n>>> vers2\n['1', '0', '0']\n>>> vers1 > vers2\nTrue\n>>> vers2 > vers1\nFalse\n>>> \n\nHere's a JavaScript alternative:\n>>> var vers1 = \...
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0006952847_python.txt
Q: Thread Safe Python Property/Attribute? I have code like the following: class SomeSharedData(object): def __init__(self): self._lock = RLock() self._errors = 0 @property def errors(self): with self._lock: return self._errors @errors.setter def errors(self, value...
Thread Safe Python Property/Attribute?
I have code like the following: class SomeSharedData(object): def __init__(self): self._lock = RLock() self._errors = 0 @property def errors(self): with self._lock: return self._errors @errors.setter def errors(self, value): with self._lock: self...
[ "You possibly need to think a bit harder about exactly what it means to be thread safe. Consider if you wrote this code instead:\nclass SomeSharedData(object):\n def __init__(self):\n self.errors = 0\n\nThis code is exactly as thread-safe as the code that you posted. Assigning a value to an attribute is t...
[ 11 ]
[]
[]
[ "attributes", "properties", "python", "thread_safety" ]
stackoverflow_0006952478_attributes_properties_python_thread_safety.txt
Q: Installing MySQL for python/Django I'm trying to use MySQL with django and right now the following isn't executing properly: python manage.py syncdb I also downloaded the Mysql-python interpreter and ran the following lines but still an error: python setup.py build sudo python setup.py install Traceback (most re...
Installing MySQL for python/Django
I'm trying to use MySQL with django and right now the following isn't executing properly: python manage.py syncdb I also downloaded the Mysql-python interpreter and ran the following lines but still an error: python setup.py build sudo python setup.py install Traceback (most recent call last): File "setup.py", lin...
[ "It seems you may not have any of the MySQL client applications installed. If you are using Linux (and this varies from distribution to distribution), the package you will need to install on Ubuntu is \"mysql-client\".\n", "From the path you show, I'm guessing you are running on Mac OS X (you really need to state...
[ 2, 1, 0 ]
[]
[]
[ "django", "mysql", "python" ]
stackoverflow_0006917480_django_mysql_python.txt
Q: How to do IIR filter when most of the coefficients are zero I what to do some audio effect in Python. For example, the simplest echo effect formula: y[n] = x[n] + k*y[n-1000] This is an IIR filter, and can be calculated by lfilter() in scipy.signal: import numpy as np import time import scipy.signal as signal pu...
How to do IIR filter when most of the coefficients are zero
I what to do some audio effect in Python. For example, the simplest echo effect formula: y[n] = x[n] + k*y[n-1000] This is an IIR filter, and can be calculated by lfilter() in scipy.signal: import numpy as np import time import scipy.signal as signal pulse = np.zeros(10000) pulse[0] = 1.0 a = np.zeros(1000) a[[0,999...
[ "Try this:\nimport scipy\nimport scipy.signal as sig\nimport time\n\n# Input signal.\nx = scipy.randn(50000)\n\n# Filter coefficients.\na = scipy.zeros(1001)\na[[0,-1]] = [1, -0.7]\n\n# Method using lfilter.\nstart = time.clock()\ny0 = sig.lfilter([1], a, x)\nend = time.clock() - start\nprint end\n\n# Method using ...
[ 1 ]
[]
[]
[ "numpy", "python", "scipy" ]
stackoverflow_0006950552_numpy_python_scipy.txt
Q: Open file from specific disk What I want to achieve is a bit complicated to explain, so I hope I'll be clear enough ! I'm starting to write a Django application for my company. It is installed on a local server which has access to some disks, that the users have access to also. I want to be able to list some files...
Open file from specific disk
What I want to achieve is a bit complicated to explain, so I hope I'll be clear enough ! I'm starting to write a Django application for my company. It is installed on a local server which has access to some disks, that the users have access to also. I want to be able to list some files on these disks and when a user cl...
[ "Use the file:// protocol instead of http:// in your links.\n" ]
[ 0 ]
[]
[]
[ "django", "filesystems", "python" ]
stackoverflow_0006953132_django_filesystems_python.txt
Q: performing sum of outer products on sparse matrices I am trying to implement the following equation using scipy's sparse package: W = x[:,1] * y[:,1].T + x[:,2] * y[:,2].T + ... where x & y are a nxm csc_matrix. Basically I'm trying to multiply each col of x by each col of y and sum the resulting nxn matrices tog...
performing sum of outer products on sparse matrices
I am trying to implement the following equation using scipy's sparse package: W = x[:,1] * y[:,1].T + x[:,2] * y[:,2].T + ... where x & y are a nxm csc_matrix. Basically I'm trying to multiply each col of x by each col of y and sum the resulting nxn matrices together. I then want to make all non-zero elements 1. This ...
[ "Note that a sum of outer products in the manner you describe is simply the same as multiplying two matrices together. In other words,\nsum_i X[:,i]*Y[:,i].T == X*Y.T\n\nSo just multiply the matrices together.\nZ = X*Y.T\n\nFor n=10000 and m=100000 and where each column has one nonzero element in both X and Y, it c...
[ 3, 0 ]
[]
[]
[ "matrix", "numpy", "python", "scipy", "sparse_matrix" ]
stackoverflow_0006946544_matrix_numpy_python_scipy_sparse_matrix.txt
Q: Running Scons with two Python installations on Windows I have installed two different python versions (3.1 and 2,7) And this is now causing a headache. The default installation is the 3.1 which have the PYTHONHOME and PYTHONPATH set. Problem is that when I try to run scons from the 2.7 installation (via Python27/S...
Running Scons with two Python installations on Windows
I have installed two different python versions (3.1 and 2,7) And this is now causing a headache. The default installation is the 3.1 which have the PYTHONHOME and PYTHONPATH set. Problem is that when I try to run scons from the 2.7 installation (via Python27/Scripts/scons.bat) I get various import errors that reference...
[ "Try to set PYTHONHOME and PYTHONPATH in the scons.bat scripts to the right values for each Python installation respectively.\n" ]
[ 1 ]
[]
[]
[ "python", "scons", "windows" ]
stackoverflow_0006952987_python_scons_windows.txt
Q: QPropertyAnimation doesn't work with a child widget The below code doesn't animate the button as expected. But it works if the button is stand alone and stops working when it is a child widget. What am I doing wrong here? I'm trying this on Ubuntu. class TestWindow(QtGui.QWidget): def __init__(self): ...
QPropertyAnimation doesn't work with a child widget
The below code doesn't animate the button as expected. But it works if the button is stand alone and stops working when it is a child widget. What am I doing wrong here? I'm trying this on Ubuntu. class TestWindow(QtGui.QWidget): def __init__(self): QtGui.QWidget.__init__(self) self.button = QtGui...
[ "I've just tried it on Ubuntu 10.04 with PySide. Try to keep a reference to your animation object, it solved the problem here:\ndef anim(self):\n\n animation = QtCore.QPropertyAnimation(self.button, \"geometry\")\n animation.setDuration(10000)\n animation.setStartValue(QtCore.QRect(0,0,0,0))\n animation...
[ 6 ]
[]
[]
[ "animation", "pyqt", "python", "qt" ]
stackoverflow_0006952852_animation_pyqt_python_qt.txt
Q: Why do `print("Hello, World!")` and `print("Hello", "World!")` produce different outputs? I just installed Python 2.7.2 on Windows XP with the idea of learning how to program. Several of the tutorial books I'm using give examples of print commands which, when I try them, I get different answers. I expected both of...
Why do `print("Hello, World!")` and `print("Hello", "World!")` produce different outputs?
I just installed Python 2.7.2 on Windows XP with the idea of learning how to program. Several of the tutorial books I'm using give examples of print commands which, when I try them, I get different answers. I expected both of these to return the same thing - >>> print("Hello, World!") Hello, World! >>> print("Hello", "...
[ "Since print is a statement in Python 2.x, you're getting expected behavior. (a,b) is a tuple, so print (a,b) will print it as a tuple.\nOn the other hand, print is a function in Python 3.x, so \nprint(\"hello world\")\n\nand\nprint(\"hello\", \"world\")\n\nwill yield the same answer.\nThis is one breaking change w...
[ 4, 0, 0, 0 ]
[ "The difference in those two lines:\nprint(\"Hello, World!\")\n\n-> One string is printed, is says 'Hello, World!'\nprint(\"Hello\", \"World\")\n\n-> Two strings are given and both are printed. First 'Hello' and then 'World'\n" ]
[ -1 ]
[ "python" ]
stackoverflow_0006953550_python.txt
Q: Build/Parse an XML document from a socketstream in Python I have an issue parsing a continuous stream of (multiple) xml documents sent by a third party over a socket. A sample of the xml stream sent over the socket is: <?xml version="1.0"?><event><user id="1098"/><viewpage>109958</viewpage></event> <?xml version="...
Build/Parse an XML document from a socketstream in Python
I have an issue parsing a continuous stream of (multiple) xml documents sent by a third party over a socket. A sample of the xml stream sent over the socket is: <?xml version="1.0"?><event><user id="1098"/><viewpage>109958</viewpage></event> <?xml version="1.0"?><event><user id="1482"/><actions><edit>102865</edit><comm...
[ "You could have a look at the feed parsing in lxml.etree. However, you're still going to run into problems as your document is continually growing.\nAre the XML blobs separated by new line characters? If so I suggest that you buffer until you hit a new line and then send each line to an xml parser. Á la Twisted's L...
[ 0 ]
[]
[]
[ "elementtree", "python" ]
stackoverflow_0006941360_elementtree_python.txt
Q: Loop through list from specific point? I was wondering if there was a way to keep extremely large lists in the memory and then process those lists from specific points. Since these lists will have as many as almost 400 billion numbers before processing we need to split them up but I haven't the slightest idea (si...
Loop through list from specific point?
I was wondering if there was a way to keep extremely large lists in the memory and then process those lists from specific points. Since these lists will have as many as almost 400 billion numbers before processing we need to split them up but I haven't the slightest idea (since I can't find an example) of where to sta...
[ "Even if your numbers are bytes, 400GB (or 400TB if you use billion in the long-scale meaning) does not normally fit in RAM. Therefore I guess numpy.memmap or h5py may be what you're looking for.\n", "Further to the @lazyr's point, if you use the numpy.memmap method, then my previous discussion on views into nump...
[ 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0006953917_python.txt
Q: Python httplib.HTTPSConnection timeout -- connection vs. response When creating an HTTPSConnection with httplib, easy enough to set a timeout: connection = httplib.HTTPSConnection('some.server.com', timeout=10) connection.request('POST', '/api', xml, headers={'Content-Type': 'text/xml'}) response = connection.getr...
Python httplib.HTTPSConnection timeout -- connection vs. response
When creating an HTTPSConnection with httplib, easy enough to set a timeout: connection = httplib.HTTPSConnection('some.server.com', timeout=10) connection.request('POST', '/api', xml, headers={'Content-Type': 'text/xml'}) response = connection.getresponse().read() There are various parts to this operation, e.g. the c...
[ "It seems the standard library implementation does not support a timeout on the socket read operations. You would have to make the HTTPSConnection (technically the HTTPResponse._safe_read method) non-blocking for this.\nThere is a similar question here, which might also help:\nDoes python's httplib.HTTPConnection b...
[ 2 ]
[]
[]
[ "httplib", "python", "timeout" ]
stackoverflow_0006951956_httplib_python_timeout.txt
Q: Is there any library in C like python's inspect? Is there any library in C like python's inspect? def myfunction(): import inspect inspect.stack(): # this give you complete stack up to this function call It's very useful to debug python program. Actually I want to debug GTK Combobox widget, to understand c...
Is there any library in C like python's inspect?
Is there any library in C like python's inspect? def myfunction(): import inspect inspect.stack(): # this give you complete stack up to this function call It's very useful to debug python program. Actually I want to debug GTK Combobox widget, to understand complete flow I need complete function call stack. So i...
[ "No such portable library exists. There's a solution specific to GNU libc.\n", "If you are using gcc you can have a look at this (old) blog about getting the stacktrace in runtime.\nC++ stack traces with GCC\n" ]
[ 2, 0 ]
[]
[]
[ "c", "python" ]
stackoverflow_0006954136_c_python.txt
Q: Is it better to perform logical conditions in view or template? I'm starting to learn Django and I'm completely new to the MVC/MTV (whatever you want to call it) playground. In Django templates can perform logical conditions and filters. I want to know from a performance standpoint, is it better to do the conditio...
Is it better to perform logical conditions in view or template?
I'm starting to learn Django and I'm completely new to the MVC/MTV (whatever you want to call it) playground. In Django templates can perform logical conditions and filters. I want to know from a performance standpoint, is it better to do the conditions in the view or on the template itself. I actually find my self mo...
[ "I suggest separating your logic in the following way:\n\nImplement the logic belonging to what your application is doing under the hood in your Django handlers. It usually covers most of your logic.\nImplement only the logic belonging to the actual presentation in your HTML templates. For example you can put you l...
[ 2 ]
[]
[]
[ "django", "model_view_controller", "python" ]
stackoverflow_0006953930_django_model_view_controller_python.txt
Q: pyqt4 seg fault sequential app start stop I'm trying to read webpages using pyqt. I need to call a method multiple times with different URLs. I am currently using code similar to: http://blog.sitescraper.net/2010/06/scraping-javascript-webpages-in-python.html#comment-form However when I try I get seg faults. Any s...
pyqt4 seg fault sequential app start stop
I'm trying to read webpages using pyqt. I need to call a method multiple times with different URLs. I am currently using code similar to: http://blog.sitescraper.net/2010/06/scraping-javascript-webpages-in-python.html#comment-form However when I try I get seg faults. Any suggestions welcome. import sys from time impor...
[ "PyQt is often forgetting to keep references to objects. Workarounds:\n\nTry to use PySide instead of PyQt, it is easy, since the API is almost completely the same as PyQt. I would try PySide first, it might solve your problem immediately or at least make it predictable and reproducible.\nTry to keep references to ...
[ 1 ]
[]
[]
[ "pyqt4", "python", "segmentation_fault" ]
stackoverflow_0006948704_pyqt4_python_segmentation_fault.txt
Q: Resize Tkinter Window FROM THE RIGHT (python) I'm not sure on how to articulate this... I have a Tkinter window, and I need to hide half of this window when a button is pressed. However, I need the left-most side to be hidden, so that the window is now half the size it originally was, and shows the right half o...
Resize Tkinter Window FROM THE RIGHT (python)
I'm not sure on how to articulate this... I have a Tkinter window, and I need to hide half of this window when a button is pressed. However, I need the left-most side to be hidden, so that the window is now half the size it originally was, and shows the right half of the original window. All of Tkinter's resize fu...
[ "You can use right-anchored geometry specifications by using a minus sign in the right place:\n123x467-78+9\nHowever, I don't know if this will work on Windows (the above is an X11 trick, and I don't know if it is implemented in the platform-compatibility layer or not); you might have to just calculate the new posi...
[ 2, 1, 0 ]
[]
[]
[ "python", "resize", "tk_toolkit", "tkinter" ]
stackoverflow_0006870118_python_resize_tk_toolkit_tkinter.txt
Q: What is the Python equivalent of Comparables in Java? I have a dictionary of the following form: { <Category('Simulate', 'False', 'False', 'False', 'INTERMEDIATE')>: {'link': u'/story/4/tvb-adapters-simulator-simulatorAdapter/SimulatorAdapter', 'name': u'Simulate'}, <Category('View Results', 'True', 'False', 'T...
What is the Python equivalent of Comparables in Java?
I have a dictionary of the following form: { <Category('Simulate', 'False', 'False', 'False', 'INTERMEDIATE')>: {'link': u'/story/4/tvb-adapters-simulator-simulatorAdapter/SimulatorAdapter', 'name': u'Simulate'}, <Category('View Results', 'True', 'False', 'True', 'INTERMEDIATE')>: {'link': '/story/step/3', 'name': u...
[ "First: use True and False (boolean properties) instead of 'True' and 'False' (string properties).\nGenerally, you can make everything comparable in Python. You just have to define specific methods (like __eq__, __lt__, etc.) for your class.\nSo, let's say I want to compare instances of class A, and the comparison ...
[ 17, 3, 2, 1, 1 ]
[]
[]
[ "python" ]
stackoverflow_0006954501_python.txt
Q: Is there a Python library for custom autocompletion? Is there a generic library that would allow me to have autocompletion according to a custom grammar and item list? Here's an example of what I am looking for. Grammar: You can munch apples and mangoes You can drink milk and water You can move everything Sentenc...
Is there a Python library for custom autocompletion?
Is there a generic library that would allow me to have autocompletion according to a custom grammar and item list? Here's an example of what I am looking for. Grammar: You can munch apples and mangoes You can drink milk and water You can move everything Sentence structure: verb [+ adjective] + object Items: 1 green ...
[ "One module for auto-completion I'm aware of is Qt's QCompleter, which you can use in Python via PyQt or PySide. I don't think it understands grammar in the way you mean, but it's generic enough to allow you writing code that does.\n", "I finally found an acceptable solution by using a combination of SPARK (for g...
[ 2, 2 ]
[]
[]
[ "autocomplete", "grammar", "parsing", "python", "user_interface" ]
stackoverflow_0006844243_autocomplete_grammar_parsing_python_user_interface.txt
Q: Macports select default Python interpreter for executing scripts? I used python_select, it seems like it does not change the default python for executing scripts, for instance django-admin.py runserver (without python in front). How do i change this? A: There is /usr/bin/python, which is usually earlier in the p...
Macports select default Python interpreter for executing scripts?
I used python_select, it seems like it does not change the default python for executing scripts, for instance django-admin.py runserver (without python in front). How do i change this?
[ "There is /usr/bin/python, which is usually earlier in the path (has a higher precedence) than MacPort's binary folder (/opt/local/bin/python). The python_select script changes only /opt/local/bin/python, so you have to make sure there is no other python binary on your path taking precedence over it.\nSolution (as ...
[ 19 ]
[]
[]
[ "macos", "macports", "python" ]
stackoverflow_0006943812_macos_macports_python.txt
Q: Django: How to restart webserver so that changes in sourcecode get applied I using Eclipse with PyDev to develop Django Webapplication. I can start my webserver with python manage.py runserver and then I can test my webapplication locally in my browser. However everytime I change the sourcecode I have to restart ...
Django: How to restart webserver so that changes in sourcecode get applied
I using Eclipse with PyDev to develop Django Webapplication. I can start my webserver with python manage.py runserver and then I can test my webapplication locally in my browser. However everytime I change the sourcecode I have to restart eclipse so that these changes get applied in my webapplication. I guess I have t...
[ "Django dev server restarts it self when python code changes. This may not happed if you run it with noreload option\n./manage.py runserver --noreload\nAnother case when the server is not reloaded automatically is when the files changes is not used by django. For example if you have syntax error in your admin.py dj...
[ 6, 2 ]
[]
[]
[ "django", "python", "restart" ]
stackoverflow_0006954603_django_python_restart.txt
Q: Create a constraint in a field depending of another field I have a table T1 with three field: id integer Vocation integer : VOCATION = 1 or 2 or 3 or 4 or 5 TYPE integer : TYPE = 1 or 2 or 3 or 4 or 5 or 6 or 7 or 8 TYPE depend on VOCATION. For example if VOCATION = 1, TYPE should be = 2 or 3 or 4 or 6, other...
Create a constraint in a field depending of another field
I have a table T1 with three field: id integer Vocation integer : VOCATION = 1 or 2 or 3 or 4 or 5 TYPE integer : TYPE = 1 or 2 or 3 or 4 or 5 or 6 or 7 or 8 TYPE depend on VOCATION. For example if VOCATION = 1, TYPE should be = 2 or 3 or 4 or 6, other example if VOCATION = 2, TYPE should be = 4 or 5, etc. I would...
[ "Perhaps you could utilise the power of Python dictionaries and do the following:\n>>> vocdict = {1:[2,3,4,6], 2:[4,5]}\n>>> vocdict.get(1)\n [2, 3, 4, 6] \n>>> vocdict.get(2)\n [4, 5]\n\n" ]
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0006954650_python.txt
Q: Creating a Pylons Thread with Access to app_globals I'd like to create a process that runs in the background of my pylons environment, unbound to client requests, with access to the pylons app_globals object. The general purpose of the process is to check client sessions for expiration and perform some post-expira...
Creating a Pylons Thread with Access to app_globals
I'd like to create a process that runs in the background of my pylons environment, unbound to client requests, with access to the pylons app_globals object. The general purpose of the process is to check client sessions for expiration and perform some post-expiration analysis. Is this possible? I've tried creating a th...
[ "You need register app_globals (in pylons app_globals registerd per request):\npylons.app_globals._push_object(config['pylons.app_globals'])\n\n", "The object you are trying to access is StackedObjectProxy registered by pylons for every request, for the serving thread.\nIf you only intend to read it, it is safe t...
[ 3, 1 ]
[]
[]
[ "multithreading", "pylons", "python", "wsgi" ]
stackoverflow_0004741079_multithreading_pylons_python_wsgi.txt
Q: Python string and UTF-8 problems I am programming a script that will grab some data from my website using http GET. My problem is that i have to pass unicode characters to the website. I am reading a file that contains these characters and then i try produce a url in order to make the request. The file is utf-8 en...
Python string and UTF-8 problems
I am programming a script that will grab some data from my website using http GET. My problem is that i have to pass unicode characters to the website. I am reading a file that contains these characters and then i try produce a url in order to make the request. The file is utf-8 encoded and i use this to read from it f...
[ "Quote the url\nimport urllib\ns = u'Здравей'\nurllib.quote(s.encode('utf-8'))\n# %D0%97%D0%B4%D1%80%D0%B0%D0%B2%D0%B5%D0%B9\n\nor use urlencode directly to build the query part of the url\nurllib.urlencode({'data': s.encode('utf-8')})\n# 'data=%D0%97%D0%B4%D1%80%D0%B0%D0%B2%D0%B5%D0%B9'\n\n", "Build the URL with...
[ 3, 1 ]
[]
[]
[ "python", "utf_8" ]
stackoverflow_0006955418_python_utf_8.txt
Q: Jpeg plugin not loading in PySide/Qt I'm at wits end trying to figure out why my Qt install will not display JPEG. Initially I noticed when PySide would not display the image. I built a simplified version in both c++ and python, none work. I've tried qt.conf but no-go. I don't know what else to try, but I do know ...
Jpeg plugin not loading in PySide/Qt
I'm at wits end trying to figure out why my Qt install will not display JPEG. Initially I noticed when PySide would not display the image. I built a simplified version in both c++ and python, none work. I've tried qt.conf but no-go. I don't know what else to try, but I do know that it's not just PySide. P.S. this is ...
[ "Try to include PySides plugin directory with: app.addLibraryPath(pathToPluginDirectory)\n", "Probably Qt was built without jpeg support. From where did you install it?\n" ]
[ 2, 0 ]
[]
[]
[ "macos", "pyside", "python", "qt" ]
stackoverflow_0006590666_macos_pyside_python_qt.txt
Q: Adding extra fields to UserAdmin i have this custom class class CustomUserAdmin(UserAdmin): add_fieldsets = ( (None, { 'classes': ('wide',), 'fields': ('username', 'email', 'password1', 'password2', 'location')} ), ) fieldsets = ( (None, {'fields': ('user...
Adding extra fields to UserAdmin
i have this custom class class CustomUserAdmin(UserAdmin): add_fieldsets = ( (None, { 'classes': ('wide',), 'fields': ('username', 'email', 'password1', 'password2', 'location')} ), ) fieldsets = ( (None, {'fields': ('username', 'password')}), (('Perso...
[ "You are not going to modify UserAdmin right?\nSupposing that location is an actual field of CustomUser, try to use\nlist_display = UserAdmin.list_display + ('location',)\n\nEDIT: simpler answer\nUse the standard django way to show custom things in the list_display:\nclass CustomUserAdmin(UserAdmin):\n # other t...
[ 2 ]
[]
[]
[ "admin", "django", "python" ]
stackoverflow_0006955527_admin_django_python.txt
Q: Difference between shutil.copy2(s,d) and shutil.move(s,d) I have read the documentation provided for shutil.move and copy2. From my understanding move just calls the copy2 function, then calls the remove function, while copy2 calls copy then copystat. That all makes sense, except when I use them I find an intere...
Difference between shutil.copy2(s,d) and shutil.move(s,d)
I have read the documentation provided for shutil.move and copy2. From my understanding move just calls the copy2 function, then calls the remove function, while copy2 calls copy then copystat. That all makes sense, except when I use them I find an interesting caveat (I think) If I use the move function on a file all...
[ "From my understanding of the shutil documentation, shutil.copystat() doesn't preserve the creation date, it only preserves last access time and last modification date.\nAlso, shutil.move() uses shutil.copy2() followed by shutil.copystat() only if the source and destination are on different filesystems, otherwise i...
[ 5 ]
[]
[]
[ "copy", "move", "python", "shutil", "timestamp" ]
stackoverflow_0006955504_copy_move_python_shutil_timestamp.txt
Q: Ruby’s “method_missing” in Python Possible Duplicate: Python equivalent of Ruby's 'method_missing' Is there any technique available in Python for intercepting messages (method calls) like the method_missing technique in Ruby? A: As others have mentioned, in Python, when you execute o.f(x), it's really a two-st...
Ruby’s “method_missing” in Python
Possible Duplicate: Python equivalent of Ruby's 'method_missing' Is there any technique available in Python for intercepting messages (method calls) like the method_missing technique in Ruby?
[ "As others have mentioned, in Python, when you execute o.f(x), it's really a two-step operation: First, get the f attribute of o, then call it with parameter x. It's the first step that fails because there is no attribute f, and it's that step that invokes the Python magic method __getattr__.\nSo you have to imple...
[ 46, 1 ]
[]
[]
[ "metaprogramming", "method_missing", "python" ]
stackoverflow_0006954116_metaprogramming_method_missing_python.txt
Q: Django aggregate function problem (Count = -number-) User id name Device id name user-id is_enabled I want to select all Users who has At least one device enabled. Exactly 2 device enabled All devices enabled Note: enabled means (Device.is_enabled = 1) I know I can use annotate to get numbe...
Django aggregate function problem (Count = -number-)
User id name Device id name user-id is_enabled I want to select all Users who has At least one device enabled. Exactly 2 device enabled All devices enabled Note: enabled means (Device.is_enabled = 1) I know I can use annotate to get number of devices. But how to use annonate to get number of use...
[ "from django.db.models import Count\nUser.objects.filter(device__is_enabled=1).annotate(\n device_count=Count('device')).filter(device_count=2)\n\nUser.objects.exclude(device__is_enabled=0)\n\n" ]
[ 1 ]
[]
[]
[ "django", "django_models", "python" ]
stackoverflow_0006955775_django_django_models_python.txt
Q: How to get Registry().settings during Pyramid app startup time? I am used to develop web applications on Django and gunicorn. In case of Django, any application modules in a Django application can get deployment settings through django.conf.settings. The "settings.py" is written in Python, so that any arbitrary se...
How to get Registry().settings during Pyramid app startup time?
I am used to develop web applications on Django and gunicorn. In case of Django, any application modules in a Django application can get deployment settings through django.conf.settings. The "settings.py" is written in Python, so that any arbitrary settings and pre-processing can be defined dynamically. In case of guni...
[ "Another option, if you enjoy global configuration via Python, create a settings.py file. If it needs values from the ini file, parse the ini file and grab them out (at module scope, so it runs at import time):\nfrom paste.deploy.loadwsgi import appconfig\nconfig = appconfig('config:development.ini', 'myapp', rela...
[ 17, 13, 1 ]
[]
[]
[ "paste", "pyramid", "python" ]
stackoverflow_0006509856_paste_pyramid_python.txt
Q: How to access Gunicorn's configuration params from application code? I have a Werkzeug application served on gunicorn. The script directory layout looks like this: prj/ __init__.py application.py :which has a WSGI application object "wsgi_app". settings_app.py :settings for werkzeug applicaiton code...
How to access Gunicorn's configuration params from application code?
I have a Werkzeug application served on gunicorn. The script directory layout looks like this: prj/ __init__.py application.py :which has a WSGI application object "wsgi_app". settings_app.py :settings for werkzeug applicaiton code. Then, I usually use the following command-line to start the Werkzeug ap...
[ "Currently there's no direct way to be able to import Gunicorn config parameters into your application code.\nWhat you could do is use one of the various config hooks to automatically set the debug variable in your application code.\n", "You can use use optparse before Gunicorn parses args.\n" ]
[ 1, 1 ]
[]
[]
[ "python", "werkzeug" ]
stackoverflow_0004222857_python_werkzeug.txt
Q: Python regex findall into output file i got an inputfile which contains a javascript code which contains many five-figure ids. I want to have these ids in a list like: 53231,53891,72829 etc This is my actual python file: import re fobj = open("input.txt", "r") text = fobj.read() output = re.findall(r'[0-9][0-9...
Python regex findall into output file
i got an inputfile which contains a javascript code which contains many five-figure ids. I want to have these ids in a list like: 53231,53891,72829 etc This is my actual python file: import re fobj = open("input.txt", "r") text = fobj.read() output = re.findall(r'[0-9][0-9][0-9][0-9][0-9]' ,text) outp = open("outp...
[ "import re\n# Use \"with\" so the file will automatically be closed\nwith open(\"input.txt\", \"r\") as fobj:\n text = fobj.read()\n# Use word boundary anchors (\\b) so only five-digit numbers are matched.\n# Otherwise, 123456 would also be matched (and the match result would be 12345)!\noutput = re.findall(r'\\...
[ 13 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0006956279_python_regex.txt
Q: Office 2010 Product Key & Registration Lookup I have a small python program I wrote for a friend, one of the tasks is to audit the Office Version & Product Key on the machine it's run on. I was able to locate the 32bit/64bit keys in the registry easily but it seems my algorithm breaks down on the new Office 2010 s...
Office 2010 Product Key & Registration Lookup
I have a small python program I wrote for a friend, one of the tasks is to audit the Office Version & Product Key on the machine it's run on. I was able to locate the 32bit/64bit keys in the registry easily but it seems my algorithm breaks down on the new Office 2010 system. My first problem is there's now 30+ entries ...
[ "You have to read another section out of DigitalProductID\nIn CSharp I used \nfor (int ilByte = 52; ilByte <= 66; ilByte++)\nto read the necessary section to calculate the product key for O2K - O2K7. \nWith Office 2010 you need to use\nfor (int ilByte = 808; ilByte <= 822; ilByte++)\nto read the bytes which make ou...
[ 3, 0 ]
[]
[]
[ "ms_office", "python", "registry" ]
stackoverflow_0006462462_ms_office_python_registry.txt
Q: django issue with image encoding on upload I have some issues with saving images with swedish characters such as ö å ö I am getting a traceback of the following Request Method: POST Request URL: http://localhost:8000/admin/project/project/41/ Exception Type: KeyError Exception Value: ö Exception Location: /S...
django issue with image encoding on upload
I have some issues with saving images with swedish characters such as ö å ö I am getting a traceback of the following Request Method: POST Request URL: http://localhost:8000/admin/project/project/41/ Exception Type: KeyError Exception Value: ö Exception Location: /System/Library/Frameworks/Python.framework/Versio...
[ "I used pythons Unidecode to decode the file before upload.\nOne thing I've learned, always decode before encoding.\n" ]
[ 0 ]
[]
[]
[ "django", "django_models", "django_views", "python", "utf_8" ]
stackoverflow_0005088168_django_django_models_django_views_python_utf_8.txt
Q: Best practice for reusing python code I have write a python library app(which contains several *.py files). And several of my python projects need to reuse the code in the library app. What's the recommended best practice for reusing python code? Currently I have thought out three options: Copy and paste. This is...
Best practice for reusing python code
I have write a python library app(which contains several *.py files). And several of my python projects need to reuse the code in the library app. What's the recommended best practice for reusing python code? Currently I have thought out three options: Copy and paste. This is far away from best practice. It violates t...
[ "Allow me to propose a fourth alternative: take the time to learn how to package your library and install it in your site-packages; it's easier than one may think and I'm convinced it's time well spent. This is a very good starting point: https://packaging.python.org/en/latest/\n", "Of your three options, PYTHONP...
[ 46, 5, 3, 2 ]
[]
[]
[ "dry", "python", "pythonpath" ]
stackoverflow_0006956690_dry_python_pythonpath.txt
Q: Working with unicode encoded Strings from Active Directory via python-ldap I already came up with this problem, but after some testing I decided to create a new question with some more specific Infos: I am reading user accounts with python-ldap (and Python 2.7) from our Active Directory. This does work well, but I...
Working with unicode encoded Strings from Active Directory via python-ldap
I already came up with this problem, but after some testing I decided to create a new question with some more specific Infos: I am reading user accounts with python-ldap (and Python 2.7) from our Active Directory. This does work well, but I have problems with special chars. They do look like UTF-8 encoded strings when ...
[ "First, know that printing to a Windows console is often the step that garbles data, so for your tests, you should print repr(s) to see the precise bytes you have in your string.\nYou need to find out how the data from AD is encoded. Again, print repr(s) will let you see the content of the data.\nUPDATED:\nOK, it ...
[ 8 ]
[]
[]
[ "active_directory", "python", "unicode", "utf_8" ]
stackoverflow_0006956799_active_directory_python_unicode_utf_8.txt
Q: Translating content in filesystem for a Plone product I'm trying to get certain strings in a .py file translated, using the i18n machinery. Translating .pt files is not a problem, but whenever I try to translate using _('Something') in Python code on the filesystem, it always gives English text (which is the defa...
Translating content in filesystem for a Plone product
I'm trying to get certain strings in a .py file translated, using the i18n machinery. Translating .pt files is not a problem, but whenever I try to translate using _('Something') in Python code on the filesystem, it always gives English text (which is the default) instead of the Norwegian text that should be there. S...
[ "Is the domain name used for _('Something') the same as what you use in the Norwegian .po file that has the translation? They should be the same, so do not use 'plone' in one case and 'my.domain' in the other.\nAlso, the call to the underscore function does not in itself translate the string; it only creates a str...
[ 4, 3, 3 ]
[]
[]
[ "internationalization", "plone", "python", "zope" ]
stackoverflow_0006953370_internationalization_plone_python_zope.txt
Q: Problem running a python script (pypdf/hex errors) I am trying to create a Python script using the PyPDF Module. What the script does it take the 'Root' folder, merges all the PDFs in it and outputs the merged PDF in an 'Output' folder and renames it to 'Root.pdf' (the folder which containes the split PDFs). What ...
Problem running a python script (pypdf/hex errors)
I am trying to create a Python script using the PyPDF Module. What the script does it take the 'Root' folder, merges all the PDFs in it and outputs the merged PDF in an 'Output' folder and renames it to 'Root.pdf' (the folder which containes the split PDFs). What it does then is do the same with the sub-directories, gi...
[ "It looks like the PDF files you are reading are not valid PDF files, or they are more exotic than PyPDF is prepared for. Are you sure you have good PDF files to read?\nAlso, there are a few odd things in your code, but this one might really matter:\noutput_dir = \"\\Output\\\\\"\n\nYou have a \\O escape sequence ...
[ 0 ]
[]
[]
[ "hex", "merge", "pypdf", "python" ]
stackoverflow_0006956166_hex_merge_pypdf_python.txt
Q: django: Changing URL Patterns gets only applied when I restart Eclipse If I change anything in my python sourcecode of my django webapplication it gets applied as soon as I save the changes. I can test it right away locally in my browser. However when I change url patterns in my urls.py I apparently have to restar...
django: Changing URL Patterns gets only applied when I restart Eclipse
If I change anything in my python sourcecode of my django webapplication it gets applied as soon as I save the changes. I can test it right away locally in my browser. However when I change url patterns in my urls.py I apparently have to restart eclipse until these changes get applied? Whats going on here? Update I'm ...
[ "Restarting the server will pick up the changes, sounds like either the server isn't being restarted correctly, or perhaps there is a browser caching issue. (Try clearing the cache, see if that helps). If you are running the django server as a run configuration in eclipse, then you should see the incoming request...
[ 0, 0 ]
[]
[]
[ "django", "python", "url" ]
stackoverflow_0006944329_django_python_url.txt
Q: Ideal Data Structure to Deal with XML Data Maybe a silly question, but I usually learn a lot with those. :) I'm working on a software that deals a lot with XML, both as input and as output, and in between a lot of processing occurs. My first thought was to use internally a dict as a internal data structure, and f...
Ideal Data Structure to Deal with XML Data
Maybe a silly question, but I usually learn a lot with those. :) I'm working on a software that deals a lot with XML, both as input and as output, and in between a lot of processing occurs. My first thought was to use internally a dict as a internal data structure, and from there, work my way with a process of reading...
[ "An XML document in general is a tree with lots of bells and whistles (attributes vs. child nodes, mixing of text with child nodes, entities, xml declarations, comments, and many more). Handling that should be left to existing, mature libraries - for Python, it's commonly agreed that lxml is the most convenient cho...
[ 4, 0 ]
[]
[]
[ "python" ]
stackoverflow_0006957355_python.txt
Q: Install mixture of extension module. pure python module and shared libraries with distutils I am using cython for building an extension module. The module depends on an external shared library, which is found when the module is built. Further I have some pure Python modules in the same directory. Can anybody give...
Install mixture of extension module. pure python module and shared libraries with distutils
I am using cython for building an extension module. The module depends on an external shared library, which is found when the module is built. Further I have some pure Python modules in the same directory. Can anybody give me an example setup.py for this task ? I have problems getting the extension module, the pure py...
[ "I found a solution: I have a package dir ABC like\nABC/\n __init__.py\n A.py\n B.pyx\n C.so (or C.dll and C.lib on win)\n\nthen the following setup.py does the job:\n#input-encoding: utf-8\nfrom distutils.core import setup\nfrom distutils.extension import Extension\nfrom Cython.Distutils im...
[ 1 ]
[]
[]
[ "cython", "distutils", "python" ]
stackoverflow_0006945969_cython_distutils_python.txt
Q: How can I hyperlink a method from a Python module in Sphinx? While writing documentation using Sphinx, I know that I can link to a class by using Intersphinx: :py:class:`logging.Logger` But how do I link directly to a specific method, like logging.Logger.warning()? A: Just use :py:meth:`module.class.mymethodna...
How can I hyperlink a method from a Python module in Sphinx?
While writing documentation using Sphinx, I know that I can link to a class by using Intersphinx: :py:class:`logging.Logger` But how do I link directly to a specific method, like logging.Logger.warning()?
[ "Just use \n:py:meth:`module.class.mymethodname`\n\n" ]
[ 12 ]
[]
[]
[ "python", "python_sphinx" ]
stackoverflow_0006957083_python_python_sphinx.txt
Q: Minimalistic python webframework I used to create web applications with Django framework, but now I have to create only simply web GUI for python application. I would be very glad if someone will recommend to me any small python web framework. A: web.py is a popular choice for this sort of thing. "web.py is a we...
Minimalistic python webframework
I used to create web applications with Django framework, but now I have to create only simply web GUI for python application. I would be very glad if someone will recommend to me any small python web framework.
[ "web.py is a popular choice for this sort of thing.\n\"web.py is a web framework for Python that is as simple as it is powerful.\"\n", "And of course let's not forgot bottle!\n" ]
[ 2, 2 ]
[]
[]
[ "python", "web_frameworks" ]
stackoverflow_0006958404_python_web_frameworks.txt
Q: URL building with Flask and non-unique handler names Flask provides a url_for function to generate URLs to handlers based on the URL pattern. But this would imply that the handler functions must have unique names across the entire application. Is that correct? Example Module A has a handler index: @app.route('/')...
URL building with Flask and non-unique handler names
Flask provides a url_for function to generate URLs to handlers based on the URL pattern. But this would imply that the handler functions must have unique names across the entire application. Is that correct? Example Module A has a handler index: @app.route('/') def index(): pass And Module B has another handler index...
[ "I don't know how you could do with all the views routed by the same module.\nWhat I usually do is separate my views in different modules (like you did with module A and B), and register them as blueprints, after that, when using the url_for() function, you can prefix the view name with your blueprint name and then...
[ 51 ]
[]
[]
[ "flask", "python", "url", "url_routing", "wsgi" ]
stackoverflow_0006957396_flask_python_url_url_routing_wsgi.txt
Q: What's the Pythonic way to store a data block in a Python script? Perl allows me to use the __DATA__ token in a script to mark the start of a data block. I can read the data using the DATA filehandle. What's the Pythonic way to store a data block in a script? A: It depends on your data, but dict literals and m...
What's the Pythonic way to store a data block in a Python script?
Perl allows me to use the __DATA__ token in a script to mark the start of a data block. I can read the data using the DATA filehandle. What's the Pythonic way to store a data block in a script?
[ "It depends on your data, but dict literals and multi-line strings are both really good ways.\nstate_abbr = {\n 'MA': 'Massachusetts',\n 'MI': 'Michigan',\n 'MS': 'Mississippi',\n 'MN': 'Minnesota',\n 'MO': 'Missouri',\n }\n\ngettysburg = \"\"\"\nFour score and seven years ago,\nour fathers brough...
[ 11, 6, 1, 0 ]
[]
[]
[ "filehandle", "perl", "python" ]
stackoverflow_0006942843_filehandle_perl_python.txt
Q: Python, problems modifying a text file, searching for terms I posted a question yesterday here: Finding and adding to a .kml file using python I have read a bunch of tutorial and now have a better understanding of python and that is good. Yet I still can't seem to get my script right. I know I am so very close. Ba...
Python, problems modifying a text file, searching for terms
I posted a question yesterday here: Finding and adding to a .kml file using python I have read a bunch of tutorial and now have a better understanding of python and that is good. Yet I still can't seem to get my script right. I know I am so very close. Basically I want to add a bunch of jpg's to a .kml file, which is b...
[ "Because indentation is syntax in python you really need to be careful about where things are located. This may come closer. It's not 100% complete, but it will point you in the right direction:\nwith open(infile) as fhi, open(outfile, 'w') as fho:\n for line in fhi:\n if line == 'myMatchString':\n fho.w...
[ 1, 1, 1 ]
[]
[]
[ "python", "text_parsing" ]
stackoverflow_0006958593_python_text_parsing.txt
Q: python sqlite string insertion I'm trying to insert a string that was received as an argument into a sqlite db using python: def addUser(self, name): cursor=self.conn.cursor() t = (name) cursor.execute("INSERT INTO users ( unique_key, name, is_online, translate) VALUES (NUL...
python sqlite string insertion
I'm trying to insert a string that was received as an argument into a sqlite db using python: def addUser(self, name): cursor=self.conn.cursor() t = (name) cursor.execute("INSERT INTO users ( unique_key, name, is_online, translate) VALUES (NULL, ?, 1, 0);", t) self.c...
[ "You need this:\nt = (name,)\n\nto make a single-element tuple.\nRemember, it's commas that make a tuple, not brackets!\n", "Your t variable isn't a tuple, i think it is a 7-length string. To make a tuple, don't forget to put a trailing coma:\nt = (name,)\n\n" ]
[ 8, 1 ]
[]
[]
[ "python", "sqlite" ]
stackoverflow_0006958833_python_sqlite.txt
Q: Copying triangular image region with PIL I have two PIL images and two sets of corresponding 2D points that make a triangle. For example: image1: 100x100 pixels points = [(10,10), (20,20), (10,20)] image2: 250x250 pixels points = [(35,30), (75,19), (50,90)] I want to copy the triangular region from image1 and tr...
Copying triangular image region with PIL
I have two PIL images and two sets of corresponding 2D points that make a triangle. For example: image1: 100x100 pixels points = [(10,10), (20,20), (10,20)] image2: 250x250 pixels points = [(35,30), (75,19), (50,90)] I want to copy the triangular region from image1 and transform it to fit into the corresponding trian...
[ "I was able to do this with an affine transformation (thanks to this question). After the affine transformation, the destination triangle is drawn to a mask and then pasted on to the destination image. Here's what I came up with:\nimport Image\nimport ImageDraw\nimport numpy\n\ndef transformblit(src_tri, dst_tri, s...
[ 6, 0 ]
[]
[]
[ "affinetransform", "image_processing", "python", "python_imaging_library" ]
stackoverflow_0006946653_affinetransform_image_processing_python_python_imaging_library.txt
Q: Python - Extend an API client class or pass instance I'm interacting with an API for which I have a Python library. The library provides an APIClient class which provides all the functionality of the API. I want to interact with this API according to some logic, and I would like to be able to test the logic wihtou...
Python - Extend an API client class or pass instance
I'm interacting with an API for which I have a Python library. The library provides an APIClient class which provides all the functionality of the API. I want to interact with this API according to some logic, and I would like to be able to test the logic wihtout making API calls (i.e. a mock) as it is transactional. ...
[ "You would normally not mock parts of the unit under test. If you're testing MyClass, one of the things you would like to test is that it creates and executes transactions when it's really supposed to do that. The overridden method, in your example, would go un-tested.\nInstead, you should mock the layer that wou...
[ 0, 0 ]
[]
[]
[ "python", "testing" ]
stackoverflow_0006959154_python_testing.txt
Q: How to maximize performance in Python when doing many I/O bound operations? I have a situation where I'm downloading a lot of files. Right now everything runs on one main Python thread, and downloads as many as 3000 files every few minutes. The problem is that the time it takes to do this is too long. I realize Py...
How to maximize performance in Python when doing many I/O bound operations?
I have a situation where I'm downloading a lot of files. Right now everything runs on one main Python thread, and downloads as many as 3000 files every few minutes. The problem is that the time it takes to do this is too long. I realize Python has no true multi-threading, but is there a better way of doing this? I was ...
[ "Multithreading is just fine for the specific purpose of speeding up I/O on the net (although asynchronous programming would give even greater performance). CPython's multithreading is quite \"true\" (native OS threads) -- what you're probably thinking of is the GIL, the global interpreter lock that stops differen...
[ 16, 5, 3, 0 ]
[]
[]
[ "python" ]
stackoverflow_0002971381_python.txt
Q: Python module generator for github I'm newbie to python and it's philosophy. I'm trying to develop a module on github. Is there any Ruby's gem generator like tool for developing module? How to develop a module? Thank you for any advise. A: You don't need a tool to create a python module, any filename ending in ....
Python module generator for github
I'm newbie to python and it's philosophy. I'm trying to develop a module on github. Is there any Ruby's gem generator like tool for developing module? How to develop a module? Thank you for any advise.
[ "You don't need a tool to create a python module, any filename ending in .py is sufficient. A package, which is a collection of modules, is similarly created by the presence of a file named __init__.py in the same folder as other modules (and possibly other packages). The __init__.py file can be empty or not, you...
[ 2 ]
[]
[]
[ "python", "python_module" ]
stackoverflow_0006959310_python_python_module.txt
Q: python class attributes and sql alchemy relationships Ok so I have two problems: My first would by sqlalchemy related. So I'm forced to use sqllite and I have to implement some cascade deletes. Now I've found relationships do the job however these should be declared normally in the parent table. But due to some de...
python class attributes and sql alchemy relationships
Ok so I have two problems: My first would by sqlalchemy related. So I'm forced to use sqllite and I have to implement some cascade deletes. Now I've found relationships do the job however these should be declared normally in the parent table. But due to some design decision I'm forced to do this in the child so I'm doi...
[ "For the second part or your question, keep in mind, anything in your class constructor won't be instrumented by SqlAlchemy. In your example you can simply declare the relationship in its own class (note it does not inherit from you declarative_base class) and then inherit it in any subclass something like this:\nc...
[ 0 ]
[]
[]
[ "python", "sqlalchemy" ]
stackoverflow_0006956660_python_sqlalchemy.txt
Q: Split file into files with keyword in Python? I am trying to figure out how to take a file and divide in into sub-files using a keyword as the split indicator. In my case, I have a large file that looks like this: Racecar line2... line3... Racecar line5... line6... line7... line8... Racecar line10... At each occu...
Split file into files with keyword in Python?
I am trying to figure out how to take a file and divide in into sub-files using a keyword as the split indicator. In my case, I have a large file that looks like this: Racecar line2... line3... Racecar line5... line6... line7... line8... Racecar line10... At each occurrence of the word Racecar I would like to split th...
[ "with open(\"bigfile\", mode=\"r\") as bigfile:\n reader = bigfile.read()\n for i,part in enumerate(reader.split(\"Racecar\")):\n with open(\"File_\" + i+1, mode=\"w\") as newfile:\n newfile.write(\"Racecar\"+part)\n\n", "out_array = []\nwith open(\"bigfile\", mode=\"r\") as bigfile:\n ...
[ 4, 0, 0 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0006959558_python_python_3.x.txt
Q: rounded rectangle in pygtk what is the best way to draw a rounded rectangle in a pygtk application A: #!/usr/bin/env python import gtk def rounded_rectangle(cr, x, y, w, h, r=20): # This is just one of the samples from # http://www.cairographics.org/cookbook/roundedrectangles/ # A****BQ # H...
rounded rectangle in pygtk
what is the best way to draw a rounded rectangle in a pygtk application
[ "#!/usr/bin/env python\n\nimport gtk\n\ndef rounded_rectangle(cr, x, y, w, h, r=20):\n # This is just one of the samples from \n # http://www.cairographics.org/cookbook/roundedrectangles/\n # A****BQ\n # H C\n # * *\n # G D\n # F****E\n\n cr.move_to(x+r,y) ...
[ 6, 1, 0 ]
[]
[]
[ "gtk", "pygtk", "python" ]
stackoverflow_0002384374_gtk_pygtk_python.txt
Q: Psych Experiment in Python (w/Django) - how to port to interactive web app? I'm writing a psychology experiment in Python, and I need to make it available as a web app. I've already got the Python basically working as a command-line program. On the recommendation of a CS buddy I'm using Django with a sqlite db. ...
Psych Experiment in Python (w/Django) - how to port to interactive web app?
I'm writing a psychology experiment in Python, and I need to make it available as a web app. I've already got the Python basically working as a command-line program. On the recommendation of a CS buddy I'm using Django with a sqlite db. This is also working, my development server is up and the database tables are re...
[ "You are going to need to use HTML/Javascript, and then you can collect and send the results to the server. The results can get gamed though, as the code for the exercise is going to be client side.\nEdit: I recommend a Javascript library, jQuery: http://docs.jquery.com/Tutorials\nEdit 2: \nI'll be a bit more speci...
[ 3 ]
[]
[]
[ "django", "python", "sqlite" ]
stackoverflow_0006960090_django_python_sqlite.txt
Q: twisted.internet.reactor.spawnProcess raises OSError(13, 'Permission denied') When I try running a python script via `twisted.internet.reactor.spawnProcess': from twisted.internet import protocol, reactor class ProcessProtocol(protocol.ProcessProtocol): def connectionMade(self): self.transport.closeSt...
twisted.internet.reactor.spawnProcess raises OSError(13, 'Permission denied')
When I try running a python script via `twisted.internet.reactor.spawnProcess': from twisted.internet import protocol, reactor class ProcessProtocol(protocol.ProcessProtocol): def connectionMade(self): self.transport.closeStdin() def childDataReceived(self, childFD, data): print data def main...
[ "You might not have the permission to execute '/var/projects/python/worker.py', or that script's execute bit is not set. Do an ls -l /var/projects/python/worker.py and check it?\n" ]
[ 4 ]
[]
[]
[ "python", "spawn", "twisted", "twisted.internet" ]
stackoverflow_0006960211_python_spawn_twisted_twisted.internet.txt
Q: How to replace all occurrences of X between Y's? I'm not sure if this problem solvable with regular expressions (in Perl5 syntax), but here is self-explanatory example: smth Y1 test X foo X Y2 bar X Y1 X X Y2 s/?/Z/g smth Y1 test Z foo Z Y2 bar X Y1 Z Z Y2 Consider that Y1 always have a matching Y2 and there is n...
How to replace all occurrences of X between Y's?
I'm not sure if this problem solvable with regular expressions (in Perl5 syntax), but here is self-explanatory example: smth Y1 test X foo X Y2 bar X Y1 X X Y2 s/?/Z/g smth Y1 test Z foo Z Y2 bar X Y1 Z Z Y2 Consider that Y1 always have a matching Y2 and there is no overlapping.
[ "Here you go:\n$str = 'smth Y1 test X foo X Y2 bar X Y1 X X Y2';\n$str =~ s/X(?=((?!Y1).)*Y2)/Z/g;\nprint $str; #smth Y1 test Z foo Z Y2 bar X Y1 Z Z Y2\n\n", "A little awkward, but:\nmy $string = 'smth Y1 test X foo X Y2 bar X Y1 X X Y2';\n$string =~ s/(Y1.*?Y2)/ (my $tmp = \"$1\") =~ tr!X!Z!; $tmp /ge;\nprint $...
[ 4, 3, 1 ]
[]
[]
[ "perl", "python", "regex", "sed" ]
stackoverflow_0006959955_perl_python_regex_sed.txt
Q: GET request with headers using keep-alive connection under python I want to make a connection to http://mysite.org using GET method keeping connection alive and sending an user-agent header to the server. I know I should use urlgrabber or smth like that but I need the actual code actually. Please help me friends.....
GET request with headers using keep-alive connection under python
I want to make a connection to http://mysite.org using GET method keeping connection alive and sending an user-agent header to the server. I know I should use urlgrabber or smth like that but I need the actual code actually. Please help me friends.. THANK YOU conn = httplib.HTTPConnection(urlparse(url)[1]) conn.request...
[]
[]
[ "Use httplib\nThe Python docs page has examples there.\nhttp://docs.python.org/library/httplib.html\n" ]
[ -2 ]
[ "get", "http_headers", "keep_alive", "python" ]
stackoverflow_0006960282_get_http_headers_keep_alive_python.txt
Q: Pythonic way of filtering by descendant element in a dictionary If I have some json data represented in a dictionary type, what's the pythonic way of finding all 'type' nodes that match a particular value from the 'results' list of items? "results" : [ { "address_components" : [ ... child element...
Pythonic way of filtering by descendant element in a dictionary
If I have some json data represented in a dictionary type, what's the pythonic way of finding all 'type' nodes that match a particular value from the 'results' list of items? "results" : [ { "address_components" : [ ... child elements ... ], "verified" : "some data here", "geometry" ...
[ "You can use a list comprehension:\nfoundItems = [elem for elem in results if 'type_two' in elem['types']]\n\nOf course you'll probably use a variable instead of hard-coding 'type_two' like that.\nThis will allow other values in the types list alongside the one you are looking for. You can use if elem['types'] == [...
[ 2, 0 ]
[]
[]
[ "python" ]
stackoverflow_0006960593_python.txt
Q: Difference between Python print/format methods When combining a variable and a string to be printed in Python, there seem to be a number of ways to do the same thing; test = "Hello" print "{} World".format(test) #Prints 'Hello World' print test+" World" #Prints 'Hello World' print "%s World" % test #Prints 'Hello ...
Difference between Python print/format methods
When combining a variable and a string to be printed in Python, there seem to be a number of ways to do the same thing; test = "Hello" print "{} World".format(test) #Prints 'Hello World' print test+" World" #Prints 'Hello World' print "%s World" % test #Prints 'Hello World' What (if any) is the difference between thes...
[ "As you mentioned, various open source projects will use all of these methods for string formatting. However, I would stick to one method for one project so as not to confuse other developers with differing styles.\nprint test+\" World\" is the most efficient, performance-wise, but gives you the least amount flexib...
[ 9, 8, 1 ]
[]
[]
[ "python" ]
stackoverflow_0006960442_python.txt
Q: Error using SqlSoup with database views I'd like to use SqlSoup with an existing database that contains views. Accessing a table goes swimmingly, but accessing a view results in "PKNotFoundError: table '[viewname]' does not have a primary key defined..." Do I correctly infer that SqlSoup does not work with databas...
Error using SqlSoup with database views
I'd like to use SqlSoup with an existing database that contains views. Accessing a table goes swimmingly, but accessing a view results in "PKNotFoundError: table '[viewname]' does not have a primary key defined..." Do I correctly infer that SqlSoup does not work with database views (by default, at least)? I've been una...
[ "Thanks to Randy for the map() tip. Here's a complete solution that you may try verbatim (the database is publicly available):\nfrom sqlalchemy.ext.sqlsoup import SqlSoup\nfrom sqlalchemy import Table\nu = SqlSoup('postgresql+psycopg2://PUBLIC@unison-db.org:5432/unison')\npa_t = Table(\"palias\", u._metadata, auto...
[ 3, 1, 0 ]
[]
[]
[ "postgresql", "python", "sql", "sqlalchemy" ]
stackoverflow_0006286704_postgresql_python_sql_sqlalchemy.txt
Q: OSX - socket connect redirection In my application, I want to redirect certain applications connections. In windows 7, you can modify the host and port used in a TCP/UDP connect call: http://msdn.microsoft.com/en-us/library/ff571005(v=vs.85).aspx I was going to look at the tsocks source, however the author says it...
OSX - socket connect redirection
In my application, I want to redirect certain applications connections. In windows 7, you can modify the host and port used in a TCP/UDP connect call: http://msdn.microsoft.com/en-us/library/ff571005(v=vs.85).aspx I was going to look at the tsocks source, however the author says it's not working with asynchronous socke...
[ "Mac OS X, being a BSD-derived system, has ipfw, which is like Linux iptables. It lets you do this kind of thing at the OS level. The command-line tool is already installed on your mac (try man ipfw); Google will help you find graphical front ends for it.\n" ]
[ 0 ]
[]
[]
[ "c", "c++", "macos", "python", "sockets" ]
stackoverflow_0006958635_c_c++_macos_python_sockets.txt
Q: python - exporting dictionary(array) to json I have an array of dictionaries like so: myDict[0] = {'date':'today', 'status': 'ok'} myDict[1] = {'date':'yesterday', 'status': 'bad'} and I'm trying to export this array to a json file where each dictionary is its own entry. The problem is when I try to run: dump(myD...
python - exporting dictionary(array) to json
I have an array of dictionaries like so: myDict[0] = {'date':'today', 'status': 'ok'} myDict[1] = {'date':'yesterday', 'status': 'bad'} and I'm trying to export this array to a json file where each dictionary is its own entry. The problem is when I try to run: dump(myDict, open("test.json", "w")) It outputs a json fi...
[ "Use a list instead of a dictionary; you probably used:\nmyDict = {}\nmyDict[0] = {...}\n\nYou should use:\nmyList = []\nmyList.append({...}\n\nP.S.: It seems valid json to me anyways, but it is an object and not a list; maybe this is the reason why your parser is complaining\n", "You should use a JSON serializer...
[ 4, 0 ]
[]
[]
[ "dump", "json", "python" ]
stackoverflow_0006961076_dump_json_python.txt
Q: How to create a GUI with multiple lines of glyphs/text in parallel where the glyphs have x and y coordinates I'm currently creating an application to edit parallel lists of events which happen on a timeframe. In the model/backend there is a list of lists where the sublist has all the items in order. Each event sho...
How to create a GUI with multiple lines of glyphs/text in parallel where the glyphs have x and y coordinates
I'm currently creating an application to edit parallel lists of events which happen on a timeframe. In the model/backend there is a list of lists where the sublist has all the items in order. Each event should be represented by a string/glyph (from a ttf font) and each of the textlines should be edited like a normal li...
[ "I would suggest trying to setup a QGraphicsScene with your events as QGraphicText objects (or possibly a class derived from QGraphicText). Let each be positioned independently, but let them know about the \"next\" event on their line, like a linked list. Then, when one is inserted or deleted, you can quickly do ...
[ 1 ]
[]
[]
[ "pyqt", "python", "qgraphicsscene", "qt" ]
stackoverflow_0006954633_pyqt_python_qgraphicsscene_qt.txt
Q: Cannot register custom logging handler class with Django dictConfig My goal is to create a "log" app, apart from my main app, that will be used for several custom handler classes, filters, etc, and other error and stat reporting. But when running the dev server for my Django project, I receive the error: File "/...
Cannot register custom logging handler class with Django dictConfig
My goal is to create a "log" app, apart from my main app, that will be used for several custom handler classes, filters, etc, and other error and stat reporting. But when running the dev server for my Django project, I receive the error: File "/Library/Python/2.7/site-packages/Django-1.3-py2.7.egg/django/conf/__init_...
[ "It looks like you are getting a circular import. You cannot define a handler class in a module which itself imports settings.py\nIt is documented at https://docs.djangoproject.com/en/dev/topics/logging/#topic-logging-parts-handlers (Search for 'circular imports')\n" ]
[ 12 ]
[]
[]
[ "django", "django_1.3", "logging", "python", "python_2.6" ]
stackoverflow_0006958871_django_django_1.3_logging_python_python_2.6.txt
Q: Django logging with dictConfig cannot find "logging" module My LOGGING directive in settings is set to: LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'default': { 'format': '[%(asctime)s] %(levelname)s::(%(process)d %(thread)d)::%(module)s - %(message)...
Django logging with dictConfig cannot find "logging" module
My LOGGING directive in settings is set to: LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'default': { 'format': '[%(asctime)s] %(levelname)s::(%(process)d %(thread)d)::%(module)s - %(message)s' }, }, 'handlers': { 'file_handler': { ...
[ "You'll have to write,\nlogging.handlers.TimedRotatingFileHandler\n\nas the TimedRotatingFileHandler is part of the handlers package of logging.\n" ]
[ 10 ]
[]
[]
[ "django", "django_1.3", "logging", "python", "python_2.6" ]
stackoverflow_0006961212_django_django_1.3_logging_python_python_2.6.txt
Q: Conditional addition in Python I have been struggling with a text file to perform conditional appending/extending certain text using Python. My apologies in advance if this is too basic and already been discussed here in someway or the other :( Concerning the code (attached), I need to add statement "mtu 1546" und...
Conditional addition in Python
I have been struggling with a text file to perform conditional appending/extending certain text using Python. My apologies in advance if this is too basic and already been discussed here in someway or the other :( Concerning the code (attached), I need to add statement "mtu 1546" under the statement containing "descrip...
[ "The basic answer to your question is very simple. Strings are immutable, so you can't append to or extend them. You have to create a new string using concatenation. \n>>> print i\ninterface Vlan2286\n description mgmt_SNMA_Rs\n no ip address\n xconnect 22.93.94.86 2286 encapsulation mpls\n\n>>> print i + ' mtu 154...
[ 1, 1 ]
[]
[]
[ "python" ]
stackoverflow_0006960895_python.txt
Q: matplotlib does not work in Eclipse I seem to have a problem that is in parts very similar to the one mentioned here: Python with eclipse import problem But unfortunatly just in parts otherwise that would have solved mine as well. I use Eclipse SDK, Version: 3.7.0 with PyDev 101. Furthermore I have installed nu...
matplotlib does not work in Eclipse
I seem to have a problem that is in parts very similar to the one mentioned here: Python with eclipse import problem But unfortunatly just in parts otherwise that would have solved mine as well. I use Eclipse SDK, Version: 3.7.0 with PyDev 101. Furthermore I have installed numpy-1.6.1rc1-win32-superpack-python2.6.ex...
[ "pylab is in matplotlibs namespace, so this should work:\nimport matplotlib.pylab as pylab\n\n", "I found that turning off interactive move and then calling show worked. \nimport matplotlib.pyplot as plt\n\n#...your code...\n\nplt.ioff()\nplt.show()\n\n" ]
[ 2, 2 ]
[]
[]
[ "eclipse", "matplotlib", "python" ]
stackoverflow_0006513753_eclipse_matplotlib_python.txt
Q: Non-test methods in a Python TestCase Ok, as Google search isn't helping me in a while (even when using the correct keywords). I have a class extending from TestCase in which I want to have some auxiliary methods that are not going to be executed as part of the test, they'll be used to generate some mocked objects...
Non-test methods in a Python TestCase
Ok, as Google search isn't helping me in a while (even when using the correct keywords). I have a class extending from TestCase in which I want to have some auxiliary methods that are not going to be executed as part of the test, they'll be used to generate some mocked objects, etc, auxiliary things for almost any test...
[ "I believe that you don't have to do anything. Your helper methods should just not start with test_.\n", "The only methods that unittest will execute [1] are setUp, anything that starts with test, and tearDown [2], in that order. You can make helper methods and call them anything except for those three things, a...
[ 97, 4, 3 ]
[]
[]
[ "python", "unit_testing" ]
stackoverflow_0006961099_python_unit_testing.txt
Q: Changing the static directory path in webpy I'd love to be able to change the webpy static directory without the need to set up and run nginx locally. Right now, it seems webpy will only create a static directory if /static/ exists. In my case, I want to use /foo/bar/ as my static directory, but couldn't find any ...
Changing the static directory path in webpy
I'd love to be able to change the webpy static directory without the need to set up and run nginx locally. Right now, it seems webpy will only create a static directory if /static/ exists. In my case, I want to use /foo/bar/ as my static directory, but couldn't find any info related to configuring this (other than runn...
[ "If you need to have different directory for the same path then you may subclass web.httpserver.StaticMiddleware or write your own middleware like this (it tricks StaticApp by modifying PATH_INFO):\nimport web\nimport os\nimport urllib\nimport posixpath\n\nurls = (\"/.*\", \"hello\")\napp = web.application(urls, gl...
[ 5 ]
[]
[]
[ "python", "web.py" ]
stackoverflow_0006960295_python_web.py.txt
Q: What are the relative advantages of various Python/PHP web frameworks (particularly for my project)? I'm deciding on a web framework for an upcoming project, and I'd appreciate any advice. We've decided to use jQuery for the JavaScript, and are heavily leaning toward Python or PHP (more Python) for our server-side...
What are the relative advantages of various Python/PHP web frameworks (particularly for my project)?
I'm deciding on a web framework for an upcoming project, and I'd appreciate any advice. We've decided to use jQuery for the JavaScript, and are heavily leaning toward Python or PHP (more Python) for our server-side logic. I'm especially interested in web2py because of its jQuery integration. About our project Our proj...
[ "Before deciding on a framework, you should first decide if you want to commit to a language you are unfamiliar with.\nYou said you've both got minimal PHP experience, so you have to weigh up the advantages here; Will the pros for going PHP (if any) out weigh the amount of time the developers will need to spend to ...
[ 2, 1, 0, 0, 0 ]
[]
[]
[ "django", "php", "python", "web2py", "web_frameworks" ]
stackoverflow_0006935094_django_php_python_web2py_web_frameworks.txt
Q: Django prepopulation + appending fixed string Consider the following (simplified) Django model: Noun(models.Model): noun = models.CharField(max_length=30) plural = models.CharField(max_length=30) I want to be able to enter, say, 'cat' in the noun field and have the plural field be automatically populated ...
Django prepopulation + appending fixed string
Consider the following (simplified) Django model: Noun(models.Model): noun = models.CharField(max_length=30) plural = models.CharField(max_length=30) I want to be able to enter, say, 'cat' in the noun field and have the plural field be automatically populated with 'cats'. That is, I want to define a string to...
[ "Make the plural blank=True and do something like this in your save():\ndef save(self, *args, **kwargs):\n if not self.plural:\n self.plural = self.noun + 's'\n super(Noun, self).save(*args, **kwargs)\n\nI would actually do this in javascript client side so the data entry person can correct if it is in...
[ 2 ]
[]
[]
[ "django", "django_admin", "django_models", "python" ]
stackoverflow_0006962266_django_django_admin_django_models_python.txt
Q: Sending failure messages between classes Ok, so this is really just a conceptual question I'm having a bit of trouble with rather than a coding problem. I'm building a simple, weekly time tracker to automate some admin in a game. So, I have a TimeSheet class and a TimeBlock class. Here is the Timesheet class with ...
Sending failure messages between classes
Ok, so this is really just a conceptual question I'm having a bit of trouble with rather than a coding problem. I'm building a simple, weekly time tracker to automate some admin in a game. So, I have a TimeSheet class and a TimeBlock class. Here is the Timesheet class with a comment where I'm not sure what to do. class...
[ "You could provide an event listener interface, where \"interested parties\" can register to get events that you generate for example in your else above. Having an agreed-upon Event interface allows you to then react on these intelligently, e.g. have an event type (enumeration) or a UserAlertEvent subclass.\n", "...
[ 0, 0 ]
[]
[]
[ "communication", "exception_handling", "python" ]
stackoverflow_0006959127_communication_exception_handling_python.txt
Q: Splitting semicolon separated string in Python I want to split a semicolon separated string so that I can store each individual string to be used as text between XML tags using Python. The string value looks like this: 08-26-2009;08-27-2009;08-29-2009 They are just dates stored as string values I want to iterate ...
Splitting semicolon separated string in Python
I want to split a semicolon separated string so that I can store each individual string to be used as text between XML tags using Python. The string value looks like this: 08-26-2009;08-27-2009;08-29-2009 They are just dates stored as string values I want to iterate through each value, store to a variable and call the...
[ "Split returns a list as follows\n>>> a=\"08-26-2009;08-27-2009;08-29-2009\"\n>>> a_split = a.split(';')\n>>> a_split\n['08-26-2009', '08-27-2009', '08-29-2009']\n\n", "child2.text, child3.text, child4.text = three_dates_text.split(';')\n\n", "When you have variables named child1, child2, child3, and child4, th...
[ 20, 4, 3 ]
[]
[]
[ "python", "split", "string" ]
stackoverflow_0006962230_python_split_string.txt
Q: Split a list to individual entries I am extracting some emails from a CSV file and then saving it to another CSV file. email variable should be in this format: email = ['email@email.com'], ['email2@company.com'], ['email3@company2.com'] but in certain cases it will be returned as: email = ['email@email.com', 'e...
Split a list to individual entries
I am extracting some emails from a CSV file and then saving it to another CSV file. email variable should be in this format: email = ['email@email.com'], ['email2@company.com'], ['email3@company2.com'] but in certain cases it will be returned as: email = ['email@email.com', 'email2@email.com'], ['email3@email.com'] ...
[ "The next should be quite efficient:\n>>> import itertools\n>>> data = [ ['email@email.com', 'email2@email.com'], ['email3@email.com'] ]\n>>> [[i] for i in itertools.chain(*data)]\n[['email@email.com'], ['email2@email.com'], ['email3@email.com']]\n\n", "data = [ ['email@email.com', 'email2@email.com'], ['email3@e...
[ 1, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0006961527_python.txt
Q: Creating a dynamic path when I upload images I'm trying to create a dynamic path for when my users upload images. It works something like this: View: photo = Photo(...) photo.save() photo.original.save(filename, content) Model: album = models.ForeignKey(Album) original = models.ImageField(upload_to="photos/%s/o"...
Creating a dynamic path when I upload images
I'm trying to create a dynamic path for when my users upload images. It works something like this: View: photo = Photo(...) photo.save() photo.original.save(filename, content) Model: album = models.ForeignKey(Album) original = models.ImageField(upload_to="photos/%s/o" % str(album.id), max_length=200) But when I try ...
[ "Use a callback (callable): https://docs.djangoproject.com/en/dev/ref/models/fields/#django.db.models.FileField.upload_to\ndef fancy_path(instance, filename):\n return 'fancy_path/file_%s.xml' % self.instance.album.id\n\noriginal = models.ImageField(upload_to=fancy_path, max_length=200)\n\n" ]
[ 2 ]
[]
[]
[ "django", "django_models", "foreign_keys", "models", "python" ]
stackoverflow_0006962634_django_django_models_foreign_keys_models_python.txt
Q: Python - print text if action is true I'm trying to get Python to print a sentence if it successfully copies a file. While it copies the file, it ignores the print. why is this? here's a similar example of my code: from shutil import copyfile if copyfile('/Library/demo.xls','/Jobs/newdemo.xls'): print "the file...
Python - print text if action is true
I'm trying to get Python to print a sentence if it successfully copies a file. While it copies the file, it ignores the print. why is this? here's a similar example of my code: from shutil import copyfile if copyfile('/Library/demo.xls','/Jobs/newdemo.xls'): print "the file has copied" For reference, I'm using Pyth...
[ "copyfile does not return anything, but it throws an exception if an error occurs. Use the following idiom instead of the if check:\nimport shutil\n\ntry:\n shutil.copyfile('/Library/demo.xls','/Jobs/newdemo.xls')\nexcept (Error, IOError):\n # Handle error\n pass\nelse:\n # Handle success\n print \"t...
[ 9, 4, 0 ]
[]
[]
[ "if_statement", "printing", "python" ]
stackoverflow_0006962707_if_statement_printing_python.txt