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: Find two of the same character in a string with regular expressions This is in reference to a question I asked before here I received a solution to the problem in that question but ended up needing to go with regex for this particular part. I need a regular expression to search and replace a string for instances o...
Find two of the same character in a string with regular expressions
This is in reference to a question I asked before here I received a solution to the problem in that question but ended up needing to go with regex for this particular part. I need a regular expression to search and replace a string for instances of two vowels in a row that are the same, so the "oo" in "took", or the "e...
[ "Try this:\nre.sub(r'([aeiou])\\1', r'\\1:', str)\n\n", "Search for ([aeiou])\\1 and replace it with \\1:\nI don't know about python, but you should be able to make the regex case insensitive and global with something like /([aeiou])\\1/gi\n", "You'll need to use a back reference in your search expression. Try ...
[ 7, 1, 0, 0 ]
[]
[]
[ "python", "regex", "replace" ]
stackoverflow_0001868481_python_regex_replace.txt
Q: In Google App Engines, how to display the HTML source of a page of a fetched URL in Python? On Google App Engine I found this code that is fetching a web page's URL: from google.appengine.api import urlfetch url = "http://www.google.com/" result = urlfetch.fetch(url) if result.status_code == 200: doSomethingWith...
In Google App Engines, how to display the HTML source of a page of a fetched URL in Python?
On Google App Engine I found this code that is fetching a web page's URL: from google.appengine.api import urlfetch url = "http://www.google.com/" result = urlfetch.fetch(url) if result.status_code == 200: doSomethingWithResult(result.content) Is this the right code to fecth that page's HTML source? Does the result ...
[ "Yes, result.content will contain the raw content of that page. You should check the Content-Type header and verify that it's either text/html or application/xhtml+xml.\nTo write the content of that page to the response, first write your status and headers and then:\nself.response.out.write(result.content)\n\n" ]
[ 5 ]
[]
[]
[ "fetch", "google_app_engine", "html", "python", "url" ]
stackoverflow_0001868587_fetch_google_app_engine_html_python_url.txt
Q: WxPython, Windows Vista 64-bit, and failure I have Windows Vista 64-bit SP2. I am trying to use wxPython for GUI development with Python, because all my research pointed to that as the way to go. I have downloaded and installed the win64 wxPython. I get the same error every time. Python 2.6 (r26:66721, Oct 2 2008...
WxPython, Windows Vista 64-bit, and failure
I have Windows Vista 64-bit SP2. I am trying to use wxPython for GUI development with Python, because all my research pointed to that as the way to go. I have downloaded and installed the win64 wxPython. I get the same error every time. Python 2.6 (r26:66721, Oct 2 2008, 11:35:03) [MSC v.1500 32 bit (Intel)] on win 32...
[ "It looks like you're trying to run 64-bit wxPython on 32-bit Python. You need them both to be for the same architecture.\n" ]
[ 6 ]
[]
[]
[ "64_bit", "python", "windows_vista", "wxpython" ]
stackoverflow_0001868749_64_bit_python_windows_vista_wxpython.txt
Q: Convert and merge strings into a list in Python In Python I have four strings that include the formatting of a list: line1 ="['a.b.c','b.c.a','c.d.e']" line2 ="['def','efg']" line3 ="['f']" line4 ="['g']" How do I merge them all so I get a valid Python list such as: SumLine = ['a.b.c','b.c.a','c.d.e','def','efg',...
Convert and merge strings into a list in Python
In Python I have four strings that include the formatting of a list: line1 ="['a.b.c','b.c.a','c.d.e']" line2 ="['def','efg']" line3 ="['f']" line4 ="['g']" How do I merge them all so I get a valid Python list such as: SumLine = ['a.b.c','b.c.a','c.d.e','def','efg','f','g']
[ "import ast\n\nline1 =\"['a.b.c','b.c.a','c.d.e']\"\nline2 =\"['def','efg']\"\nline3 =\"['f']\"\nline4 =\"['g']\"\n\nSumLine = []\n\nfor x in (line1, line2, line3, line4):\n SumLine.extend(ast.literal_eval(x))\n\nprint SumLine\n\nDon't use the built-in eval unless you have preternatural trust in the strings you're...
[ 11, 2, 1, 1, 1, 0 ]
[]
[]
[ "list", "python", "string" ]
stackoverflow_0001868857_list_python_string.txt
Q: Calling a function using ctypes with pointers to structs I am trying to call a C function sitting in a shared object from python, and using ctypes seems to be the best way of accomplishing this. I have to pass derived types to this function, with the following function prototype: int MyFunc (Config *config, int *a...
Calling a function using ctypes with pointers to structs
I am trying to call a C function sitting in a shared object from python, and using ctypes seems to be the best way of accomplishing this. I have to pass derived types to this function, with the following function prototype: int MyFunc (Config *config, int *argc, char **argv ) The Config struct is defined as typedef s...
[ "char** corresponds to POINTER(c_char_p), not to c_char_p.\n", "It doesn't look like your rewritten config structure is the same as the original one. If you're passing it back and forth the alignment would be off.\nEdit: I see you've fixed part of it. But I'm not sure that c_char_p is the same as char**.\n" ]
[ 2, 1 ]
[]
[]
[ "c", "ctypes", "python" ]
stackoverflow_0001835429_c_ctypes_python.txt
Q: Basic easy_install question on python 2.6 I'm trying to install a python api for controlling imagemagick (this) and followed the instructions. I imported easy_install: import easy_install and then input the line: easy_install http://svn2.assembla.com/svn/pythonmagickwand/trunk However I got the error SyntaxE...
Basic easy_install question on python 2.6
I'm trying to install a python api for controlling imagemagick (this) and followed the instructions. I imported easy_install: import easy_install and then input the line: easy_install http://svn2.assembla.com/svn/pythonmagickwand/trunk However I got the error SyntaxError: invalid syntax and 'http' was highlighte...
[ "Check\nhttp://peak.telecommunity.com/DevCenter/EasyInstall#using-easy-install\nfor a good reference.\nalso, easy_install is run from the command line.\n", "easy_install is a shell command, run at the shell.\nIt's not a python command; it's not run from within Python.\n", "I believe easy_install is a script tha...
[ 4, 2, 1, 0 ]
[]
[]
[ "easy_install", "imagemagick", "python" ]
stackoverflow_0001868798_easy_install_imagemagick_python.txt
Q: how to set the unique identifier key dynamically from a list containing unique numbers from a csv file? I would like to know if there is a way to set the key of an entity in google app engine dynamically from a list of unique numbers stored in a csv file and bulkload it to the datastore. Also is it possible to hav...
how to set the unique identifier key dynamically from a list containing unique numbers from a csv file?
I would like to know if there is a way to set the key of an entity in google app engine dynamically from a list of unique numbers stored in a csv file and bulkload it to the datastore. Also is it possible to have an entity model with out any properties and just use the the set of predefined unique numbers as keys. Than...
[ "Yes, I think that is completely possible. \nOnly keep in mind that a key has to be unique across the whole application, so if you use it as the key for an entity in the data model you design to keep the keys, you won't be able to use it in your application's real data models entities (wherever you intend to use th...
[ 1 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0001866727_google_app_engine_python.txt
Q: media.set_xx ValueError I asked a while back about a sprite recolouring program that I was having difficulty with and got some great responses. Basically, I tried to write a program that would recolour pixels of all the pictures in a given folder from one given colour to another. I believe I have it down, but, now...
media.set_xx ValueError
I asked a while back about a sprite recolouring program that I was having difficulty with and got some great responses. Basically, I tried to write a program that would recolour pixels of all the pictures in a given folder from one given colour to another. I believe I have it down, but, now the program is telling me th...
[ "Slow going; but no worries I got it. Didn't convert the values to integers, was trying to use strings as arguments...\n" ]
[ 0 ]
[]
[]
[ "media", "python" ]
stackoverflow_0001829810_media_python.txt
Q: Design principles for complete noobs? I've been programming for around a year now, and all the stuff that I've written works - it's just extremely poorly written from my point of view. I'd like to know if there are any (free) good books on Software Design out there that can offer a little guidance to the beginning...
Design principles for complete noobs?
I've been programming for around a year now, and all the stuff that I've written works - it's just extremely poorly written from my point of view. I'd like to know if there are any (free) good books on Software Design out there that can offer a little guidance to the beginning programmer? I don't think I'd have as many...
[ "Head First Design Patterns might be a gentler intro to the GoF \"Design Patterns\" book\nSteve McConnell's Code Complete is a good guide to many things code, including how to use good strategies in languages that don't natively support them.\nMartin Fowler's Refactoring refers heavily to Design Patterns, but is a ...
[ 12, 7, 4, 4, 3, 3, 2, 2, 2, 2, 2, 1, 1, 1, 1, 0, 0, 0 ]
[]
[]
[ "python", "software_design" ]
stackoverflow_0001868879_python_software_design.txt
Q: Hook into and log "everything" in the windows message queue Has anyone got a working code example of how to connect to the windows message queue(post/sendMessage) and log all messages there? Preferably in Python. I'm interrested in this to easier be able to create test-scripts that emulates user input. A: There'...
Hook into and log "everything" in the windows message queue
Has anyone got a working code example of how to connect to the windows message queue(post/sendMessage) and log all messages there? Preferably in Python. I'm interrested in this to easier be able to create test-scripts that emulates user input.
[ "There's actually a package that wraps the SetWindowsHookEx function, called pyHook. I've used it before to write a primitive key-logger (as an experiment in monitoring myself to assist with reporting work hours) and it worked fine for that.\n", "Usually this is done with SetWindowsHookEx Function.\n\nIn Python ...
[ 2, 1, 1 ]
[]
[]
[ "message_queue", "python", "windows" ]
stackoverflow_0001305847_message_queue_python_windows.txt
Q: Python unable to acquire Oracle environment handle in Apache I can run my django application using the developer server, but it does not run under apache. The error is: Unable to acquire Oracle environment handle Adding an ORACLE_HOME environment variable pointing to my 10g client did not fix the issue. NOTE: th...
Python unable to acquire Oracle environment handle in Apache
I can run my django application using the developer server, but it does not run under apache. The error is: Unable to acquire Oracle environment handle Adding an ORACLE_HOME environment variable pointing to my 10g client did not fix the issue. NOTE: the ORACLE_HOME did not end with a slash. Also, this is using the XA...
[ "What is path to where your django application resides?\nIf it's in c:\\Program Files (x86)\\XXX (as seen on 64-bit Windows), this is a known issue\n" ]
[ 0 ]
[]
[]
[ "oracle10g", "python", "windows" ]
stackoverflow_0001869832_oracle10g_python_windows.txt
Q: Scaffolding in pylons Is there anything similar to rails' scaffolding for pylons? I've been poking around google, but only found this thing called dbsprockets, which is fine, although probably way too much for my needs. What I really need is a basic CRUD that is based on the SQLAlchemy model. A: The question is ...
Scaffolding in pylons
Is there anything similar to rails' scaffolding for pylons? I've been poking around google, but only found this thing called dbsprockets, which is fine, although probably way too much for my needs. What I really need is a basic CRUD that is based on the SQLAlchemy model.
[ "The question is super old, but hell: http://code.google.com/p/formalchemy/\nGives you basic crud out of the box, customizable to do even relatively complex things easily, and gives you a drop-in Pylons admin app too (written and customizable with the same api, no magic).\n", "I hear you, I've followed the Pylons...
[ 7, 5, 0 ]
[]
[]
[ "pylons", "python" ]
stackoverflow_0000034916_pylons_python.txt
Q: Recreating Postgres COPY directly in Python? I have a block of data, currently as a list of n-tuples but the format is pretty flexible, that I'd like to append to a Postgres table - in this case, each n-tuple corresponds to a row in the DB. What I had been doing up to this point is writing these all to a CSV file ...
Recreating Postgres COPY directly in Python?
I have a block of data, currently as a list of n-tuples but the format is pretty flexible, that I'd like to append to a Postgres table - in this case, each n-tuple corresponds to a row in the DB. What I had been doing up to this point is writing these all to a CSV file and then using postgres' COPY to bulk load all of ...
[ "If you're using the psycopg2 driver, the cursors provide a copy_to and copy_from function that can read from any file-like object (including a StringIO buffer).\nThere are examples in the files examples/copy_from.py and examples/copy_to.py that come with the psycopg2 source distribution.\nThis excerpt is from the ...
[ 53 ]
[]
[]
[ "postgresql", "psycopg2", "python" ]
stackoverflow_0001869973_postgresql_psycopg2_python.txt
Q: How to get the URL Image which is displyed by script When I view the source of page, I do not find the image src. but the image is displayed on the page. This image is generated by some server side code. I am using the selenium for testing. I want to download this image for verification/comparison. How to get that...
How to get the URL Image which is displyed by script
When I view the source of page, I do not find the image src. but the image is displayed on the page. This image is generated by some server side code. I am using the selenium for testing. I want to download this image for verification/comparison. How to get that image using python?
[ "You need to step through the Javascript on that page which might be calling some server-side code to generate that image (e.g. a Captcha image). Using the tools-> page info-> media in Firefox also gives you images on the page that the browser knows about. This post for example gives me https://stackoverflow.com/po...
[ 0, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0001838047_python.txt
Q: Python to generate output ready for Excel I have a Python script gathering info from some remote network devices. The output can be maybe 20 to 1000 lines of text. This then goes into excel on my local PC for now. Now access to this Linux device is convoluted, a citrix session to a remote windows server then ssh t...
Python to generate output ready for Excel
I have a Python script gathering info from some remote network devices. The output can be maybe 20 to 1000 lines of text. This then goes into excel on my local PC for now. Now access to this Linux device is convoluted, a citrix session to a remote windows server then ssh to the Linux device half way around the world. T...
[ "CSV is more robust than your current format under \"copy and paste transfer\" -- spaces and tabs can easily get confused, commas and doublequotes aren't. And the Python standard library's csv module makes it pretty easy to solidly generate good CSV output.\n", "Reformat it as CSV. It's dead easy to do, is fairl...
[ 7, 0, 0 ]
[]
[]
[ "csv", "excel", "python", "xml" ]
stackoverflow_0001870383_csv_excel_python_xml.txt
Q: skip an element in zip I have two files that are zipped with something like the following: for line in zip(open(file1), open(file2)): # do-something Unfortunately, now file2 has changed, and there is an additional line at the beginning. Yes, I could get rid of that manually (or with an additional script/progr...
skip an element in zip
I have two files that are zipped with something like the following: for line in zip(open(file1), open(file2)): # do-something Unfortunately, now file2 has changed, and there is an additional line at the beginning. Yes, I could get rid of that manually (or with an additional script/program), but since the actual nu...
[ "open gives you an iterator, so it's not \"subscriptable\" but it can easily be advanced by one (with the next builtin in 2.6 or better, the .next() method in older Python versions -- I'm assuming 2.6 or better here).\nSo where you'd like to say:\nfor line in zip(open(file1), open(file2)[1:]):\n\nsay, instead:\nf2 ...
[ 4, 2, 1 ]
[]
[]
[ "python" ]
stackoverflow_0001870372_python.txt
Q: Recognizing newline characters in Python So I would like to grab stdout from a subprocess and then write the output to a file using python. The problem I'm having is the stdout from the subprocess loses the formatting, it contains \n's where there are newlines. I would like to write the output to a file with form...
Recognizing newline characters in Python
So I would like to grab stdout from a subprocess and then write the output to a file using python. The problem I'm having is the stdout from the subprocess loses the formatting, it contains \n's where there are newlines. I would like to write the output to a file with formatting intact, meaning instead of one line con...
[ "Don't call repr(), ie. just call\nf.write(stdout_value)\n\n", "Why repr? That turns a object into its representation, which for strings means converting things like chr(10) (newline) into '\\n'.\n", "The repr (which doubles up the \"escapes\", i.e. backslash characters) is what's causing you to \"lose formatt...
[ 3, 1, 0 ]
[]
[]
[ "formatting", "python" ]
stackoverflow_0001870435_formatting_python.txt
Q: Quickly alphabetize a large file via python #!/usr/bin/python import random import string appendToFile = open("appendedFile", "a" ) # Generator for i in range(1, 100000): chars = "".join( [random.choice(string.letters) for i in xrange(15)] ) chars2 = "".join( [random.choice(string.letters) for i in xr...
Quickly alphabetize a large file via python
#!/usr/bin/python import random import string appendToFile = open("appendedFile", "a" ) # Generator for i in range(1, 100000): chars = "".join( [random.choice(string.letters) for i in xrange(15)] ) chars2 = "".join( [random.choice(string.letters) for i in xrange(15)] ) appendToFile.write(chars + ":" +...
[ "The obvious first approach is simply to use the built-in sort feature in Python. Is this not what you had in mind? If not, why? With only 100,000 lines of random text, the built-in sort would be very fast.\nlst = open(\"appendedFile\", \"rt\").readlines()\nlst.sort(key=str.lower)\n\nDone. We could do it as a o...
[ 8, 5, 1 ]
[]
[]
[ "alphabetical", "file", "python" ]
stackoverflow_0001870541_alphabetical_file_python.txt
Q: Is there any python package that could configure IP address of network interface? I am writing a server application which allow remote client to show/add/change/delete IP addresses of network interfaces of the machine where the host is running. The OS is Linux(CentOS 5.2), so I could do that by simply parse and ed...
Is there any python package that could configure IP address of network interface?
I am writing a server application which allow remote client to show/add/change/delete IP addresses of network interfaces of the machine where the host is running. The OS is Linux(CentOS 5.2), so I could do that by simply parse and edit configure file. But is there any package that could simplify the job? And if there ...
[ "It looks like the open source project confparse should be able to easily do what you're looking for. In fact, one of their examples is parsing and modifying /etc/sysconfig/network-scripts/ifcfg-eth0 with ease.\nIf you find this isn't what you need, I say that any efforts towards open sourcing software will inevit...
[ 2 ]
[]
[]
[ "linux", "python" ]
stackoverflow_0001865920_linux_python.txt
Q: Render in infinity loop Question for Python 2.6 I would like to create an simple web application which in specified time interval will run a script that modifies the data (in database). My problem is code for infinity loop or some other method to achieve this goal. The script should be run only once by the user. N...
Render in infinity loop
Question for Python 2.6 I would like to create an simple web application which in specified time interval will run a script that modifies the data (in database). My problem is code for infinity loop or some other method to achieve this goal. The script should be run only once by the user. Next iterations should run aut...
[ "You mentioned that you're using Google App Engine. You can schedule recurring tasks by placing a cron.yaml file in your application folder. The details are here.\nUpdate: It sounds like you're not looking for GAE-specific solutions, so the more general advice I'd give is to use the native scheduling abilities of...
[ 4, 1, 0, 0 ]
[]
[]
[ "cron", "google_app_engine", "python" ]
stackoverflow_0001870140_cron_google_app_engine_python.txt
Q: In Python, how do I refer to an identifier by its absolute fully-qualified name? I have a project with a directory structure that looks like: /foo/baz/__init__.py /bar/foo.py /bar/splat.py Problem is, /bar/splat.py refers to the foo.baz module. This fails with the error No module named baz because it's trying t...
In Python, how do I refer to an identifier by its absolute fully-qualified name?
I have a project with a directory structure that looks like: /foo/baz/__init__.py /bar/foo.py /bar/splat.py Problem is, /bar/splat.py refers to the foo.baz module. This fails with the error No module named baz because it's trying to search for this module within /bar/foo.py. I don't want Python to search the bar mo...
[ "In Python 2.5 and 2.6,\nfrom __future__ import absolute_import\n\nshould change Python's import behavior to do what you want (if the very root, /, is on sys.path of course;-). This becomes the normal Python behavior in 2.7 (not released yet, but an early alpha is already tagged, if you're curious).\n" ]
[ 4 ]
[]
[]
[ "namespaces", "python" ]
stackoverflow_0001870718_namespaces_python.txt
Q: python regular expression across multiple lines I'm gathering some info from some cisco devices using python and pexpect, and had a lot of success with REs to extract pesky little items. I'm afraid i've hit the wall on this. Some switches stack together, I have identified this in the script and used a separate rou...
python regular expression across multiple lines
I'm gathering some info from some cisco devices using python and pexpect, and had a lot of success with REs to extract pesky little items. I'm afraid i've hit the wall on this. Some switches stack together, I have identified this in the script and used a separate routine to parse the data. If the switch is stacked you ...
[ "To have . match any character, including a newline, compile your RE with re.DOTALL among the options (remember, if you have multiple options, use |, the bit-or operator, between them, in order to combine them).\nIn this case I'm not sure you actually do need this -- why not something like\nre.findall(r'(\\d+)\\s+\...
[ 16, 8 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0001870954_python_regex.txt
Q: Python String parse Im working on a data packet retrieval system which will take a packet, and process the various parts of the packet, based on a system of tags [similar to HTML tags]. [text based files only, no binary files]. Each part of the packet is contained between two identical tags, and here is a sample p...
Python String parse
Im working on a data packet retrieval system which will take a packet, and process the various parts of the packet, based on a system of tags [similar to HTML tags]. [text based files only, no binary files]. Each part of the packet is contained between two identical tags, and here is a sample packet: "<PACKET><HEAD><ID...
[ "Something like this?\nimport re\ndef getPacketContent ( code, packetName ):\n match = re.search( '<' + packetName + '>(.*?)<' + packetName + '>', code )\n return match.group( 1 ) if match else ''\n\n# usage\ncode = \"<PACKET><HEAD><ID><ID><SEQ><SEQ><FILENAME><FILENAME><HEAD><DATA><DATA><PACKET>\"\nprint( get...
[ 1, 1, 1 ]
[]
[]
[ "python" ]
stackoverflow_0001870044_python.txt
Q: What are the advantages and disadvantages of the require vs. import methods of loading code? Ruby uses require, Python uses import. They're substantially different models, and while I'm more used to the require model, I can see a few places where I think I like import more. I'm curious what things people find pa...
What are the advantages and disadvantages of the require vs. import methods of loading code?
Ruby uses require, Python uses import. They're substantially different models, and while I'm more used to the require model, I can see a few places where I think I like import more. I'm curious what things people find particularly easy — or more interestingly, harder than they should be — with each of these models. I...
[ "The Python import has a major feature in that it ties two things together -- how to find the import and under what namespace to include it.\nThis creates very explicit code:\nimport xml.sax\nThis specifies where to find the code we want to use, by the rules of the Python search path.\nAt the same time, all objects...
[ 17, 4, 1, 1 ]
[]
[]
[ "language_design", "language_features", "programming_languages", "python", "ruby" ]
stackoverflow_0001849376_language_design_language_features_programming_languages_python_ruby.txt
Q: Dictionary (same value, different key) Newbie Alert: I'm new to Python and when I'm basically adding values to a dict, I find that when I'm printing the whole dictionary, I get the same value of something for all keys of a specific key. Seems like a pointer issue? Here's a snippet when using the event-based XML pa...
Dictionary (same value, different key)
Newbie Alert: I'm new to Python and when I'm basically adding values to a dict, I find that when I'm printing the whole dictionary, I get the same value of something for all keys of a specific key. Seems like a pointer issue? Here's a snippet when using the event-based XML parser (SAX): Basically with every end element...
[ "You'll get the value self for every single entry in self.mapping, of course, since that's the only value you ever store there. Did you rather mean to take a copy/snapshot of self or some of its attributes at that point, then have self change before it gets stored again...?\nEdit: as the OP has clarified (in comme...
[ 4, 2 ]
[]
[]
[ "dictionary", "python" ]
stackoverflow_0001871296_dictionary_python.txt
Q: Python ctypes: initializing c_char_p() I wrote a simple C++ program to illustrate my problem: extern "C"{ int test(int, char*); } int test(int i, char* var){ if (i == 1){ strcpy(var,"hi"); } return 1; } I compile this into an so. From python I call: from ctypes import * libso = CDLL("De...
Python ctypes: initializing c_char_p()
I wrote a simple C++ program to illustrate my problem: extern "C"{ int test(int, char*); } int test(int i, char* var){ if (i == 1){ strcpy(var,"hi"); } return 1; } I compile this into an so. From python I call: from ctypes import * libso = CDLL("Debug/libctypesTest.so") func = libso.test fun...
[ "The string which you initialized with the characters \"bye\", and whose address you keep taking and assigning to charP, does not get re-initialized after the first time.\nFollow the advice here:\n\nYou should be careful, however, not to\n pass them to functions expecting\n pointers to mutable memory. If you\n n...
[ 8, 2 ]
[]
[]
[ "c++", "ctypes", "python", "shared_objects" ]
stackoverflow_0001871375_c++_ctypes_python_shared_objects.txt
Q: Plotting color map with zip codes in R or Python I have some US demographic and firmographic data. I would like to plot zipcode areas in a state or a smaller region (e.g. city). Each area would be annotated by color and/or text specific to that area. The output would be similar to http://maps.huge.info/ but a) wit...
Plotting color map with zip codes in R or Python
I have some US demographic and firmographic data. I would like to plot zipcode areas in a state or a smaller region (e.g. city). Each area would be annotated by color and/or text specific to that area. The output would be similar to http://maps.huge.info/ but a) with annotated text; b) pdf output; c) scriptable in R or...
[ "I am assuming you want static maps. \n\n(source: eduardoleoni.com) \n1) Get the shapefiles of the zip boundaries and state boundaries at census.gov: \n2) Use the plot.heat function I posted in this SO question.\nFor example (assumes you have the maryland shapefiles in the map subdirectory):\nlibrary(maptools)\n##s...
[ 39, 10, 3, 3, 1, 1, 0, 0 ]
[]
[]
[ "graphics", "python", "r", "zipcode" ]
stackoverflow_0001441717_graphics_python_r_zipcode.txt
Q: Debugging Django/Python on Dreamhost Debugging Django on Dreamhost is proving quite the challenge. To my knowledge, print statements aren't available, and neither are logs... any suggestions? A: The Django Debug Toolbar, as already mentioned, is damn useful. But as long as Django is running in debug mode, the br...
Debugging Django/Python on Dreamhost
Debugging Django on Dreamhost is proving quite the challenge. To my knowledge, print statements aren't available, and neither are logs... any suggestions?
[ "The Django Debug Toolbar, as already mentioned, is damn useful.\nBut as long as Django is running in debug mode, the brute force method equivalent to the print statement is to simply throw an exception. Put whatever output you want in the exception's text, whenever you need a quick idea of you code's state, and v...
[ 3, 1 ]
[]
[]
[ "debugging", "django", "dreamhost", "python" ]
stackoverflow_0001871252_debugging_django_dreamhost_python.txt
Q: While loop example x = y // 2 # For some y > 1 while x > 1: if y % x == 0: # Remainder print(y, 'has factor', x) break # Skip else x -= 1 else: # Normal exit print(y, 'is prime') This is an example for understanding while loop in a book I'm reading, I don't quite understand why a floor d...
While loop example
x = y // 2 # For some y > 1 while x > 1: if y % x == 0: # Remainder print(y, 'has factor', x) break # Skip else x -= 1 else: # Normal exit print(y, 'is prime') This is an example for understanding while loop in a book I'm reading, I don't quite understand why a floor division and then y % x? ...
[ "This is a lame primality test.\n% is the mod operator. It performs division and returns the remainder rather than the result of the division. For example, 5 // 2 == 2, and 5 % 2 == 1.\nCommented:\nx = y // 2 # For some y > 1 ##Reduce search space to half of y\nwhile x > 1:\n if y % x == 0: # Remainder ##If x d...
[ 4, 1, 1, 1, 1, 0, 0, 0 ]
[]
[]
[ "prime_factoring", "python", "while_loop" ]
stackoverflow_0001872261_prime_factoring_python_while_loop.txt
Q: Writing my own django-cms plugin. Any recommendations? I don't see any possibility for creating a table in django-cms. I need this functionnality so I am evaluating the possibility to write my own plugin. I am getting started with this product. I've read the documentation carefully and I see more or less how to do...
Writing my own django-cms plugin. Any recommendations?
I don't see any possibility for creating a table in django-cms. I need this functionnality so I am evaluating the possibility to write my own plugin. I am getting started with this product. I've read the documentation carefully and I see more or less how to do that. However, I would be happy to hear some tips and trick...
[ "This all depends on your model. Plugins use standard django admin features.\nThis also depends on the source data for the table. \nIf you have a CSV or Exel sheet as source i only would make a file field and render the file in the render function with some optional caching.\nIf you want to enter data by hand:\nA T...
[ 1 ]
[]
[]
[ "django", "django_cms", "python" ]
stackoverflow_0001861267_django_django_cms_python.txt
Q: Pymsn/Papyon contact memberships Dear Stackoverflow, I'm having the following problem: I'm programming a bot for MSN Messenger in python with the pymsn/papyon library. I have everything running, except that I don't know how to accept new contacts already pending or new requests. Sadly the documentation of the libr...
Pymsn/Papyon contact memberships
Dear Stackoverflow, I'm having the following problem: I'm programming a bot for MSN Messenger in python with the pymsn/papyon library. I have everything running, except that I don't know how to accept new contacts already pending or new requests. Sadly the documentation of the library is very bad. I've achieved to retr...
[ "if you want check there is any contact, just list all you contact and check if the contact status is pending. Short code like:\nfor contact in self.client._address_book.contacts:\n if contact.is_pending:\n self.client._address_book.accept_contact_invitation(contact)\n\nis_pending is my implement but you ...
[ 0 ]
[]
[]
[ "bots", "msn_messenger", "python" ]
stackoverflow_0001498634_bots_msn_messenger_python.txt
Q: Questionnaire/survey app like Google Form - (python+javascript) Django-survey or django-questionnaire is too admin-centric for me (beside tied to django). I want my user to create their own survey. Something like Google Form survey (view example), where form creation feels fluid and intuitive (because of js magic)...
Questionnaire/survey app like Google Form - (python+javascript)
Django-survey or django-questionnaire is too admin-centric for me (beside tied to django). I want my user to create their own survey. Something like Google Form survey (view example), where form creation feels fluid and intuitive (because of js magic). I've googling around with no luck. Is there any python-based surve...
[ "Have tried taking a look at google app engine?\nIt really is not just a survey library, but much much more - and since it gives you Python APIs it probably is not too hard to create a web service that can be used by your users to create new surveys.\nHere is the python documentation and here are the docs for form ...
[ 1 ]
[]
[]
[ "python", "survey" ]
stackoverflow_0001857739_python_survey.txt
Q: Django and multiple databases My current Django setup uses MySQL as the main database to store models. Now for my project I need to connect to a remote PostgreSQL database and retrieve data from it. Is it possible to do this by using built-in Django and Python features or I will need to use library such as Psycopg...
Django and multiple databases
My current Django setup uses MySQL as the main database to store models. Now for my project I need to connect to a remote PostgreSQL database and retrieve data from it. Is it possible to do this by using built-in Django and Python features or I will need to use library such as Psycopg2? It would be great for me, if I w...
[ "Django Project is working on Multiple Database Support. There is also a recent (Nov 10 2009) blog post about \"The state of MultiDB (in Django)\".\nUpdate: Multiple Databases is supported since Django v1.2 (release May 2010).\n" ]
[ 4 ]
[]
[]
[ "django", "multiple_databases", "postgresql", "python" ]
stackoverflow_0001872456_django_multiple_databases_postgresql_python.txt
Q: Not possible to do (a, b) += (1, 2) in python? The following line doesn't seem to work: (count, total) += self._GetNumberOfNonZeroActions((state[0] + x, state[1] - ring, state[2])) I guess it is not possible to use the += operator in this case. I wonder why? edit: Actually what I want is to add to variables count...
Not possible to do (a, b) += (1, 2) in python?
The following line doesn't seem to work: (count, total) += self._GetNumberOfNonZeroActions((state[0] + x, state[1] - ring, state[2])) I guess it is not possible to use the += operator in this case. I wonder why? edit: Actually what I want is to add to variables count and total the values given by the tuple returned by...
[ "Your observation is right: a += b for any a and b means the same as a = a + b (except that it may save one evaluation of a). So if a is a tuple, the only thing that can be +='d to it is another tuple; if a is a temporary unnamed tuple, that += will of course be unobservable -- Python helps you out by catching tha...
[ 10, 5, 1 ]
[]
[]
[ "python" ]
stackoverflow_0001871786_python.txt
Q: Django Admin doesn't show entries If I create a new entry for one particular model it doesn't show up in the django admin. The Agency Model is causing the trouble. # catalog.models class Content(models.Model): class Meta: abstract = True BUNDESLAND_CHOICES = ( ('bw', 'Baden-Württemberg')...
Django Admin doesn't show entries
If I create a new entry for one particular model it doesn't show up in the django admin. The Agency Model is causing the trouble. # catalog.models class Content(models.Model): class Meta: abstract = True BUNDESLAND_CHOICES = ( ('bw', 'Baden-Württemberg'), ('by', 'Bayern'), ('b...
[ "The first manager listed in the model class definition is the one that is used for the admin site and a number of other operations.\nThere have been a number of bugs in Django related to using a manager that does not return all instances as the default manager. IMHO, you are best to use a standard manager as the d...
[ 3 ]
[]
[]
[ "django_admin", "django_models", "python" ]
stackoverflow_0001873177_django_admin_django_models_python.txt
Q: Level Design in Pygame Hey--I'm trying to design my first game using the Pygame library for Python, and I was wondering what the best practices are for level design in general. I would love to hear what you guys think are good object oriented design patterns for managing levels. Also, I'm fairly new to Python--tha...
Level Design in Pygame
Hey--I'm trying to design my first game using the Pygame library for Python, and I was wondering what the best practices are for level design in general. I would love to hear what you guys think are good object oriented design patterns for managing levels. Also, I'm fairly new to Python--thanks!
[ "With this type of game your maps are in terms of tiles (I'm assuming that by level you mean an individual level, not managing all of your levels). Each tile has\n\nan associated picture (what it looks like on the display)\na type (ie, a wall, the ground, a trap, etc.)\n\nWhen I create tile-based games in Pygame, I...
[ 7, 6, 1 ]
[]
[]
[ "design_patterns", "oop", "pygame", "python" ]
stackoverflow_0001871672_design_patterns_oop_pygame_python.txt
Q: String Conversion s='This is sample' i need to convert like this s='"This is sample"' output="This is sample" how to do this in dynamic Thanks in advance A: orig = 'This is sample' converted = '"%s"' % orig A: >>> s= 'This is a sample' >>> s = '"' + s + '"' # or s = '"%s"' % s >>> s '"This is a sample"' >>...
String Conversion
s='This is sample' i need to convert like this s='"This is sample"' output="This is sample" how to do this in dynamic Thanks in advance
[ "orig = 'This is sample'\nconverted = '\"%s\"' % orig\n\n", ">>> s= 'This is a sample'\n>>> s = '\"' + s + '\"' # or s = '\"%s\"' % s\n>>> s\n'\"This is a sample\"'\n>>> print(s)\n\"This is a sample\"\n>>>\n\n" ]
[ 5, 1 ]
[]
[]
[ "python", "string" ]
stackoverflow_0001873659_python_string.txt
Q: How to detect an invalid C escaped string using a regular expression? I would like to find a regular expression (regex) that does detect if you have some invalid escapes in a C double quoted escaped string (where you can find double quotes only escaped). I consider valid \\ \n \r \" (the test string is using ") A ...
How to detect an invalid C escaped string using a regular expression?
I would like to find a regular expression (regex) that does detect if you have some invalid escapes in a C double quoted escaped string (where you can find double quotes only escaped). I consider valid \\ \n \r \" (the test string is using ") A partial solution to this is to use (?<!\\)\\[^\"\\nr] but this one fails to...
[ "(?:^|[^\\\\])(?:\\\\\\\\)*((?:\\\"|\\\\(?:[^\\\"\\\\nr]|$)))\n\nThat's the start of a string, or something that's not a backslash. Then some (possibly zero) properly escaped backslashes, then either an unescaped \" or another backslash; if it's another backslash, it must be followed by something that is neither \"...
[ 3, 0 ]
[]
[]
[ "c", "escaping", "python", "regex" ]
stackoverflow_0001873652_c_escaping_python_regex.txt
Q: Pros and Cons of different approaches to web programming in Python I'd like to do some server-side scripting using Python. But I'm kind of lost with the number of ways to do that. It starts with the do-it-yourself CGI approach and it seems to end with some pretty robust frameworks that would basically do all the j...
Pros and Cons of different approaches to web programming in Python
I'd like to do some server-side scripting using Python. But I'm kind of lost with the number of ways to do that. It starts with the do-it-yourself CGI approach and it seems to end with some pretty robust frameworks that would basically do all the job themselves. And a huge lot of stuff in between, like web.py, Pyroxide...
[ "CGI is great for low-traffic websites, but it has some performance problems for anything else. This is because every time a request comes in, the server starts the CGI application in its own process. This is bad for two reasons: 1) Starting and stopping a process can take time and 2) you can't cache anything i...
[ 17, 12, 7, 4, 3, 2, 2, 1, 1 ]
[]
[]
[ "cgi", "frameworks", "python", "wsgi" ]
stackoverflow_0000043709_cgi_frameworks_python_wsgi.txt
Q: Pygame: Blitting a moving background creates too much blur What I am trying to do is create a viewport to view a small portion of a background. (And later put sprites in). However the problem I have noticed is there seems to be an issue of the background blurring when it starts moving. I was not sure if this is be...
Pygame: Blitting a moving background creates too much blur
What I am trying to do is create a viewport to view a small portion of a background. (And later put sprites in). However the problem I have noticed is there seems to be an issue of the background blurring when it starts moving. I was not sure if this is because blitting is slow or because of a problem in the code. I wa...
[ "I couldn't know what caused the problem you faced, but I guess it is related to double buffering. \nDid you use at least two surfaces? \n# preparing two surfaces in __init__()\nscreen = pygame.display.set_mode((800,600))\nbackground = pygame.Surface(screen.get_size())\nbackground.fill((250, 250, 250))\n\n# called ...
[ 3, 0 ]
[]
[]
[ "blit", "pygame", "python", "sprite" ]
stackoverflow_0001871607_blit_pygame_python_sprite.txt
Q: Display the result on the webpage as soon as the data is available at server I am writing a cgi page in Python. Let's say a client sends request to my cgi page. My cgi page does the calculation and as soon as it has the first output, it sends back that output to the client, but it will CONTINUE to do the calculati...
Display the result on the webpage as soon as the data is available at server
I am writing a cgi page in Python. Let's say a client sends request to my cgi page. My cgi page does the calculation and as soon as it has the first output, it sends back that output to the client, but it will CONTINUE to do the calculation and send other responses AFTER the first response is sent. Is what I have pres...
[ "Sure.\nThere's traditional server-driven approach, where the script runs just once, but takes a long time to complete, spitting out bits of page as it goes:\nimport sys, time\n\nsys.stdout.write('Content-Type: text/html;charset=utf-8\\r\\n\\r\\n')\n\nprint '<html><body>'\nfor i in range(10):\n print '<div>%i</d...
[ 10, 1, 1, 1 ]
[]
[]
[ "cgi", "python" ]
stackoverflow_0001873735_cgi_python.txt
Q: Extract resulted list data to a xml file in python How can I extract my resulted list data to an xml file? My resulted list is given below: week=[{'item': Electrelane, 'weight': 140}, {'item': Kraftwerk, 'weight': 117},{'item': The Flaming Lips, 'weight': 113}] A: You can trivially adjust this to your needs. A:...
Extract resulted list data to a xml file in python
How can I extract my resulted list data to an xml file? My resulted list is given below: week=[{'item': Electrelane, 'weight': 140}, {'item': Kraftwerk, 'weight': 117},{'item': The Flaming Lips, 'weight': 113}]
[ "You can trivially adjust this to your needs.\n", "Since you don't provide any information on how you want to format your XML, i just invented my own notation.\nweek=[{'item': 'Electrelane', 'weight': 140}, {'item': 'Kraftwerk', 'weight': 117},{'item': 'The Flaming Lips', 'weight': 113}]\n\nprint \"<?xml version=...
[ 1, 1, 1 ]
[]
[]
[ "python", "xml" ]
stackoverflow_0001872861_python_xml.txt
Q: Send raw ethernet packet with data field length in type field I'm trying to send a raw ethernet frame with the length of my data written in the type field. This should be a valid ethernet frame. My code for this looks like this: ethData = "foobar" proto =len(ethData) if proto < 46: proto = 46 soc = socket.soc...
Send raw ethernet packet with data field length in type field
I'm trying to send a raw ethernet frame with the length of my data written in the type field. This should be a valid ethernet frame. My code for this looks like this: ethData = "foobar" proto =len(ethData) if proto < 46: proto = 46 soc = socket.socket(socket.AF_PACKET, socket.SOCK_RAW, proto) soc.bind((iface, prot...
[ "Sorry, my fault. I just parsed the wrong portion of the packet and didn't get any output. My bad. The package gets there just like it is supposed to.\n" ]
[ 0 ]
[]
[]
[ "ethernet", "python", "sockets" ]
stackoverflow_0001873427_ethernet_python_sockets.txt
Q: How to implement objects modification trace With django admin, we have an history of who altered an object and when. I would like to add an "old value", "new value" to this to be able to roll back if needed. Plus I would like every modification made to my objects (also outside of admin) to be recorded as well. The...
How to implement objects modification trace
With django admin, we have an history of who altered an object and when. I would like to add an "old value", "new value" to this to be able to roll back if needed. Plus I would like every modification made to my objects (also outside of admin) to be recorded as well. The final objective is to be able to trace every mod...
[ "I haven't personally tried it but it sounds like you should check out django-reversion.\n" ]
[ 3 ]
[]
[]
[ "django", "django_admin", "django_models", "python", "trace" ]
stackoverflow_0001873966_django_django_admin_django_models_python_trace.txt
Q: How to use re to search for items in one list inside another list in Python I am reading a list of strings, each of which relate to a file name. However, each string is minus the extension. I have come up with the following code: import re item_list = ['item1', 'item2'] search_list = ['item1.exe', 'item2.pdf'] mat...
How to use re to search for items in one list inside another list in Python
I am reading a list of strings, each of which relate to a file name. However, each string is minus the extension. I have come up with the following code: import re item_list = ['item1', 'item2'] search_list = ['item1.exe', 'item2.pdf'] matches = [] for item in item_list: # Match item in search_list using re - I ass...
[ "You could combine all the items into one regexp like this which will be more efficient\nimport re\nitem_list = ['item1', 'item2']\nregex = re.compile(\"^(\"+\"|\".join(item_list)+\")\\.\")\nsearch_list = ['item1.exe', 'item2.pdf']\nmatches = []\nfor file in search_list:\n match = regex.match(file)\n if match...
[ 2, 2, 1, 1, 0, 0, 0 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0001872016_python_regex.txt
Q: I need a clean approach for range-checking floats in Python I'm looking for a simple way of range checking floats in Python where the minimum and maximum bounds may be null. The code in question is: tval = float(-b - discriminant) / float (2*a) if tval >= tmin and tval <= tmax: return tval ...
I need a clean approach for range-checking floats in Python
I'm looking for a simple way of range checking floats in Python where the minimum and maximum bounds may be null. The code in question is: tval = float(-b - discriminant) / float (2*a) if tval >= tmin and tval <= tmax: return tval tval = float(-b + discriminant) / float (2*a) if tval >= tmin...
[ "First, some setup: we'll need a float infinity constant.\nINF = float(1e3000)\n\nor\nINF = float('inf') # Python 2.6+\n\nFirst option can be considered portable for practical purposes; just use some really huge value which is guaranteed to be outside the range representable by your platform's floating point type....
[ 4, 4, 3, 2 ]
[]
[]
[ "python" ]
stackoverflow_0001873625_python.txt
Q: unhexlify in objective c is there something like Python's unhexlify for objc / cocoa? >>> from binascii import unhexlify >>> help(unhexlify) Help on built-in function unhexlify in module binascii: unhexlify(...) a2b_hex(hexstr) -> s; Binary data of hexadecimal representation. hexstr must contain an even number ...
unhexlify in objective c
is there something like Python's unhexlify for objc / cocoa? >>> from binascii import unhexlify >>> help(unhexlify) Help on built-in function unhexlify in module binascii: unhexlify(...) a2b_hex(hexstr) -> s; Binary data of hexadecimal representation. hexstr must contain an even number of hex digits (upper or lower ...
[ "Edit: I didn't grok what unhexlify does. I still don't grok why it might be useful (commenters?). \nYou would have to pick off the hex characters two at a time, convert them to an int, and spit out the characters. \nchar *hex = \"abc123d35d\";\n\nNSData *data = [NSData dataWithBytesNoCopy:hex length:strlen(hex)];\...
[ 3, 2, 0 ]
[]
[]
[ "cocoa_touch", "iphone", "python" ]
stackoverflow_0001870475_cocoa_touch_iphone_python.txt
Q: Pip + WSGI import errors when i deploy my apps that worked fine using the django test server I usually get errors for every package I installed using pip install -e ....#egg=foo. I usually do this using virtualenv, which placed the files into env/src/foo and places another file into python/site-packages (this is a...
Pip + WSGI import errors
when i deploy my apps that worked fine using the django test server I usually get errors for every package I installed using pip install -e ....#egg=foo. I usually do this using virtualenv, which placed the files into env/src/foo and places another file into python/site-packages (this is an example of django-css): djan...
[ "This is what my WSGI script for Django in a virtualenv looks like:\nimport os\nos.environ['DJANGO_SETTINGS_MODULE'] = 'myproject.settings'\n\nimport site\nsite.addsitedir('/path/to/virtualenv/lib/python2.6/site-packages')\n\nfrom django.core.handlers.wsgi import WSGIHandler\napplication = WSGIHandler()\n\nThe key ...
[ 4, 0 ]
[]
[]
[ "django", "pip", "python", "virtualenv", "wsgi" ]
stackoverflow_0001875037_django_pip_python_virtualenv_wsgi.txt
Q: Data extraction and manipulation in jython For a given file For ex : 11 ,345 , sdfsfsfs , 1232 i need to such above records from a file , read 11 to delimiter and strip the white space and store in the another file , similarly 345 to delimiter strip the while space and store in the file. This way i need to do ...
Data extraction and manipulation in jython
For a given file For ex : 11 ,345 , sdfsfsfs , 1232 i need to such above records from a file , read 11 to delimiter and strip the white space and store in the another file , similarly 345 to delimiter strip the while space and store in the file. This way i need to do for multiple rows. so finally in the other file ...
[ "Open the input file (1) and the output file (2) for reading and writing respectively. \nfile1 = open('file1', 'r')\nfile2 = open('file2', 'w')\n\nIterate over the input file, getting each line. Split the line on a comma. Then re-join the line using a comma, but first stripping the whitespace (using a list compre...
[ 2, 0 ]
[]
[]
[ "jython", "python", "string" ]
stackoverflow_0001874712_jython_python_string.txt
Q: Dynamic function with local variables I'm trying to dynamically create a bunch of class properties, but each dynamic fget accessor needs a unique local variable. Here is a simplified example: class Test(object): def __metaclass__(name, bases, dict): for i in range(5): def fget(self, i=i): ...
Dynamic function with local variables
I'm trying to dynamically create a bunch of class properties, but each dynamic fget accessor needs a unique local variable. Here is a simplified example: class Test(object): def __metaclass__(name, bases, dict): for i in range(5): def fget(self, i=i): return i dict['...
[ "\"Each dynamic fget accessor needs a unique local variable.\"\nThat tells you that each \"property\" is a separate instance of some class.\nConsider using descriptors for this so that you have a complete class instead of some cobbed-up instance variable.\nOr consider using some variant on the Strategy design patte...
[ 1, 1, 0, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0001875497_python.txt
Q: Saving wx widget contents to a file I have created different shapes like circle/rect etc in my program using BufferedPaintDC on event. Now i want to save the file as I click the saveas button in the menu option. For that I am using memoryDC and save the contents as bmp file. def Saveas(self,event): dlg = wx.Fi...
Saving wx widget contents to a file
I have created different shapes like circle/rect etc in my program using BufferedPaintDC on event. Now i want to save the file as I click the saveas button in the menu option. For that I am using memoryDC and save the contents as bmp file. def Saveas(self,event): dlg = wx.FileDialog(self, "Choose a file", self.dirn...
[ "What you're asking is very close to saying you want to take a screenshot. Although technically grabbing a copy of what the window currently looks like is not the same as cloning what the OnPaint does, it's possible it would do the job for you.\nIf it doesn't work, take note of the technique, including the use of ...
[ 0 ]
[]
[]
[ "python", "wxpython", "wxwidgets" ]
stackoverflow_0001875538_python_wxpython_wxwidgets.txt
Q: Python 2.6+ str.format() and regular expressions Using str.format() is the new standard for formatting strings in Python 2.6, and Python 3. I've run into an issue when using str.format() with regular expressions. I've written a regular expression to return all domains that are a single level below a specified doma...
Python 2.6+ str.format() and regular expressions
Using str.format() is the new standard for formatting strings in Python 2.6, and Python 3. I've run into an issue when using str.format() with regular expressions. I've written a regular expression to return all domains that are a single level below a specified domain or any domains that are 2 levels below the domain s...
[ "you first would need to format string and then use regex. It really doesn't worth it to put everything into a single line. Escaping is done by doubling the curly braces:\n>>> pat= '^(w{{3}}\\.)?([0-9A-Za-z-]+\\.){{1}}{domainName}$'.format(domainName = 'delivery.com')\n>>> pat\n'^(w{3}\\\\.)?([0-9A-Za-z-]+\\\\.){1}...
[ 40, 16 ]
[]
[]
[ "format", "python", "regex", "string_formatting" ]
stackoverflow_0001875676_format_python_regex_string_formatting.txt
Q: Deleting key/value from list of dictionaries using lambda and map I have a list of dictionaries that have the same keys within eg: [{k1:'foo', k2:'bar', k3...k4....}, {k1:'foo2', k2:'bar2', k3...k4....}, ....] I'm trying to delete k1 from all dictionaries within the list. I tried map(lambda x: del x['k1'], list) ...
Deleting key/value from list of dictionaries using lambda and map
I have a list of dictionaries that have the same keys within eg: [{k1:'foo', k2:'bar', k3...k4....}, {k1:'foo2', k2:'bar2', k3...k4....}, ....] I'm trying to delete k1 from all dictionaries within the list. I tried map(lambda x: del x['k1'], list) but that gave me a syntax error. Where have I gone wrong?
[ "lambda bodies are only expressions, not statements like del.\nIf you have to use map and lambda, then:\nmap(lambda d: d.pop('k1'), list_of_d)\n\nA for loop is probably clearer:\nfor d in list_of_d:\n del d['k1']\n\n" ]
[ 41 ]
[]
[]
[ "dictionary", "lambda", "python" ]
stackoverflow_0001875932_dictionary_lambda_python.txt
Q: Django password change:Reverse for '' with arguments '()' and keyword arguments '{}' not found When inckuded the following in urls.py (r'^settings/users/change_password/$', 'django.contrib.auth.views.password_change' The following shows up on the screen, Reverse for '<function password_change_done at 0xa3b0f0c>'...
Django password change:Reverse for '' with arguments '()' and keyword arguments '{}' not found
When inckuded the following in urls.py (r'^settings/users/change_password/$', 'django.contrib.auth.views.password_change' The following shows up on the screen, Reverse for '<function password_change_done at 0xa3b0f0c>' with arguments '()' and keyword arguments '{}' not found. And i am trying to give the access to us...
[ "The password_change view redirects to django.contrib.auth.views.password_change_done - this needs to be listed in your urls.py.\nAlternatively, add the post_change_redirect argument to your password_change view to tell it where to redirect to:\n(r'^settings/users/change_password/$', 'django.contrib.auth.views.pass...
[ 4 ]
[]
[]
[ "django", "python" ]
stackoverflow_0001875318_django_python.txt
Q: Fabric error: Fatal error: local() encountered an error (return code 2) while executing 'git commit -m 'message' I'm trying to setup a fabfile to deploy my Django app. I can't figure out why I'm getting this error: Fatal error: local() encountered an error (return code 2) while executing 'git commit -m 'changed s...
Fabric error: Fatal error: local() encountered an error (return code 2) while executing 'git commit -m 'message'
I'm trying to setup a fabfile to deploy my Django app. I can't figure out why I'm getting this error: Fatal error: local() encountered an error (return code 2) while executing 'git commit -m 'changed settings for prodserver' $ fab create_branch_deploy_to_prodserver [localhost] run: git checkout prodserver_server [loc...
[ "I was able to diagnose the issue when I added capture=False to the declaration:\nlocal('git rm fabfile.py', capture=False)\nlocal('git add settings.py', capture=False)\n\nThis allowed the error to be displayed more verbosely.\nApparently, the maintainer of Fabric will to revert local's behavior back to not capturi...
[ 7, 1 ]
[]
[]
[ "fabric", "git", "python" ]
stackoverflow_0001875306_fabric_git_python.txt
Q: How to get the REMOTE_PORT (the client port) in Python running at IIS 7.5? REMOTE_PORT server variable cannot be found! Hey. I'm coding a cgi in Python, running on an IIS 7.5 web server, on Windows. I would like to get the tcp port (usually was the server environment variable REMOTE_PORT) from which the client is ...
How to get the REMOTE_PORT (the client port) in Python running at IIS 7.5? REMOTE_PORT server variable cannot be found!
Hey. I'm coding a cgi in Python, running on an IIS 7.5 web server, on Windows. I would like to get the tcp port (usually was the server environment variable REMOTE_PORT) from which the client is connecting to it. I've tried to look up all the way throuhout the keys as in os.environ.keys() and I can get the user IP add...
[ "Googling suggests people with ASP.NET and PHP solutions have similar problems and that since IIS 5.0 that variable hasn't been available. I get the impression you have to call a routine called GetServerVariable() to retrieve it. That routine sounds like it's available through various libraries, which you may be ...
[ 0 ]
[]
[]
[ "cgi", "iis_7", "python", "windows" ]
stackoverflow_0001876131_cgi_iis_7_python_windows.txt
Q: Which tools do I need to create installers multi-platform for my python application? Possible Duplicate: An executable Python app imagine that I developed the next killer application in Python using pySide and other several third party libraries. Which tools do i need to create different installers for every OS ...
Which tools do I need to create installers multi-platform for my python application?
Possible Duplicate: An executable Python app imagine that I developed the next killer application in Python using pySide and other several third party libraries. Which tools do i need to create different installers for every OS out there (windows, osx, nix)?
[ "You may use CXFreeze that works on all platforms that Python works. :)\n" ]
[ 0 ]
[]
[]
[ "installation", "multiplatform", "python" ]
stackoverflow_0001876176_installation_multiplatform_python.txt
Q: Proper help for arguments Python optparse works very good when script usage is something like this %prog [options] [args] But I need to write help for script with 1 required argument, so usage will be like this %prog action [options] [args] You can see something similar when you use Subversion - its usage string...
Proper help for arguments
Python optparse works very good when script usage is something like this %prog [options] [args] But I need to write help for script with 1 required argument, so usage will be like this %prog action [options] [args] You can see something similar when you use Subversion - its usage string is svn <subcommand> [options] ...
[ "I think a good solution for you is argparse, which has been proposed for inclusion in Python 2.7 and 3.2. It handles subcommands, I believe as you want, and the linked page includes a link to a page on porting your code from optparse.\nSee also the question command-line-arguments-in-python, into which someone edi...
[ 7, 2, 0 ]
[]
[]
[ "optparse", "python" ]
stackoverflow_0001876289_optparse_python.txt
Q: Python: How do I dynamically alter methods of dict and list objects? Here is a mockup of what I want to do: alist = [1,2,3,4,5] # create a vanilla python list object replacef (alist) # replace __setitem__, extend,... with custom functions alist[0]=2 # now the custom __setitem__ is called This is...
Python: How do I dynamically alter methods of dict and list objects?
Here is a mockup of what I want to do: alist = [1,2,3,4,5] # create a vanilla python list object replacef (alist) # replace __setitem__, extend,... with custom functions alist[0]=2 # now the custom __setitem__ is called This is for a DSL project where the syntax should be as close to normal python as...
[ "Maybe you can do the \"alist = MyList(1,2,3,4,5)\" thing inside the replaceref function? \ndef replacef(l):\n return MyList(l) # Return instance of list subclass that has custom __setitem__\n\nalist = [1,2,3,4,5]\nalist = replaceref(alist)\n\nThis way user would still use the standard list syntax when defining ...
[ 4, 2 ]
[]
[]
[ "dictionary", "dynamic", "list", "methods", "python" ]
stackoverflow_0001876028_dictionary_dynamic_list_methods_python.txt
Q: Python print buffering Let me rephrase my previous question. I just created a tool in ArcGIS using pythong as script language. The tool executes (runs) an outside program using the subprocess.popen. When I run the tool from ArcGSIS, a window appears that only shows the following. Executing: RunFLOW C:\FLOW C:\FLOW...
Python print buffering
Let me rephrase my previous question. I just created a tool in ArcGIS using pythong as script language. The tool executes (runs) an outside program using the subprocess.popen. When I run the tool from ArcGSIS, a window appears that only shows the following. Executing: RunFLOW C:\FLOW C:\FLOW\FLW.bat Start Time: Mon Nov...
[ "I know nothing about ArcGIS, so I may be shooting in the dark here, but...if you want stdout, you usually don't want the communicate() method. You want something like this:\np=subprocess.Popen(Flow_bat,shell=True,stdout=subprocess.PIPE)\nstdout_value = p.stdout.read()\n\nThe communicate() method is used for inter...
[ 0, 0 ]
[]
[]
[ "arcgis", "executable", "printing", "python" ]
stackoverflow_0001823528_arcgis_executable_printing_python.txt
Q: why is python reusing a class instance inside in function I'm running a for loop inside a function which is creating instances of a class to test them. instead of making new classes it appears to be reusing the same two over and over. Is there something I'm missing about how classes and variables are handled in py...
why is python reusing a class instance inside in function
I'm running a for loop inside a function which is creating instances of a class to test them. instead of making new classes it appears to be reusing the same two over and over. Is there something I'm missing about how classes and variables are handled in python methods? how can I generate a new object for each iteratio...
[ "All that shows is that the memory of the objects is being reused, not that new objects aren't being instantiated. In each iteration collection is being overwritten, hence the previous object's reference count drops and the Python interpreter is free to deallocate its memory and reuse it (for the next object).\n>>>...
[ 11, 4 ]
[]
[]
[ "class", "namespaces", "python" ]
stackoverflow_0001876905_class_namespaces_python.txt
Q: how to auto-update a Django page only when required? As described in how to update a Django page without a page reload?, I send periodic XMLHTTPRequests from the browser to the server using JavaScript to get those pieces of the webpage that changes during the course of my application. However, most of the time, no...
how to auto-update a Django page only when required?
As described in how to update a Django page without a page reload?, I send periodic XMLHTTPRequests from the browser to the server using JavaScript to get those pieces of the webpage that changes during the course of my application. However, most of the time, nothing changes; the server replies with the same response a...
[ "The difficulty in answering is in not knowing what the server-side resources are that are being returned to the user.\nI'll make up something which may serve as an example. Let's say you were developing an application that allowed you to monitor in real-time comments being made by users on your site. We can do s...
[ 9 ]
[]
[]
[ "ajax", "django", "javascript", "python" ]
stackoverflow_0001876625_ajax_django_javascript_python.txt
Q: Implementing python exceptions I'm having some problems implementing an exception system in my program. I found somewhere the following piece of code that I am trying to use for my program: class InvalidProgramStateException(Exception): def __init__(self, expr, msg): self.expr = expr self.msg =...
Implementing python exceptions
I'm having some problems implementing an exception system in my program. I found somewhere the following piece of code that I am trying to use for my program: class InvalidProgramStateException(Exception): def __init__(self, expr, msg): self.expr = expr self.msg = msg I think msg must be a string m...
[ "Your custom exceptions don't actually need to take parameters at all. If you haven't got any particular error message or state to encapsulate in the Exception, this will work just fine:\nclass MyException(Exception):\n pass\n\nThis would allow your program to catch cases of this exception by type:\ntry:\n ra...
[ 11 ]
[]
[]
[ "exception", "python" ]
stackoverflow_0001877686_exception_python.txt
Q: Setting numpy slice in lambda function I want to create a lambda function that takes two numpy arrays and sets a slice of the first to the second and returns the newly set numpy array. Considering you can't assign things in lambda functions is there a way to do something similar to this? The context of this is tha...
Setting numpy slice in lambda function
I want to create a lambda function that takes two numpy arrays and sets a slice of the first to the second and returns the newly set numpy array. Considering you can't assign things in lambda functions is there a way to do something similar to this? The context of this is that I want to set the centre of a zeros array ...
[ "This is ugly; you should not use it. But it is oneline lambda as you've asked:\nf = lambda b, a=None, s=slice(1,-1): f(b, numpy.zeros(numpy.array(b.shape) + 2))\\\n if a is None else (a.__setitem__([s]*a.ndim, b), a)[1]\n\nWhat is __setitem__?\nobj.__setitem__(index, value) is equivalent to ob...
[ 4 ]
[]
[]
[ "lambda", "numpy", "python" ]
stackoverflow_0001877437_lambda_numpy_python.txt
Q: Euclidian distance between posts based on tags I am playing with the euclidian distance example from programming collective intelligence book, # Returns a distance-based similarity score for person1 and person2 def sim_distance(prefs,person1,person2): # Get the list of shared_items si={} for item in pr...
Euclidian distance between posts based on tags
I am playing with the euclidian distance example from programming collective intelligence book, # Returns a distance-based similarity score for person1 and person2 def sim_distance(prefs,person1,person2): # Get the list of shared_items si={} for item in prefs[person1]: if item in prefs[person2]: ...
[ "Okay, first off, your code looks incomplete: I see only one return from your function. I think you mean something like this:\ndef sim_distance(prefs, person1, person2): \n # Get the list of shared_items\n p1, p2 = prefs[person1], prefs[person2]\n si = set(p1).intersection(set(p2))\n\n # Add up the squares of a...
[ 1, 1 ]
[]
[]
[ "euclidean_distance", "python", "similarity" ]
stackoverflow_0001877725_euclidean_distance_python_similarity.txt
Q: Optimal way to access a value from the last iteration in a loop What's the best and fastest way to access a value from the previous iteration in a for loop, assuming that the object will be very large (example, a cursor object which has 100,000+ records) Using a simple example: tmp = [ ['xyz', 335], ['zz...
Optimal way to access a value from the last iteration in a loop
What's the best and fastest way to access a value from the previous iteration in a for loop, assuming that the object will be very large (example, a cursor object which has 100,000+ records) Using a simple example: tmp = [ ['xyz', 335], ['zzz', 338], ['yyy', 339], ['yyy', 442], ['abc', 443], ['efg',...
[ "Just iterate over pairs, using zip(), which is much more readable.\nUPDATE: for python 2.x, use itertools.izip instead as it is more efficient!\nfrom itertools import izip\nfor prev, next in izip(tmp, tmp[1:]):\n print 'seq: ', next[1], 'prev seq:', prev[1], 'variance: ', next[1]-prev[1]\n\nwhich can also use v...
[ 4, 3, 2, 1, 0, 0 ]
[]
[]
[ "loops", "python" ]
stackoverflow_0001876587_loops_python.txt
Q: Raise of an eoferror for a file import pickle filename=input('Enter a file name:') def commands(): f=open(filename,'w') names=[] grades=[] while True: name=input("Give a student's name:") if name.lower()=='end': f.close() print("File...
Raise of an eoferror for a file
import pickle filename=input('Enter a file name:') def commands(): f=open(filename,'w') names=[] grades=[] while True: name=input("Give a student's name:") if name.lower()=='end': f.close() print("File closed") print("...
[ "You're running into the end of the file \"EOF\" before your program expects to.\n", "I would suggest keeping the students/grades in a dictionary. If the user has finished her input, pickle the dictionary into a file. Like\ngrades = {}\nwhile True:\n # ask for student's name n\n # ...\n\n if n.lower() ==...
[ 1, 1, 1, 0 ]
[]
[]
[ "eoferror", "file", "python" ]
stackoverflow_0001876100_eoferror_file_python.txt
Q: Python: "unsupported operand types for +: 'long' and 'numpy.float64' " My program uses genetic techniques to build equations. It randomly assembles strings into an equation with one unknown. "(((x + 1) * x) / (4 * 6) ** 2)" One of the strings is: "math.factorial(random.randint(1,9))" So an equation is typically s...
Python: "unsupported operand types for +: 'long' and 'numpy.float64' "
My program uses genetic techniques to build equations. It randomly assembles strings into an equation with one unknown. "(((x + 1) * x) / (4 * 6) ** 2)" One of the strings is: "math.factorial(random.randint(1,9))" So an equation is typically something like: "(((x + 1) * x) / (4 * 6) ** 2) + math.factorial(random.rand...
[ "First, you are missing a closing bracket in your example, and the (+ or - or / or * or **) is confusing.\nWhat are you trying to achieve?\nDo you just want to insert the result in the string? \nTry this:\nfor x in numpy.arange(1,6.4,.1):\n s = \"sinus %f is %f!\" % (x, numpy.sin(x))\n print type(s), s\n\nSee...
[ 3, 1 ]
[]
[]
[ "numpy", "python" ]
stackoverflow_0001877789_numpy_python.txt
Q: Search Python list and return 2 or more of the same character I've just started to learn Python and I'm creating the game Hangman. I've got the basic functionality down. I have a list containing the words and they're randomly selected. I have an input for the user to guess letters and check it against the list tha...
Search Python list and return 2 or more of the same character
I've just started to learn Python and I'm creating the game Hangman. I've got the basic functionality down. I have a list containing the words and they're randomly selected. I have an input for the user to guess letters and check it against the list that the word is split into, I have another list that the correctly gu...
[ "You need to loop over all matching indices:\nfor word_index, letter in enumerate(letter_list):\n if letter == user_input:\n correct_letters[word_index] = user_input\n\nNote: If the loop would be for letter in letter_list: you would only iterate over letters but won't get the corresponding index. The enum...
[ 4, 0 ]
[]
[]
[ "list", "python" ]
stackoverflow_0001875989_list_python.txt
Q: Add tuple to list of tuples in Python I am new to python and don't know the best way to do this. I have a list of tuples which represent points and another list which represents offsets. I need a set of all the combinations that this forms. Here's some code: offsets = [( 0, 0),( 0,-1),( 0, 1),( 1, 0),(-1, 0)] poin...
Add tuple to list of tuples in Python
I am new to python and don't know the best way to do this. I have a list of tuples which represent points and another list which represents offsets. I need a set of all the combinations that this forms. Here's some code: offsets = [( 0, 0),( 0,-1),( 0, 1),( 1, 0),(-1, 0)] points = [( 1, 5),( 3, 3),( 8, 7)] So my set o...
[ "result = [(x+dx, y+dy) for x,y in points for dx,dy in offsets]\n\nFor more, see list comprehensions.\n", "Pretty simple:\n>>> rslt = []\n>>> for x, y in points:\n... for dx, dy in offsets:\n... rslt.append( (x+dx, y+dy) )\n... \n>>> rslt\n[(1, 5), (1, 4), (1, 6), (2, 5), (0, 5), (3, 3), (3, 2), (3, 4...
[ 33, 15, 8, 5 ]
[]
[]
[ "python", "tuples" ]
stackoverflow_0001878470_python_tuples.txt
Q: How to Determine The Module a Particular Exception Class is Defined In Note: i edited my Q (in the title) so that it better reflects what i actually want to know. In the original title and in the text of my Q, i referred to the source of the thrown exception; what i meant, and what i should have referred to, as p...
How to Determine The Module a Particular Exception Class is Defined In
Note: i edited my Q (in the title) so that it better reflects what i actually want to know. In the original title and in the text of my Q, i referred to the source of the thrown exception; what i meant, and what i should have referred to, as pointed out in one of the high-strung but otherwise helpful response below, i...
[ "\nthe second [[exception was thrown]] from a python core module\n\nFalse: it was thrown from a call to cursor.next, exactly like the first one was thrown from a call to cursor.execute -- it's hard to say why you're baldly asserting this counterfactual, but contrary to fact it nevertheless remains.\nIf you're speak...
[ 5, 4, 2, 1, 1 ]
[]
[]
[ "exception", "exception_handling", "module", "python" ]
stackoverflow_0001878801_exception_exception_handling_module_python.txt
Q: Python directory searching and organizing by dict Hey all, this is my first time recently trying to get into the file and os part of Python. I am trying to search a directory then find all sub directories. If the directory has no folders, add all the files to a list. And organize them all by dict. So for instance ...
Python directory searching and organizing by dict
Hey all, this is my first time recently trying to get into the file and os part of Python. I am trying to search a directory then find all sub directories. If the directory has no folders, add all the files to a list. And organize them all by dict. So for instance a tree could look like this Starting Path Dir 1 Su...
[ "Maybe you want something like:\ndef explore(starting_path):\n alld = {'': {}}\n\n for dirpath, dirnames, filenames in os.walk(starting_path):\n d = alld\n dirpath = dirpath[len(starting_path):]\n for subd in dirpath.split(os.sep):\n based = d\n d = d[subd]\n if dirnames:\n for dn in di...
[ 4, 1, 1 ]
[]
[]
[ "directory", "os.walk", "path", "python", "subdirectory" ]
stackoverflow_0001878247_directory_os.walk_path_python_subdirectory.txt
Q: Order a list of files by size via python Example dump from the list of a directory: hello:3.1 GB world:1.2 MB foo:956.2 KB The above list is in the format of FILE:VALUE UNIT. How would one go about ordering each line above according to file size? I thought perhaps to parse each line for the unit via the pattern "...
Order a list of files by size via python
Example dump from the list of a directory: hello:3.1 GB world:1.2 MB foo:956.2 KB The above list is in the format of FILE:VALUE UNIT. How would one go about ordering each line above according to file size? I thought perhaps to parse each line for the unit via the pattern ":VALUE UNIT" (or somehow use the delimiter) th...
[ "thelines = ['hello:3.1 GB', 'world:1.2 MB', 'foo:956.2 KB']\n\nmult = dict(KB=2**10, MB=2**20, GB=2**30)\n\ndef getsize(aline):\n fn, size = aline.split(':', 1)\n value, unit = size.split(' ')\n multiplier = mult[unit]\n return float(value) * multiplier\n\nthelines.sort(key=getsize)\nprint thelines\n\nemits ['...
[ 10 ]
[]
[]
[ "arrays", "dictionary", "hash", "python" ]
stackoverflow_0001879081_arrays_dictionary_hash_python.txt
Q: Count Parenthesis in a file with a Python program? I Wanna fix a function through it i can count how many times are used the:(,),[,] if the counts of ( are equal to those of ) and if the counts of [ are equal to those of ] then i have valid syntax! my first -dissapointed- try: filename=input("Give a file name:") ...
Count Parenthesis in a file with a Python program?
I Wanna fix a function through it i can count how many times are used the:(,),[,] if the counts of ( are equal to those of ) and if the counts of [ are equal to those of ] then i have valid syntax! my first -dissapointed- try: filename=input("Give a file name:") def parenthesis(filename): try: f=open(file...
[ "Please excuse the length of this reply.\nIf I understand you correctly, you want to do simple syntax\nchecking of parentheses to make sure they are balanced correctly.\nIn your question you specify a test based on simple counting, but\nas others have pointed out, this does not catch things like\n\"([)]\".\nI'd als...
[ 4, 1, 1, 1, 0, 0, 0 ]
[]
[]
[ "exception", "file", "parentheses", "python" ]
stackoverflow_0001878167_exception_file_parentheses_python.txt
Q: What signal can be connected to an initial dialog display in pyqt4 (qt) I have an application in which I would like to connect whatever signal is emitted when a pyqt4 dialog is displayed in order to do execute an initial method. I don't want the method to be called in the __init__ method for a number of reasons. I...
What signal can be connected to an initial dialog display in pyqt4 (qt)
I have an application in which I would like to connect whatever signal is emitted when a pyqt4 dialog is displayed in order to do execute an initial method. I don't want the method to be called in the __init__ method for a number of reasons. I've spent quite some time searching but I have yet to find an answer. I'm sur...
[ "There is no signal emitted on first display, instead, you will have to intercept the first resizeEvent or paintEvent by overloading these methods (as you don't want to initialize from the __init__ method).\nAnother option would be to add your own showAndInit method, that initializes and then calls show.\n" ]
[ 3 ]
[]
[]
[ "pyqt4", "python", "qt" ]
stackoverflow_0001878353_pyqt4_python_qt.txt
Q: Django & customising a legacy database I'm currently working on a project to implement a Django interface to an existing calendar application. The calendar application has MySQL as the backend DB. In our custom application we would like to modify/extend the data in one of the tables used by the existing calendar a...
Django & customising a legacy database
I'm currently working on a project to implement a Django interface to an existing calendar application. The calendar application has MySQL as the backend DB. In our custom application we would like to modify/extend the data in one of the tables used by the existing calendar application e.g. # Auto-generated by inspectd...
[ "It appears that you are trying to extend CalendarEvent with more fields.\nFirst, I would make this change to CustomCalendarEvent:\ncode = models.CharField(max_length=80) # Mapped from name\ncalendar_event = models.ForeignKey(CalendarEvent)\nand if length is just calculating the difference in days between sta...
[ 2, 2 ]
[]
[]
[ "django", "legacy_database", "python" ]
stackoverflow_0001876163_django_legacy_database_python.txt
Q: Python Ascendance and descendance I apologize in advance for the basic level of my question. I would like to the print the: total number and identity of nodes that have 0 child, 1 child, 2 children, 3 children. total number of node that have 0 parent, 1 parent, 2 parents, 3 parents. here is my simple script. tha...
Python Ascendance and descendance
I apologize in advance for the basic level of my question. I would like to the print the: total number and identity of nodes that have 0 child, 1 child, 2 children, 3 children. total number of node that have 0 parent, 1 parent, 2 parents, 3 parents. here is my simple script. thanks. Vicinci search = [] search += sear...
[ "You can either create a map and do it yourself or use itertools.groupBy\n1) Do-it-yourself way:\nnodes_by_num_children={}\nfor node in search:\n children=len(node.get_children())\n if children not in nodes_by_num_children:\n nodes_by_num_children[children]=[]\n nodes_by_num_children[children].append(node)\n\...
[ 1, 1 ]
[]
[]
[ "python" ]
stackoverflow_0001879851_python.txt
Q: How to run the program generated by pyuic4? I'm new to PyQt though I know python a bit.. I wanted to Qt designer for GUI programming since it'll make my job easier. I've taken a simple dialog in Qt designer and converted using pyuic4. from PyQt4 import QtCore, QtGui class Ui_Form1(object): def setupUi(self, F...
How to run the program generated by pyuic4?
I'm new to PyQt though I know python a bit.. I wanted to Qt designer for GUI programming since it'll make my job easier. I've taken a simple dialog in Qt designer and converted using pyuic4. from PyQt4 import QtCore, QtGui class Ui_Form1(object): def setupUi(self, Form1): Form1.setObjectName("Form1") ...
[ "You may pass -x parameter to pyuic. It will generate addtional code to make the script executable.\n\nIn real application you should better write a subclass of QMainWindow which could look like this:\n# Store this code in the file MyMainWindow.py\nfrom PyQt4.QtGui import *\n\nclass MyMainWindow(QMainWindow):\n ...
[ 6 ]
[]
[]
[ "pyqt", "python", "qt", "qt_designer" ]
stackoverflow_0001880039_pyqt_python_qt_qt_designer.txt
Q: Hashing Multiple Files Problem Specification: Given a directory, I want to iterate through the directory and its non-hidden sub-directories,  and add a whirlpool hash into the non-hidden file's names. If the script is re-run it would would replace an old hash with a new one. <filename>.<extension>   ==>  <filenam...
Hashing Multiple Files
Problem Specification: Given a directory, I want to iterate through the directory and its non-hidden sub-directories,  and add a whirlpool hash into the non-hidden file's names. If the script is re-run it would would replace an old hash with a new one. <filename>.<extension>   ==>  <filename>.<a-whirlpool-hash>.<exte...
[ "Updated to fix:\n1. File names with '[' or ']' in their name (really, any character now. See comment)\n2. Handling of md5sum when hashing a file with a backslash or newline in its name\n3. Functionized hash-checking algo for modularity\n4. Refactored hash-checking logic to remove double-negatives\n#!/bin/bash\nif ...
[ 6, 4, 3, 3, 2, 1, 1, 1, 1, 1, 1, 0, 0 ]
[]
[]
[ "bash", "batch_processing", "hash", "perl", "python" ]
stackoverflow_0001841737_bash_batch_processing_hash_perl_python.txt
Q: PKI verification across Java and Python I am trying to implement a PKI verification scheme, where a message string is signed with a private key on server, the signature is stored on the client along with the message string. The client then verifies the signature using a public key. The restrictions of my environme...
PKI verification across Java and Python
I am trying to implement a PKI verification scheme, where a message string is signed with a private key on server, the signature is stored on the client along with the message string. The client then verifies the signature using a public key. The restrictions of my environment are, the server is Google App Engine and t...
[ "These are different operations. In Python, you need to use hashAndSign. The default happens to be SHA1 hash.\n", "Keyczar should work fine on App Engine, and is available in both Java and Python flavours.\n" ]
[ 1, 1 ]
[]
[]
[ "cryptography", "google_app_engine", "java", "python" ]
stackoverflow_0001867355_cryptography_google_app_engine_java_python.txt
Q: Use Python to insert xml markup around the difference of two strings I have an oldstring: 'foobarba <span class="foo">z</span>' and a newstring: 'foodbar ba<span class="foo">z</span>' a string is given for a classname, it could be "foo" again, let's say "bar". Given newstring, oldstring and bar, I want to end up...
Use Python to insert xml markup around the difference of two strings
I have an oldstring: 'foobarba <span class="foo">z</span>' and a newstring: 'foodbar ba<span class="foo">z</span>' a string is given for a classname, it could be "foo" again, let's say "bar". Given newstring, oldstring and bar, I want to end up with: 'foo<span class="bar">d</span> ba<span class="foo">z</span>' I wan...
[ "Use difflib from the stdlib to find differences between your strings, then just insert your span tags around the diffs.\n" ]
[ 1 ]
[]
[]
[ "html", "parsing", "python", "string" ]
stackoverflow_0001880356_html_parsing_python_string.txt
Q: pythonic way to explode a list of tuples I need to do the opposite of this Multiple Tuple to Two-Pair Tuple in Python? Namely, I have a list of tuples [(1,2), (3,4), (5,6)] and need to produce this [1,2,3,4,5,6] I would personally do this >>> tot = [] >>> for i in [(1,2), (3,4), (5,6)]: ... tot.extend(list(i...
pythonic way to explode a list of tuples
I need to do the opposite of this Multiple Tuple to Two-Pair Tuple in Python? Namely, I have a list of tuples [(1,2), (3,4), (5,6)] and need to produce this [1,2,3,4,5,6] I would personally do this >>> tot = [] >>> for i in [(1,2), (3,4), (5,6)]: ... tot.extend(list(i)) but I'd like to see something fancier.
[ "The most efficient way to do it is this:\ntuples = [(1,2), (3,4), (5,6)]\n[item for t in tuples for item in t]\n\noutput\n[1, 2, 3, 4, 5, 6]\n\nHere is the comparison I did for various way to do it in a duplicate question.\nI know someone is going to suggest this solution\nsum(tuples, ())\n\nBut don't use it, it w...
[ 21, 6, 2 ]
[]
[]
[ "list", "python" ]
stackoverflow_0001880683_list_python.txt
Q: Does 'p' have a special meaning in Django? Why are p and p8 different in the following code? The beginning of a view function (in file views.py in a Django app named "proteinSearch" with a model named "Protein" that has a field named "description"): def searchForProteins2(request, searchStr): p8 = Protein.obje...
Does 'p' have a special meaning in Django?
Why are p and p8 different in the following code? The beginning of a view function (in file views.py in a Django app named "proteinSearch" with a model named "Protein" that has a field named "description"): def searchForProteins2(request, searchStr): p8 = Protein.objects.filter( description__icontains=searchStr) ...
[ "When you are in Debugging mode (pdb or ipdb REPL), 'p' is meant for a specific functionality, i.e. evaluating an expression expr.\nLike, \nipdb> x = 1\nipdb> p x\n1\nipdb> p x==True\nTrue\nipdb> p x==1\nTrue\n\nIn Django, 'p' will simply means a variable.\nIf you want to print value of 'p' variable, try,\nipdb> p ...
[ 13 ]
[]
[]
[ "django", "python" ]
stackoverflow_0001880753_django_python.txt
Q: Decoding packed data into a structure What would the best way of unpacking a python string into fields I have data received from a tcp socket, it is packed as follows, I believe it will be in a string from the socket recv function It has the following format uint8 - header uint8 - length uint32 - typeID uint16 -pa...
Decoding packed data into a structure
What would the best way of unpacking a python string into fields I have data received from a tcp socket, it is packed as follows, I believe it will be in a string from the socket recv function It has the following format uint8 - header uint8 - length uint32 - typeID uint16 -param1 uint16 -param2 uint16 -param3 uint16 -...
[ "The struct module is designed to unpack heterogeneous data to a tuple based on a format string. It makes more sense to unpack the whole struct at once rather than trying to pull out one field at a time. Here is an example:\nfields = struct.unpack('!BBI4H20sIB', data)\n\nThen you can access a given field, for examp...
[ 7, 4, 4, 1, 0 ]
[]
[]
[ "python", "string", "unpack" ]
stackoverflow_0001879914_python_string_unpack.txt
Q: Retrieve the source of a dynamic website using python (bypassing onclick) I wish to retrieve the source of a website, that is dynamically generated upon clicking a link. The link itself is as below: <a onclick="function(); return false" href="#">Link</a> This stops me from directly querying for a URL that would a...
Retrieve the source of a dynamic website using python (bypassing onclick)
I wish to retrieve the source of a website, that is dynamically generated upon clicking a link. The link itself is as below: <a onclick="function(); return false" href="#">Link</a> This stops me from directly querying for a URL that would allow me to get the dynamically generated website (urllib/2). How would one ret...
[ "You will probably have to reverse engineer the JavaScript to work out what is going on.\nCan you provide the site and the link in question?\n", "I don't immediately see any content-generation or link-following code in that script; all importText does is toggle whether a few divs are shown.\nIf you want to study ...
[ 2, 1 ]
[]
[]
[ "javascript", "onclick", "python", "urllib", "urllib2" ]
stackoverflow_0001879876_javascript_onclick_python_urllib_urllib2.txt
Q: Best XMPP Library for Python Web Application I want to learn how to use XMPP and to create a simple web application with real collaboration features. I am writing the application with Python(WSGI), and the application will require javascript enabled because I am going to use jQuery or Dojo. I have downloaded Openf...
Best XMPP Library for Python Web Application
I want to learn how to use XMPP and to create a simple web application with real collaboration features. I am writing the application with Python(WSGI), and the application will require javascript enabled because I am going to use jQuery or Dojo. I have downloaded Openfire for the server and which lib to choose? SleekX...
[ "I think the Python way to go is to use Twisted along with Words.\nGood luck!\n", "Along with what Julien mentioned, also check out the excellent Strophe XMPP javascript client library, as well as the Twisted based XMPP toolkit called Wokkel.\n", "I have found a lot of issues with Openfire and TLS are not with ...
[ 1, 1, 0 ]
[]
[]
[ "javascript", "python", "wsgi", "xmpp" ]
stackoverflow_0001847120_javascript_python_wsgi_xmpp.txt
Q: Large functionality change based on variables I'm in a situation where I've got a project that has a large number of Django views across quite a few different apps. The same codebase and database is being used by a large number of clients. There are a few site-specific use-cases that are coming in and this require...
Large functionality change based on variables
I'm in a situation where I've got a project that has a large number of Django views across quite a few different apps. The same codebase and database is being used by a large number of clients. There are a few site-specific use-cases that are coming in and this requires quite a bit of custom code to be written. I'd lik...
[ "The most pythonic way would be to use classes for your views and then use inheritance to override specific parts of each view. In your description you describe something which sounds exactly like inheritance.\nThere are two relevant SO questions you might want to look at class views in django and django class vie...
[ 2 ]
[]
[]
[ "django", "python" ]
stackoverflow_0001880619_django_python.txt
Q: Django MTMField: limit_choices_to = other_ForeignKeyField_on_same_model? I've got a couple django models that look like this: from django.contrib.sites.models import Site class Photo(models.Model): title = models.CharField(max_length=100) site = models.ForeignKey(Site) file = models.ImageField(upload_...
Django MTMField: limit_choices_to = other_ForeignKeyField_on_same_model?
I've got a couple django models that look like this: from django.contrib.sites.models import Site class Photo(models.Model): title = models.CharField(max_length=100) site = models.ForeignKey(Site) file = models.ImageField(upload_to=get_site_profile_path) def __unicode__(self): return self.tit...
[ "Yes. You need to override the form that admin uses for the Gallery model, then limit the queryset of the photos field in that form:\nclass GalleryAdminForm(django.forms.ModelForm):\n\n class Meta:\n model = Gallery\n\n def __init__(self, *args, **kwargs):\n super(GalleryAdminForm, self).__init...
[ 6, 2 ]
[ "According to the docs, \"limit_choices_to has no effect when used on a ManyToManyField with an intermediate table\". By my reading, that means it has no effect at all, because ManyToManyFields use intermediate tables...\nI haven't tried to make it work in the Admin site, but from your own views, you can create a ...
[ -1 ]
[ "django", "foreign_keys", "limit_choices_to", "manytomanyfield", "python" ]
stackoverflow_0000345401_django_foreign_keys_limit_choices_to_manytomanyfield_python.txt
Q: How to get the absolute path of a file using tkFileDialog? I am using: file = tkFileDialog.askopenfile(parent=root, mode='rb', filetypes=[('Subrip Subtitle File','*.srt')], title='Choose a subtitle file') to get a file object specified by the user. Is there any way I can get the absolute path of this fil...
How to get the absolute path of a file using tkFileDialog?
I am using: file = tkFileDialog.askopenfile(parent=root, mode='rb', filetypes=[('Subrip Subtitle File','*.srt')], title='Choose a subtitle file') to get a file object specified by the user. Is there any way I can get the absolute path of this file from the file object?
[ "file = tkFileDialog.askopenfile(parent=root,mode='rb',filetypes=[('Subrip Subtitle File','*.srt')],title='Choose a subtitle file')\nabs_path = os.path.abspath(file.name)\n\n", "os.path.abspath should do what you want, if I understand your question correctly.\n" ]
[ 13, 3 ]
[]
[]
[ "dialog", "file", "python", "tkinter" ]
stackoverflow_0001881202_dialog_file_python_tkinter.txt
Q: How to upgrade the version of Python used by Apache? On a Red hat box, I upgraded Python from 2.3 to 2.6.4 and changed the symlink to python so when I type in python the 2.6.4 interpreter comes up. However my .py file works from the command-line, but not in the browser. It seemed like a sys.path issue so I opened ...
How to upgrade the version of Python used by Apache?
On a Red hat box, I upgraded Python from 2.3 to 2.6.4 and changed the symlink to python so when I type in python the 2.6.4 interpreter comes up. However my .py file works from the command-line, but not in the browser. It seemed like a sys.path issue so I opened the file in a browser and printed out sys.path. Surprising...
[ "If you're using mod_python or mod_wsgi, you should reinstall them as they've probably been built to the python version you had when they were first installed on the system (which in your case appears to be Python 2.3).\n", "Apache isn't calling python directly, so the path is irrelevant. You will probably want t...
[ 2, 1, 0 ]
[]
[]
[ "apache", "python", "sys.path", "upgrade" ]
stackoverflow_0001880746_apache_python_sys.path_upgrade.txt
Q: How to unpickle from C code I have a python code computing a matrix, and I would like to use this matrix (or array, or list) from C code. I wanted to pickle the matrix from the python code, and unpickle it from c code, but I could not find documentation or example on how to do this. I found something about marshal...
How to unpickle from C code
I have a python code computing a matrix, and I would like to use this matrix (or array, or list) from C code. I wanted to pickle the matrix from the python code, and unpickle it from c code, but I could not find documentation or example on how to do this. I found something about marshalling data, but nothing about unpi...
[ "You might want to use something more standardized, like JSON. You have a JSON module in Python 2.6. There are 6 different JSON modules for C. \nYou might want to use something more C-like, like the Python struct module. It can build a C-compatible object directly, saving you from pickling and unpickling. http...
[ 5, 3, 2, 1, 1, 0, 0 ]
[]
[]
[ "c", "python" ]
stackoverflow_0001881851_c_python.txt
Q: Is it possible to make a custom mouse cursor with Python Tkinter? (Using matplotlib with the TkAgg backend) It's likely that this is just a general Python Tkinter question, not necessarily a matplotlib one. So I'm in the midst of developing a rather large suite of plotting functionality on top of matplotlib using ...
Is it possible to make a custom mouse cursor with Python Tkinter? (Using matplotlib with the TkAgg backend)
It's likely that this is just a general Python Tkinter question, not necessarily a matplotlib one. So I'm in the midst of developing a rather large suite of plotting functionality on top of matplotlib using the Matplotlib "TkAgg" backend (Agg rendering to a Tk canvas using TkInter). I'm using some of the default zoomi...
[ "Something like this works with unix X11 XBM files:\nimport Tkinter\nt = Tkinter.Tk()\nt.configure(cursor=('@/usr/include/X11/bitmaps/star', '/usr/include/X11/bitmaps/starMask', 'black', 'white'))\nt.mainloop()\n\nAs for the Macs, from the man page for \"Tk_GetCursorFromData\":\n\nThe Macintosh version of Tk suppor...
[ 3 ]
[]
[]
[ "matplotlib", "mouse_cursor", "python", "tkinter" ]
stackoverflow_0001877360_matplotlib_mouse_cursor_python_tkinter.txt
Q: How do I transfer data in .csv file into my sqlite database in django? This is my models.py from django.db import models class School(models.Model): school = models.CharField(max_length=300) def __unicode__(self): return self.school class Lawyer(models.Model): firm_url = models.URLField('B...
How do I transfer data in .csv file into my sqlite database in django?
This is my models.py from django.db import models class School(models.Model): school = models.CharField(max_length=300) def __unicode__(self): return self.school class Lawyer(models.Model): firm_url = models.URLField('Bio', max_length=200) firm_name = models.CharField('Firm', max_length=100...
[ "I created a complete script using this data as a test:\n\"http://www.graychase.com/aabbas\",\"Gray & Chase LLP\",\"Amr A\",\"Abbas\",\"The George Washington University Law School\",\"2005\"\n\"http://www.graychase.com/kadam\",\"Gray & Chase LLP\",\"Karin\",\"Adam\",\"Ernst Moritz Arndt University Greifswald\",\"20...
[ 8 ]
[]
[]
[ "csv", "django", "python" ]
stackoverflow_0001882469_csv_django_python.txt
Q: WMD Preview Doesn't Match Output I am using WMD in a google app situation whereby the site administrator can update the pages of the site and the users see the information. The preview function is working fine and I can see the text the way I want it to appear, but when I am in the users section, the markdown is ...
WMD Preview Doesn't Match Output
I am using WMD in a google app situation whereby the site administrator can update the pages of the site and the users see the information. The preview function is working fine and I can see the text the way I want it to appear, but when I am in the users section, the markdown is being returned without the formatting ...
[ "The reason this is happening is because the Django Form is only seeing the value of the <textarea> tag that represents WMD editor. That value is the actual markdown, not the rendered HTML that you see in the preview.\nThere are several ways to fix this, on either the client or the server...\n\nWhen the form is sa...
[ 2, 1, 0 ]
[]
[]
[ "django", "google_app_engine", "markdown", "python", "wmd" ]
stackoverflow_0001864081_django_google_app_engine_markdown_python_wmd.txt
Q: SQL Alchemy default value function for simulating autoincrement within a unique group of parent-child records I have a small problem that I think should be easily handled by SQL Alchemy but I can't seem to get it right. I have two tables with one being a parent table and the other a child table. For each child r...
SQL Alchemy default value function for simulating autoincrement within a unique group of parent-child records
I have a small problem that I think should be easily handled by SQL Alchemy but I can't seem to get it right. I have two tables with one being a parent table and the other a child table. For each child record it needs a unique ID but only with the context of the unique parent record. I am using the Declarative Base a...
[ "I see 3 ways to go:\n\nThe most obvious and well documented. Create a mapper extension with before_insert() hook replacing inserted parameter.\nPass function as default argument. This function is called with context parameter with all data you need: context.compiled_parameters[0]['CategoryUniqueName'], context.con...
[ 3, 1, 0 ]
[]
[]
[ "auto_increment", "declarative", "primary_key", "python", "sqlalchemy" ]
stackoverflow_0001870364_auto_increment_declarative_primary_key_python_sqlalchemy.txt
Q: How does Smalltalk (Pharo for example) compare to Python? I've seen some comparisons between Smalltalk and Ruby on the one hand and Ruby and Python on the other, but not between Python and Smalltalk. I'd especially like to know what the fundamental differences in Implementation, Syntax, Extensiabillity and Philoso...
How does Smalltalk (Pharo for example) compare to Python?
I've seen some comparisons between Smalltalk and Ruby on the one hand and Ruby and Python on the other, but not between Python and Smalltalk. I'd especially like to know what the fundamental differences in Implementation, Syntax, Extensiabillity and Philosophy are. For example Python does not seem to have Metaclasses....
[ "\nFor example Python does not seem to\n have Metaclasses.\n\nIt sure does -- it just doesn't implicitly generate a new metaclass for every class: it uses the same metaclass as the parent class, or type by default. Python's design philosophy, aka \"The Zen of Python\", can be perused by doing import this at an in...
[ 9, 7, 2, 2, 1 ]
[]
[]
[ "comparison", "language_comparisons", "language_features", "python", "smalltalk" ]
stackoverflow_0001508256_comparison_language_comparisons_language_features_python_smalltalk.txt
Q: DJANGO : Update div with AJAX I am building a chat application. So far I am adding chat messages with jquery $.post() and this works fine. Now I need to retrieve the latest chat message from the table and append the list on the chat page. I am new to Django, so please go slow. So how do I get data from the chat ta...
DJANGO : Update div with AJAX
I am building a chat application. So far I am adding chat messages with jquery $.post() and this works fine. Now I need to retrieve the latest chat message from the table and append the list on the chat page. I am new to Django, so please go slow. So how do I get data from the chat table back to the chat page? Thanks i...
[ "My favorite technique for this kind of thing is to use an inclusion tag\nbasically you make a separate template for rendering the individual objects in the page template\npage template:\n{% load message_tags %} \n\n<h3>Messages</h3>\n<div class=\"message_list\">\n {% for message in messages %}\n {% re...
[ 14, 2, 2 ]
[]
[]
[ "ajax", "django", "django_templates", "jquery", "python" ]
stackoverflow_0001879872_ajax_django_django_templates_jquery_python.txt
Q: Python stacktrace help I have this stack trace error when I try view some data in my Python website, could some one clue me up as to what the problem is I am so lost Environment: Request Method: GET Request URL: http://mywesbite.genericdomain.co.uk/admin/shop/passwordresetrequest/4/ Django Version: 1.1.1 Pyth...
Python stacktrace help
I have this stack trace error when I try view some data in my Python website, could some one clue me up as to what the problem is I am so lost Environment: Request Method: GET Request URL: http://mywesbite.genericdomain.co.uk/admin/shop/passwordresetrequest/4/ Django Version: 1.1.1 Python Version: 2.5.2 Installed ...
[ "The significant piece is in the last few lines (remember that the most recent call, ie: the one that cause the error, is always printed last in a stacktrace):\n File \"/var/www/mywesbite/src/mywebsite/../mywesbite/shop/models.py\", line 1105, in \n __unicode__\n return \", \".join((str(self.account),self.da...
[ 5, 1, 0, 0 ]
[]
[]
[ "django", "python", "stack_trace" ]
stackoverflow_0001881485_django_python_stack_trace.txt
Q: Where should django manager code live? This is a pretty simple django patterns question. My manager code usually lives in models.py, but what happens when models.py is really huge? Is there any other alternative pattern to letting your manager code live in models.py for maintainability and to avoid circular import...
Where should django manager code live?
This is a pretty simple django patterns question. My manager code usually lives in models.py, but what happens when models.py is really huge? Is there any other alternative pattern to letting your manager code live in models.py for maintainability and to avoid circular imports? A question may be asked as to why models....
[ "I prefer to keep my models in models.py and managers in managers.py (forms in forms.py) all within the same app. For more generic managers, I prefer to keep them in core.managers if they can be re-used for other apps. In some of our larger apps with models/modelname.py that will contains a manager and the model ...
[ 32, 12, 9, 4 ]
[]
[]
[ "design_patterns", "django", "django_managers", "django_models", "python" ]
stackoverflow_0001883322_design_patterns_django_django_managers_django_models_python.txt
Q: Linting Python: what is good? Are there any good modules that you can run against your code to catch coding errors? I expected pylint to catch mistakes in the use of default arguments to functions like this: >>> def spam(eggs=[]): ... eggs.append("spam") ... return eggs but was disappointed to find them u...
Linting Python: what is good?
Are there any good modules that you can run against your code to catch coding errors? I expected pylint to catch mistakes in the use of default arguments to functions like this: >>> def spam(eggs=[]): ... eggs.append("spam") ... return eggs but was disappointed to find them unreported. I am looking for somethi...
[ "I tried the first example and PyLint 0.18.1 gave me the warning:\nW: 1:spam: Dangerous default value [] as argument\n\n", "That is not an error in your code if that is what you want to do. However, as specified in the accepted answer, an empty list is a \"dangerous\" default value in that it is easy to introduc...
[ 5, 1 ]
[]
[]
[ "pylint", "python" ]
stackoverflow_0001883725_pylint_python.txt