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: Python opening a file and putting list of names on separate lines I am trying to write a python program using Python 3 I have to open a text file and read a list of names, print the list, sort the list in alphabetical order and then finally re-print the list. There's a little more to it than that BUT the problem I...
Python opening a file and putting list of names on separate lines
I am trying to write a python program using Python 3 I have to open a text file and read a list of names, print the list, sort the list in alphabetical order and then finally re-print the list. There's a little more to it than that BUT the problem I am having is that I'm supposed to print the list of names with each na...
[ "The problem is here: print('original order:', names). This is printing all the list in a single line. So do print each element of the list in a new line, you have to do something like:\nprint('original order:')\nfor name in names:\n print(name)\nnames.sort()\nprint('sorted order:')\nfor name in names:\n prin...
[ 2 ]
[]
[]
[ "file_io", "python" ]
stackoverflow_0008198764_file_io_python.txt
Q: Wrong Environment in Trac SVN post-commit-hook I use a the SVN post-commit-hook script from the official Trac website to update tickets the tickets. (This is the script) If a user commits something into SVN, the ticket gets the update and an E-Mail is generated. This works fine with one exception: It seems the env...
Wrong Environment in Trac SVN post-commit-hook
I use a the SVN post-commit-hook script from the official Trac website to update tickets the tickets. (This is the script) If a user commits something into SVN, the ticket gets the update and an E-Mail is generated. This works fine with one exception: It seems the environment in the post-commit-hook is different from t...
[ "As of version 0.11, you need to set base_url under [trac] to the same value as url under [project]. Ticket #3965 has some more information.\n" ]
[ 2 ]
[]
[]
[ "python", "system_administration", "trac" ]
stackoverflow_0008184029_python_system_administration_trac.txt
Q: How do I write coding using while loops and if statements in jes? How do i write a code in JES program for cropping a specific image with a give coordinates and how do i write a code in JES program for pixelating an image using while loops and if statements? Also, how do i write code in JES program for blur heavy...
How do I write coding using while loops and if statements in jes?
How do i write a code in JES program for cropping a specific image with a give coordinates and how do i write a code in JES program for pixelating an image using while loops and if statements? Also, how do i write code in JES program for blur heavy and reduce jaggies if it is a 5x5 grid?
[ "\nStart by downloading and installing JES from googlecode\nRead Introduction to Programming with JES and work through the examples\nGoogle for more information\n\n" ]
[ 0 ]
[]
[]
[ "jes", "python" ]
stackoverflow_0008198991_jes_python.txt
Q: Efficiently introspecting Python object IP address instance ownership In the code below, I am trying to find a way to eliminate self.owner from the L3Address() class... the idea is that I want to know who owns the IP address on a given Vlan or Interface without having to explicitly call it out. Is there a better w...
Efficiently introspecting Python object IP address instance ownership
In the code below, I am trying to find a way to eliminate self.owner from the L3Address() class... the idea is that I want to know who owns the IP address on a given Vlan or Interface without having to explicitly call it out. Is there a better way to derive the IPv4 addresses' owner (perhaps through introspection)? imp...
[ "Your current approach using owner is the probably the cleanest solution.\nThat being said, if you need to find out who owns an IP address, then gc.get_referrers() may be of help.\n", "There is no way to just remove the owner field from L3Protocol and just magically determine it at runtime. What you're essentiall...
[ 4, 2 ]
[]
[]
[ "introspection", "object", "python" ]
stackoverflow_0008198915_introspection_object_python.txt
Q: Python PDF Libraries I am looking for a good Python PDF library that would parse some format to pdf (I want to use it to programmatically create documents). I have dome some search, and PyPDF looks like an option. Is there any other libraries that I should be aware of? A: Here are a few options: ReportLab, PyX, ...
Python PDF Libraries
I am looking for a good Python PDF library that would parse some format to pdf (I want to use it to programmatically create documents). I have dome some search, and PyPDF looks like an option. Is there any other libraries that I should be aware of?
[ "Here are a few options: ReportLab, PyX, and pyfpdf.\n" ]
[ 2 ]
[]
[]
[ "python" ]
stackoverflow_0008198721_python.txt
Q: Enforcing method order in a Python module What is the most Pythonic way to deal with a module in which methods must be called in a certain order? As an example, I have an XML configuration that must be read before doing anything else because the configuration affects behavior. The parse_config() must be called fir...
Enforcing method order in a Python module
What is the most Pythonic way to deal with a module in which methods must be called in a certain order? As an example, I have an XML configuration that must be read before doing anything else because the configuration affects behavior. The parse_config() must be called first with the configuration file provided. Calli...
[ "If the object isn't valid before it's called, then call that method in __init__ (or use a factory function). You don't need any silly singletons, that's for sure.\n", "The model I have been using is that subsequent functions are only available as methods on the return value of previous functions, like this:\ncla...
[ 7, 2, 1, 0, 0 ]
[ "A module doesn't do anything it isn't told to do so put your function calls at the bottom of the module so that when you import it, things get ran in the order you specify:\ntest.py\nimport testmod\n\ntestmod.py\ndef fun1():\n print('fun1')\n\ndef fun2():\n print('fun2')\n\nfun1()\nfun2()\n\nWhen you run tes...
[ -1 ]
[ "oop", "python", "singleton" ]
stackoverflow_0007906187_oop_python_singleton.txt
Q: Formatting the prompt when using the input function I'm trying to write a script that will prompt a user for an answer to an addition problem. To do this I need to pass a variable to the string that is displayed during the prompt but I'm having a hard time figuring out how to do this. I've come up with the followi...
Formatting the prompt when using the input function
I'm trying to write a script that will prompt a user for an answer to an addition problem. To do this I need to pass a variable to the string that is displayed during the prompt but I'm having a hard time figuring out how to do this. I've come up with the following code that does not work: operand = 4 ans = input('What...
[ "ans = input('What is 4 + {0} ?'.format(operand)) \n\nYou need to modify the string argument to input. In your code you are trying to format the input string returned by the input function\n", "format is a method on the string, so like so:\nans = input('What is 4 + {0} ?'.format(operand)) \n\n" ]
[ 4, 2 ]
[]
[]
[ "python", "python_3.x", "string_formatting" ]
stackoverflow_0008199355_python_python_3.x_string_formatting.txt
Q: Python 3.2.1: Can't Index Shape, Need to Access a Particular Rectangle Later I am using a nested for loop to draw a grid of 10 rows of rectangles and 10 columns of rectangles (100 total): gridTiles = [] for r in range(totalSpaces): for c in range(totalSpaces): tiles = Rectangle(Point(borderSet + r * s...
Python 3.2.1: Can't Index Shape, Need to Access a Particular Rectangle Later
I am using a nested for loop to draw a grid of 10 rows of rectangles and 10 columns of rectangles (100 total): gridTiles = [] for r in range(totalSpaces): for c in range(totalSpaces): tiles = Rectangle(Point(borderSet + r * spaceSize, borderSet + c * spaceSize), Point(borderSet + (r + 1) * spaceSize, borde...
[ "Make gridTiles have nested lists:\ngridTiles = []\n\nfor r in range(totalSpaces):\n row = []\n\n for c in range(totalSpaces):\n tiles = Rectangle(Point(borderSet + r * spaceSize, borderSet + c * spaceSize), Point(borderSet + (r + 1) * spaceSize, borderSet + (c + 1) * spaceSize))\n tiles.setWidt...
[ 3 ]
[]
[]
[ "graphics", "indexing", "python" ]
stackoverflow_0008199509_graphics_indexing_python.txt
Q: Where do I issue commands? When tools such as cx_freeze tell you to use a command such as "python setup.py build", where is this command issued? I have tried both the python command line and the Windows command prompt, but neither one worked with inputting that phrase. A: Here is what : This goes on the windows...
Where do I issue commands?
When tools such as cx_freeze tell you to use a command such as "python setup.py build", where is this command issued? I have tried both the python command line and the Windows command prompt, but neither one worked with inputting that phrase.
[ "Here is what :\n\nThis goes on the windows command prompt.\nYou first need to cd to the directory where your setup.py is situated.\n\nFor Eg: C:\\folder\\setup.py\nOn the command prompt :\n\nC:\\\ncd folder\npython setup.py build\n\nNow, this will call python and pass the file setup.py and asks to build it.\n", ...
[ 2, 1, 0 ]
[]
[]
[ "command", "cx_freeze", "input", "prompt", "python" ]
stackoverflow_0008199646_command_cx_freeze_input_prompt_python.txt
Q: Python, Matching uneven length scraped lists Please prepare for a long read. I am at a standstill and don't know where to look at for an answer / what else to try. Needless to say I am kinda new to programming. Been hacking away at this project for the past couple of weeks. PROBLEM I got this table, 25 lines, 2...
Python, Matching uneven length scraped lists
Please prepare for a long read. I am at a standstill and don't know where to look at for an answer / what else to try. Needless to say I am kinda new to programming. Been hacking away at this project for the past couple of weeks. PROBLEM I got this table, 25 lines, 2 columns. Each line is structured like: Needed e...
[ "From your description, I haven't yet figured out exactly what you are trying to do. But I can tell you one thing right now: with regular expressions, Python raw strings are your friend.\nTry using r'pattern' instead of just 'pattern' in your BeautifulSoup program.\nAlso, when you are working with regular expressi...
[ 3, 1, 1, 0 ]
[]
[]
[ "beautifulsoup", "python", "regex" ]
stackoverflow_0008197444_beautifulsoup_python_regex.txt
Q: change max HTTP response size google app engine is there a way to change the HTTP response size limit from 33554432 bytes to, im my case, 4418142208 bytes? Its all on the local server. A: If you're talking about the response size limit on the URL Fetch service, then Google explicitly says no. If you're talking a...
change max HTTP response size google app engine
is there a way to change the HTTP response size limit from 33554432 bytes to, im my case, 4418142208 bytes? Its all on the local server.
[ "If you're talking about the response size limit on the URL Fetch service, then Google explicitly says no.\nIf you're talking about outgoing data from your application, I don't know. It's not mentioned anywhere in the App Engine documentation, though, so it's probably unchangable.\n" ]
[ 0 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0008196745_google_app_engine_python.txt
Q: Using Python to call Mencoder with some arguments I'll start by saying that I am very, very new to Python. I used to have a Windows/Dos batch file in order to launch Mencoder with the right set of parameters, without having to type them each time. Things got messy when I tried to improve my script, and I decided t...
Using Python to call Mencoder with some arguments
I'll start by saying that I am very, very new to Python. I used to have a Windows/Dos batch file in order to launch Mencoder with the right set of parameters, without having to type them each time. Things got messy when I tried to improve my script, and I decided that it would be a good opportunity to try coding someth...
[ "Python have two types of quotes, \" and ' and they are completely equal. So easiest way to get quotes in a string is to say '\"C:\\Program Files\\MPlayer-1.0rc2\\mencoder.exe\"'.\nUsing the raw prefix (ie r'\"C:\\Program Files\\MPlayer-1.0rc2\\mencoder.exe\"') is a good idea, but that is not the error here, as non...
[ 4, 1, 1, 0 ]
[]
[]
[ "mencoder", "python", "windows" ]
stackoverflow_0001090503_mencoder_python_windows.txt
Q: Currency Formating with Locale in Google App Engine Python I'm attempting to format currency to the US locale using google app engine with python 2.7. This is the code that I'm using: import locale locale.setlocale( locale.LC_ALL, 'US') tFloatCash = 50.00 tStringCash = locale.currency(tFloatCash) ...
Currency Formating with Locale in Google App Engine Python
I'm attempting to format currency to the US locale using google app engine with python 2.7. This is the code that I'm using: import locale locale.setlocale( locale.LC_ALL, 'US') tFloatCash = 50.00 tStringCash = locale.currency(tFloatCash) This works perfectly in the interactive shell. However, I get th...
[ "Google doesn't support locale.\nhttp://code.google.com/p/googleappengine/issues/detail?id=992\nTry moneyfmt.\nhttp://docs.python.org/library/decimal.html#recipes \n" ]
[ 8 ]
[]
[]
[ "google_app_engine", "locale", "python" ]
stackoverflow_0008198952_google_app_engine_locale_python.txt
Q: How can I make an HTML button affect the data of a python script when pressed? I'm generating an HTML page via Python, using the Flask framework to receive messages and the requests module to send them. My python script has a global list variable called History, and when a button is clicked I want the python scrip...
How can I make an HTML button affect the data of a python script when pressed?
I'm generating an HTML page via Python, using the Flask framework to receive messages and the requests module to send them. My python script has a global list variable called History, and when a button is clicked I want the python script to run the command History = [] (e.g. dump the contents of the list). How do i ach...
[ "Have the HTML page send a value using either POST or GET, which is then picked up by a cgi form in Python, converted to integer, and\n<input type=\"submit\" name=\"reset_hist\" />\n\n\nif(reset_hist):\n History = []\n\n\nOr you could use AJAX to send the request, instead of loading a new page. see xmlHttpReques...
[ 4 ]
[]
[]
[ "button", "flask", "html", "python", "python_requests" ]
stackoverflow_0008200405_button_flask_html_python_python_requests.txt
Q: creating multiple lists by extracting contents from a single list I have a list which is shown below. plist = [('s', [0.0, 0.1, 0.0, 0.4, 0.0]), ('aa', [0.0, 0.1, 0.0, 0.5, 0.0]), ('m', [0.0, 0.0, 0.1, 0.3, 0.0]), ('ih', [0.0, 0.1, 0.1, 0.2, 0.0]), ('k', [0.0, 0.1, 0.0, 0.1, 0.0...
creating multiple lists by extracting contents from a single list
I have a list which is shown below. plist = [('s', [0.0, 0.1, 0.0, 0.4, 0.0]), ('aa', [0.0, 0.1, 0.0, 0.5, 0.0]), ('m', [0.0, 0.0, 0.1, 0.3, 0.0]), ('ih', [0.0, 0.1, 0.1, 0.2, 0.0]), ('k', [0.0, 0.1, 0.0, 0.1, 0.0]), ('l', [0.0, 0.1, 0.0, 0.6, 0.0]), ('eh', [0.0, 0....
[ "You can separate out all of the data with:\nv = [[row[1][i] for row in plist] for i in range(len(plist[0][1]))]\n\nNow you have one list where v[0] is the first set of values, v[1] is the second set, and so on. If you still want five separate lists, you can now do:\nv0 = v[0]\nv1 = v[1]\n.\n.\n.\n\n" ]
[ 3 ]
[]
[]
[ "python" ]
stackoverflow_0008200362_python.txt
Q: python function as parameter to c++ exposed class using ::boost::python Ive been working with Python and C++ together for some time, but never tried to implement what follows: Id like the python user to be able to write something like: def foo(a,b): return a+b myclass.myfunc(foo) where myclass is a c++ class...
python function as parameter to c++ exposed class using ::boost::python
Ive been working with Python and C++ together for some time, but never tried to implement what follows: Id like the python user to be able to write something like: def foo(a,b): return a+b myclass.myfunc(foo) where myclass is a c++ class exposed to python with Boost.Python, with one of its methods (myfunc) that t...
[ "You pretty much guessed the answer. Python functions are indeed just boost::python::object instances. You can then just have a boost::function<int (int, int)> and put the Python object inside that.\nI just installed my OS and I don't have Boost yet, so I can't test it, but I think it will work if you just do this ...
[ 3 ]
[]
[]
[ "boost_python", "c++", "python" ]
stackoverflow_0008200414_boost_python_c++_python.txt
Q: How can I do windowed query on multiple columns primary key? Based on example found here but I guess I'm not understanding it. This works for single column primary keys but fails on multiple ones. This is my code @classmethod def column_windows(cls, q, columns, windowsize, where = None): """Return a se...
How can I do windowed query on multiple columns primary key?
Based on example found here but I guess I'm not understanding it. This works for single column primary keys but fails on multiple ones. This is my code @classmethod def column_windows(cls, q, columns, windowsize, where = None): """Return a series of WHERE clauses against a given column that break i...
[ "Well, result is not what expected but got it to work: Now it really windows any query keeping all in place, multi column unique ordering, and so on:\nHere is my code, hope it may be usefull for someone else:\n@classmethod\n def window_query(cls, q, windowsize, windows=None):\n \"\"\"\n q=Query...
[ 0 ]
[]
[]
[ "python", "sql_server", "sqlalchemy", "window_functions" ]
stackoverflow_0008193965_python_sql_server_sqlalchemy_window_functions.txt
Q: Iterable property I have a library (django-piston) which is expecting some parameters of the class as class properties. I would like to define this value dynamically in a method. So I wanted to do something like: class MyHandler(BaseHandler): @property def fields(self): fields = self.model._meta.fi...
Iterable property
I have a library (django-piston) which is expecting some parameters of the class as class properties. I would like to define this value dynamically in a method. So I wanted to do something like: class MyHandler(BaseHandler): @property def fields(self): fields = self.model._meta.fields + self.model._meta...
[ "Your original code looks fine (though I wouldn't have named the local variable the same name as the enclosing function).\nNote, properties only work in new-style classes, so you will need to inherit from object. Also, you need to call the property attribute from an instance.\nIf you need a class attribute, then p...
[ 14, 2, 1 ]
[]
[]
[ "class_properties", "python" ]
stackoverflow_0008198240_class_properties_python.txt
Q: Using external URLs in Django's TEMPLATE_DIRS Django's TEMPLATE_DIRS in Settings.py calls for unix style slashes. Because of this, when I call get_template('some/template.html') in a view, the result always starts at the root, and results in a call to /home/username/projectname/public/some/template.html The pro...
Using external URLs in Django's TEMPLATE_DIRS
Django's TEMPLATE_DIRS in Settings.py calls for unix style slashes. Because of this, when I call get_template('some/template.html') in a view, the result always starts at the root, and results in a call to /home/username/projectname/public/some/template.html The problem is that I'd like to use templates hosted on an...
[ "You don't need to use the template directory is you dont want to. If you have a server that is serving template files, you can simply fetch them remotely using urllib2 and create and render the template with a context manually:\nimport urllib2\nfrom django.template import Context, Template\n\ntpl_html = urllib2.ur...
[ 5, 3, 0 ]
[]
[]
[ "django", "django_settings", "python" ]
stackoverflow_0008201192_django_django_settings_python.txt
Q: Network traffic monitor with pcapy in python I have written simple network traffic monitor to get transfer rate in B/s and/or total data transfer (in B). However when I test it by transferring a file with ftp (using Total Commander) I just can not make it measure total transfer as a size of the file. It always giv...
Network traffic monitor with pcapy in python
I have written simple network traffic monitor to get transfer rate in B/s and/or total data transfer (in B). However when I test it by transferring a file with ftp (using Total Commander) I just can not make it measure total transfer as a size of the file. It always give much lower size than actual one. I am not sure ...
[ "Use a filter to capture only the useful tcp streams, ftp-data :\nport ftp-data\n\nI suggest also to capture in promiscous mode, only the packet headers ( you don't need the full data to know the length ):\nopen_live( device, 4096, True, 100 )\n\nIn your handler, it is correct to use header.getlen().\n" ]
[ 0 ]
[]
[]
[ "networking", "pcap", "python" ]
stackoverflow_0008148608_networking_pcap_python.txt
Q: checking if there is a folder with a name that start with a specific string I'm writing a python script that is supposed to manage my running files. I want to make sure that the source and target folder exist before I run it and I can do this with os.path.exists. However, I have a set of foldernames runner<i>. Is ...
checking if there is a folder with a name that start with a specific string
I'm writing a python script that is supposed to manage my running files. I want to make sure that the source and target folder exist before I run it and I can do this with os.path.exists. However, I have a set of foldernames runner<i>. Is there a way to check that there is some folders begining with that name? For exam...
[ "You could do the following:\nimport os\nif any(x.startswith('runner') for x in os.listdir('/path/to/runners')):\n print \"At least one entry begins with 'runner'\"\n\nThat uses the helpful any function and a generator expression. \n", "Mark Longair's answer is quite fine, and an (equivalent) alternative for t...
[ 15, 6, 6 ]
[]
[]
[ "python" ]
stackoverflow_0008201295_python.txt
Q: How To Generate TCP, IP And UDP Packets In Python Can anyone tell me the most basic approach to generate UDP, TCP, and IP Packets with Python? A: As suggested by jokeysmurf, you can craft packets with scapy If you you want to send/receive regular, i.e. non-custom, packets then you should use socket or socketserv...
How To Generate TCP, IP And UDP Packets In Python
Can anyone tell me the most basic approach to generate UDP, TCP, and IP Packets with Python?
[ "As suggested by jokeysmurf, you can craft packets with scapy\nIf you you want to send/receive regular, i.e. non-custom, packets then you should use socket or socketserver:\n\nhttp://docs.python.org/library/socket.html#module-socket\nhttp://docs.python.org/library/socketserver.html#module-SocketServer\n\nFor exampl...
[ 10, 6 ]
[]
[]
[ "network_programming", "network_protocols", "python" ]
stackoverflow_0008196886_network_programming_network_protocols_python.txt
Q: Python not returning expected value I simply cannot understand what is happening here. The problem is important for my homework (studying programming so I'm a beginner... also my English is not that good, sorry). I am trying to read a string... it can be either a number or a set number of commands. I'll just give ...
Python not returning expected value
I simply cannot understand what is happening here. The problem is important for my homework (studying programming so I'm a beginner... also my English is not that good, sorry). I am trying to read a string... it can be either a number or a set number of commands. I'll just give a very small example of what I'm trying t...
[ "In case you enter the except block, the function validate() uses a recursive call to call itself. When this call returns, it returns to the place where the function was called, i.e. into the except block. The return value of validate() is ignored at this point, and control reaches the end of the outer call witho...
[ 6, 3, 1 ]
[]
[]
[ "python" ]
stackoverflow_0008197823_python.txt
Q: Assigning list to one value in that list I have a slight problem understanding the behaviour of lists. My exercise question is: Draw a memory model showing the effect of the following statements: values = [0, 1, 2] values[1] = values My thinking was that executing these statements will change the list to somethin...
Assigning list to one value in that list
I have a slight problem understanding the behaviour of lists. My exercise question is: Draw a memory model showing the effect of the following statements: values = [0, 1, 2] values[1] = values My thinking was that executing these statements will change the list to something like this [0, [0, 1, 2], 3] , in other word...
[ "You've created a recursive data structure. The second element in the list is a reference to the list itself. When you print this out, normally you would expect to see the original list in the second place, as you suggest in your question.\nHowever, you aren't inserting a copy of the original list, you are insertin...
[ 14, 3, 0 ]
[]
[]
[ "python" ]
stackoverflow_0008201478_python.txt
Q: What's the cost of releasing the GIL? Let's suppose I have a C extension function that does something that is completely independent of the Python interpreter. Is there any reason not to release the GIL? For example, is there any reason not to write code like this (apart from issues like readability and avoiding ...
What's the cost of releasing the GIL?
Let's suppose I have a C extension function that does something that is completely independent of the Python interpreter. Is there any reason not to release the GIL? For example, is there any reason not to write code like this (apart from issues like readability and avoiding micro-optimization - things that are import...
[ "The GIL is an ordinary mutex. The cost of locking or unlocking an uncontested mutex is extremely low, not much more than the cost of changing a global variable. However, if you lock and unlock a contested mutex very often, the cost of the mutex can become significant.\nSo, this is not usually a good idea:\nPy_BE...
[ 9, 1, 0, 0 ]
[]
[]
[ "gil", "multithreading", "python", "python_c_extension" ]
stackoverflow_0007856506_gil_multithreading_python_python_c_extension.txt
Q: Python CSV and Sum I would like to sum amount by a company name, but often format of company name is different.. such as Apple Inc is sometimes Apple computer, Apple Inc. Also.. I don't know how I could handle "header" My file format is CSV. company amount a 20 b 10 A' 30 bb 20 I would like to do like this:...
Python CSV and Sum
I would like to sum amount by a company name, but often format of company name is different.. such as Apple Inc is sometimes Apple computer, Apple Inc. Also.. I don't know how I could handle "header" My file format is CSV. company amount a 20 b 10 A' 30 bb 20 I would like to do like this: line = readline() if li...
[ "Your data is not in true CSV format. The apparent columns are not separated by a comma, nor a tab, or even a single space. Sometimes there are multiple spaces... If this were a space-separated-values file, each space would indicate a new column. Multiple spaces would mean you have more than two columns per line.\n...
[ 2, 0 ]
[]
[]
[ "csv", "python" ]
stackoverflow_0008201865_csv_python.txt
Q: (NameError: global name is not defined) error over passing a list to a function I am sorry to post a long code. I have extracted the parts of my code where the list lower_lip_under_upper_list_plist is generated and used. There is an error of linking the functions where this list has been used. Thegenerate_t_u() fu...
(NameError: global name is not defined) error over passing a list to a function
I am sorry to post a long code. I have extracted the parts of my code where the list lower_lip_under_upper_list_plist is generated and used. There is an error of linking the functions where this list has been used. Thegenerate_t_u() function is called inside time() function but time() function wouldn't recognize this l...
[ "Consider this line in the time function:\ndef time(transcriptionFile) :\n ...\n generate_t_u(timeList, lower_lip_under_upper_list_plist)\n\nlower_lip_under_upper_list_plist is not defined in the time function, so Python looks for it in the global scope. It is not defined there either, so Python raises a Name...
[ 2, 2 ]
[]
[]
[ "python" ]
stackoverflow_0008201564_python.txt
Q: How to split a string into a list, taking negative numbers into account? I want to split a string like: strg = "22+11-aa+bb-44-" into a list like this: my_list = ['22', '+','11', '-', 'aa', '+', 'bb', '-44', '-'] All the non-digit elements are totally split out, if the element after '-' is made of digits, then ...
How to split a string into a list, taking negative numbers into account?
I want to split a string like: strg = "22+11-aa+bb-44-" into a list like this: my_list = ['22', '+','11', '-', 'aa', '+', 'bb', '-44', '-'] All the non-digit elements are totally split out, if the element after '-' is made of digits, then it should join together with the '-' and become a negative number.
[ "import re\n\nstrg = \"22+11-aa+bb-44+-zz99+-33-\" \nprint re.findall(r'-?\\d+|[a-z]+|\\W+?', strg)\n\nresult:\n['22', '+', '11', '-', 'aa', '+', 'bb', '-44', '+', '-', 'zz', '99', '+', '-33', '-']\n\n", "A solution without regexs that makes it longer, but faster on the large data sets:\nstrg=\"22+11-aa+bb-44-\"\...
[ 6, 1 ]
[]
[]
[ "python", "split", "string" ]
stackoverflow_0008201737_python_split_string.txt
Q: Access/Call Simulink from Python I want to model a system in Simulink, and then access that simulation from a python program to feed it new conditions or inputs. I know there is a module out there that allows you to access the Matlab engine from Python, but this is a little different. I'd like to have a system mod...
Access/Call Simulink from Python
I want to model a system in Simulink, and then access that simulation from a python program to feed it new conditions or inputs. I know there is a module out there that allows you to access the Matlab engine from Python, but this is a little different. I'd like to have a system modeled in Simulink, and monitor some har...
[ "There's an open-source HTTP and XML-RPC server for Matlab Simulink called SimServer:\nhttp://simulinksimserv.sourceforge.net/\nAn example Python script has been provided(in the package) which shows how the XML-RPC interface can be used to Get and Set data in a running Simulink model.\n" ]
[ 4 ]
[]
[]
[ "matlab", "python", "simulink" ]
stackoverflow_0008198488_matlab_python_simulink.txt
Q: How getattr() function works with variables? I've been reading about getattr() function in dive into python. From that book I know it works great with modules - no questions about that! I've conducted some test and I don't know what's wrong with that snippet of code where I use getattr() with a specific variable: ...
How getattr() function works with variables?
I've been reading about getattr() function in dive into python. From that book I know it works great with modules - no questions about that! I've conducted some test and I don't know what's wrong with that snippet of code where I use getattr() with a specific variable: var="lol" a=getattr(var,"join") a(["A","B","C"]) ...
[ "In Python, assignment to a variable doesn't change the object that variable references. It merely assigns a different object to the variable. The method held by a remains bound to the string var referenced when you called getattr().\n", "From my understanding, this has nothing to do with getattr. Consider\nobj =...
[ 5, 0 ]
[]
[]
[ "python" ]
stackoverflow_0008202022_python.txt
Q: Does Python have an argc argument? I have written the same program (open text file and display contents) in C and C++. Now am doing the same in Python (on a Linux machine). In the C programs I used the code: if (argc != 2) { /* exit program */ } Question: What is used in Python to check the number of argument...
Does Python have an argc argument?
I have written the same program (open text file and display contents) in C and C++. Now am doing the same in Python (on a Linux machine). In the C programs I used the code: if (argc != 2) { /* exit program */ } Question: What is used in Python to check the number of arguments #!/usr/bin/python import sys try: ...
[ "In python a list knows its length, so you can just do len(sys.argv) to get the number of elements in argv.\n", "I often use a quick-n-dirty trick to read a fixed number of arguments from the command-line:\n[filename] = sys.argv[1:]\n\nin_file = open(filename) # Don't need the \"r\"\n\nThis will assign the one ...
[ 143, 20, 8, 0 ]
[]
[]
[ "arguments", "error_handling", "file_io", "linux", "python" ]
stackoverflow_0008201955_arguments_error_handling_file_io_linux_python.txt
Q: Hand tagging a training set with customized tags I would like to perform some natural language processing on cooking recipes, in particular the ingredients (perhaps preparation later on). Basically I am looking to create my own set of POS tags to help me determine the meaning of an ingredient line. For example, i...
Hand tagging a training set with customized tags
I would like to perform some natural language processing on cooking recipes, in particular the ingredients (perhaps preparation later on). Basically I am looking to create my own set of POS tags to help me determine the meaning of an ingredient line. For example, if one of the ingredients was: 3/4 cup (lightly packed)...
[ "Use pattern.search library.\nThe python pattern library supports many tags[1] , including a cardinal number tag(CD).\nOnce you have tagged cardinals , fractions are \"cardinal/cardinal\" or something like \"cardinal cardinal/cardinal\". \nAnd regarding quantities , you should build a taxonomy of cooking quantities...
[ 3 ]
[]
[]
[ "nltk", "python" ]
stackoverflow_0008197565_nltk_python.txt
Q: wxPython, Disabling buttons? I have a list of buttons and I have made a loop to find out what button is pressed, then disable that button on click. Here is the snippet of code: def change(self,event): self.Disable() for i in enumerate(file_pool): self.button_pool.append(wx.Button(self.size...
wxPython, Disabling buttons?
I have a list of buttons and I have made a loop to find out what button is pressed, then disable that button on click. Here is the snippet of code: def change(self,event): self.Disable() for i in enumerate(file_pool): self.button_pool.append(wx.Button(self.sizer, -1, i[1], pos=(20, i[0]*45),si...
[ "you can get your object from the event:\ndef change(self, event):\n myobject = event.GetEventObject()\n myobject.Disable()\n\n" ]
[ 12 ]
[]
[]
[ "python", "wxpython" ]
stackoverflow_0008202280_python_wxpython.txt
Q: redirect() and NoReverseMatch I am trying to write correct redirection to other view, but now I have no idea This is my last try: txt2png/urls.py urlpatterns = patterns('txt2png.views', # ... url(r'^list/(?P<what>\w)/', 'list', name='list-notes'), url(r'^search/', 'search', name='search-notes'), ) txt2png...
redirect() and NoReverseMatch
I am trying to write correct redirection to other view, but now I have no idea This is my last try: txt2png/urls.py urlpatterns = patterns('txt2png.views', # ... url(r'^list/(?P<what>\w)/', 'list', name='list-notes'), url(r'^search/', 'search', name='search-notes'), ) txt2png/views.py def list(request, what): ...
[ "have you tried the .../list/anything/ ?\nIt is 404, because of your url config. The (?P<what>\\w) means only ONE character, so .../list/a/ will work.\nReplace that row in your url config:\nurl(r'^list/(?P<what>\\w+)/', list, name='list-notes'),\n\n(a + sign added to the regex)\n" ]
[ 1 ]
[]
[]
[ "django", "python" ]
stackoverflow_0008202279_django_python.txt
Q: In python, can a whole file be just a variable? I saw a javascript project had defined very large variables in their own files named the same as the variable eg the large array named marker was in a file called marker.js. Conveniently the variable could be used directly with any import or so, directly acessing it ...
In python, can a whole file be just a variable?
I saw a javascript project had defined very large variables in their own files named the same as the variable eg the large array named marker was in a file called marker.js. Conveniently the variable could be used directly with any import or so, directly acessing it as though it were in the same file. Now I have large ...
[ "I am not totally sure about your question, but isn't that what modules are for?\n\nExample: I have some zipcode logic and a large python data structure containing actual zipcodes:\nzipproj/zipcodelogic.py\nzipproj/zipcodes.py\n\nwhere zipcodes.py would look like\nzipcodes = [\n ('10304', 'Richmond County, NY'),...
[ 3, 2, 1, 1 ]
[]
[]
[ "file", "python", "variables" ]
stackoverflow_0008202539_file_python_variables.txt
Q: Plugins for pyramid (themes, views etc) Ok here is the problem in brief. I do have a pyramid setup that does start to look like a cms. I have as base models: [accounts, pages, errors, menus, configs] It works pretty well but I do have a little problem with something. Currently i'm using git and on some branches I ...
Plugins for pyramid (themes, views etc)
Ok here is the problem in brief. I do have a pyramid setup that does start to look like a cms. I have as base models: [accounts, pages, errors, menus, configs] It works pretty well but I do have a little problem with something. Currently i'm using git and on some branches I do have different templates and on the master...
[ "In Pyramid you can pick templates at run-time using render_to_reponse function. But if you want a more cooked solution, you might get inspired by Kotti, a Pyramid CMS that already has support for addons and look and feel customization with 'Babel' for internationalization. In order to use another 'theme' you have ...
[ 6 ]
[]
[]
[ "entry_point", "plugins", "pyramid", "python" ]
stackoverflow_0008200976_entry_point_plugins_pyramid_python.txt
Q: Image Comparison using c++ or python I am looking for a C++ or Python library to compare two JPEG or BMP formatted Images. Here, I want to compare them pixel wise. For instance assume we have Image1 = 500 pixels, Image2 = 500 pixels; now i need to know the color values ie (RGB, R = 24, G = 15, B = 4) for each pixe...
Image Comparison using c++ or python
I am looking for a C++ or Python library to compare two JPEG or BMP formatted Images. Here, I want to compare them pixel wise. For instance assume we have Image1 = 500 pixels, Image2 = 500 pixels; now i need to know the color values ie (RGB, R = 24, G = 15, B = 4) for each pixel and compare the same with image2 at the ...
[ "If all you need to do is just comparison pixel-wise, you might achieve better performance by using numpy.\nNumpy is an extremely fast python module that works with n-dimensional arrays (containing all the same type, as it is in the case of pixel data) and by operating on them element-wise.\nSo, \"tell me were the ...
[ 3, 1, 1, 1 ]
[]
[]
[ "c++", "python" ]
stackoverflow_0008202407_c++_python.txt
Q: Evaluating numerical expressions Can someone explain to me why when evaluating numerical expressions Python as a result of evaluation returns the last thing that was evaluated? For example: 3 and 5 evaluates to 5 Another question I have is why is it even evaluating these expressions, when I try to check: 3 == Tr...
Evaluating numerical expressions
Can someone explain to me why when evaluating numerical expressions Python as a result of evaluation returns the last thing that was evaluated? For example: 3 and 5 evaluates to 5 Another question I have is why is it even evaluating these expressions, when I try to check: 3 == True I get False but when I evaluate: 3...
[ "Yes, in python any value is either truthy or falsy. Every integer is truthy except for 0. With the boolean operators or and and, python returns the last expression it evaluates, for example 3 or 5 will return 3 as python first sees that 3 is truthy and does not have to evaluate 5 and returns 3.\nIn 0 and 5, 0 is f...
[ 3, 2, 0 ]
[]
[]
[ "boolean", "python" ]
stackoverflow_0008202288_boolean_python.txt
Q: How to notify client's browser about some event on server? I'm using python (Tornado) on server side and some javascript on a client side. I have the common situation - one user send a message to another. And I want server to notify client's browser (reciever of the message) about new message. How can I do it? Sho...
How to notify client's browser about some event on server?
I'm using python (Tornado) on server side and some javascript on a client side. I have the common situation - one user send a message to another. And I want server to notify client's browser (reciever of the message) about new message. How can I do it? Should I establish long-alive connection with client (maybe using w...
[ "\nI'm using python (Tornado) on server side and some javascript on a client side. I have the common situation - one user send a message to another. And I want server to notify client's browser (reciever of the message) about new message. How can I do it? Should I establish long-alive connection with client (maybe ...
[ 2 ]
[]
[]
[ "c10k", "comet", "javascript", "python", "tornado" ]
stackoverflow_0008199683_c10k_comet_javascript_python_tornado.txt
Q: Django Ldap authentication timed out I am hosting a django-based site on a local machine (I have full access/control to it). This site authenticates users against a remote active directory via the django ldap plugin. authenticating against LDAP server used to work! Now, when trying to authenticate against the LDAP...
Django Ldap authentication timed out
I am hosting a django-based site on a local machine (I have full access/control to it). This site authenticates users against a remote active directory via the django ldap plugin. authenticating against LDAP server used to work! Now, when trying to authenticate against the LDAP server, the request just hangs until it t...
[ "Active Directory does not allow anonymous binds for authorization; you can bind anonymously but you cannot do anything else.\nCheck if the user that is being used to bind with AD has valid credentials (ie, the account hasn't expired). If it has, you'll get these strange errors.\n" ]
[ 0 ]
[]
[]
[ "django", "ldap", "nginx", "python" ]
stackoverflow_0008201185_django_ldap_nginx_python.txt
Q: Variable scoping error during recursion in Python The following code recursively processes a list of dictionaries into a tree while building an HTML output string. I'm getting a scope access error when trying to access the output string variable from within the recursing function. However, it has no problem access...
Variable scoping error during recursion in Python
The following code recursively processes a list of dictionaries into a tree while building an HTML output string. I'm getting a scope access error when trying to access the output string variable from within the recursing function. However, it has no problem accessing the nodes list object in the same scope- and in fac...
[ "The error stems from this:\noutput = ''\ndef add(s):\n output = output + s\n\nwhich is equivalent to output+=s. The two output-s in the expanded form refer to different scopes. The assignment sets a local variable while the expression on the right references a global (because local isn't set yet).\nPython detec...
[ 3, 1, 1 ]
[]
[]
[ "python", "recursion", "scope" ]
stackoverflow_0008202536_python_recursion_scope.txt
Q: compiler vs interpreter ( on basis of construction and design ) After viewing lots of posts about the difference between compilers and interpreters, I'm still not able to figure out the difference in their construction and internal mechanism. The most common difference I read was that a compiler produces a target ...
compiler vs interpreter ( on basis of construction and design )
After viewing lots of posts about the difference between compilers and interpreters, I'm still not able to figure out the difference in their construction and internal mechanism. The most common difference I read was that a compiler produces a target program which is executable { means machine code as its output } whic...
[ "First off, \"compiler\" does not imply \"outputs machine code\". You can compile from any language to any other, be it a high-level programming language, some intermediate format, code for a virtual machine (bytecode) or code for a physical machine (machine code).\n\nLike a compiler, an interpreter needs to read a...
[ 5 ]
[]
[]
[ "bytecode", "compiler_construction", "interpreter", "python" ]
stackoverflow_0008203221_bytecode_compiler_construction_interpreter_python.txt
Q: How to get pylibnet installed on a Mac In example.py file I have: import libnet but when I execute it via: /opt/local/bin/python2.5 example.py I'm getting "ImportError: No module named libnet" How I tried to install it: went to http://pylibnet.sourceforge.net/ and downloaded it read the README file which said:...
How to get pylibnet installed on a Mac
In example.py file I have: import libnet but when I execute it via: /opt/local/bin/python2.5 example.py I'm getting "ImportError: No module named libnet" How I tried to install it: went to http://pylibnet.sourceforge.net/ and downloaded it read the README file which said: compiling on Mac doesn't work, load it with...
[ "After you installed the C libraries with MacPorts, did you then install the python libnet wrapper you downloaded? If not, cd to the de-tarred pylibnet directory and try:\nsudo /opt/local/bin/python2.5 setup.py install\n\nUpdate: From your updated question, it now appears you have another version of the libnet C l...
[ 1 ]
[]
[]
[ "installation", "libnet", "macports", "python" ]
stackoverflow_0008202251_installation_libnet_macports_python.txt
Q: Building a menu tree from an adjacency list in Python Consider a basic adjacency list; a list of nodes represent by a Node class, with properties id, parent_id, and name. The parent_id of top-level nodes = None. What would be a Pythonic way of transforming the list into an un-ordered html menu tree, e.g.: nod...
Building a menu tree from an adjacency list in Python
Consider a basic adjacency list; a list of nodes represent by a Node class, with properties id, parent_id, and name. The parent_id of top-level nodes = None. What would be a Pythonic way of transforming the list into an un-ordered html menu tree, e.g.: node name node name sub-node name ...
[ "Assuming you've got something like this:\ndata = [\n\n { 'id': 1, 'parent_id': 2, 'name': \"Node1\" },\n { 'id': 2, 'parent_id': 5, 'name': \"Node2\" },\n { 'id': 3, 'parent_id': 0, 'name': \"Node3\" },\n { 'id': 4, 'parent_id': 5, 'name': \"Node4\" },\n { 'id': 5, 'parent_id': 0, 'name': \"Node5\" ...
[ 5, 2 ]
[]
[]
[ "adjacency_list", "hierarchy", "python" ]
stackoverflow_0008191683_adjacency_list_hierarchy_python.txt
Q: Create a copy of a subclass, recursively? The class Event implements a function copyFrom(self, event) and copy(self). The implementation of both methods is simple made cake. class Event(object): def __init__(self, a, b): self.a = a self.b = b def copyFrom(self, event): self.a = ev...
Create a copy of a subclass, recursively?
The class Event implements a function copyFrom(self, event) and copy(self). The implementation of both methods is simple made cake. class Event(object): def __init__(self, a, b): self.a = a self.b = b def copyFrom(self, event): self.a = event.a self.b = event.b def copy(se...
[ "First, isn't it enough that the MouseEvent constructor recursively calls the Event constructor?\nIf not, have a look at the copy module. It is based on pickle's state retrieval and restoration protocol. Using this protocol, recursive calls are easy. You could of course just copy this basic design if you don't w...
[ 3 ]
[]
[]
[ "class", "copy", "python" ]
stackoverflow_0008203593_class_copy_python.txt
Q: Splitting strings in Python using specific characters I'm trying to split an inputted document at specific characters. I need to split them at [ and ] but I'm having a difficult time figuring this out. def main(): for x in docread: words = x.split('[]') for word in words: doclist.append(word) this...
Splitting strings in Python using specific characters
I'm trying to split an inputted document at specific characters. I need to split them at [ and ] but I'm having a difficult time figuring this out. def main(): for x in docread: words = x.split('[]') for word in words: doclist.append(word) this is the part of the code that splits them into my list. How...
[ "You could try using re.split() instead:\n>>> import re\n>>> re.split(r\"[\\[\\]]\", \"I need to [go out] to lunch\")\n['I need to ', 'go out', ' to lunch']\n\nThe odd-looking regular expression [\\[\\]] is a character class that means split on either [ or ]. The internal \\[ and \\] must be backslash-escaped becau...
[ 9, 2, 0 ]
[]
[]
[ "python", "split" ]
stackoverflow_0008203677_python_split.txt
Q: generate cartesian product of boolean parameter values class Config: def __init__(self, a=False, b=False, c=False, d=False): ... I need to generate all instances of Config with different values for a, b, c, d. They can be True or False. What's the best way to do this? A: Use itertools.product(): [Co...
generate cartesian product of boolean parameter values
class Config: def __init__(self, a=False, b=False, c=False, d=False): ... I need to generate all instances of Config with different values for a, b, c, d. They can be True or False. What's the best way to do this?
[ "Use itertools.product():\n[Config(*x) for x in itertools.product([False, True], repeat=4)]\n\n(Note that these are not permutations.)\n" ]
[ 10 ]
[]
[]
[ "python" ]
stackoverflow_0008203737_python.txt
Q: PyQt: How to transfer text data between widgets? So here's my problem. I attached an image of what I'm working with to give you some visual idea of what I'm doing. I have my list of icons at the bottom. I have a QGraphicsView above it (with the line going through it). http://oi43.tinypic.com/2uhx1xj.jpg (app...
PyQt: How to transfer text data between widgets?
So here's my problem. I attached an image of what I'm working with to give you some visual idea of what I'm doing. I have my list of icons at the bottom. I have a QGraphicsView above it (with the line going through it). http://oi43.tinypic.com/2uhx1xj.jpg (apparently I'm not able to post images yet because I'm a ...
[ "Well I didn't think I'd get this one but I figured it out. After reading more extensively about drag/drop functions I got something that works. QMimeData is confusing. \nHere's what I did. First re-implemented the startDrag() for the list widget:\ndef scene_startDrag(self, dropActions):\n item = self.listWid...
[ 2 ]
[]
[]
[ "pyqt", "python" ]
stackoverflow_0008200062_pyqt_python.txt
Q: wxPython wx.TextCtrl Problems on Mac OSX Lion? I'm using the latest version of wxPython and Python in Mac OSX Lion and haven't had any problems in using any of the wxPython widgets apart from wx.TextCtrl. Every time this control is initialized, the following error occurs and the text control fails to render. 2011-...
wxPython wx.TextCtrl Problems on Mac OSX Lion?
I'm using the latest version of wxPython and Python in Mac OSX Lion and haven't had any problems in using any of the wxPython widgets apart from wx.TextCtrl. Every time this control is initialized, the following error occurs and the text control fails to render. 2011-11-11 16:58:57.255 Python[15021:1107] CFURLCreateWi...
[ "Upgrading to wxPython 2.9.2.4 Cocoa for Python 2.7, which is the latest unstable build seems to have alleviated the problem for me. Probably not the wisest solution.\n" ]
[ 2 ]
[]
[]
[ "osx_lion", "python", "wxpython" ]
stackoverflow_0008097440_osx_lion_python_wxpython.txt
Q: pyqt main window keeps crashing after receiving data from a thread i have a QMainWindow that starts a QThread and waits for data from the network. updates UI when it receive any data. the problem is : it sometimes crash. and sometimes doesn't , all i do i start it and wait for data. here is the thread class : cl...
pyqt main window keeps crashing after receiving data from a thread
i have a QMainWindow that starts a QThread and waits for data from the network. updates UI when it receive any data. the problem is : it sometimes crash. and sometimes doesn't , all i do i start it and wait for data. here is the thread class : class ListenerThread(QtCore.QThread): def __init__(self,host,port...
[ "GUI widgets may be accessed only from main thread, meaning the thread that calls QApplication.exec(). Access to GUI widgets from any other thread – what you're doing with your calls to self.parent() – is undefined behaviour, in your case this means crashes.\nYou signals and slots to communicate between background...
[ 3 ]
[]
[]
[ "pyqt", "python", "qthread" ]
stackoverflow_0008203702_pyqt_python_qthread.txt
Q: Django: how to install tinymce? 1- I want to install tinymce. not django-tinymce (for some reason) 2-I don't want to do it using the admin.py method (for some reason) I want to do it my way: in urls.py: from django.conf.urls.defaults import patterns, include, url # Uncomment the next two lines to enable the adm...
Django: how to install tinymce?
1- I want to install tinymce. not django-tinymce (for some reason) 2-I don't want to do it using the admin.py method (for some reason) I want to do it my way: in urls.py: from django.conf.urls.defaults import patterns, include, url # Uncomment the next two lines to enable the admin: from django.contrib import admin ...
[ "This fixes the errors in urls.py:\nfrom django.conf.urls.defaults import patterns, include, url\n\n# Uncomment the next two lines to enable the admin:\nfrom django.contrib import admin\nadmin.autodiscover()\n\nurlpatterns = patterns('',\n url(r'^admin/', include(admin.site.urls),\n url(r'^tiny_mce/(?P<path...
[ 1, 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0008203883_django_python.txt
Q: Loop colours from variables for graphics.py I am creating a graphics program that draws 100 x 100 squares next to each other depending on the user-specified grid size. The user also inputs 4 colours for the squares to be coloured (e.g. if they enter red,green,blue,yellow the squares will be coloured in that order,...
Loop colours from variables for graphics.py
I am creating a graphics program that draws 100 x 100 squares next to each other depending on the user-specified grid size. The user also inputs 4 colours for the squares to be coloured (e.g. if they enter red,green,blue,yellow the squares will be coloured in that order, repeating the colours). Is it possible to loop ...
[ "If you want to select 4 colors given a user variable you can use modulus.\ncolor_index = user_var % 4\n\nthen you can get your color as:\nmycolor = colours[color_index]\n\nAlternatively, if you want to give a different color each time a user need it and cycle on them when the available colors are exhausted you can...
[ 0, 0 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0008202979_python_python_3.x.txt
Q: python, codecs, file.writelines(), UnicodeDecodeError Do not know how to resolve the UnicodeDecodeError: I am not able to write text to file --> UnicodeDecodeError about character â = '0xe2'. 1) â = '0xe2' character for sure does not exists in that string 2) re.search is not able to find â character in the strin...
python, codecs, file.writelines(), UnicodeDecodeError
Do not know how to resolve the UnicodeDecodeError: I am not able to write text to file --> UnicodeDecodeError about character â = '0xe2'. 1) â = '0xe2' character for sure does not exists in that string 2) re.search is not able to find â character in the string, which I am trying to write file.writelines(string) 3) th...
[ "You're using codecs.open so your file object expects unicode strings, not byte strings.\nThe point in using this function is that you don't have to encode the strings yourself before writing them to the file. You write unicode strings and the file object will encode them internally.\nIt looks like the smart_str re...
[ 3 ]
[]
[]
[ "codec", "file_io", "python", "regex" ]
stackoverflow_0008204088_codec_file_io_python_regex.txt
Q: Python trying to write string to file then read string and eval, but something went wrong I am trying to write a very simple script that would simulate a pocket secretary for my homework, but I have a small issue. I want all my data to be saved in a file (abstract form) each time I exit the program and then when ...
Python trying to write string to file then read string and eval, but something went wrong
I am trying to write a very simple script that would simulate a pocket secretary for my homework, but I have a small issue. I want all my data to be saved in a file (abstract form) each time I exit the program and then when i boot it up I want to read that file, eval(stack) (basically load the data into memory) then v...
[ "To handle your immediate problem, change the line load_stack = str(stack) to load_stack = repr(stack). That will add the apostrophes.\nAfterwards, you may want to look at the csv module or shelve module. Both are easy to use and will take care of many of the low level details.\n" ]
[ 2 ]
[]
[]
[ "python" ]
stackoverflow_0008204111_python.txt
Q: getting sin curve values using python I am looking to create a sin curve using python. I want a code to generate the values in the form of a sine curve. Such that if i plot those values i should get this curve. Can someone help me with this ? I should be able to differ the number of values it takes to reach the pe...
getting sin curve values using python
I am looking to create a sin curve using python. I want a code to generate the values in the form of a sine curve. Such that if i plot those values i should get this curve. Can someone help me with this ? I should be able to differ the number of values it takes to reach the peak (basically varying the frequency). Thank...
[ "Have you got Matplotlib and NumPy installed?\n>>> import matplotlib.pyplot as plt\n>>> import numpy as np\n>>> x = np.linspace(-10, 10, 1000)\n>>> y = np.sin(x)\n>>> plt.plot(x, y)\n[<matplotlib.lines.Line2D object at 0x25d1ed0>]\n>>> plt.show()\n\nSkip the last few steps if you don't need the plot.\n", "You can...
[ 3, 1 ]
[]
[]
[ "math", "python", "trigonometry" ]
stackoverflow_0008204210_math_python_trigonometry.txt
Q: How to perform arithmetic operations in Sparql with python? I am writting a public domain calculator, whose code is available at: https://github.com/okfn/pdcalc/blob/master/pd/map.rdf The code is currently unable to properly determine the public domain status of a work because of an issue that has been encountere...
How to perform arithmetic operations in Sparql with python?
I am writting a public domain calculator, whose code is available at: https://github.com/okfn/pdcalc/blob/master/pd/map.rdf The code is currently unable to properly determine the public domain status of a work because of an issue that has been encountered with sparql 1.0: it does not appear to be possible to perform a...
[ "Even SPARQL 1.1 does not support arithmetic operations on dates by default. See the section on SPARQL operator mapping: arithmetic operations are only defined on numeric datatypes.\nThere may be some SPARQL 1.1 implementations that offer an extension for this purpose, but I'm not immediately aware of any that have...
[ 3, 1 ]
[]
[]
[ "python", "rdflib", "sparql" ]
stackoverflow_0008201012_python_rdflib_sparql.txt
Q: Checking if certain words are on a web page using Python? I have a list of words, in Python I need to loop through each word and check if the word is on a website. Currently, this is a snippet of what I have (relating to this problem): words = ['word', 'word1', 'word2'] site = urllib.request.urlopen(link) for word...
Checking if certain words are on a web page using Python?
I have a list of words, in Python I need to loop through each word and check if the word is on a website. Currently, this is a snippet of what I have (relating to this problem): words = ['word', 'word1', 'word2'] site = urllib.request.urlopen(link) for word in words: if word in site: print(word) else: ...
[ "The urlopen() function returns a \"file-like object\". In order to read the data, you must call read():\nsite = urllib.request.urlopen(link).read()\n\nThere are other ways to read the data too, but this is a simple way to load the whole page data into memory for quick searching.\nThe reason your code worked as wri...
[ 7, 2 ]
[]
[]
[ "python", "web" ]
stackoverflow_0008204373_python_web.txt
Q: Python3: What is the difference between keywords and builtins? In python 3, >>> import keyword >>> keyword.kwlist and >>> import builtins >>> dir(builtins) are two different lists, yet they have some common values, specifically >>> set(dir(builtins)) & set(keyword.kwlist) {'False', 'True', 'None'} What is the d...
Python3: What is the difference between keywords and builtins?
In python 3, >>> import keyword >>> keyword.kwlist and >>> import builtins >>> dir(builtins) are two different lists, yet they have some common values, specifically >>> set(dir(builtins)) & set(keyword.kwlist) {'False', 'True', 'None'} What is the difference of keywords and builtins in python? and when are 'False', ...
[ "Keywords are core language constructs handled by the parser. These words are reserved and cannot be used as identifiers: http://docs.python.org/reference/lexical_analysis.html#keywords\nBuiltins are a list of commonly used, preloaded functions, constants, types, and exceptions: http://docs.python.org/library/fun...
[ 26 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0008204542_python_python_3.x.txt
Q: Python's argparser: how to set command line input of a positional argument as the default for an optional argument? I want the command line input of a positional input to be the default for an optional argument, like this: parser.add_argument("Foo") parser.add_argument("-b", dest="bar") parser.set_defaults(parser....
Python's argparser: how to set command line input of a positional argument as the default for an optional argument?
I want the command line input of a positional input to be the default for an optional argument, like this: parser.add_argument("Foo") parser.add_argument("-b", dest="bar") parser.set_defaults(parser.Foo) options = parser.parse_args() Is something like this possible at all? Or should I just do something like: parser.a...
[ "I'd try like you do in the second block of code, but use None as the sentinel value rather than a magic string.\n" ]
[ 1 ]
[]
[]
[ "argparse", "python" ]
stackoverflow_0008203554_argparse_python.txt
Q: confusion over sequence of function calling I have a silly confusion here. I have the following main() in my code and I pass transcriptionFile and phonemeFile as inputs. Is it the time() function that is called first and then the coart() function? But I input the files together that are passed in these functions i...
confusion over sequence of function calling
I have a silly confusion here. I have the following main() in my code and I pass transcriptionFile and phonemeFile as inputs. Is it the time() function that is called first and then the coart() function? But I input the files together that are passed in these functions in a single line, so don't they have to be called ...
[ "Statements are always executed in the order listed. So in your case, sys.argv[1] will first be assigned to the global variable transcriptionFile. Then, the time function will be called. Then the value of sys.argv[2] will be assigned to the phonemeFile variable, and finally the coart function will be called. If...
[ 1, 1, 1 ]
[]
[]
[ "python" ]
stackoverflow_0008204567_python.txt
Q: How to render tuples in bottlepy I have been using bottlepy and i have a thing like this: ..code.. comments = [(u'34782439', 78438845, 6, u'hello im nick'), (u'34754554', 7843545, 5, u'hello im john'), (u'332432434', 785345545, 3, u'hello im phil')] return comments In the view i have done this: %for address d...
How to render tuples in bottlepy
I have been using bottlepy and i have a thing like this: ..code.. comments = [(u'34782439', 78438845, 6, u'hello im nick'), (u'34754554', 7843545, 5, u'hello im john'), (u'332432434', 785345545, 3, u'hello im phil')] return comments In the view i have done this: %for address date user text in comments: <h3>{...
[ "Your code has two problems. First, response cannot be a list of tuples. It can be a string or a list of strings, as Peter suggests, or, in case you want to use the view, it can (and should) be a dictionary of view variables. Keys are variable names (these names, such as comments, will be available in the view), va...
[ 7, 4 ]
[]
[]
[ "bottle", "python", "templates" ]
stackoverflow_0008184805_bottle_python_templates.txt
Q: Is Python similar to UnityScript, (JavaScript)? I'm wondering if Python is similar to the way JavaScript is used with the Unity3d Game Engine? I know standard JavaScript that manipulates the DOM is very different from how Unity utilizes JS. Would knowing Python be beneficial to getting started with UnityScript? A...
Is Python similar to UnityScript, (JavaScript)?
I'm wondering if Python is similar to the way JavaScript is used with the Unity3d Game Engine? I know standard JavaScript that manipulates the DOM is very different from how Unity utilizes JS. Would knowing Python be beneficial to getting started with UnityScript?
[ "Python is very unlike JavaScript, so my vote would be for no.\n", "In general, knowing one language will help you learn others, but past that, you're probably better off learning JavaScript itself. I'd suggest looking at this site to get started.\n" ]
[ 3, 1 ]
[]
[]
[ "python", "unity3d", "unityscript" ]
stackoverflow_0008205091_python_unity3d_unityscript.txt
Q: py2app not including pythonpath I'm trying to build an app with py2app. I can build the app but when I run it I get ImportError in the console, the import error is that there is No module named PythonApp which is the folder all my source is in, the location of which is in my PYTHONPATH. I have been importing local...
py2app not including pythonpath
I'm trying to build an app with py2app. I can build the app but when I run it I get ImportError in the console, the import error is that there is No module named PythonApp which is the folder all my source is in, the location of which is in my PYTHONPATH. I have been importing local files like from PythonApp import fil...
[ "If I understood your problem well, you have the following layout:\nPythonApp/\n __init__.py\n file.py\n foo.py\n\nAnd you try to import the module file from foo.py by from PythonApp import file. If this the only reason you want to set PYTHONPATH, there is a simpler solution: use relative imports:\nfrom . import...
[ 1 ]
[]
[]
[ "py2app", "python" ]
stackoverflow_0008203797_py2app_python.txt
Q: Calling 'del' on a list class ToBeDeleted: def __init__(self, value): self.value = val # Whatever... def __del__(self): print self.value l = [ToBeDeleted(i) for i in range(3)] del l This prints 2, 1, 0. Now, is the order of the deleted elements defined somewhere in specification or...
Calling 'del' on a list
class ToBeDeleted: def __init__(self, value): self.value = val # Whatever... def __del__(self): print self.value l = [ToBeDeleted(i) for i in range(3)] del l This prints 2, 1, 0. Now, is the order of the deleted elements defined somewhere in specification or is it implementation-specif...
[ "Running del l will remove any reference to the list, so the symbol l will be gone. In contrast, running del l[:] removes the contents of the list, leaving l as an empty list.\nThe __del__ method is what runs when the last reference to an instance is being destroyed. \nThe order of deletion isn't specified and is...
[ 8, 2, 1 ]
[]
[]
[ "del", "list", "python" ]
stackoverflow_0008205102_del_list_python.txt
Q: Python equation substitution So i am starting with python and was wondering how i could substitute numbers for variables into that equation into a equation (python 2.7.2) help please? for example def main(): e = raw_input("input equation here") g = input("number to substitute") so you "e" would be a equa...
Python equation substitution
So i am starting with python and was wondering how i could substitute numbers for variables into that equation into a equation (python 2.7.2) help please? for example def main(): e = raw_input("input equation here") g = input("number to substitute") so you "e" would be a equation in terms of g and you could r...
[ "Using sympy:\nimport sympy\n\ndef main():\n e = sympy.sympify(raw_input(\"input equation here: \"))\n g = input(\"number to substitute for g: \")\n print 'e=',e.subs({'g':g})\n\n" ]
[ 3 ]
[]
[]
[ "equation", "python" ]
stackoverflow_0008205182_equation_python.txt
Q: How to escape or unscape this sequence? Hi how should I escape to make the link render? The way I write it now is with filter: {{article.text|striptags|urlize|nl2br|safe}} Can you recommend how to do it? Related question: https://stackoverflow.com/questions/8179801/autolinebreaks-filter-in-jinja2 Thank you A: U...
How to escape or unscape this sequence?
Hi how should I escape to make the link render? The way I write it now is with filter: {{article.text|striptags|urlize|nl2br|safe}} Can you recommend how to do it? Related question: https://stackoverflow.com/questions/8179801/autolinebreaks-filter-in-jinja2 Thank you
[ "Usually I'd like to use HTMLParser for processing (overkill maybe?), sample code below for Python 2.7 (3.0 library is renamed html.parser)\nfrom HTMLParser import HTMLParser\n\nclass MyHTMLParser(HTMLParser):\n def handle_starttag(self, tag, attrs):\n print \"Found Start Tag\", attrs\n\ns = \"noivos, con...
[ 1 ]
[]
[]
[ "escaping", "google_app_engine", "jinja2", "python" ]
stackoverflow_0008194394_escaping_google_app_engine_jinja2_python.txt
Q: Relationship between python map reduce and cloud-computing map/reduce? I'm new to Python, Do someone know what's relationships between Python (and functional languages') functions map() / reduce() and MapReduce concept related to distributed computations? A: The cloud concept of map/reduce is very similar, but c...
Relationship between python map reduce and cloud-computing map/reduce?
I'm new to Python, Do someone know what's relationships between Python (and functional languages') functions map() / reduce() and MapReduce concept related to distributed computations?
[ "The cloud concept of map/reduce is very similar, but changed to work in parallel. First, each data object is passed through a function that maps it to a new object (usually, some sort of dictionary). Then, a reduce function is called on pairs of the objects returned by map until there is only one left. That is ...
[ 8, 2 ]
[]
[]
[ "cloud", "mapreduce", "python" ]
stackoverflow_0008117515_cloud_mapreduce_python.txt
Q: passing contents from multiple lists generated in different functions to a file I have 3 functions which generate three different lists. I am trying to generate a mel script which is a text file which will write the values taken from these three lists. All three lists have same number of values. All the values in ...
passing contents from multiple lists generated in different functions to a file
I have 3 functions which generate three different lists. I am trying to generate a mel script which is a text file which will write the values taken from these three lists. All three lists have same number of values. All the values in these lists are animation data and therefore they have to be passed in a mel script t...
[ "Use zip.\nfor x, y, z in zip(func1(), func2(), func3()):\n melFile.write(\"currentTime %f\" % x)\n melFile.write('setAttr \"blend_shape.lip_round\" %f' % y)\n melFile.write('setAttr \"blend_shape.jaw_open\" %f' % z)\n\nAdd in all of the other boilerplate you want to generate, and try to think of better va...
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0008205400_python.txt
Q: Python - Hide Console Mid-Way Through Script Hopefully a simple answer. I have a console python program compiled to exe writing information constantly to the terminal, but half way through the script I'd like the terminal to hide but for the program to continue on hidden. Is there a quick fix for this or is this m...
Python - Hide Console Mid-Way Through Script
Hopefully a simple answer. I have a console python program compiled to exe writing information constantly to the terminal, but half way through the script I'd like the terminal to hide but for the program to continue on hidden. Is there a quick fix for this or is this more complicated then it seems? Any help is appreci...
[ "I don't think there is a quick fix for this. \nYou could start without a window, fire up a subprocess with a console, and terminate that process when you want the console to go away.\n" ]
[ 4 ]
[]
[]
[ "console", "python", "terminal" ]
stackoverflow_0008205413_console_python_terminal.txt
Q: python variable passing problems A little while ago I decided to take on a text adventure game. I always wanted to do that. But the first time it did an epic fail. This time I'm getting closer but just not there. I think I saw the error, though: The problem is that the variable isn't carried to the next def. So t...
python variable passing problems
A little while ago I decided to take on a text adventure game. I always wanted to do that. But the first time it did an epic fail. This time I'm getting closer but just not there. I think I saw the error, though: The problem is that the variable isn't carried to the next def. So the thing I want to know is how do I so...
[ "You overwrite the function named rm() with the return value of raw_input(\"> \"). After this line, the name rm will point to a string object, and trying to call this string object fails because string objects aren't callable. Rename the variable so that it does not shadow the function name.\n", "From the way y...
[ 6, 1 ]
[]
[]
[ "python" ]
stackoverflow_0008205656_python.txt
Q: Strange site codification. Is there possible get it using python? For example, I have the phrase Olá mundo! and I need it written as ol%E1%20mundo! to create my urls. I need this to connect to some specif sites who uses this kind of encode. An example of site who use this type of encode is the Michaellis translato...
Strange site codification. Is there possible get it using python?
For example, I have the phrase Olá mundo! and I need it written as ol%E1%20mundo! to create my urls. I need this to connect to some specif sites who uses this kind of encode. An example of site who use this type of encode is the Michaellis translator. How can I create urls with these type of encode using python? I trye...
[ "Here is one way using urllib's quote and string's encode(\"utf8\"):\nIn [1]: url = u'Ol\\xe1 mundo!'\n\nIn [2]: url.encode(\"utf8\")\nOut [2]: 'Ol\\xc3\\xa1 mundo!'\n\nIn [3]: print url.encode(\"utf8\")\nOlá mundo!\n\nIn [4]: urllib.quote(url.encode(\"utf8\"))\nOut [4]: 'Ol%C3%A1%20mundo%21'\n\nIn [5]: print ...
[ 1 ]
[]
[]
[ "character_encoding", "encoding", "html", "python", "url" ]
stackoverflow_0008205674_character_encoding_encoding_html_python_url.txt
Q: Django: Referencing a manytomany field that has been defined in another model I'm trying to work out how to calculate the number of books written by an author. The book model sets up the manytomany field with the author model. I have no idea how even google something like this which I thought would be very simple ...
Django: Referencing a manytomany field that has been defined in another model
I'm trying to work out how to calculate the number of books written by an author. The book model sets up the manytomany field with the author model. I have no idea how even google something like this which I thought would be very simple to do but I don't even know how to start. Here's the stripped down code: class Auth...
[ "when you define a foreignkey or manytomany field, django sets up a reverse relation for you, which in your case is book_set. so something like:\ndef books(self):\n books = self.book_set.all()\n return ', '.join([book.title for book in books])\n\nsee related objects in the docs\n" ]
[ 4 ]
[]
[]
[ "django", "models", "python" ]
stackoverflow_0008205789_django_models_python.txt
Q: Enter-Notify-Event Signal not working on gtk.ToolButton On a happy (if not irrevelent) note, this is the absolute last obstacle in this particular project. If I fix this, I have my first significant dot release (1.0), and the project will be going public. Thanks to everyone here on SO for helping me through this p...
Enter-Notify-Event Signal not working on gtk.ToolButton
On a happy (if not irrevelent) note, this is the absolute last obstacle in this particular project. If I fix this, I have my first significant dot release (1.0), and the project will be going public. Thanks to everyone here on SO for helping me through this project, and my other two (the answers help across the board, ...
[ "Your guess was correct, you should wrap your widget in a gtk.EventBox, here is an example that i hope will be hopeful:\nimport gtk\n\n\ndef callback(widget, event, data):\n print event, data\n\n\nclass Win(gtk.Window):\n\n def __init__(self):\n super(Win, self).__init__()\n self.connect(\"destr...
[ 4, 2 ]
[]
[]
[ "events", "gtk", "pygtk", "python", "signals" ]
stackoverflow_0007351947_events_gtk_pygtk_python_signals.txt
Q: Play .swf with Python/Pygame/OcempGUI I'm looking at switching programming languages due to some unavoidable roadblocks. However, before I dedicate myself to a whole new language, I need to know if it is possible for me to play .swf or .flv files underneath other GUI elements if I am using OcempGUI and pygame? Wil...
Play .swf with Python/Pygame/OcempGUI
I'm looking at switching programming languages due to some unavoidable roadblocks. However, before I dedicate myself to a whole new language, I need to know if it is possible for me to play .swf or .flv files underneath other GUI elements if I am using OcempGUI and pygame? Will using those two libraries back me into a ...
[ "Judging from the GUI's features list and usage, it does not appear to support .swf playback. If anyone has evidence to the contrary, an additional answer would be appreciated.\n" ]
[ 0 ]
[]
[]
[ "flash", "pygame", "python" ]
stackoverflow_0006233805_flash_pygame_python.txt
Q: While loop won't run in Python (beginner)? For some reason I'm having trouble getting my program to run a while loop. No error messages, just that it stops the program. I tried having it print "hi" as the first instruction, but it didn't, so I know it's not even running the loop. Here's a bit of code (Note: The te...
While loop won't run in Python (beginner)?
For some reason I'm having trouble getting my program to run a while loop. No error messages, just that it stops the program. I tried having it print "hi" as the first instruction, but it didn't, so I know it's not even running the loop. Here's a bit of code (Note: The testing for correct values works fine, but the loo...
[ "you didn't give the print out for letter and number, it could be that the \"number\" is actually a string?\n", "Your syntax is fine. Without seeing all of your code, I generically recommend that you might want to make sure there aren't any invisible whitespace characters that are breaking you out of the loop une...
[ 3, 0 ]
[]
[]
[ "python", "while_loop" ]
stackoverflow_0008205869_python_while_loop.txt
Q: Pythoncom error IDLE (PumpMessage) Trying to run this script: import pythoncom, pyHook def OnMouseEvent(event): # called when mouse events are received print 'MessageName:',event.MessageName print 'Message:',event.Message print 'Time:',event.Time print 'Window:',event.Window print 'Window...
Pythoncom error IDLE (PumpMessage)
Trying to run this script: import pythoncom, pyHook def OnMouseEvent(event): # called when mouse events are received print 'MessageName:',event.MessageName print 'Message:',event.Message print 'Time:',event.Time print 'Window:',event.Window print 'WindowName:',event.WindowName print 'Posit...
[ "It looks like you've got a file pythoncom.py in that folder, which is being imported instead of the real pythoncom module. Try renaming that file to something else, then running click.py.\n" ]
[ 4 ]
[]
[]
[ "python", "python_idle", "pythoncom", "shell" ]
stackoverflow_0008205695_python_python_idle_pythoncom_shell.txt
Q: Make this a one-liner: `return sum[dict.get(char) for char in word]` Obviously, the title has code that can't be interpreted. An uninformative SyntaxError: invalid syntax stderr message didn't tell me much, so I threw it in line by line, using: [dict.get(['val','val','foo'])] and have since discovered that dict...
Make this a one-liner: `return sum[dict.get(char) for char in word]`
Obviously, the title has code that can't be interpreted. An uninformative SyntaxError: invalid syntax stderr message didn't tell me much, so I threw it in line by line, using: [dict.get(['val','val','foo'])] and have since discovered that dict.get() and iterables don't play well together. If you haven't already gues...
[ "Use parentheses, not brackets, to call a function:\ndef wordpoints(word):\n return sum(dict.get(char) for char in word)\n\nThe parser actually told you a bit more than just \"invalid syntax\":\n return sum[dict.get(char) for char in word]\n ^\nSyntaxError: invalid syntax\n\nSee...
[ 2 ]
[]
[]
[ "python" ]
stackoverflow_0008205926_python.txt
Q: How to provide SQL initial data for third party application in Django I'm using a third party application in my Django project (photologue) and I wonder if it is possible to provide initial sql data for this application the same way I do with my own. As the application is installed in the central python site packa...
How to provide SQL initial data for third party application in Django
I'm using a third party application in my Django project (photologue) and I wonder if it is possible to provide initial sql data for this application the same way I do with my own. As the application is installed in the central python site package, and I don't want/can create an sql file there (and doubt that it will ...
[ "Yes, you can provide initial SQL data or fixtures:\n\nhttps://docs.djangoproject.com/en/dev/howto/initial-data/#providing-initial-sql-data\nhttps://docs.djangoproject.com/en/dev/howto/initial-data/#providing-initial-data-with-fixtures\n\nThe sql solution will work only for syncdb upon creation of models of the app...
[ 0 ]
[]
[]
[ "django", "python", "sql" ]
stackoverflow_0008205269_django_python_sql.txt
Q: Python: list comprehension, do f(x) if x exists? How can I do something like the following in Python? row = [unicode(x.strip()) if x for x in row] Basically, a list comprehension where you carry out a function if the variable exists. Thanks! A: The "if" goes at the end" row = [unicode(x.strip()) for x in row if...
Python: list comprehension, do f(x) if x exists?
How can I do something like the following in Python? row = [unicode(x.strip()) if x for x in row] Basically, a list comprehension where you carry out a function if the variable exists. Thanks!
[ "The \"if\" goes at the end\"\nrow = [unicode(x.strip()) for x in row if x]\n\n", "So close.\nrow = [unicode(x.strip()) for x in row if x]\n\n", "Not sure about the goals, but this should work\nrow = [unicode(x.strip()) for x in row if x ]\n\n", "Maybe you're were thinking of the ternary operator syntax as us...
[ 19, 3, 3, 1 ]
[]
[]
[ "list_comprehension", "python" ]
stackoverflow_0004259866_list_comprehension_python.txt
Q: Splitting strings but keeping "split" character I've split a string by [ and ] but I want these characters to still appear. How do I do this? words = [beginning for ending in x.split('[') for beginning in ending.split(']')] A: I think you need re.split to do this easily: >>> import re >>> s = 'Hello, my name is ...
Splitting strings but keeping "split" character
I've split a string by [ and ] but I want these characters to still appear. How do I do this? words = [beginning for ending in x.split('[') for beginning in ending.split(']')]
[ "I think you need re.split to do this easily:\n>>> import re\n>>> s = 'Hello, my name is [name] and I am [age] years old'\n>>> re.split(r'(\\[|\\])', s)\n['Hello, my name is ', '[', 'name', ']', ' and I am ', '[', 'age', ']', ' years old']\n\n", "Would need to know more about the context of your list and what x, ...
[ 3, 0 ]
[]
[]
[ "python", "split", "string" ]
stackoverflow_0008206019_python_split_string.txt
Q: Web-based Python interpreter with explanations On reddit, I've seen a link to web site, which does not only interpret Python code, but also gives a graphical explanation of how the code is interpreted. I found this potentially very helpful for learning and teaching. Sadly, I don't remember the link. Given code suc...
Web-based Python interpreter with explanations
On reddit, I've seen a link to web site, which does not only interpret Python code, but also gives a graphical explanation of how the code is interpreted. I found this potentially very helpful for learning and teaching. Sadly, I don't remember the link. Given code such as A = [] B = A B.append(1) print A print B this ...
[ "The Online Python Tutor is probably what you want.\n" ]
[ 4 ]
[]
[]
[ "interpreter", "python" ]
stackoverflow_0008205330_interpreter_python.txt
Q: Defining "boolness" of a class in python Why doesn't this work as one may have naively expected? class Foo(object): def __init__(self): self.bar = 3 def __bool__(self): return self.bar > 10 foo = Foo() if foo: print 'x' else: print 'y' (The output is x) A: For Python 2-3 compat...
Defining "boolness" of a class in python
Why doesn't this work as one may have naively expected? class Foo(object): def __init__(self): self.bar = 3 def __bool__(self): return self.bar > 10 foo = Foo() if foo: print 'x' else: print 'y' (The output is x)
[ "For Python 2-3 compatibility, just add this to your example:\nFoo.__nonzero__ = Foo.__bool__\n\nor expand the original definition of Foo to include:\n__nonzero__ = __bool__\n\nYou could of course define them in reverse too, where the method name is __nonzero__ and you assign it to __bool__, but I think the name __...
[ 80, 73, 27 ]
[]
[]
[ "boolean", "class", "python", "python_2.7", "python_2.x" ]
stackoverflow_0008205558_boolean_class_python_python_2.7_python_2.x.txt
Q: python: strange behavior about exec statement exec statement: exec code [ in globals[, locals]] When I execute the following code in python, the result really confused me. Some of the variables were setup into the globals, some were setup into the locals. s = """ # test var define int_v1 = 1 list_v1 = [1, 2, 3] ...
python: strange behavior about exec statement
exec statement: exec code [ in globals[, locals]] When I execute the following code in python, the result really confused me. Some of the variables were setup into the globals, some were setup into the locals. s = """ # test var define int_v1 = 1 list_v1 = [1, 2, 3] dict_v1 = {1: 'hello', 2:'world', 3:'!'} # test bu...
[ "I will just leave it here:\n>>> code = \"a_bad_idea.func_globals['__builtins__'].open.__doc__\"\n>>> print eval(code, {}, {'a_bad_idea': lambda: None})\nopen(name[, mode[, buffering]]) -> file object\n\nOpen a file using the file() type, returns a file object. This is the\npreferred way to open a file. See file....
[ 1, 0 ]
[]
[]
[ "exec", "python" ]
stackoverflow_0008147502_exec_python.txt
Q: Pure Python Web App Framework compatible with 2.4.3 My host only has python 2.4.3 and I don't have shell access. What choices do I have for a pure python-based web app framework? edit: I should also probably say it's running as CGI on the server. A: You should get a new host, seriously. That version of Python is...
Pure Python Web App Framework compatible with 2.4.3
My host only has python 2.4.3 and I don't have shell access. What choices do I have for a pure python-based web app framework? edit: I should also probably say it's running as CGI on the server.
[ "You should get a new host, seriously. That version of Python is ancient.\nIf you must insist, though, you could try Flask. It is my favorite platform, if that will sway your opinion.\n", "Why not try Django?\n" ]
[ 3, 1 ]
[]
[]
[ "python", "web_frameworks" ]
stackoverflow_0008206492_python_web_frameworks.txt
Q: Efficiently determine "how sorted" a list is, eg. Levenshtein distance I'm doing some research on ranking algorithms, and would like to, given a sorted list and some permutation of that list, calculate some distance between the two permutations. For the case of the Levenshtein distance, this corresponds to calcula...
Efficiently determine "how sorted" a list is, eg. Levenshtein distance
I'm doing some research on ranking algorithms, and would like to, given a sorted list and some permutation of that list, calculate some distance between the two permutations. For the case of the Levenshtein distance, this corresponds to calculating the distance between a sequence and a sorted copy of that sequence. The...
[ "Levenshtein distance is an O(n**2) algorithm, so if you want to go faster, use the alternative fast algorithm in the difflib module. The ratio method computes a measure of similarity between two sequences.\nIf you have to stick with Levenshtein, there is a Python recipe for it on the ASPN Python Cookbook: http:/...
[ 4 ]
[]
[]
[ "levenshtein_distance", "permutation", "python", "ranking_functions", "sorting" ]
stackoverflow_0008206617_levenshtein_distance_permutation_python_ranking_functions_sorting.txt
Q: What's your Django 1.3 tutorial recommendation? Other than the Django docs tutorial, what are recommendations for good Django 1.3 tutorials? The resources listed in the Django wiki all seem pretty outdated. Related to https://stackoverflow.com/questions/130061/book-and-tutorial-recommedations-for-django-1-0 but I'...
What's your Django 1.3 tutorial recommendation?
Other than the Django docs tutorial, what are recommendations for good Django 1.3 tutorials? The resources listed in the Django wiki all seem pretty outdated. Related to https://stackoverflow.com/questions/130061/book-and-tutorial-recommedations-for-django-1-0 but I'm looking specifically for updated Django 1.3 guides....
[ "Having searched on a regular basis, I can say that there simply aren't any very new books on Django being sold at the major retailers. And there have been some significant changes to the code since 1.1. \nYour best bet is just to continue using the django docs. The docs for Django are some of the best and most ...
[ 1, 1 ]
[]
[]
[ "django", "python" ]
stackoverflow_0006930490_django_python.txt
Q: Raw Input on for loops I want to print something out on a raw input that is in a for loop for x in doclist: if x == '[': count=count+1 elif count == 1: response=raw_input("Please enter", x) count=count-1 else: pass when I do this it gives me the error two arguments when...
Raw Input on for loops
I want to print something out on a raw input that is in a for loop for x in doclist: if x == '[': count=count+1 elif count == 1: response=raw_input("Please enter", x) count=count-1 else: pass when I do this it gives me the error two arguments when only one is expected I want...
[ "Think you want something more like this:\nfor x in doclist:\n if x == '[':\n count=count+1\n elif count == 1:\n response=raw_input(\"Please enter %s\" % x)\n count=count-1\n else:\n pass\n\nUsing something like what you had only works with print.\n" ]
[ 1 ]
[]
[]
[ "input", "python" ]
stackoverflow_0008206706_input_python.txt
Q: VERY odd python NameError I am making a python program to pickle some data and then save it to a file. It isn't working. path="C:/foo/bar" def newData(): import pickle data = [ ["foo"], ["bar"], ["baz"] ] file = None i = 0 while file==None: if not exists(pat...
VERY odd python NameError
I am making a python program to pickle some data and then save it to a file. It isn't working. path="C:/foo/bar" def newData(): import pickle data = [ ["foo"], ["bar"], ["baz"] ] file = None i = 0 while file==None: if not exists(path + str(i)+".data"): ...
[ "You are editing your file, but your web server is still running the old code. The traceback reads the source file to show you the line, but that doesn't mean it's running that line. This is clear from the traceback you mentioned that indicates a comment line as the problem.\nAs @JBernardo commented, you need to ...
[ 5 ]
[]
[]
[ "nameerror", "pickle", "python", "python_2.7", "wsgi" ]
stackoverflow_0008206683_nameerror_pickle_python_python_2.7_wsgi.txt
Q: Recursion Error - Degrees of Separation I'm trying to find degrees of separation between any two actors in a movie database. I succeed when I reach my base case, which is 1 degree of separation (i.e. actor is in same movie as another actor) but I use recursion to find all other degrees of separation, and I get: r...
Recursion Error - Degrees of Separation
I'm trying to find degrees of separation between any two actors in a movie database. I succeed when I reach my base case, which is 1 degree of separation (i.e. actor is in same movie as another actor) but I use recursion to find all other degrees of separation, and I get: runtime error: maximum recursion depth exceede...
[ "Two suggestions (I haven't looked on the text file, just going on first principles here and a quick read of your code):\nWhen you return from getDegrees, you're still going through the rest of the function following the return. You need to return a True (or something) to indicate that the search is over and the en...
[ 2, 1, 1 ]
[]
[]
[ "database", "python", "recursion" ]
stackoverflow_0008206707_database_python_recursion.txt
Q: Why doesn't using nonlocal scope variable as default value for parameter work? Code would explain this much better :) def a(): x=0 def b(z=x): print("X: %d, Z: %d" % (x,z,)) x=5 b() Result: X: 5, Z: 0 What's going on here? (Ok, now I've figured it out) A: Ok, the answer from the Python ...
Why doesn't using nonlocal scope variable as default value for parameter work?
Code would explain this much better :) def a(): x=0 def b(z=x): print("X: %d, Z: %d" % (x,z,)) x=5 b() Result: X: 5, Z: 0 What's going on here? (Ok, now I've figured it out)
[ "Ok, the answer from the Python docs is: \n\nDefault parameter values are evaluated when the function definition is executed. This means that the expression is evaluated once, when the function is defined, and that the same “pre-computed” value is used for each call.\n\nFair enough.\n" ]
[ 2 ]
[]
[]
[ "optional_arguments", "parameter_passing", "python" ]
stackoverflow_0008207038_optional_arguments_parameter_passing_python.txt
Q: Trouble getting Pypar to work with matplotlib I just started using Pypar for parallel programming in Python. I can get a simple script to run in parallel which is cool, and I can get matplotlib to work as well, but if I try to: import matplotlib and run it through Pypar, I get: ImportError: No module named ma...
Trouble getting Pypar to work with matplotlib
I just started using Pypar for parallel programming in Python. I can get a simple script to run in parallel which is cool, and I can get matplotlib to work as well, but if I try to: import matplotlib and run it through Pypar, I get: ImportError: No module named matplotlib help appreciated..
[ "This is probably WAY to late to answer this question. However, my guess is, that you simply did not install matplotlib on all you computational nodes...\nSo install and configure matplotlib on all the computers you are using for parallel computation and then try again.\n" ]
[ 0 ]
[]
[]
[ "matplotlib", "python" ]
stackoverflow_0005955226_matplotlib_python.txt
Q: How can I get App Engine's custom 404 page working? I've tried every combination of this I can think of: error_handlers: - file: error.html Before the handlers block, after the handlers block, with the file in a folder, with the file at the root, with a url: /* handler, without a url: /* handler, with spaces in f...
How can I get App Engine's custom 404 page working?
I've tried every combination of this I can think of: error_handlers: - file: error.html Before the handlers block, after the handlers block, with the file in a folder, with the file at the root, with a url: /* handler, without a url: /* handler, with spaces in front of - file, without spaces in front of -file, in the ...
[ "Use the spacing used in the documentation:\nerror_handlers:\n - file: default_error.html\n\nand make sure your URLs are really not matched in app.yaml by, say, a handler for .* and that your error page itself isn't matched by a static file handler.\n", "404s are not handled by custom error handler pages. If you...
[ 0, 0 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0008180038_google_app_engine_python.txt
Q: Hitting rate limit for google maps API, But don't know why I've written a script to send an address to Google Maps' API and receive back the Lat and Lng. However, I'm receiving error messages that I've exceeded Google's rate limit after 20 or so queries. Is there something I'm not considering? I'd appreciate any h...
Hitting rate limit for google maps API, But don't know why
I've written a script to send an address to Google Maps' API and receive back the Lat and Lng. However, I'm receiving error messages that I've exceeded Google's rate limit after 20 or so queries. Is there something I'm not considering? I'd appreciate any help. I'm very new at using API's so better understanding why I'm...
[ "Each gmaps.address_to_latlng call sends a request to the Google server, and you can only make a limited number of those.\nGoogle's docs on usage limits:\n\nUse of the Google Geocoding API is subject to a query limit of 2,500 geolocation requests per day. [...] Additionally, we enforce a request rate limit to preve...
[ 8, 2 ]
[]
[]
[ "geocoding", "google_maps_api_2", "python" ]
stackoverflow_0007643296_geocoding_google_maps_api_2_python.txt
Q: Saving to external PY file? I'm working on a online server, and I need all my list and dict saved. What would be the best and quickest way to approach this? I tried importing the data, and it works to load the data. But how can I update the imported file? A: I think you can use pickle/cPickle module to save...
Saving to external PY file?
I'm working on a online server, and I need all my list and dict saved. What would be the best and quickest way to approach this? I tried importing the data, and it works to load the data. But how can I update the imported file?
[ "I think you can use pickle/cPickle module to save and load the date, which are built-in module and easy to use.\nI am not very sure the meaning of update import file, what about rewrite the content back to the file after updating in the program?\n" ]
[ 1 ]
[]
[]
[ "pickle", "python", "storage" ]
stackoverflow_0008207512_pickle_python_storage.txt
Q: Facebook Connect API error 191 with Django-socialregistration I have seen error 191 all over the web and know it has something to do with there being something wrong with the configuration of the app. However I have not found an answer to most of the questions and also none that help me. My app on Facebook is setu...
Facebook Connect API error 191 with Django-socialregistration
I have seen error 191 all over the web and know it has something to do with there being something wrong with the configuration of the app. However I have not found an answer to most of the questions and also none that help me. My app on Facebook is setup like this: Site URL http://example.com/ Site Domain example.com (...
[ "Plz check the redirect Uri, while taking permisiion from user.\n" ]
[ 0 ]
[]
[]
[ "django", "facebook", "python" ]
stackoverflow_0007018344_django_facebook_python.txt
Q: word compression function using regular expressions in python Can someone tell me why it seems I am not getting the right results using this regular expression in this python code? I would have thought, for example, that the initial vowel in the word "about" should not disappear. Thanks. >>> sentence = "But the th...
word compression function using regular expressions in python
Can someone tell me why it seems I am not getting the right results using this regular expression in this python code? I would have thought, for example, that the initial vowel in the word "about" should not disappear. Thanks. >>> sentence = "But the third reason Americans should care about Europe is more important ...
[ "^ and $ anchor to the ends of the entire string, so you're not anchoring to the beginning and end of each word, but to the beginning and end of the entire sentence. When the sentence is only the word \"about,\" it works as you expect. I think you want to anchor to word boundaries (\\b) instead.\nhttp://www.regular...
[ 4, 1 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0008207860_python_regex.txt
Q: How to invoke an RPC call in a Python script residing on a windows server from a Linux client I want to invoke a python function residing on windows 7 machine through RPC call from a linux client. Please suggest some methods. Thanks A: XML-rpc is build into python, and very simple to use.
How to invoke an RPC call in a Python script residing on a windows server from a Linux client
I want to invoke a python function residing on windows 7 machine through RPC call from a linux client. Please suggest some methods. Thanks
[ "XML-rpc is build into python, and very simple to use.\n" ]
[ 0 ]
[]
[]
[ "python", "rpc" ]
stackoverflow_0008208047_python_rpc.txt
Q: Python String to list processing I feel my recently gained knowledge is still not sufficient when it comes to string processing. Please help me solve the below problem statement: (Please note:This is the simpler version of my requirement) So.. I have a file (myoption) with content as below: day=monday,tuesday,wedn...
Python String to list processing
I feel my recently gained knowledge is still not sufficient when it comes to string processing. Please help me solve the below problem statement: (Please note:This is the simpler version of my requirement) So.. I have a file (myoption) with content as below: day=monday,tuesday,wednesday month=jan,feb,march,april holida...
[ "If you use the standard ConfigParser module your data would need to be in INI file format, and so would look something like this:\n[options]\nday = monday,tuesday,wednesday\nmonth = jan,feb,march,april\nholiday = thanksgiving,christmas\n\nAnd then you could read the file as follows:\nimport ConfigParser\n\nparser ...
[ 5, 2, 1, 1 ]
[]
[]
[ "file", "list", "python", "string" ]
stackoverflow_0008208196_file_list_python_string.txt
Q: Time Date Difference in Microseconds I'm really new to Python and I have a problem with calculating the difference between two times. I have a file with a list containing a time that a specific message left and a time that a message came back in. Each are displayed on a different line. Each are recorded in micros...
Time Date Difference in Microseconds
I'm really new to Python and I have a problem with calculating the difference between two times. I have a file with a list containing a time that a specific message left and a time that a message came back in. Each are displayed on a different line. Each are recorded in microseconds. I want to take the find the differ...
[ "The general procedure consists in first reading the file, with something like:\nwith open('/path/to/file') as input_file:\n for line in input_file:\n # 'line' is the contents of each line (including line termination characters)\n # ... the strings representing the times are obtained here ...\n\nCa...
[ 0 ]
[]
[]
[ "datetime", "python" ]
stackoverflow_0008207984_datetime_python.txt
Q: How to distribute Thrift-generated code in development and production environments with Git? How do you manage generated source code files in you repositories and deployment routines with Git (PHP, Python, etc)? For example, I have a repository named "interfaces" with Thrift definitions in it. They can be converte...
How to distribute Thrift-generated code in development and production environments with Git?
How do you manage generated source code files in you repositories and deployment routines with Git (PHP, Python, etc)? For example, I have a repository named "interfaces" with Thrift definitions in it. They can be converted to Python, PHP, JS, etc skeletons/stubs. Other projects in different languages, each in its own ...
[ "It is generally best to favour the \"generation\" route over the \"storing generated content\" route, mainly because you are not always 100% sure of the current status of said generated content: is it in sync with the sources?\nA post-receive hook can take care, upon a push, of generating the relevant content.\nSe...
[ 4, 0 ]
[]
[]
[ "deployment", "git", "php", "python", "thrift" ]
stackoverflow_0008201189_deployment_git_php_python_thrift.txt