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: What makes something iterable in python What makes something iterable in Python? ie. can loop over it with for Is it possible for me to create an iterable class in Python? If so, how? A: To make a class iterable, write an __iter__() method that returns an iterator: class MyList(object): def __init__(self): ...
What makes something iterable in python
What makes something iterable in Python? ie. can loop over it with for Is it possible for me to create an iterable class in Python? If so, how?
[ "To make a class iterable, write an __iter__() method that returns an iterator:\nclass MyList(object):\n def __init__(self):\n self.list = [42, 3.1415, \"Hello World!\"]\n def __iter__(self):\n return iter(self.list)\n\nm = MyList()\nfor x in m:\n print(x)\n\nprints\n42\n3.1415\nHello World!\...
[ 64, 8, 5 ]
[ "You'll want next() and __iter__() methods. Here's a nice little tutorial.\n" ]
[ -2 ]
[ "python" ]
stackoverflow_0005262235_python.txt
Q: Django south migration tool error with existing app I have existing app named auth with models and synced db with tables. I install south in project settings, run ./manage.py convert_to_south auth. It successfully created and applied fake migration. Then i add new model in this app and run ./manage.py schemamigra...
Django south migration tool error with existing app
I have existing app named auth with models and synced db with tables. I install south in project settings, run ./manage.py convert_to_south auth. It successfully created and applied fake migration. Then i add new model in this app and run ./manage.py schemamigration auth --auto. And when i was trying to migrate it by ...
[ "I had a similar error the other day. It happened because I was using MySQL and the forwards() part of the migration doesn't run in a transaction on MySQL. This caused me to have an issue where I couldn't fix it by migrating back down and then up because the south_migrationhistory table didn't register my most re...
[ 2, 0 ]
[]
[]
[ "database_migration", "django", "django_south", "python" ]
stackoverflow_0005261716_database_migration_django_django_south_python.txt
Q: Problem with Replacing special characters in a string I am trying to feed some text to a special pupose parser. The problem with this parser is that it is sensitive to ()[] characters and in my sentence in the text have quite a lot of these characters. The manual for the parser suggests that all the ()[] get repl...
Problem with Replacing special characters in a string
I am trying to feed some text to a special pupose parser. The problem with this parser is that it is sensitive to ()[] characters and in my sentence in the text have quite a lot of these characters. The manual for the parser suggests that all the ()[] get replaced with \( \) \[ \]. So using str.replace i am using to a...
[ "That's just how escaped characters (like backslashes) are printed in the REPL. The actual value of the string is as you expected.\n>>> a = '\\('\n>>> a\n'\\\\('\n>>> print(a)\n\\(\n\n", "Nothing is wrong with your code. This is Python's way to tell you that the string contains a literal \\, by showing you that t...
[ 3, 3, 1 ]
[]
[]
[ "python", "string" ]
stackoverflow_0005262356_python_string.txt
Q: How to set a deeply nested JSON value? For the JSON below, I want to add/update an item to "bonuses". Is there a way I can directly put a the variable {"name": "ham", "bonus": 12} ? { "abilities": { "FGI": { "score": 10, "mod": 1, "bonuses": [ { ...
How to set a deeply nested JSON value?
For the JSON below, I want to add/update an item to "bonuses". Is there a way I can directly put a the variable {"name": "ham", "bonus": 12} ? { "abilities": { "FGI": { "score": 10, "mod": 1, "bonuses": [ { "name": "spam", ...
[ "abilities.FGI.bonuses.push({\"name\": \"ham\", \"bonus\": 12});\nEDIT or:\nabilities[\"FGI\"][\"bonuses\"].push(..);\n", "That'll be a fun one! There isn't really an easy (built-in) way to do it. In markusf's answer, he mentions pushing at item on the end, but that's only half of your problem. If you want to ...
[ 1, 0 ]
[]
[]
[ "dictionary", "json", "list", "python" ]
stackoverflow_0005262347_dictionary_json_list_python.txt
Q: how to set time interval in app engine How do you set time interval before the events occurs in google app engine? like I want to give the users 3 seconds to read the warnings before they are redirected to some pages. like there is 3 second pause before self.redirect("/"). Thank you A: If you want to have a pau...
how to set time interval in app engine
How do you set time interval before the events occurs in google app engine? like I want to give the users 3 seconds to read the warnings before they are redirected to some pages. like there is 3 second pause before self.redirect("/"). Thank you
[ "If you want to have a pause on the client-side before redirecting to a different page, you need to do that on the client side, so it will have nothing to do with AppEngine directly.\nYou can create such an effect with a meta refresh tag in the <head> section of your page:\n<meta http-equiv=\"refresh\" content=\"3;...
[ 3 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0005262595_google_app_engine_python.txt
Q: What is the correct way to backup ZODB blobs? I am using plone.app.blob to store large ZODB objects in a blobstorage directory. This reduces size pressure on Data.fs but I have not been able to find any advice on backing up this data. I am already backing up Data.fs by pointing a network backup tool at a directory...
What is the correct way to backup ZODB blobs?
I am using plone.app.blob to store large ZODB objects in a blobstorage directory. This reduces size pressure on Data.fs but I have not been able to find any advice on backing up this data. I am already backing up Data.fs by pointing a network backup tool at a directory of repozo backups. Should I simply point that tool...
[ "It should be safe to do a repozo backup of the Data.fs followed by an rsync of the blobstorage directory, as long as the database doesn't get packed while those two operations are happening.\nThis is because, at least when using blobs with FileStorage, modifications to a blob always results in the creation of a ne...
[ 13, 3, 2, 1 ]
[]
[]
[ "blobstorage", "plone", "python", "zodb", "zope" ]
stackoverflow_0000451952_blobstorage_plone_python_zodb_zope.txt
Q: is it necessary enough in my boss's django code this is the code: params = dict(request.REQUEST.items()) but i think it is not necessary , because i think the request.REQUEST must be the dict , so it should be : params = request.REQUEST am i right ? thanks A: The documentation states: For convenience, a dict...
is it necessary enough in my boss's django code
this is the code: params = dict(request.REQUEST.items()) but i think it is not necessary , because i think the request.REQUEST must be the dict , so it should be : params = request.REQUEST am i right ? thanks
[ "The documentation states:\n\nFor convenience, a dictionary-like\n object that searches POST first, then\n GET. Inspired by PHP's $_REQUEST.\n\n(Emphasis added)\nHttpRequest.REQUEST is a dictionary-like item. It is not a dictionary. Your boss might've wanted dictionary operations that weren't on the dictionary-li...
[ 2, 0, 0, 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0005257540_django_python.txt
Q: SqlAlchemy / Sqlite Distance calculation I'm using sqlAlchemy ORM and would like to like to calculate and return the distance from a given point and the stored points. class Event(Base): __tablename__ = 'events' # Schema id = Column(Integer, primary_key=True) title = Column(String(150)) descr...
SqlAlchemy / Sqlite Distance calculation
I'm using sqlAlchemy ORM and would like to like to calculate and return the distance from a given point and the stored points. class Event(Base): __tablename__ = 'events' # Schema id = Column(Integer, primary_key=True) title = Column(String(150)) description = Column(Text) url = Column(String(...
[ "Problem 1: Latitude degrees and longitude degrees have different lengths ... same at the equator (assuming earth is a sphere) but at the poles a longitude degree has zero length.\nUpdate To give an example of the severity of your problem:\nTravelling north or south by one degree of latitude will cover about 111.2 ...
[ 2, 0, 0 ]
[]
[]
[ "geospatial", "python", "sqlalchemy", "sqlite" ]
stackoverflow_0005206786_geospatial_python_sqlalchemy_sqlite.txt
Q: pdf file with python How can search a word or a line in a pdf file? Is there an existing module to do that by being concise? Thank you in advance, A: There's something called as pyPDF. It is a Pure-Python library built as a PDF toolkit. You can extract ( using extractText() method ) & also perform search on the ...
pdf file with python
How can search a word or a line in a pdf file? Is there an existing module to do that by being concise? Thank you in advance,
[ "There's something called as pyPDF.\nIt is a Pure-Python library built as a PDF toolkit.\nYou can extract ( using extractText() method ) & also perform search on the pdf file with using something like following code. \npdf = pyPdf.PdfFileReader(file(path, \"rb\"))\ncontent = pdf.getPage(1).extractText()\n\n" ]
[ 3 ]
[]
[]
[ "file", "line", "pdf", "python", "word" ]
stackoverflow_0005263250_file_line_pdf_python_word.txt
Q: read a very very big file with python What is the best solution to process each line of a text file whose size is about 500 MB? The proposal to which I had thought : def files(mon_fichier): while True: data = mon_fichier.read(1024) if not data: break yield data fichier = op...
read a very very big file with python
What is the best solution to process each line of a text file whose size is about 500 MB? The proposal to which I had thought : def files(mon_fichier): while True: data = mon_fichier.read(1024) if not data: break yield data fichier = open('tonfichier.txt', 'r') for bloc in files...
[ "with open('myfile.txt') as inf:\n for line in inf:\n # do something\n pass\n\n", "Just using the standard file operations should work as long as you keep away from readlines and instead just use readline.\n", "The answer is depending what you want to do with the datas...\nI recommend to read b...
[ 11, 7, 1, 0 ]
[]
[]
[ "file", "python", "text" ]
stackoverflow_0005262391_file_python_text.txt
Q: python pickle.dumps AssertionError I'm trying to pickle a class instance containing two lists of another instances. The instances in the two lists have attributes that refer instances of each other. Here are the classes. import pickle from copy import copy class Graph: def __init__(self): self.vertice...
python pickle.dumps AssertionError
I'm trying to pickle a class instance containing two lists of another instances. The instances in the two lists have attributes that refer instances of each other. Here are the classes. import pickle from copy import copy class Graph: def __init__(self): self.vertices = {} self.edges = set() de...
[ "There are some kinds of data the older pickle protocol cannot handle. To solve your problem, use pickle.HIGHEST_PROTOCOL\n>>> p = pickle.dumps(g)\n File \"/usr/lib/python2.6/pickle.py\", line 244, in memoize\n assert id(obj) not in self.memo\nAssertionError:\n>>> p = pickle.dumps(g, pickle.HIGHEST_PROTOCOL)\n>...
[ 0 ]
[]
[]
[ "cross_reference", "pickle", "python" ]
stackoverflow_0004426981_cross_reference_pickle_python.txt
Q: What's Python's os.system() equivalent to cocoa/Objective-C? I'd like to run some terminal command within my Mac program. For example, I normally use mate abc.txt or python abc.py from my shell to open Text Mate or running python script. How can I do the same thing with Cocoa/Objective-C? I thought about this me...
What's Python's os.system() equivalent to cocoa/Objective-C?
I'd like to run some terminal command within my Mac program. For example, I normally use mate abc.txt or python abc.py from my shell to open Text Mate or running python script. How can I do the same thing with Cocoa/Objective-C? I thought about this method, but I prefer just running in one line. For example, when use...
[ "You can use an NSTask object. If you don't like all of the setup that goes in to this, you can create an NSTask category that does it for you.\n", "You can use the C runtime system() call.\n#include <stdlib.h>\n\nsystem([item UTF8String]);\n\n" ]
[ 3, 1 ]
[]
[]
[ "cocoa", "command", "objective_c", "python", "shell" ]
stackoverflow_0005263470_cocoa_command_objective_c_python_shell.txt
Q: How to use python to turn a .dbf into a shapefile I have been scouring the internet trying to find a pythonic (sp?!) way to process this data.. Everyday we will recieve a load of data in .dbf format (hopefully) - we then need to save this data as a shapefile. Does anyone have any links or any suggestions as to my ...
How to use python to turn a .dbf into a shapefile
I have been scouring the internet trying to find a pythonic (sp?!) way to process this data.. Everyday we will recieve a load of data in .dbf format (hopefully) - we then need to save this data as a shapefile. Does anyone have any links or any suggestions as to my process?
[ "To append the file's creation_date to its name, you need to obtain the creation date with os.stat() and then rename the file with os.rename(). You can format the date string with date.strftime().\nimport datetime, os\n\nfilename = 'original.ext'\n\nfileinfo = os.stat(filename)\ncreation_date = datetime.date.fromti...
[ 2, 1, 0, 0 ]
[]
[]
[ "arcmap", "gis", "python" ]
stackoverflow_0005041209_arcmap_gis_python.txt
Q: Extracting a substring makes the for loop break in python I am having a lot of trouble with a text file given to me that I need to parse. This is my third attempt at parsing it (I tried both C and php which seem to fail in different ways). I have this extremely simple code : import fileinput for line in filei...
Extracting a substring makes the for loop break in python
I am having a lot of trouble with a text file given to me that I need to parse. This is my third attempt at parsing it (I tried both C and php which seem to fail in different ways). I have this extremely simple code : import fileinput for line in fileinput.input(['basin_stclair.txt']): print line[0:64] For so...
[ "You have some problem with the newline characters in your file. Try opening the file using Python's universal newline support:\nfor line in open('basin_stclair.txt', 'U'):\n print line[0:64]\n\n", "Are you trying to print the first 64 lines? If so, try something like this:\ni = 0\nfor line in fileinput.input...
[ 3, 1 ]
[]
[]
[ "python" ]
stackoverflow_0005263968_python.txt
Q: C++ equivalent to Python's cmp or Haskell's compare Question: Is there a C++ equivalent for Python's cmp or Haskell's compare? compare is like operator== and operator< in one. It returns LT, EQ, or GT. But it's twice as fast as calling both operator== and operator< because it does it in one pass. More details: At ...
C++ equivalent to Python's cmp or Haskell's compare
Question: Is there a C++ equivalent for Python's cmp or Haskell's compare? compare is like operator== and operator< in one. It returns LT, EQ, or GT. But it's twice as fast as calling both operator== and operator< because it does it in one pass. More details: At work, I often have structs that are used as keys for maps...
[ "You can easily implement it yourself, as a free function.\n#include <string>\n#include <vector>\nenum order {\n order_lt = -1,\n order_eq,\n order_gt\n};\n\n// General case, templated version.\ntemplate < typename T >\norder compare(T left, T right) {\n if (left < right)\n return order_lt;\n ...
[ 3, 2, 1, 1 ]
[]
[]
[ "c++", "haskell", "python" ]
stackoverflow_0005257984_c++_haskell_python.txt
Q: How to condense this function? def average(tup): """ ugiufh """ total = ((int(tup[0]) + int(tup[1]) + int(tup[2]))/3, (int(tup[0]) + int(tup[1]) + int(tup[2]))/3, (int(tup[0]) + int(tup[1]) + int(tup[2]))/3) return total I am writing a function to average out three element in a tup...
How to condense this function?
def average(tup): """ ugiufh """ total = ((int(tup[0]) + int(tup[1]) + int(tup[2]))/3, (int(tup[0]) + int(tup[1]) + int(tup[2]))/3, (int(tup[0]) + int(tup[1]) + int(tup[2]))/3) return total I am writing a function to average out three element in a tuple which means if the original tuple...
[ "If you are sure you want integer division, you can use\ndef average(tup):\n n = len(tup)\n return (sum(int(x) for x in tup) / n,) * n\n\n", "There are ways to condense the code you listed, but what you should really strive for is making the code more readable.\ndef average(a):\n \"\"\"Return a tuple whe...
[ 5, 1, 0, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0005263287_python.txt
Q: Store a lot of data inside python Maybe I start will a small introduction for my problem. I'm writing a python program which will be used for post-processing of different physical simulations. Every simulation can create up to 100 GB of output. I deal with different informations (like positions, fields and densiti...
Store a lot of data inside python
Maybe I start will a small introduction for my problem. I'm writing a python program which will be used for post-processing of different physical simulations. Every simulation can create up to 100 GB of output. I deal with different informations (like positions, fields and densities,...) for different time steps. I wou...
[ "I would try using HDF5. There are two commonly used Python interfaces, h5py and PyTables. While the latter seems to be more widespread, I prefer the former.\n", "If you're on a 64-bit operating system, you can use the mmap module to map that entire file into memory space. Then, reading random bits of the data ...
[ 7, 7, 0 ]
[]
[]
[ "python" ]
stackoverflow_0005264228_python.txt
Q: sorting strings based on your own values in python I think this may be a rather simple question but I've searched other questions and haven't really found anything completely relevant. Say I have a list containing a number of strings like mylist = ['queen', 'jack', 'queen', 'king', 'jack'] Now, I want to sort t...
sorting strings based on your own values in python
I think this may be a rather simple question but I've searched other questions and haven't really found anything completely relevant. Say I have a list containing a number of strings like mylist = ['queen', 'jack', 'queen', 'king', 'jack'] Now, I want to sort the strings in this list based on their relative values. ...
[ "Use a key lookup:\nsuits = {'queen': 2, 'jack': 1, 'king': 2}\nl = ['queen','jack','king']\nprint sorted(l, key=suits.get)\n\n" ]
[ 4 ]
[]
[]
[ "list", "python", "string" ]
stackoverflow_0005264432_list_python_string.txt
Q: generate python regex at runtime to match numbers from 'n' to infinite I am using scrapy to crawl a website and extract data from it, scrapy uses regex-based rules to check if a page has to be parsed, or a link has to be followed. I am implementing a resume feature for my spider, so it could continue crawling from...
generate python regex at runtime to match numbers from 'n' to infinite
I am using scrapy to crawl a website and extract data from it, scrapy uses regex-based rules to check if a page has to be parsed, or a link has to be followed. I am implementing a resume feature for my spider, so it could continue crawling from the last visited page. For this, I get the last followed link from a databa...
[ "Why not group the page number, then check if it is qualified:\n>>> m=re.match(\"/page(\\d+)\\.html\",\"/page18.html\")\n>>> if m:\n ID=int(m.groups()[0])\n>>> ID > 15\nTrue\n\nOr more specifically what you requested:\n>>> def genRegex(n):\n return ''.join('[' + \"0123456789\"[int(d):] + ']' for d in str(n))\...
[ 3, 2, 2, 0 ]
[]
[]
[ "python", "regex", "scrapy" ]
stackoverflow_0005205668_python_regex_scrapy.txt
Q: Python or PHP for small windows administration scripts? I'm choosing between these two languages, in contrast to another question here. My program going to be set of scripts checking files, free space, checking that apps are running etc. and writing information to database. Then PHP web page will show results. Pyt...
Python or PHP for small windows administration scripts?
I'm choosing between these two languages, in contrast to another question here. My program going to be set of scripts checking files, free space, checking that apps are running etc. and writing information to database. Then PHP web page will show results. Python have more examples of winapi calls (at least at StackOver...
[ "Don't shrink from using a language just because you haven't used it before. Learning a new language is one of ways to expand your overall capabilities as a programmer. True, you won't be as productive with it at first but learning how the language tackles common problems (manipulation of data structures, creatio...
[ 1, 0, 0, 0 ]
[]
[]
[ "php", "python", "scripting", "winapi", "windows" ]
stackoverflow_0004038124_php_python_scripting_winapi_windows.txt
Q: Configuring Python 2.7 to use modules I installed Python 2.7, OpenCV2.2, Numpy 1.51, SCIPY 0.9.0 and PIL 1.1.7 on a Windows 32-bit system. Everything works fine (i.e. I can import modules) when Python is called from the directory it is installed in (i.e. C:\Program Files\Python27). However, I cannot load modules (...
Configuring Python 2.7 to use modules
I installed Python 2.7, OpenCV2.2, Numpy 1.51, SCIPY 0.9.0 and PIL 1.1.7 on a Windows 32-bit system. Everything works fine (i.e. I can import modules) when Python is called from the directory it is installed in (i.e. C:\Program Files\Python27). However, I cannot load modules (e.g. ImportError: No module named PIL) if I...
[ "You should set the PYTHONPATH environment variable.\nhttp://docs.python.org/using/cmdline.html#envvar-PYTHONPATH\nFor some reason on my Linux system, this variable isn't set. But if I go into the Python shell and run:\nimport sys\nprint sys.path\n\nit shows the location of all my modules.\n" ]
[ 0 ]
[]
[]
[ "opencv", "python", "zend_framework_modules" ]
stackoverflow_0005264679_opencv_python_zend_framework_modules.txt
Q: Does Python's `tarfile` module store the archives it's building in memory? I'm working in a memory constrained environment where I need to make archives of SQL dumps. If I use python's built in tarfile module is the '.tar' file held in memory or written to disk as it's created? For instance, in the following code...
Does Python's `tarfile` module store the archives it's building in memory?
I'm working in a memory constrained environment where I need to make archives of SQL dumps. If I use python's built in tarfile module is the '.tar' file held in memory or written to disk as it's created? For instance, in the following code, if huge_file.sql is 2GB will the tar variable take up 2GB in memory? import ta...
[ "No it is not loading it in memory. You can read the source for tarfile to see that it's using copyfileobj, which is using a fixed size buffer to copy from the file to the tarball:\ndef copyfileobj(src, dst, length=None):\n \"\"\"Copy length bytes from fileobj src to fileobj dst.\n If length is None, copy ...
[ 5 ]
[]
[]
[ "memory", "python", "tar", "tarfile" ]
stackoverflow_0005264755_memory_python_tar_tarfile.txt
Q: What is best pythonic way to communicate between spreaded services/unix machines? Mornink! I need to design, write and implement wide system consisting of multiple unix servers performing different roles and running different services. The system must be bullet proof, robust and fast. Yeah, I know. ;) Since I dont...
What is best pythonic way to communicate between spreaded services/unix machines?
Mornink! I need to design, write and implement wide system consisting of multiple unix servers performing different roles and running different services. The system must be bullet proof, robust and fast. Yeah, I know. ;) Since I dont know how to approach this task, I've decided to ask you for your opinion before I leav...
[ "Some general ideas for you:\nYou could have a master-client approach. Requests would be inserted in the master, stored in a database. Master knows the state of each client (same db). Whenever there is a request, the master redirects it to a free client. The client reports back when has finished the task (including...
[ 0, 0 ]
[]
[]
[ "communication", "django", "python", "tcp", "unix" ]
stackoverflow_0005264414_communication_django_python_tcp_unix.txt
Q: Python - Human sort of numbers with alpha numeric, but in pyQt and a __lt__ operator I have data rows and wish to have them presented as follows: 1 1a 1a2 2 3 9 9.9 10 10a 11 100 100ab ab aB AB As I am using pyQt and code is contained within a TreeWidgetItem, the code I'm trying to solve is: def __lt__(self, othe...
Python - Human sort of numbers with alpha numeric, but in pyQt and a __lt__ operator
I have data rows and wish to have them presented as follows: 1 1a 1a2 2 3 9 9.9 10 10a 11 100 100ab ab aB AB As I am using pyQt and code is contained within a TreeWidgetItem, the code I'm trying to solve is: def __lt__(self, otherItem): column = self.treeWidget().sortColumn() #return self.text(column).toLower...
[ "This may help you. Edit the regexp to match the digit patterns you're interested in. Mine will treat any digit fields containing . as floats. Uses swapcase() to invert your case so that 'A' sorts after 'a'.\nUpdated: Refined:\nimport re\n\ndef _human_key(key):\n parts = re.split('(\\d*\\.\\d+|\\d+)', key)\n ...
[ 6, 2, 0, 0 ]
[]
[]
[ "operator_keyword", "pyqt", "python", "sorting" ]
stackoverflow_0005254021_operator_keyword_pyqt_python_sorting.txt
Q: Equation solver in Python Given a simple equation such as: x = y + z You can get the third variable if you bind the other two (ie: y = x - z and z = x - y). A straightforward way to put this in code: def solve(args): if 'x' not in args: return args['y'] + args['z'] elif 'z' not in args: re...
Equation solver in Python
Given a simple equation such as: x = y + z You can get the third variable if you bind the other two (ie: y = x - z and z = x - y). A straightforward way to put this in code: def solve(args): if 'x' not in args: return args['y'] + args['z'] elif 'z' not in args: return args['x'] - args['y'] ...
[ "Consider using Sympy. It includes various tools to solve equations and a lot more. \nThe following is an excerpt from the docs: \n>>> from sympy import I, solve\n>>> from sympy.abc import x, y\n\n>>> solve(x**4-1, x)\n[1, -1, -I, I]\n\n" ]
[ 9 ]
[]
[]
[ "equation_solving", "parsing", "python" ]
stackoverflow_0005264780_equation_solving_parsing_python.txt
Q: Python Adventure Game -> Chose A or B in a while loop not working! I'm trying to create a simple adventure game in Python. I've come to a point where I need to ask the user if they wish to choose option A or B and am using a while loop to try and do this: AB = input("A or B?") while AB != "A" or "a" or "B" or "b"...
Python Adventure Game -> Chose A or B in a while loop not working!
I'm trying to create a simple adventure game in Python. I've come to a point where I need to ask the user if they wish to choose option A or B and am using a while loop to try and do this: AB = input("A or B?") while AB != "A" or "a" or "B" or "b": input("Choose either A or B") if AB == "A" or "a": print("A")...
[ "Your while statement is evaluating on the conditionals or, which is always true for the strings you provided.\nwhile AB != \"A\" or \"a\" or \"B\" or \"b\":\n\nmeans:\nwhile (AB != \"A\") or \"a\" or \"B\" or \"b\":\n\nNon-empty strings are always True, so writing or \"B\" will always be true, and will always ask ...
[ 5, 3, 2, 1, 1, 0 ]
[]
[]
[ "if_statement", "loops", "python", "while_loop" ]
stackoverflow_0005264792_if_statement_loops_python_while_loop.txt
Q: S3 Backup Memory Usage in Python I currently use WebFaction for my hosting with the basic package that gives us 80MB of RAM. This is more than adequate for our needs at the moment, apart from our backups. We do our own backups to S3 once a day. The backup process is this: dump the database, tar.gz all the files i...
S3 Backup Memory Usage in Python
I currently use WebFaction for my hosting with the basic package that gives us 80MB of RAM. This is more than adequate for our needs at the moment, apart from our backups. We do our own backups to S3 once a day. The backup process is this: dump the database, tar.gz all the files into one backup named with the correct ...
[ "It's a little late but I had to solve the same problem so here's my answer.\nShort answer: in Python 2.6+ yes! This is because the httplib supports file-like objects as of v2.6. So all you need is...\nfileobj = open(filename, 'rb')\ncontent_type = mimetypes.guess_type(filename)[0]\nif not content_type:\n conten...
[ 2, 0 ]
[]
[]
[ "amazon_s3", "memory", "python", "upload" ]
stackoverflow_0002464685_amazon_s3_memory_python_upload.txt
Q: Capturing webcam stream in Python using OpenCV - Need help I'm running Python2.7 on Arch Linux. I installed OpenCV via Pacman. The Python code I'm using is: import cv capture = cv.CaptureFromCAM(0) Very simple. All I'm trying to do, for now, is get Python access to my webcam. But that above code outputs: [user@h...
Capturing webcam stream in Python using OpenCV - Need help
I'm running Python2.7 on Arch Linux. I installed OpenCV via Pacman. The Python code I'm using is: import cv capture = cv.CaptureFromCAM(0) Very simple. All I'm trying to do, for now, is get Python access to my webcam. But that above code outputs: [user@host python]$ python2.7 webcam.py VIDIOC_QUERYMENU: Invalid argu...
[ "Take a look at this: Displaying a webcam feed using OpenCV and Python\nIt appears that you're not passing .CaptureFromCAM() the right argument. If there is only one camera, you can do something like this:\n capture = cv.CaptureFromCAM(-1)\n\nThe -1 tells it to just grab whatever camera it can find (see this).\n...
[ 3 ]
[]
[]
[ "linux", "opencv", "python", "webcam" ]
stackoverflow_0004835146_linux_opencv_python_webcam.txt
Q: Messing around with Aliasing I have the following code that works as expected: a = [1, 2, 3, 4] b = a >>> b is a True if I change it up a little it still works: a = [1, 2, 3, 4] b = a[2] * 2 >>> b is a[2] * 2 True Now the problem: a = [1, 2, 3, 4] b = a * 2 >>> b is a * 2 False Can someone please explain...
Messing around with Aliasing
I have the following code that works as expected: a = [1, 2, 3, 4] b = a >>> b is a True if I change it up a little it still works: a = [1, 2, 3, 4] b = a[2] * 2 >>> b is a[2] * 2 True Now the problem: a = [1, 2, 3, 4] b = a * 2 >>> b is a * 2 False Can someone please explain to me why this returns False, whi...
[ "When a is a list, a * 2 creates a new list instance. If you call a * 2 twice, you create two new list instances -- that's why b is a * 2 yields False.\nThe reason that you get True for b is a[2] * 2 is an optimisation of CPython that caches small integers. Since integers are immutable in Python, it actually does...
[ 4, 2, 0 ]
[]
[]
[ "pointer_aliasing", "python" ]
stackoverflow_0005265651_pointer_aliasing_python.txt
Q: How to run python test files I am developing python in eclipse. As a result, python src files and test files are in different directories. Question is: How do we run on command line specific test files in the test folder? These obviously depend on files in the src folder. Cheers Edit: if I run python test/myTest...
How to run python test files
I am developing python in eclipse. As a result, python src files and test files are in different directories. Question is: How do we run on command line specific test files in the test folder? These obviously depend on files in the src folder. Cheers Edit: if I run python test/myTestFile.py I get dependency errors, ...
[ "You need to make sure your PYTHONPATH is set correctly so the command-line interpreter can find your packages, or run your test cases from within Eclipse Pydev. Update: Another option: running your tests using nose might make things a bit easier, since it can auto-discover packages and test cases.\nIf your project...
[ 5, 1 ]
[]
[]
[ "python", "unit_testing" ]
stackoverflow_0005265746_python_unit_testing.txt
Q: Python: If there are multiple egg versions of the same package installed, how do I import specifically the version I need? Say, for example that FooPackage-1.1 and FooPackage-1.2 are both installed in dist-packages as eggs. How do I import the one I need? A: You can use pkg_resources to specify your requirements...
Python: If there are multiple egg versions of the same package installed, how do I import specifically the version I need?
Say, for example that FooPackage-1.1 and FooPackage-1.2 are both installed in dist-packages as eggs. How do I import the one I need?
[ "You can use pkg_resources to specify your requirements at import time:\nimport pkg_resources\npkg_resources.require('FooPackage==1.2')\nimport FooPackage\n\nFor example:\n% easy_install simplejson==2.1.3\n% easy_install simplejson==2.1.2\n\npkg_resources.require('simplejson==2.1.2')\nimport simplejson\nassert simp...
[ 16 ]
[]
[]
[ "distutils", "egg", "python", "setuptools" ]
stackoverflow_0005265731_distutils_egg_python_setuptools.txt
Q: Regex to match the first file in a rar archive file set in Python I need to uncompress all the files in a directory and for this I need to find the first file in the set. I'm currently doing this using a bunch of if statements and loops. Can i do this this using regex? Here's a list of files that i need to match:...
Regex to match the first file in a rar archive file set in Python
I need to uncompress all the files in a directory and for this I need to find the first file in the set. I'm currently doing this using a bunch of if statements and loops. Can i do this this using regex? Here's a list of files that i need to match: yes.rar yes.part1.rar yes.part01.rar yes.part001.rar yes.r01 yes.r001 ...
[ "Don't rely on the names of the files to determine which one is first. You're going to end up finding an edge case where you get the wrong file.\nRAR's headers will tell you which file is the first on in the volume, assuming they were created in a somewhat-recent version of RAR.\n\nHEAD_FLAGS Bit flags:\n 2 b...
[ 5, 3, 1 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0002537882_python_regex.txt
Q: Python idiomatic unpacking assignment or False If function returns a two value list or tuple on success or False on failure, how can I best unpack the return list into two variables while also checking for False? def get_key_value(): if (cond != True): return False return [val1, val2] # Call it # How can ...
Python idiomatic unpacking assignment or False
If function returns a two value list or tuple on success or False on failure, how can I best unpack the return list into two variables while also checking for False? def get_key_value(): if (cond != True): return False return [val1, val2] # Call it # How can I also check for False while unpacking? key, value =...
[ "Coverting @Felix Kling's great comment into an answer.\nIf not being able to find a (key, value) pair indicates some kind of system failure, it would be better to throw an exception. If your failure doesn't really fall into any of the standard exceptions, you should build a new exception type of your own.\nThe con...
[ 4, 3, 1, 1 ]
[]
[]
[ "iterable_unpacking", "python" ]
stackoverflow_0005266113_iterable_unpacking_python.txt
Q: Getting Shoutcast Metadata in Appengine I currently have an appengine application set up that polls a Shoutcast station's 7.html file and saves the result. However, I have recently come across some stations which are running Shoutcast version 2.0 and don't seem to support the 7.html method. So how can I somehow re...
Getting Shoutcast Metadata in Appengine
I currently have an appengine application set up that polls a Shoutcast station's 7.html file and saves the result. However, I have recently come across some stations which are running Shoutcast version 2.0 and don't seem to support the 7.html method. So how can I somehow retrieve the metadata from such servers?
[ "According to current ShoutCast v2 docs you should be able to call:\nhttp://blah:port/currentsong?sid=<streamid>\n\nIf you don't know the streamid (ShoutCast v2 adds stream multiplexing), you can get http://blah:port/index.html for a list of active stations on that port and their id's.\nMore details at:\nhttp://dev...
[ 3 ]
[]
[]
[ "google_app_engine", "python", "shoutcast" ]
stackoverflow_0004446719_google_app_engine_python_shoutcast.txt
Q: cProfile taking a lot of memory I am attempting to profile my project in python, but I am running out of memory. My project itself is fairly memory intensive, but even half-size runs are dieing with "MemoryError" when run under cProfile. Doing smaller runs is not a good option, because we suspect that the run ti...
cProfile taking a lot of memory
I am attempting to profile my project in python, but I am running out of memory. My project itself is fairly memory intensive, but even half-size runs are dieing with "MemoryError" when run under cProfile. Doing smaller runs is not a good option, because we suspect that the run time is scaling super-linearly, and we...
[ "Updated: Since cProfile is built into current versions of Python (the _lsprof extension) it should be using the main allocator. If this doesn't work for you, Python 2.7.1 has a --with-valgrind compiler option which causes it to switch to using malloc() at runtime. This is nice since it avoids having to use a supp...
[ 1 ]
[]
[]
[ "cprofile", "memory", "python" ]
stackoverflow_0005266699_cprofile_memory_python.txt
Q: How to calculate tag-wise precision and recall for POS tagger? I am using some rule-based and statistical POS taggers to tag a corpus(of around 5000 sentences) with Parts of Speech(POS). Following is a snippet of my test corpus where each word is seperated by its respective POS tag by '/'. No/RB ,/, it/PRP was/VBD...
How to calculate tag-wise precision and recall for POS tagger?
I am using some rule-based and statistical POS taggers to tag a corpus(of around 5000 sentences) with Parts of Speech(POS). Following is a snippet of my test corpus where each word is seperated by its respective POS tag by '/'. No/RB ,/, it/PRP was/VBD n't/RB Black/NNP Monday/NNP ./. But/CC while/IN the/DT New/NNP York...
[ "Note that since every word has exactly one tag, overall recall and precision scores are meaningless for this task (they'll both just equal the accuracy measure). But it does make sense to ask for recall and precision measures per tag - for example, you could find the recall and precision for the DT tag.\nThe most ...
[ 7 ]
[]
[]
[ "machine_learning", "nlp", "python", "shell", "text_processing" ]
stackoverflow_0005264492_machine_learning_nlp_python_shell_text_processing.txt
Q: Python/numpy: all values in array up to x? I have an ordered array like this: numpy.array([1, 2, 5, 10, 25, 36, 66, 90, 121, 230, 333, 500]) Suppose I want all values up to 60 (if 60 isn't in, i want to stop at the first value greater than 60), so I want [1, 2, 5, 10, 25, 36, 66]. If I use numpy.where() with <= 60...
Python/numpy: all values in array up to x?
I have an ordered array like this: numpy.array([1, 2, 5, 10, 25, 36, 66, 90, 121, 230, 333, 500]) Suppose I want all values up to 60 (if 60 isn't in, i want to stop at the first value greater than 60), so I want [1, 2, 5, 10, 25, 36, 66]. If I use numpy.where() with <= 60, it stops before 66. My solution from numpy i...
[ "there is a specific numpy function to do this, np.searchsorted, which is much faster than bisect.\na=np.arange(1e7)\nc=2e6\n%timeit bisect.bisect(a,c)\n10000 loops, best of 3: 31.6 us per loop\n%timeit np.searchsorted(a,c)\n100000 loops, best of 3: 6.77 us per loop\n\nMore remarkably ,it has also a specific keywor...
[ 10, 2 ]
[]
[]
[ "arrays", "numpy", "python" ]
stackoverflow_0005265275_arrays_numpy_python.txt
Q: Python lightweight server for embedded devices Is there any lightweight Python server for embedded processors ( to 10 MB )? Do I need any framework for developing pages on this small server or can I do that in plain Python? A: bottle.py might be what you're looking for. It is a light-weight framework, as well a...
Python lightweight server for embedded devices
Is there any lightweight Python server for embedded processors ( to 10 MB )? Do I need any framework for developing pages on this small server or can I do that in plain Python?
[ "bottle.py might be what you're looking for. It is a light-weight framework, as well as a server. \nweb.py is similar.\nI'm not sure of your exact needs or requirements, but they are two good options to investigate. \n" ]
[ 3 ]
[]
[]
[ "embedded", "python" ]
stackoverflow_0005267066_embedded_python.txt
Q: Website to image I'm running Python 3.1 and you would call me an advanced novice :) My question is simple: I'm trying to make a simple program which asks the users for a URL (or multiple URLs) and then goes to the website and takes a screenshot (of the whole page, not just what can be seen in the browser without s...
Website to image
I'm running Python 3.1 and you would call me an advanced novice :) My question is simple: I'm trying to make a simple program which asks the users for a URL (or multiple URLs) and then goes to the website and takes a screenshot (of the whole page, not just what can be seen in the browser without scrolling all the way d...
[ "There is a package called webkit2png that you can use for this, its located: here\nMore information on this blog post\nExample from blog post(copied to SO for preservation, read the blog post to understand it if you have issues):\n#!/usr/bin/env python\nimport sys\nimport signal\n\nfrom PyQt4.QtCore import *\nfrom...
[ 3, 0 ]
[]
[]
[ "image", "python", "python_3.x" ]
stackoverflow_0005266830_image_python_python_3.x.txt
Q: wxpython TextCtrl and infinite loop question TextCtrl is not working when it's inside an infinite loop for some reason, here's my code: while 1: localtime = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) i = i + 1 #print str(i) serRead = ser.readline() serSplit = s...
wxpython TextCtrl and infinite loop question
TextCtrl is not working when it's inside an infinite loop for some reason, here's my code: while 1: localtime = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) i = i + 1 #print str(i) serRead = ser.readline() serSplit = serRead.split(",") #this works pri...
[ "I suspect wxpython has some processing it needs to do (dispatching events and so forth) in its main loop. But until you return from your event handler, that loop can't run. You'd probably be better off setting up a timer to update your text control periodically.\n", "You should probably use wx.Timer instead of i...
[ 6, 3, 3 ]
[]
[]
[ "infinite_loop", "python", "user_interface", "wxpython" ]
stackoverflow_0005266396_infinite_loop_python_user_interface_wxpython.txt
Q: How to call django template in order to use it through Jquery? I've installed the django-newsletter application, and customized the subscribing form. But, right now, I'd like to print it through a Jquery Overlay, instead of a flatpage containing that form. Problem is I don't know how to include this flatpages ele...
How to call django template in order to use it through Jquery?
I've installed the django-newsletter application, and customized the subscribing form. But, right now, I'd like to print it through a Jquery Overlay, instead of a flatpage containing that form. Problem is I don't know how to include this flatpages elements into every page where the link calling the overlay will be pre...
[ "Create a Django view which renders just the HTML for the form using your preferred template. Then use $.ajax() with dataType: \"html\" to get the code for the form for use in your overlay.\n", "So this kind of expands in more detail what @Nathan suggested.\nTake one\nFirst, you can publish the subscription form ...
[ 2, 1, 0 ]
[]
[]
[ "django", "forms", "jquery", "python" ]
stackoverflow_0005266425_django_forms_jquery_python.txt
Q: Yielding a dictionary containing an object's attributes in Python I'm currently trying to write a piece of code that will dump all attributes of a given class instance to a dictionary so that I can change them without changing the source object. Is there a method for doing this, or perhaps a built-in dictionary I ...
Yielding a dictionary containing an object's attributes in Python
I'm currently trying to write a piece of code that will dump all attributes of a given class instance to a dictionary so that I can change them without changing the source object. Is there a method for doing this, or perhaps a built-in dictionary I can copy and access? What I'm really doing is making a special class th...
[ "Why not write a __getattr__() (or __getattribute__()) method on your \"mimic\" object that does this only when an attribute is requested, rather than copying the attributes? Among other benefits, this will keep properties as executable code (rather than copying their return value) and will work even if a new attri...
[ 2, 1 ]
[]
[]
[ "python" ]
stackoverflow_0005266978_python.txt
Q: python + psycopg2 = unknown types? It seems when I use callproc(), psycopg2 isn't properly casting strings as text or character varying. For example: values = [pid, 4, 4, 'bureau ama', 0, 130, row['report_dte'], row['report_dte'], 1, 1, 1, None, None, 'published', row['report_dte']] cur.callproc('header', values) ...
python + psycopg2 = unknown types?
It seems when I use callproc(), psycopg2 isn't properly casting strings as text or character varying. For example: values = [pid, 4, 4, 'bureau ama', 0, 130, row['report_dte'], row['report_dte'], 1, 1, 1, None, None, 'published', row['report_dte']] cur.callproc('header', values) Yields: psycopg2.ProgrammingError: func...
[ "Based on your updated mogrify() output, your strings and datetimes appear to be correctly interpreted. The E'foo bar' is Postgres' \"escape string constant\". It lets you represent C-style escape sequences, like \\t for tab, in text. Also the unknown you see in the psycopg2.ProgrammingError are nothing to worry ...
[ 2 ]
[]
[]
[ "postgresql", "psycopg2", "python" ]
stackoverflow_0005267027_postgresql_psycopg2_python.txt
Q: Python ctypes argument errors I wrote a test dll in C++ to make sure things work before I start using a more important dll that I need. Basically it takes two doubles and adds them, then returns the result. I've been playing around and with other test functions I've gotten returns to work, I just can't pass an arg...
Python ctypes argument errors
I wrote a test dll in C++ to make sure things work before I start using a more important dll that I need. Basically it takes two doubles and adds them, then returns the result. I've been playing around and with other test functions I've gotten returns to work, I just can't pass an argument due to errors. My code is: im...
[ "You probably got the calling conventions mixed up. I'm guessing you have a C function declared something like this:\ndouble haloshg_add(double d1, double s2)\n{\n return d1+d2;\n}\n\nThis will use the C calling convention by default. The simplest approach would be to change the calling convention in your ctyp...
[ 22 ]
[]
[]
[ "ctypes", "dll", "python" ]
stackoverflow_0005267434_ctypes_dll_python.txt
Q: Store file mapping from local to cloud In Python, what do you believe is the best way to store file mapping info from local machine to cloud storage? i.e. A user has 10 files in 3 different folders on his local machine. They are also stored on a cloud storage, each identify by URL or other descriptors. Best way -...
Store file mapping from local to cloud
In Python, what do you believe is the best way to store file mapping info from local machine to cloud storage? i.e. A user has 10 files in 3 different folders on his local machine. They are also stored on a cloud storage, each identify by URL or other descriptors. Best way - in terms of scallability, search/insert eff...
[ "You can either use the rsync program, or the rsync algorithm implemented in Python. Assumably you can have access to the remote files over something that looks like a file system, like WebDAV. \nBest \n" ]
[ 0 ]
[]
[]
[ "cloud", "python" ]
stackoverflow_0005263312_cloud_python.txt
Q: Using python graphviz ImportError: No module named _gv I'm trying to use graphviz with python and I get the error: Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/usr/lib/pymodules/python2.6/gv.py", line 7, in <module> import _gv ImportError: No module named _gv The system st...
Using python graphviz ImportError: No module named _gv
I'm trying to use graphviz with python and I get the error: Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/usr/lib/pymodules/python2.6/gv.py", line 7, in <module> import _gv ImportError: No module named _gv The system state: dpkg -l|grep graphviz ii graphviz 2.20.2-...
[ "I fixed the problem. The solution was: \nsudo su \ncd /usr/lib/pyshared/python2.6 \nmv _gv.so _gv.so- \nln -s libgv_python.so _gv.so \nsys.path.append('/usr/lib/pyshared/python2.6')\n\n", "For Ubuntu 10.04, \ncd /usr/lib/pymodules/python2.6\n\nsudo ln -s libgv_python.so _gv.so\n\n" ]
[ 7, 2 ]
[]
[]
[ "graphviz", "package", "python" ]
stackoverflow_0002133767_graphviz_package_python.txt
Q: How do I re-install python on the mac, but version 3.2 (latest) and have all the command line stuff work I uninstalled python using the following commands: sudo rm -rf /Library/Frameworks/Python.framework sudo rm -rf /Applications/Python * then deleted all python related things in here: /usr/local/bin And I ju...
How do I re-install python on the mac, but version 3.2 (latest) and have all the command line stuff work
I uninstalled python using the following commands: sudo rm -rf /Library/Frameworks/Python.framework sudo rm -rf /Applications/Python * then deleted all python related things in here: /usr/local/bin And I just installed python 3.2, but the terminal python doesn't work, $> python doesn't do anything, other than say c...
[ "Hmm not sure I'd really go around deleting things that were installed my Mac OS.... grab your install CD and get the default Python back :)\nThen install MacPorts type sudo port install python32 and you'll have a seperate install of Python 3.2 in /opt somewhere safe from the default one.\n", "Try ActivePython. N...
[ 6, 3, 2 ]
[]
[]
[ "macos", "python" ]
stackoverflow_0005263712_macos_python.txt
Q: problem displaying sympy rendered svg in python I have the following program which uses sympy and svgmath to render a user's algebraic expression. It nearly works but there are a few issues: The svg is not actually produced until the program exits so obviously cannot be diplayed. Is there a way to improve the per...
problem displaying sympy rendered svg in python
I have the following program which uses sympy and svgmath to render a user's algebraic expression. It nearly works but there are a few issues: The svg is not actually produced until the program exits so obviously cannot be diplayed. Is there a way to improve the performance (not looking up 'svgmath.xml' every time etc...
[ "You should close the file handles, because otherwise the data written may not yet have been flushed to the filesystem. \nparser.parse()\noutput.close()\n\nAlternatively, use a with expression.\nwith open(\"test.svg\", \"w\") as output:\n ...\n parser.parse()\nload()\n\n\nDoes an actual svg file need to be pr...
[ 2 ]
[]
[]
[ "pyside", "python", "qt", "svg", "sympy" ]
stackoverflow_0005265226_pyside_python_qt_svg_sympy.txt
Q: copying iterators and producing combinations Say I have a list, and I want to produce a list of all unique pairs of elements without considering the order. One way to do this is: mylist = ['W','X','Y','Z'] for i in xrange(len(mylist)): for j in xrange(i+1,len(mylist)): print mylist[i],mylist[j] W X W Y...
copying iterators and producing combinations
Say I have a list, and I want to produce a list of all unique pairs of elements without considering the order. One way to do this is: mylist = ['W','X','Y','Z'] for i in xrange(len(mylist)): for j in xrange(i+1,len(mylist)): print mylist[i],mylist[j] W X W Y W Z X Y X Z Y Z I want to do this with iterators...
[ "This has already been done and is included in the standard library as of Python 2.6:\nimport itertools\n\nmylist = ['W', 'X', 'Y', 'Z']\nfor pair in itertools.combinations(mylist, 2):\n print pair # pair is a tuple of 2 elements\n\nSeems pretty Pythonic to me ;-)\nNote that even if you're calculating a l...
[ 8, 0 ]
[]
[]
[ "combinations", "iterator", "list", "python" ]
stackoverflow_0005267959_combinations_iterator_list_python.txt
Q: gtk problem on macosx i installed gtk using homebrew brew install gtk brew info gtk gtk+ 2.20.1 http://www.gtk.org/ Depends on: pkg-config, glib, jpeg, libtiff, pango, jasper, atk /usr/local/Cellar/gtk+/2.20.1 (1051 files, 33M) http://github.com/mxcl/homebrew/commits/master/Library/Formula/gtk+.rb after th...
gtk problem on macosx
i installed gtk using homebrew brew install gtk brew info gtk gtk+ 2.20.1 http://www.gtk.org/ Depends on: pkg-config, glib, jpeg, libtiff, pango, jasper, atk /usr/local/Cellar/gtk+/2.20.1 (1051 files, 33M) http://github.com/mxcl/homebrew/commits/master/Library/Formula/gtk+.rb after that, i add LD_LIBRARY_PATH a...
[ "PyGTK is a separate project. Install that as well.\n" ]
[ 4 ]
[]
[]
[ "gtk", "homebrew", "macos", "python" ]
stackoverflow_0005268169_gtk_homebrew_macos_python.txt
Q: How does C/C++ know how long a dynamic allocated array is This question has been bothering me for a while. If I do int* a = new int[n], for example, I only have an pointer that points to the beginning of array a, but how does C/C++ know about n? I know if I want to pass this array to another function, then I have...
How does C/C++ know how long a dynamic allocated array is
This question has been bothering me for a while. If I do int* a = new int[n], for example, I only have an pointer that points to the beginning of array a, but how does C/C++ know about n? I know if I want to pass this array to another function, then I have to pass the length of the array with it, so I guess C/C++ does...
[ "C/C++ doesn't; it's the allocator (the little piece of code that implements malloc(), free(), etc.) that knows how long it is. C/C++ is welcome to wee all over itself, free of the constraints of having to worry about the length.\nAlso, PyString_AsStringAndSize().\n", "Let's hit the disassembler! This is going t...
[ 7, 4, 0 ]
[]
[]
[ "c", "c++", "dynamic_memory_allocation", "memory_management", "python" ]
stackoverflow_0005268095_c_c++_dynamic_memory_allocation_memory_management_python.txt
Q: What's the best library for automated-tests for IE with Python? I am using Python to do automated tests for IE. Currently I use PAMIE. It can click links and find words very well if a web page has no iframes. However, some of my tested pages include several iframes, and PAMIE seems can't handle it correctly. It ca...
What's the best library for automated-tests for IE with Python?
I am using Python to do automated tests for IE. Currently I use PAMIE. It can click links and find words very well if a web page has no iframes. However, some of my tested pages include several iframes, and PAMIE seems can't handle it correctly. It can't find the text strings in the iframes. Does anyone recommend some ...
[ "Use Selenium with it's Python client binding. Selenium can let you record your own workflow or write your own script in one of its supported languages. The tests are conducted on an actual browser as opposed to a simulated one. There's no system can top it at the moment.\n" ]
[ 4 ]
[]
[]
[ "automated_tests", "python", "testing" ]
stackoverflow_0005268489_automated_tests_python_testing.txt
Q: Python urllib2() functions with international/UTF-8 characters For a personal research/fun project I am using the Python urllib2() function. However, when I have a link with non-ASCII chars, say, "الراجل اللى ورا عمر سليمان" or "我爸是李刚" then the interpreter (IDLE in Windows 7) runs into problems. s = urllib2.urlop...
Python urllib2() functions with international/UTF-8 characters
For a personal research/fun project I am using the Python urllib2() function. However, when I have a link with non-ASCII chars, say, "الراجل اللى ورا عمر سليمان" or "我爸是李刚" then the interpreter (IDLE in Windows 7) runs into problems. s = urllib2.urlopen("http://www.bing.com/search?q=我爸是李刚") How should I go about rect...
[ "s = urllib2.urlopen(\"http://www.bing.com/search?\"\n + urllib.urlencode({ 'q' : u'我爸是李刚' .encode('utf8') } )\n\nShould work.\n", "# coding: utf-8\n\nimport urllib\nimport urlparse\n\nscheme = 'http'\nnetloc = 'www.bing.com'\npath = '/search'\nqs = {'q': u'我爸是李刚'.encode('utf-8')}\n\nprint urlparse.u...
[ 1, 0 ]
[]
[]
[ "ascii", "python", "urllib2", "utf_8" ]
stackoverflow_0005268516_ascii_python_urllib2_utf_8.txt
Q: Pipe numpy data in Linux? Is it possible to pipe numpy data (from one python script ) into the other? suppose that script1.py looks like this: x = np.zeros(3, dtype={'names':['col1', 'col2'], 'formats':['i4','f4']}) print x Suppose that from the linux command, I run the following: python script1.py | script2.py Wi...
Pipe numpy data in Linux?
Is it possible to pipe numpy data (from one python script ) into the other? suppose that script1.py looks like this: x = np.zeros(3, dtype={'names':['col1', 'col2'], 'formats':['i4','f4']}) print x Suppose that from the linux command, I run the following: python script1.py | script2.py Will script2.py get the piped num...
[ "Check out the save and load functions. I don't think they would object to being passed a pipe instead of a file.\n", "No, data is passed through a pipe as text. You'll need to serialize the data in script1.py before writing, and deserialize it in script2.py after reading.\n", "See this question.\nIf you're wil...
[ 3, 2, 0 ]
[]
[]
[ "linux", "numpy", "pipe", "python", "ubuntu" ]
stackoverflow_0005268391_linux_numpy_pipe_python_ubuntu.txt
Q: order_with_respect_to() Child relationship I'm trying to figure out how I can use: order_with_respect_to() to order via a Child relationship class Product(models.Model): name = models.CharField(max_length=100) class Affiliate(models.Model): product = models.ForeignKey(Product) clicks = models.Integer...
order_with_respect_to() Child relationship
I'm trying to figure out how I can use: order_with_respect_to() to order via a Child relationship class Product(models.Model): name = models.CharField(max_length=100) class Affiliate(models.Model): product = models.ForeignKey(Product) clicks = models.IntegerField(default=0) I want to be able to display t...
[ "Take a look at aggregates (http://docs.djangoproject.com/en/dev/topics/db/aggregation/). I think you can use them to help you with this problem.\n", "See order_with_respect_to documentation here, updated since this question was posted.\n" ]
[ 1, 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0001668742_django_python.txt
Q: Using threading to keep FTP control port alive My FTP download script (based on ftplib) is hanging on large downloads. The remote server I'm working with, while highly configurable (proftpd) is unable to get passed the firewall limitations imposed by the remote network. I am restricted to using passive mode at ...
Using threading to keep FTP control port alive
My FTP download script (based on ftplib) is hanging on large downloads. The remote server I'm working with, while highly configurable (proftpd) is unable to get passed the firewall limitations imposed by the remote network. I am restricted to using passive mode at my company, i.e. IT will not open a port for me to a...
[ "You might also try to use the TCP KeepAlive feature\nby adding this code:\nimport socket\nftp.sock.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)\n\nThe support of the TCP KeepAlive is highly platform and firewall dependent - thus no guarantee, but it is designed for this purpose and it would be a lot simpl...
[ 8 ]
[]
[]
[ "ftp", "multithreading", "python", "sockets" ]
stackoverflow_0005269012_ftp_multithreading_python_sockets.txt
Q: Python - Passing Function Arguments I am struggling on how to work out how I pass arguments from a function so that I can populate a list in another function - my code is: infinity = 1000000 invalid_node = -1 startNode = 0 #Values to assign to each node class Node: distFromSource = infinity previo...
Python - Passing Function Arguments
I am struggling on how to work out how I pass arguments from a function so that I can populate a list in another function - my code is: infinity = 1000000 invalid_node = -1 startNode = 0 #Values to assign to each node class Node: distFromSource = infinity previous = invalid_node visited = False #...
[ "That's because theNetwork[currentNode] returns a list. In other words: theNetwork is a list of lists. \nThis is the line where it is done:\ntheNetwork = [[int(node) for node in line.split(',')] for line in f.readlines()]\n\n", "class Node(object):\n def __init__(self, me, dists):\n super(Node,self).__...
[ 1, 1, 0 ]
[]
[]
[ "dijkstra", "python" ]
stackoverflow_0005267612_dijkstra_python.txt
Q: Naming a new list from another list in Python this may sound like a strange question from a Python noob, but here's the deal. I have a list with a bunch of (string) entries. I want to take one of those entries, add another string to the end of it, and then create a new array with that name. Eg, I have list=["fo...
Naming a new list from another list in Python
this may sound like a strange question from a Python noob, but here's the deal. I have a list with a bunch of (string) entries. I want to take one of those entries, add another string to the end of it, and then create a new array with that name. Eg, I have list=["foo","bar"] and I want to get something to the effec...
[ "I would use a python dictionary they can use practically anything as an index instead of integers. You're code could get messy and unreadable really fast if you are dynamically creating local / global variables.\nFor example\nl = [\"foo\",\"bar\"]\nd = {}\nd[l[0] + \"blah\"] = []\nd[l[0] + \"blah\"].append(\"foo\...
[ 6, 1 ]
[]
[]
[ "list", "python" ]
stackoverflow_0005269235_list_python.txt
Q: Trying to get Pyramid running under Apache + mod_wsgi but it's failing I've got Apache2 running with mod_wsgi installed. I've confirmed that mod_wsgi actually works by following this. The problem comes when I try to get Pyramid running. I get an Internal Server Error and my Apache error log contains the exception:...
Trying to get Pyramid running under Apache + mod_wsgi but it's failing
I've got Apache2 running with mod_wsgi installed. I've confirmed that mod_wsgi actually works by following this. The problem comes when I try to get Pyramid running. I get an Internal Server Error and my Apache error log contains the exception: AssertionError: The EvalException middleware is not usable in a multi-proce...
[ "You're using the EvalException middleware (as can be seen from your error message). This solution to this error is actually covered in the Debugging Techniques wiki of mod_wsgi.\nBasically, since the middleware allows browser-based interactive debugging of your application, all requests need to be sent to the same...
[ 6 ]
[]
[]
[ "apache", "mod_wsgi", "pyramid", "python" ]
stackoverflow_0005269447_apache_mod_wsgi_pyramid_python.txt
Q: Google App Engine UrlFetch - problem with urls with special characters in them I'm using Google Translate to convert a piece of text to speech with this url: http://translate.google.com/translate_tts?tl=%s&q=%s Where the parameter tl contains the language code of the language of the text you want converted to spee...
Google App Engine UrlFetch - problem with urls with special characters in them
I'm using Google Translate to convert a piece of text to speech with this url: http://translate.google.com/translate_tts?tl=%s&q=%s Where the parameter tl contains the language code of the language of the text you want converted to speech, and q contains the text you want converted. Normal words (without special charac...
[ "Apparently the problem is not an App Engine problem, but it has to do with the way the Google Translate url handles different user agents.\nAn example:\n#!/usr/bin/env python\n#coding=utf-8\n\nimport urllib\n\nclass MyOpener(urllib.FancyURLopener):\n version = \"App/1.7\" #doesn't work\n version = \"Mozilla/...
[ 0 ]
[]
[]
[ "google_app_engine", "python", "urlfetch" ]
stackoverflow_0005252445_google_app_engine_python_urlfetch.txt
Q: Using Python Image Library with VirtualEnv on Windows I'm attempting to install the PIL library in an Virtual Enviroment that I have created. Usually to install PIL I'd grab the install, however this won't allow me to choose my virtualenv only my root Python folder (C:/Python26). I tried both pip install PIL and e...
Using Python Image Library with VirtualEnv on Windows
I'm attempting to install the PIL library in an Virtual Enviroment that I have created. Usually to install PIL I'd grab the install, however this won't allow me to choose my virtualenv only my root Python folder (C:/Python26). I tried both pip install PIL and easy_install PIP but they didn't work. I've also tried downl...
[ "Rename from PIL-1.1.7-py2.6-win32.egg to PIL in site-packages dir.\n", "OK this appears to be a VirtualEnv problem. \nDespite making a new VirtualEnv with the --no-site-packages argument, my Django site is fetching the django files from the root install C:/Python26/Lib/site-packages/ rather than locally.\nDjango...
[ 6, 4, 0 ]
[]
[]
[ "django", "python", "python_imaging_library", "virtualenv", "windows" ]
stackoverflow_0003208639_django_python_python_imaging_library_virtualenv_windows.txt
Q: any python module can support enumerate 2 lists and do the "cross multiplication"? I often write below snippets in daily works, res = [] a = ["A","B","C","D"] b = [1,2,3,4] for _a in a: for _b in b: res.append((_a,_b)) # or be more simple #[(_a,_b) for _a in a for _b in b] [('A', 1), ('A', 2), ('A'...
any python module can support enumerate 2 lists and do the "cross multiplication"?
I often write below snippets in daily works, res = [] a = ["A","B","C","D"] b = [1,2,3,4] for _a in a: for _b in b: res.append((_a,_b)) # or be more simple #[(_a,_b) for _a in a for _b in b] [('A', 1), ('A', 2), ('A', 3), ('A', 4), ('B', 1), ('B', 2), ('B', 3), ('B', 4), ('C', 1), ('C', 2), ('C'...
[ "itertools.product is exactly what you need:\n>>> list(itertools.product(\"ABCD\", \"1234\"))\n[('A', '1'), ('A', '2'), ('A', '3'), ('A', '4'), ('B', '1'),\n('B', '2'), ('B', '3'), ('B', '4'), ('C', '1'), ('C', '2'),\n('C', '3'), ('C', '4'), ('D', '1'), ('D', '2'), ('D', '3'),\n('D', '4')]\n\n", "You are looking ...
[ 3, 2 ]
[]
[]
[ "combinations", "emulation", "list", "python" ]
stackoverflow_0005270541_combinations_emulation_list_python.txt
Q: Python-Gmail Email Retreving/downloading I just thought, would it be possible to make a python script which recives information (emails) from gmail? e.g. I type in my username and password then it goes to www.google.com/mail/user..... and downloads emails as .txt files for me to read? [Python 3.1] A: This might ...
Python-Gmail Email Retreving/downloading
I just thought, would it be possible to make a python script which recives information (emails) from gmail? e.g. I type in my username and password then it goes to www.google.com/mail/user..... and downloads emails as .txt files for me to read? [Python 3.1]
[ "This might be what you are looking for : Reading and parsing email from Gmail using C#, C++ or Python\n" ]
[ 5 ]
[]
[]
[ "download", "email", "gmail", "python" ]
stackoverflow_0005270108_download_email_gmail_python.txt
Q: Obtaining module name: x.__module__ vs x.__class__.__module__ I want to obtain the module from which a Python object is from. Both x.__module__ and x.__class__.__module__ seem to work. Are these completely redundant? Is there any reason to prefer one over another? A: If x is a class then x.__module__ and x.__c...
Obtaining module name: x.__module__ vs x.__class__.__module__
I want to obtain the module from which a Python object is from. Both x.__module__ and x.__class__.__module__ seem to work. Are these completely redundant? Is there any reason to prefer one over another?
[ "If x is a class then x.__module__ and x.__class__.__module__ will give you different things:\n# (Python 3 sample; use 'class Example(object): pass' for Python 2)\n>>> class Example: pass\n\n>>> Example.__module__\n'__main__'\n>>> Example.__class__.__module__\n'builtins'\n\nFor an instance which doesn't define __mo...
[ 13 ]
[]
[]
[ "module", "python", "python_module" ]
stackoverflow_0005271112_module_python_python_module.txt
Q: Replace if elif block in python It turned out that this conditional block keeps on repeating itself in my code. Any other way to make my life easier? Of course, the body to be executed for a condition differs. if self.datatype == "string": t = "z" elif self.datatype == "double": t = "d" elif self.datatype ...
Replace if elif block in python
It turned out that this conditional block keeps on repeating itself in my code. Any other way to make my life easier? Of course, the body to be executed for a condition differs. if self.datatype == "string": t = "z" elif self.datatype == "double": t = "d" elif self.datatype == "number": t = "i" elif self.da...
[ "If it’s the exact same conditional, stick it in a method and call it where you need it. Otherwise, define the dictionaries somewhere and use whichever you need.\ndatatypes = {'string': 'z', 'double': 'd', 'number': 'i', 'blob': 'z'}\nt = datatypes[self.datatype]\n\nYou may catch the KeyError and raise a domain exc...
[ 15, 4, 1 ]
[]
[]
[ "conditional", "python" ]
stackoverflow_0005269304_conditional_python.txt
Q: python regex: capture parts of multiple strings that contain spaces I am trying to capture sub-strings from a string that looks similar to 'some string, another string, ' I want the result match group to be ('some string', 'another string') my current solution >>> from re import match >>> match(2 * '(.*?), ', 's...
python regex: capture parts of multiple strings that contain spaces
I am trying to capture sub-strings from a string that looks similar to 'some string, another string, ' I want the result match group to be ('some string', 'another string') my current solution >>> from re import match >>> match(2 * '(.*?), ', 'some string, another string, ').groups() ('some string', 'another string')...
[ "Unless there's much more to this problem than you've explained, I don't see the point in using regexes. This is very simple to deal with using basic string methods:\n[s.strip() for s in mys.split(',') if s.strip()]\n\nOr if it has to be a tuple:\ntuple(s.strip() for s in mys.split(',') if s.strip())\n\nThe code is...
[ 5, 4, 2, 1, 0, -1 ]
[]
[]
[ "python", "regex", "repeat", "space" ]
stackoverflow_0005160405_python_regex_repeat_space.txt
Q: Problem with deploying django application on mod_wsgi I seem to have a problem deploying django with mod_wsgi. In the past I've used mod_python but I want to make the change. I have been using Graham Dumpleton notes here http://code.google.com/p/modwsgi/wiki/IntegrationWithDjango1, but it still seem to not work. I...
Problem with deploying django application on mod_wsgi
I seem to have a problem deploying django with mod_wsgi. In the past I've used mod_python but I want to make the change. I have been using Graham Dumpleton notes here http://code.google.com/p/modwsgi/wiki/IntegrationWithDjango1, but it still seem to not work. I get a Internal Server Error. django.wsgi file: import os i...
[ "Python Eggs are module files that are contained within zip files. The Python Egg Cache is the directory where Python extracts them so it can run them. Currently you are trying to extract them to /.python-eggs but you don't have write access to either that directory, or to / if it doesn't exist.\nYou have two optio...
[ 1, 1 ]
[]
[]
[ "apache", "deployment", "django", "mod_wsgi", "python" ]
stackoverflow_0005182954_apache_deployment_django_mod_wsgi_python.txt
Q: argparse module How to add option without any argument? I have created a script using argparse. The script needs to take a configuration file name as an option, and user can specify whether they need to proceed totally the script or only simulate it. The args to be passed: ./script -f config_file -s or ./script -f...
argparse module How to add option without any argument?
I have created a script using argparse. The script needs to take a configuration file name as an option, and user can specify whether they need to proceed totally the script or only simulate it. The args to be passed: ./script -f config_file -s or ./script -f config_file. It's ok for the -f config_file part, but It kee...
[ "As @Felix Kling suggested use action='store_true':\n>>> from argparse import ArgumentParser\n>>> p = ArgumentParser()\n>>> _ = p.add_argument('-f', '--foo', action='store_true')\n>>> args = p.parse_args()\n>>> args.foo\nFalse\n>>> args = p.parse_args(['-f'])\n>>> args.foo\nTrue\n\n", "To create an option that ne...
[ 318, 126 ]
[]
[]
[ "argparse", "python" ]
stackoverflow_0005262702_argparse_python.txt
Q: Programmatically create Google Apps Domain I am currently working on a project that involves the google apps provisioning api. Without getting too detailed about the purpose or inner workings of the project, I would like to ask a very simple question: Is there a way to programmatically create a google apps for bus...
Programmatically create Google Apps Domain
I am currently working on a project that involves the google apps provisioning api. Without getting too detailed about the purpose or inner workings of the project, I would like to ask a very simple question: Is there a way to programmatically create a google apps for business domain (especially as a reseller)? After t...
[ "There is an API only available to Google Apps Resellers, if you are one of them you should get access to it.\n", "I don't know if what you're trying to do is possible, but there are lots of APIs for Google Apps stuff. This may be of some use:\n\nThe Provisioning API provides a\n mechanism to programmatically cr...
[ 1, 0 ]
[]
[]
[ "google_app_engine", "java", "python" ]
stackoverflow_0005095117_google_app_engine_java_python.txt
Q: allow a shelve object to be pickled in python, pypar and mpich2 I have some legacy python code that using pypar and mpich2 to transmit data between multiple nodes. For some reason the data is kept in shelves and pypar wants to pickle the shelve to send it to other nodes. Pickling shelves is not allowed. So I wa...
allow a shelve object to be pickled in python, pypar and mpich2
I have some legacy python code that using pypar and mpich2 to transmit data between multiple nodes. For some reason the data is kept in shelves and pypar wants to pickle the shelve to send it to other nodes. Pickling shelves is not allowed. So I want to convert from shelve to something I can send via pypar which pic...
[ "Try converting the shelve to a dict() and then pickling it:\nsdb = shelve.open('foo.db')\nsdb['abc'] = {'a': 1, 'b': 2}\ntmp = cPickle.dumps(dict(sdb), 2)\nprint cPickle.loads(tmp)\n{'abc': {'a': 1, 'b': 2}}\n\nUpdated: (Response to a question in comments): A dict can copy the key-values from any mapping object, s...
[ 1, 1 ]
[]
[]
[ "json", "mpi", "pickle", "python", "shelve" ]
stackoverflow_0005268508_json_mpi_pickle_python_shelve.txt
Q: Problem With openPanelDidEnd in PyObjC in 10.6 The following code which worked fine under OS X 10.5 now fails on 10.6: @IBAction def addButton_(self, sender): panel = NSOpenPanel.openPanel() panel.setCanChooseDirectories_(YES) panel.setAllowsMultipleSelection_(YES) try: panel.beginSheet...
Problem With openPanelDidEnd in PyObjC in 10.6
The following code which worked fine under OS X 10.5 now fails on 10.6: @IBAction def addButton_(self, sender): panel = NSOpenPanel.openPanel() panel.setCanChooseDirectories_(YES) panel.setAllowsMultipleSelection_(YES) try: panel.beginSheetForDirectory_file_modalForWindow_modalDelegate_didEn...
[ "beginSheetForDirectory:file:modalForWindow:modalDelegate:didEndSelector:contextInfo: has been deprecated in 10.6:\nhttp://developer.apple.com/library/mac/#documentation/cocoa/reference/ApplicationKit/Classes/NSOpenPanel_Class/DeprecationAppendix/AppendixADeprecatedAPI.html\nstruggling on the same problem cause PyO...
[ 1, 1 ]
[]
[]
[ "macos", "objective_c", "pyobjc", "python" ]
stackoverflow_0003809340_macos_objective_c_pyobjc_python.txt
Q: App Engine HTTP 500s This request caused a new process to be started for your application, and thus caused your application code to be loaded for the first time. This request may thus take longer and use more CPU than a typical request for your application. I've handled all the situations, also Deadli...
App Engine HTTP 500s
This request caused a new process to be started for your application, and thus caused your application code to be loaded for the first time. This request may thus take longer and use more CPU than a typical request for your application. I've handled all the situations, also DeadlineExceededError too. But ...
[ "I'm fairly sure that the specific message is not related to the HTTP 500 you are getting. All this means that the instance of your app was initialized.\nHere's an example of this message for my app with a successful response:\n06-13 09:58AM 04.933 /favicon.ico 404 344ms 310cpu_ms 0kb Mozilla/5.0 (X11; U; Linux x86...
[ 2, 2, 0 ]
[]
[]
[ "google_app_engine", "http_error", "python" ]
stackoverflow_0003033009_google_app_engine_http_error_python.txt
Q: C++ linking to python 3.2 x64 application unable to load This is I guess a question in a few parts. I'm working through the documentation on embedding the python interpreter. I've got everything compiling and linking wonderfully, only the application crashes when I run it ( to be specific its unable to load, so i...
C++ linking to python 3.2 x64 application unable to load
This is I guess a question in a few parts. I'm working through the documentation on embedding the python interpreter. I've got everything compiling and linking wonderfully, only the application crashes when I run it ( to be specific its unable to load, so it hasn't even begun running). I'm running windows 7 profession...
[ "If the python3.dll is definitely 64bit and your application is definitely 32bit, then this will not work. You can't link to 64bit dlls from 32bit applications. Pointers just won't be able to work between the two models.\n", "You can't mix 32 and 64 bit images in the same process. End. Of. Story.\n" ]
[ 0, 0 ]
[]
[]
[ "c++", "g++", "python", "python_3.x", "windows_7_x64" ]
stackoverflow_0005245336_c++_g++_python_python_3.x_windows_7_x64.txt
Q: Python import error: no module named I am very new at Python. I have an existing example project that has the scripts YYY in path XXX/YYY, and a script A.py that call these one by one. I only want to add a script ZZZ.py to the YYY scripts so that call after them. I add this script in the same path (XXX/ZZZ.py) and...
Python import error: no module named
I am very new at Python. I have an existing example project that has the scripts YYY in path XXX/YYY, and a script A.py that call these one by one. I only want to add a script ZZZ.py to the YYY scripts so that call after them. I add this script in the same path (XXX/ZZZ.py) and try to import it in the A.py and call it....
[ "If your modules are structured like this:\n/XXX\n\n __init__.py\n ZZZ.py\n /YYY\n\n __init__.py\n\n *more scripts here*\n\nAnd if the directory containing XXX is in your PYTHONPATH, then\nimport XXX.ZZZ as Z\n\nshould work.\n", "If you want to import ZZZ, do import XXX.YYY.ZZZ as Z. This a...
[ 2, 0 ]
[]
[]
[ "python", "python_import" ]
stackoverflow_0003201898_python_python_import.txt
Q: Steganography on audio/video with Python I want to do message embedding in audio/video files using Python. Does anyone have information about some libraries I can use for bit manipulation in audio/video ? A: There is a list of audio-related modules on the python website (as well as this list), and there are othe...
Steganography on audio/video with Python
I want to do message embedding in audio/video files using Python. Does anyone have information about some libraries I can use for bit manipulation in audio/video ?
[ "There is a list of audio-related modules on the python website (as well as this list), and there are other questions dealing with video here, here and here. From looking further into it, GStreamer appears to have support for both audio and video editing, and also seems quite favored.\nAlso, if you're interested i...
[ 0, 0 ]
[]
[]
[ "audio_processing", "python", "steganography", "video_processing" ]
stackoverflow_0005258402_audio_processing_python_steganography_video_processing.txt
Q: How to write a program in python that will process a text stream? I am sorry if this is a repeat question. How do I write a python script to process data as a stream of line? I need to do this because the files that I am processing are huge, and I would rather not read the file into the memory. I know that you ca...
How to write a program in python that will process a text stream?
I am sorry if this is a repeat question. How do I write a python script to process data as a stream of line? I need to do this because the files that I am processing are huge, and I would rather not read the file into the memory. I know that you can potentially read one line of the file at a time, but I want something...
[ "You could just read the data from stdin, as described in this answer. This would look like that in code:\nfor line in sys.stdin:\n # do suff\n\nIf you want to process a file, then just call the script like this (on Unix platforms):\ncat file.txt | python script.py\n\nYou can of course pipe the output of any oth...
[ 16, 7, 0 ]
[]
[]
[ "inputstream", "python", "text_processing" ]
stackoverflow_0005272923_inputstream_python_text_processing.txt
Q: Confused about python modules and functions in it To describe my questions concisely, please have a look at examples below: Module os have a function getcwd() which returns current working directory. But there are no details about os.getcwd() in /usr/lib/python2.7/os.py file. Where is the implementation of the fu...
Confused about python modules and functions in it
To describe my questions concisely, please have a look at examples below: Module os have a function getcwd() which returns current working directory. But there are no details about os.getcwd() in /usr/lib/python2.7/os.py file. Where is the implementation of the function? os.path is also a module in python , but in /u...
[ "1 . The getcwd() functions is implemented in C look here.\n2 . os.path is defined in the module os by dynamically detecting the os type and importing the correspondent library and set in it using : sys.modules['os.path'] = path \n", "Modules do not have to be python scripts. Using the C-API you can write modules...
[ 3, 2, 1, 1 ]
[]
[]
[ "python" ]
stackoverflow_0005273024_python.txt
Q: Running a Python script in the background from a PHP file I need to run a Python script in the background after being called from a PHP file. The PHP file should continue to run independently of the Python script (i.e. it shouldn't hang waiting for the Python script to finish processing, but should instead carry ...
Running a Python script in the background from a PHP file
I need to run a Python script in the background after being called from a PHP file. The PHP file should continue to run independently of the Python script (i.e. it shouldn't hang waiting for the Python script to finish processing, but should instead carry on processing itself). The Python script takes one argument and...
[ "You could use exec() to kick off the Python interperator and have it send its output to either a file or to /dev/null with redirection. Using the & operator in the exec call will cause the command to be started and PHP to continue without waiting for a result. \nhttp://www.developertutorials.com/tutorials/php/run...
[ 2, 1, 0, 0 ]
[]
[]
[ "php", "python" ]
stackoverflow_0005273131_php_python.txt
Q: Update only some field with create_update.update_object I've defined a models.py with a "FirstClass" which contains a ForeignKey relathionship to "SecondClass". The relathionship can't be Null. The SecondClass is very expansive (90.000 records), and when i display the FirstClass html form, it requires too many tim...
Update only some field with create_update.update_object
I've defined a models.py with a "FirstClass" which contains a ForeignKey relathionship to "SecondClass". The relathionship can't be Null. The SecondClass is very expansive (90.000 records), and when i display the FirstClass html form, it requires too many time generating the "select box" field. Therefore, when I let us...
[ "Create a ModelForm and pass it into the view, according to the docs.\nSince the foreign key should always exist upon creation, it's safe to ignore it in the update.\nclass MyModelForm(forms.ModelForm):\n class Meta:\n model = FirstClass\n exclude = ('SecondClass',)\n\n# urls.py\n(r'^foo/(?P<obje...
[ 0 ]
[]
[]
[ "django", "django_forms", "generics", "python", "views" ]
stackoverflow_0005273126_django_django_forms_generics_python_views.txt
Q: How can i call a local python function from my remote app server? I have written a python application with an inclusion of an ActiveX control(ocx) to print via serial Port to an Epson receipt printer using the win32com library. It's Ok !!! but my master app in on another server. How can i comunicate with my app lo...
How can i call a local python function from my remote app server?
I have written a python application with an inclusion of an ActiveX control(ocx) to print via serial Port to an Epson receipt printer using the win32com library. It's Ok !!! but my master app in on another server. How can i comunicate with my app locally?
[ "What you need is a Remote procedure call framework. See this question for various solutions in Python.\n", "Solved!!! I've solved this problem using on my local PC a python module called SimpleHTTPServer that include my function and call my ocx component!!\n" ]
[ 2, 0 ]
[]
[]
[ "ocx", "printing", "python", "sockets" ]
stackoverflow_0005065284_ocx_printing_python_sockets.txt
Q: Python List / Index Query I am asking a user to enter a number, in which I want to print the item held at that index point in the list.. This is the code i currently have: List = ["a", "b", "c", "d", "e", "f"] print "The list has the following", len(List), "list:", List new_item = raw_input("Which item would you...
Python List / Index Query
I am asking a user to enter a number, in which I want to print the item held at that index point in the list.. This is the code i currently have: List = ["a", "b", "c", "d", "e", "f"] print "The list has the following", len(List), "list:", List new_item = raw_input("Which item would you like to add? ") List.append(ne...
[ "Try converting Number to an integer first:\ni = int(Number) \nprint \"You selected:\", List[i]\n\nIncidentally, it's good Python style to make variables lower case, and keep identifiers that begin with a capital letter for classes. So, instead of Lis...
[ 5, 1, 0, 0, 0, 0 ]
[]
[]
[ "list", "python" ]
stackoverflow_0005273026_list_python.txt
Q: Forum on Python and GAE Are there any forums that work on GAE Python? A: The FoFou forums are specifically designed for GAE Python. There is also a version of PyIB's Python-based forums which will run on app engine: http://code.google.com/p/pyib/
Forum on Python and GAE
Are there any forums that work on GAE Python?
[ "The FoFou forums are specifically designed for GAE Python.\nThere is also a version of PyIB's Python-based forums which will run on app engine: http://code.google.com/p/pyib/\n" ]
[ 3 ]
[]
[]
[ "forum", "google_app_engine", "python" ]
stackoverflow_0005272712_forum_google_app_engine_python.txt
Q: How can I extract EDB (ms exchange storage file) to PST Under Linux? (preferably in Python) I can extract and read messages from PST files using libpst , but i want to extract from edb files too (not online exchange server but from offline files). And in Linux. Any python lib or any kind for linux commandline tool...
How can I extract EDB (ms exchange storage file) to PST Under Linux? (preferably in Python)
I can extract and read messages from PST files using libpst , but i want to extract from edb files too (not online exchange server but from offline files). And in Linux. Any python lib or any kind for linux commandline tool should help. Thanks.
[ "Take a look at Joachim Metz' work. He reverse engineered the edb format and analyzed the exchange database to a limited extend. It's open source and there's even some documentation about the tables and columns:\nhttp://sourceforge.net/projects/libesedb/files/\nHowever it doesn't create a PST or anything similar. I...
[ 3 ]
[]
[]
[ "exchange_server", "extraction", "linux", "pst", "python" ]
stackoverflow_0003376692_exchange_server_extraction_linux_pst_python.txt
Q: How to create gtk.STOCK_* buttons from a modified list of strings? I'm trying to create a simple program that displays all the gtk stock buttons. I copied the list of stock id's from: http://www.pygtk.org/pygtk2tutorial/ch-ButtonWidget.html pasted them into a .txt file and created a list from the file: stock_...
How to create gtk.STOCK_* buttons from a modified list of strings?
I'm trying to create a simple program that displays all the gtk stock buttons. I copied the list of stock id's from: http://www.pygtk.org/pygtk2tutorial/ch-ButtonWidget.html pasted them into a .txt file and created a list from the file: stock_file = open('stock_buttons.txt') stock_button_list = stock_file.read...
[ "So simple:\nfor button in stock_button_list:\n self.button1=gtk.Button(stock=getattr(gtk,button))\n\nUsing getattr you can access all the attributes of an object or module by name.\n", "An example: \n>>> import gtk\n>>> a='STOCK_DIALOG_WARNING'\n>>> getattr(gtk, a)\n'gtk-dialog-warning'\n\n", "SOLVED\nAs Re...
[ 1, 0, 0 ]
[]
[]
[ "gtk", "pygtk", "python", "string", "variables" ]
stackoverflow_0005271548_gtk_pygtk_python_string_variables.txt
Q: How do I change the title of the tree view that is created I have created a basic treeview with checkboxes and below is the code: class StdItemModel(QStandardItemModel): def __init__(self, parent = None): super(StdItemModel, self).__init__(parent) class CheckBoxTreeView(QTreeView): def __init__(self, pare...
How do I change the title of the tree view that is created
I have created a basic treeview with checkboxes and below is the code: class StdItemModel(QStandardItemModel): def __init__(self, parent = None): super(StdItemModel, self).__init__(parent) class CheckBoxTreeView(QTreeView): def __init__(self, parent = None): super(CheckBoxTreeView, self).__init__(paren...
[ "Try something like the following:\ntitle = \"This is my title, there are many like it but this one is mine...\"\nself.headerItem().setText(0, title)\nObviously you can use whatever text you like.\n" ]
[ 0 ]
[]
[]
[ "checkbox", "pyqt", "python", "qcombobox" ]
stackoverflow_0005272972_checkbox_pyqt_python_qcombobox.txt
Q: Understanding pyqtProperty in PyQt4 I wrote the following little script to understand properties. One thing which I cannot understand is, that the metaObject() of my class A contains a property with the name conf_name now. How did it get that information? In my class it is only used once as name for the target var...
Understanding pyqtProperty in PyQt4
I wrote the following little script to understand properties. One thing which I cannot understand is, that the metaObject() of my class A contains a property with the name conf_name now. How did it get that information? In my class it is only used once as name for the target variable of the call to set the property. Ho...
[ "if this is not supposed to be a property of your object class, it belongs in that classes __init__ function. What you have there is a class property, which will be inherited by all objects of that object type of subclassing it. \nThis can actually be quite useful. For instance:\nfor PyQt4.QtCore import QThread\ncl...
[ 0 ]
[]
[]
[ "properties", "pyqt", "python" ]
stackoverflow_0005222631_properties_pyqt_python.txt
Q: How to convert from lat lon to zipcode or state to generate choropleth map I have a large collection (and growing) of geospatial data (lat, lon) points (stored in mongodb, if that helps). I'd like to generate a choropleth map (http://vis.stanford.edu/protovis/ex/choropleth.html), which requires knowing the state ...
How to convert from lat lon to zipcode or state to generate choropleth map
I have a large collection (and growing) of geospatial data (lat, lon) points (stored in mongodb, if that helps). I'd like to generate a choropleth map (http://vis.stanford.edu/protovis/ex/choropleth.html), which requires knowing the state which contains that point. Is there a database or algorithm that can do this wit...
[ "Actually, the web app you linked to contains the data you need -\nIf you look at http://vis.stanford.edu/protovis/ex/us_lowres.js for each state, borders[] contains a [lat,long] polyline which outlines the state. Load this data and check for point-in-polygon - http://en.wikipedia.org/wiki/Point_in_polygon\nPer Rev...
[ 3, 1, 1, 0, 0 ]
[]
[]
[ "data_visualization", "geospatial", "mongodb", "python", "visualization" ]
stackoverflow_0005268512_data_visualization_geospatial_mongodb_python_visualization.txt
Q: File filtering_Python 3.2 I'm trying to write a short file filtering code in Python that will find my desired string. I've got it worked out logically, but my Command Feed is sending me an error message for the print statement. This is how it works as of now: filename = input('give file name: ') n = input('give de...
File filtering_Python 3.2
I'm trying to write a short file filtering code in Python that will find my desired string. I've got it worked out logically, but my Command Feed is sending me an error message for the print statement. This is how it works as of now: filename = input('give file name: ') n = input('give desired string: ') f = open line ...
[ "print is a function in Python 3. Use print(line) instead.\n" ]
[ 1 ]
[]
[]
[ "python", "windows_7" ]
stackoverflow_0005274631_python_windows_7.txt
Q: Python urlopen connection aborted - urlopen error [Errno 10053] I have some code that uses mechanize and beautifulsoup for web scraping some data. The code works fine on a test machine but the production machine is blocking the connection. The error i get is: urlopen error [Errno 10053] An established connection w...
Python urlopen connection aborted - urlopen error [Errno 10053]
I have some code that uses mechanize and beautifulsoup for web scraping some data. The code works fine on a test machine but the production machine is blocking the connection. The error i get is: urlopen error [Errno 10053] An established connection was aborted by the software in your host machine I have read through ...
[ "The issue here was a host based IDS was preventing the connection out. Problem solved.\nI added my python script to the HIDS exception list. The exception list was the list of files that I allowed to connect out to the internet. Once it was added to the list, I was able to get network connectivity with the script ...
[ 2 ]
[]
[]
[ "errno", "mechanize", "proxy", "python", "web_scraping" ]
stackoverflow_0005250183_errno_mechanize_proxy_python_web_scraping.txt
Q: Django IndentationError in a working function I'm so sick of Django. I wrote a Python Function which is working correct. For reasons of visualizations I decided to make a web-page to demonstrate my function. I added some code to my function: txt_len = 0 (line 1) if text: txt_len=len(text) return txt_...
Django IndentationError in a working function
I'm so sick of Django. I wrote a Python Function which is working correct. For reasons of visualizations I decided to make a web-page to demonstrate my function. I added some code to my function: txt_len = 0 (line 1) if text: txt_len=len(text) return txt_len *it's only a example. But for a reason I ge...
[ "Let's see the whole function? Line 1 is just for example right? Line 1 would at the very least have to be a function definition for that return line to work.\nDid you just paste a function into a django view? \nThe culprit for mystery indentation errors is almost always mixing spaces and tabs. Do you have invisibl...
[ 5, 1, 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0005274412_django_python.txt
Q: Split array at value in numpy I have a file containing data in the format: 0.0 x1 0.1 x2 0.2 x3 0.0 x4 0.1 x5 0.2 x6 0.3 x7 ... The data consists of multiple datasets, each starting with 0 in the first column (so x1,x2,x3 would be one set and x4,x5,x6,x7 another one). I need to plot each dataset separately so I n...
Split array at value in numpy
I have a file containing data in the format: 0.0 x1 0.1 x2 0.2 x3 0.0 x4 0.1 x5 0.2 x6 0.3 x7 ... The data consists of multiple datasets, each starting with 0 in the first column (so x1,x2,x3 would be one set and x4,x5,x6,x7 another one). I need to plot each dataset separately so I need to somehow split the data. What...
[ "I actually liked Benjamin's answer, a slightly shorter solution would be:\nB= np.split(A, np.where(A[:, 0]== 0.)[0][1:])\n\n", "Once you have the data in a long numpy array, just do:\nimport numpy as np\n\nA = np.array([[0.0, 1], [0.1, 2], [0.2, 3], [0.0, 4], [0.1, 5], [0.2, 6], [0.3, 7], [0.0, 8], [0.1, 9], [0....
[ 27, 16, 1, 0 ]
[]
[]
[ "numpy", "python" ]
stackoverflow_0005274243_numpy_python.txt
Q: Use BeautifulSoup to get delimited contents of a div I want to get correctly delimited text out of BeautifulSoup, turning tags into whitespace if necessary. The problem is that newlines are collapsed and tags like <br/> are not rendered as whitespace. <div class="companyInfo"> <p class="identInfo"> <a...
Use BeautifulSoup to get delimited contents of a div
I want to get correctly delimited text out of BeautifulSoup, turning tags into whitespace if necessary. The problem is that newlines are collapsed and tags like <br/> are not rendered as whitespace. <div class="companyInfo"> <p class="identInfo"> <acronym title="Standard Industrial Code"> SIC ...
[ "You could have also use the getText() function. The getText() has an optional parameter for a separator. \nBeautifulSoup(sampleHTML).getText(' ').strip()\n\nThe strip() is used to remove any leading and trailing whitespace.\n", "I ended up using content method to get at the information I want from the various no...
[ 3, 1 ]
[]
[]
[ "beautifulsoup", "python" ]
stackoverflow_0003009000_beautifulsoup_python.txt
Q: Python unpack problem I have: a, b, c, d, e, f[50], g = unpack('BBBBH50cH', data) The problem is f[50] (too many values to unpack) How do I do what I want? A: I think by f[50] you are trying to denote "a list of 50 elements"? In Python 3.x you can do a, b, c, d, e, *f, g to indicate that you want f to contain...
Python unpack problem
I have: a, b, c, d, e, f[50], g = unpack('BBBBH50cH', data) The problem is f[50] (too many values to unpack) How do I do what I want?
[ "I think by f[50] you are trying to denote \"a list of 50 elements\"?\nIn Python 3.x you can do a, b, c, d, e, *f, g to indicate that you want f to contain all the values that don't fit anywhere else (see this PEP).\nIn Python 2.x, you will need to write it out explicitly:\nx = unpack(...)\na, b, c, d, e = x[:5]\nf...
[ 7, 0 ]
[]
[]
[ "python" ]
stackoverflow_0005274997_python.txt
Q: db cursor - transaction in python Is opening/closing db cursor costly operation? What is the best practice, to use a different cursor or to reuse the same cursor between different sql executions? Does it matter if a transaction consists of executions performed on same or different cursors belonging to same connect...
db cursor - transaction in python
Is opening/closing db cursor costly operation? What is the best practice, to use a different cursor or to reuse the same cursor between different sql executions? Does it matter if a transaction consists of executions performed on same or different cursors belonging to same connection? Thanks.
[ "This will depend a lot on your database as well as your chose python implementation - have you tried profiling a few short test operations?\n" ]
[ 1 ]
[]
[]
[ "cursor", "database", "python", "transactions" ]
stackoverflow_0005275236_cursor_database_python_transactions.txt
Q: Forcing encoding on bad XML files with ElementTree A big set of XML files have the wrong encoding defined. It should be utf-8 but the content has latin-1 characters all over the place. What's the best way to parse this content? <?xml version="1.0" encoding="UTF-8" standalone="yes"?> Edit: this is happening with A...
Forcing encoding on bad XML files with ElementTree
A big set of XML files have the wrong encoding defined. It should be utf-8 but the content has latin-1 characters all over the place. What's the best way to parse this content? <?xml version="1.0" encoding="UTF-8" standalone="yes"?> Edit: this is happening with Adobe InDesign IDML files, it seems the "Content" text ha...
[ "You can override the encoding specified in the XML when you parse it:\n\nclass xml.etree.ElementTree.XMLParser(html=0, target=None, encoding=None)\n\nElement\n structure builder for XML source data,\n based on the expat parser. html are\n predefined HTML entities. This flag is\n not supported by the current\n ...
[ 2, 1 ]
[]
[]
[ "encoding", "python", "xml" ]
stackoverflow_0005275325_encoding_python_xml.txt
Q: Python script on Windows to access SFTP site I need to access sftp USER@sfile.WEBSITE.com and get 20110310statement.pdf to a directory $HOME\STATEMENTS at 3am everyday. I don't know how to do it in a script giving username and password and figuring the date string on Windows. I suggest python, but am open to any ...
Python script on Windows to access SFTP site
I need to access sftp USER@sfile.WEBSITE.com and get 20110310statement.pdf to a directory $HOME\STATEMENTS at 3am everyday. I don't know how to do it in a script giving username and password and figuring the date string on Windows. I suggest python, but am open to any scripting language. Any pointers ?
[ "Have you tried paramiko? and you can use the time module to get the current date and format it however you please.\n", "Instead of building something from scratch, you might want to look at using cygwin and rsync or GoodSync or MS SyncToy\n" ]
[ 2, 0 ]
[]
[]
[ "python", "sftp", "windows" ]
stackoverflow_0005274526_python_sftp_windows.txt
Q: Python Boolean help! I have a code like this: if (X or Y) == ("Cat" or "Dog" or "Fish" or "Bird"): print X, Y It is only working if X == "Cat". Does anyone know my mistake here? A: I think you want logic like this: animals = ["Cat", "Dog", "Fish", "Bird"] if X in animals or Y in animals: print X, Y In...
Python Boolean help!
I have a code like this: if (X or Y) == ("Cat" or "Dog" or "Fish" or "Bird"): print X, Y It is only working if X == "Cat". Does anyone know my mistake here?
[ "I think you want logic like this:\nanimals = [\"Cat\", \"Dog\", \"Fish\", \"Bird\"]\nif X in animals or Y in animals:\n print X, Y\n\nIn your code the expression (\"Cat\" or \"Dog\" or \"Fish\" or \"Bird\") is treated as a logical expression which I'm sure you don't want. As it happens this expression evaluates...
[ 11, 4, 1, 0 ]
[]
[]
[ "boolean_operations", "python" ]
stackoverflow_0005275436_boolean_operations_python.txt
Q: Cython - converting pointers to arrays into Python objects Alright, I am so close to finishing this I can taste it. Over the past few week or so, I've been attempting to create a Python extension to interface with a library written in C++ via Cython. With a little help from the guys here and a couple of friends, I...
Cython - converting pointers to arrays into Python objects
Alright, I am so close to finishing this I can taste it. Over the past few week or so, I've been attempting to create a Python extension to interface with a library written in C++ via Cython. With a little help from the guys here and a couple of friends, I have managed to get what feels like 98% of the way there. Only ...
[ "ctypedef unsigned short const_ushort \"const uint16_t\"\n\nmakes the const appear in the C code, so you get typedef unsigned short const uint16_t in which the const is meaningless. (It also redefines the standard type uint16_t, which it shouldn't.)\nYou may have more success with\nctypedef unsigned short *ushort_p...
[ 5, 1 ]
[]
[]
[ "cython", "python" ]
stackoverflow_0005271690_cython_python.txt
Q: How to use the PageEditor in MoinMoin 1.9.3 with wikifarm configuration? I was able to find the documentation on PageEditor from this answer. But I can't find information on how to construct a proper ScriptContext object to pass into the PageEditor as the request parameter. when I try and create a ScriptContext as...
How to use the PageEditor in MoinMoin 1.9.3 with wikifarm configuration?
I was able to find the documentation on PageEditor from this answer. But I can't find information on how to construct a proper ScriptContext object to pass into the PageEditor as the request parameter. when I try and create a ScriptContext as in the examples, I am getting the following errors. [Fri Mar 11 11:04:42] [ro...
[ "I finally found an example on how to create the ScriptContext object, with wikifarm configuration you have to tell it which wiki you want by its URL.\n[Fri Mar 11 11:44:35] [root]@[dev] /usr/local/share/moin\n# python2.6\nPython 2.6.5 (r265:79063, Jun 4 2010, 21:43:07)\n[GCC 4.1.2 20080704 (Red Hat 4.1.2-48)] on ...
[ 0 ]
[]
[]
[ "moinmoin", "python" ]
stackoverflow_0005275535_moinmoin_python.txt
Q: Finding zero values with odeint How can I find the point where the first derivative of my equation equals 0 using scipy.integrate.ode? I set up this function, which gets the answer, but I'm not sure about accuracy and it can't be the most efficient way to do this. Basically I am using this function to find the tim...
Finding zero values with odeint
How can I find the point where the first derivative of my equation equals 0 using scipy.integrate.ode? I set up this function, which gets the answer, but I'm not sure about accuracy and it can't be the most efficient way to do this. Basically I am using this function to find the time a projectile with initial velocity ...
[ "In general, a good approach to solve this sort of problem is to rewrite your equations so that velocity is the independent variable and time and distance are the dependent variables. Then, you simply have to integrate the equations from v=v0 to v=0. \nHowever, in the example you give it is not even necessary to re...
[ 4, 0 ]
[]
[]
[ "numpy", "python", "scipy" ]
stackoverflow_0005267261_numpy_python_scipy.txt