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: String concatenation in Python Can you describe difference between two ways of string concatenation: simple __add__ operator and %s patterns? I had some investigation in this question and found %s (in form without using parentheses) a little faster. Also another question was appeared: why result of 'hell%s' % 'o' ...
String concatenation in Python
Can you describe difference between two ways of string concatenation: simple __add__ operator and %s patterns? I had some investigation in this question and found %s (in form without using parentheses) a little faster. Also another question was appeared: why result of 'hell%s' % 'o' refers to another memory region than...
[ "Here is a small exercise:\n>>> def f1():\n 'hello'\n\n\n>>> def f2():\n 'hel' 'lo'\n\n\n>>> def f3():\n 'hel' + 'lo'\n\n\n>>> def f4():\n 'hel%s' % 'lo'\n\n\n>>> def f5():\n 'hel%s' % ('lo',)\n\n\n>>> for f in (f1, f2, f3, f4, f5):\n print(f.__name__)\n dis.dis(f)\n\n\nf1\n 1 0 LOAD...
[ 7, 1 ]
[]
[]
[ "compilation", "internals", "object_identity", "python" ]
stackoverflow_0003371745_compilation_internals_object_identity_python.txt
Q: List all currently open file handles? Possible Duplicate: check what files are open in Python Hello, Is it possible to obtain a list of all currently open file handles, I presume that they are stored somewhere in the environment. I am interested in theis function as I would like to safely handle any files that ...
List all currently open file handles?
Possible Duplicate: check what files are open in Python Hello, Is it possible to obtain a list of all currently open file handles, I presume that they are stored somewhere in the environment. I am interested in theis function as I would like to safely handle any files that are open when a fatal error is raised, i.e...
[ "lsof, /proc/pid/fd/\n", "The nice way of doing this would be to modify your code to keep track of when it opens a file:\ndef log_open( *args, **kwargs ):\n print( \"Opening a file...\" )\n print( *args, **kwargs )\n return open( *args, **kwargs )\n\nThen, use log_open instead of open to open files. You ...
[ 6, 2, 0 ]
[]
[]
[ "filehandle", "linux", "python" ]
stackoverflow_0003370540_filehandle_linux_python.txt
Q: Decision maker question: compare ASP.NET / Ruby / Python on web UI controls I need to learn a language for writing web applications (not websites!). After some research in google and stackoverflow I ended up that the choice should fall in: 1) Ruby + Rails 2) Python + Django 3) c# + ASP.NET For sure even pickng one...
Decision maker question: compare ASP.NET / Ruby / Python on web UI controls
I need to learn a language for writing web applications (not websites!). After some research in google and stackoverflow I ended up that the choice should fall in: 1) Ruby + Rails 2) Python + Django 3) c# + ASP.NET For sure even pickng one randomly would not be a bad choice, but my question here is specific to UI contr...
[ "Ruby on Rails is a server-side framework that processes HTTP requests and responds with HTML†. It doesn't have any concept of the kind of UI controls that you're referring to. \nHowever, it can integrate with JavaScript frameworks such as ExtJS or jQuery and there are some Rails plugins or RubyGems that make this ...
[ 3, 2, 1 ]
[]
[]
[ "asp.net", "python", "ruby_on_rails", "uicontrol" ]
stackoverflow_0003370019_asp.net_python_ruby_on_rails_uicontrol.txt
Q: OSError in one of the threads of Bottle framework, while running the dev server When I run bottle development server, I notice some warning showing up. Can any one figure it out what exactly is the problem? Exception in thread Thread-1: Traceback (most recent call last): File "/usr/lib/python2.6/threading.py", li...
OSError in one of the threads of Bottle framework, while running the dev server
When I run bottle development server, I notice some warning showing up. Can any one figure it out what exactly is the problem? Exception in thread Thread-1: Traceback (most recent call last): File "/usr/lib/python2.6/threading.py", line 525, in __bootstrap_inner self.run() File "/usr/local/lib/python2.6/dist-packa...
[ "This is a bug in bottle (solved in 0.8.2). The reloading feature checks for modified module files and is confused by paths that point into egg archives. Update to 0.8.2 or disable the reloading-feature to solve this.\n" ]
[ 3 ]
[]
[]
[ "bottle", "multithreading", "python" ]
stackoverflow_0003306139_bottle_multithreading_python.txt
Q: enabling tty in a ssh session I would to take in some login information for a script have written in to be used by many users. In python I set the input_raw to read from dev/tty but it fails horribly when i am connecting to the script being run on a server through ssh. Thoughts? Workarounds? I would prefer to avoi...
enabling tty in a ssh session
I would to take in some login information for a script have written in to be used by many users. In python I set the input_raw to read from dev/tty but it fails horribly when i am connecting to the script being run on a server through ssh. Thoughts? Workarounds? I would prefer to avoid hard coding usernames into the sc...
[ "Try using the -t option to ssh:\n\n -t Force pseudo-tty allocation. This can be used to execute arbi-\n trary screen-based programs on a remote machine, which can be\n very useful, e.g. when implementing menu services. Multiple -t\n options force tty allocation, even ...
[ 5 ]
[]
[]
[ "python", "scripting", "ssh", "tty" ]
stackoverflow_0003372268_python_scripting_ssh_tty.txt
Q: Algorithm to determine exchange rate Given a data set of various currency pairs, how do I efficiently compute the implied fx rate for a pair not supplied in the data set? For example, say my database/table looks like this (this data is fudged): GBP x USD = 1.5 USD x GBP = 0.64 GBP x EUR = 1.19 AUD x USD = 1.1 ...
Algorithm to determine exchange rate
Given a data set of various currency pairs, how do I efficiently compute the implied fx rate for a pair not supplied in the data set? For example, say my database/table looks like this (this data is fudged): GBP x USD = 1.5 USD x GBP = 0.64 GBP x EUR = 1.19 AUD x USD = 1.1 Notice that (GBP,USD) != 1/(USD,GBP). I w...
[ "You're looking for the shortest path in a directed graph, where the currencies are the vertices and the given exchange rates are the edges.\nIf an exchange rate is given only for one direction, you can add one for the opposite direction with a higher cost.\n" ]
[ 16 ]
[]
[]
[ "currency", "finance", "python" ]
stackoverflow_0003372375_currency_finance_python.txt
Q: Dynamic Loading of Modules then using "from x import *" on loaded module I have some django apps which are versioned by app name. appv1 appv2 The models.py in the apps are slightly different based on the version, but have the same model names. I'm attempting to load the models dynamically into the current namespac...
Dynamic Loading of Modules then using "from x import *" on loaded module
I have some django apps which are versioned by app name. appv1 appv2 The models.py in the apps are slightly different based on the version, but have the same model names. I'm attempting to load the models dynamically into the current namespace. So I've made a function that attempts to get the module and return it: def ...
[ "At from models import * you are NOT referring to the models variable. You are just trying to import module called 'models', which, obviously, does not exist.\nYou can use hack like this to import everything from the module into current namespace:\nldict = locals()\nfor k in models.__dict__:\n if not k.startswit...
[ 4 ]
[]
[]
[ "django", "import", "python" ]
stackoverflow_0003372361_django_import_python.txt
Q: Calling Python instance methods in function decorators Is there a clean way to have a decorator call an instance method on a class only at the time an instance of the class is instantiated? class C: def instance_method(self): print('Method called') def decorator(f): print('Locals in decorato...
Calling Python instance methods in function decorators
Is there a clean way to have a decorator call an instance method on a class only at the time an instance of the class is instantiated? class C: def instance_method(self): print('Method called') def decorator(f): print('Locals in decorator %s ' % locals()) def wrap(f): print('...
[ "I came up with this as a possible alternative solution. I like it because there is only one call that happens when the function is defined, and one when the class is instantiated. The only downside is a tiny bit of extra memory consumption for the function attribute.\nfrom types import FunctionType\n\nclass C:\n ...
[ 1, 0, 0, 0 ]
[]
[]
[ "decorator", "instance", "methods", "python" ]
stackoverflow_0003371680_decorator_instance_methods_python.txt
Q: Dealing with timezones in Django I'm trying to deal with timezone information in Django. I tried doing something like: results = Competitor.objects.raw("SELECT official_start AT TIME ZONE 'UTC', official_finish AT TIME ZONE 'UTC' FROM competitor WHERE race_id=1") Thinking that this way I would know that the timez...
Dealing with timezones in Django
I'm trying to deal with timezone information in Django. I tried doing something like: results = Competitor.objects.raw("SELECT official_start AT TIME ZONE 'UTC', official_finish AT TIME ZONE 'UTC' FROM competitor WHERE race_id=1") Thinking that this way I would know that the timezone was UTC but say I store a time in ...
[ "I realized that in the settings.py file there is an option: TIME_ZONE. setting this to UTC solved the problem.\n" ]
[ 1 ]
[]
[]
[ "django", "python", "time", "timezone" ]
stackoverflow_0003372600_django_python_time_timezone.txt
Q: When to thread? I have never written any code that uses threads. I have a web application that accepts a POST request, and creates an image based on the data in the body of the request. Would I want to spin off a thread for the image creation, as to prevent the server from hanging until the image is created? Is t...
When to thread?
I have never written any code that uses threads. I have a web application that accepts a POST request, and creates an image based on the data in the body of the request. Would I want to spin off a thread for the image creation, as to prevent the server from hanging until the image is created? Is this an appropriate us...
[ "Rather than thinking about handling this via threads or even processes, consider using a distributed task manager such as Celery to manage this sort of thing.\n", "Usual approach for handling HTTP requests synchronously is to spawn (or re-use one in the pool) new thread for each request as soon as it comes.\nHow...
[ 3, 2 ]
[]
[]
[ "multithreading", "python" ]
stackoverflow_0003372774_multithreading_python.txt
Q: Python: best/efficient way of finding a list of words in a text? I have a list of approximately 300 words and a huge amount of text that I want to scan to know how many times each word appears. I am using the re module from python: for word in list_word: search = re.compile(r"""(\s|,)(%s).?(\s|,|\.|\))""" % wo...
Python: best/efficient way of finding a list of words in a text?
I have a list of approximately 300 words and a huge amount of text that I want to scan to know how many times each word appears. I am using the re module from python: for word in list_word: search = re.compile(r"""(\s|,)(%s).?(\s|,|\.|\))""" % word) occurrences = search.subn("", text)[1] but I want to know if ...
[ "If you have a huge amount of text, I wouldn't use regexps in this case but simply split text:\nwords = {\"this\": 0, \"that\": 0}\nfor w in text.split():\n if w in words:\n words[w] += 1\n\nwords will give you the frequency for each word\n", "Try stripping all the punctuation from your text and then splittin...
[ 5, 1, 0, 0, 0, 0, 0, 0 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0003372332_python_regex.txt
Q: How do I fix a "JSONDecodeError: No JSON object could be decoded: line 1 column 0 (char 0)"? I'm trying to get Twitter API search results for a given hashtag using Python, but I'm having trouble with this "No JSON object could be decoded" error. I had to add the extra % towards the end of the URL to prevent a stri...
How do I fix a "JSONDecodeError: No JSON object could be decoded: line 1 column 0 (char 0)"?
I'm trying to get Twitter API search results for a given hashtag using Python, but I'm having trouble with this "No JSON object could be decoded" error. I had to add the extra % towards the end of the URL to prevent a string formatting error. Could this JSON error be related to the extra %, or is it caused by something...
[ "There were a couple problems with your initial code. First you never read in the content from twitter, just opened the url. Second in the url you set a callback (twitterSearch). What a call back does is wrap the returned json in a function call so in this case it would have been twitterSearch(). This is useful if ...
[ 8 ]
[]
[]
[ "json", "python", "simplejson", "twitter" ]
stackoverflow_0003372643_json_python_simplejson_twitter.txt
Q: Passing an array of long strings ( >4000 bytes) to an Oracle (11gR2) stored procedure using cx_Oracle We need to bulk load many long strings (>4000 Bytes, but <10,000 Bytes) using cx_Oracle. The data type in the table is CLOB. We will need to load >100 million of these strings. Doing this one by one would suck. Do...
Passing an array of long strings ( >4000 bytes) to an Oracle (11gR2) stored procedure using cx_Oracle
We need to bulk load many long strings (>4000 Bytes, but <10,000 Bytes) using cx_Oracle. The data type in the table is CLOB. We will need to load >100 million of these strings. Doing this one by one would suck. Doing it in a bulk fashion, ie using cursor.arrayvar() would be ideal. However, CLOB does not support arrays....
[ "Off the wall suggestion, but since you are on 11gR2 have a look at DBFS\nFrom the 'load' point of view, you are just copying files and they 'appear' as LOBs. You can do a similar thing with the built-in FTP server but file handling is a lot easier.\nYou just then write a procedure that pulls them from the dbfs_con...
[ 0, 0 ]
[]
[]
[ "cx_oracle", "oracle", "python" ]
stackoverflow_0003358666_cx_oracle_oracle_python.txt
Q: Pylons 1.0 - c.id no longer being automatically set on python v2.6.2 and 2.7 I am at a loss on this one, I intalled a SSD on my dev box today and started with a fresh development environment. In short, pylons no longer sets the c.id based on the id passed to the action. Code, error, and libs install: http://pastie...
Pylons 1.0 - c.id no longer being automatically set on python v2.6.2 and 2.7
I am at a loss on this one, I intalled a SSD on my dev box today and started with a fresh development environment. In short, pylons no longer sets the c.id based on the id passed to the action. Code, error, and libs install: http://pastie.org/1064929 Very strange, because my production server is mirroring my python ver...
[ "Well, after trying older releases of paste and routes I gave up and removed all usage of c.id. I suppose that is what I get for relying on too much magic.\n" ]
[ 0 ]
[]
[]
[ "paster", "pylons", "python" ]
stackoverflow_0003359295_paster_pylons_python.txt
Q: How do I get an instance of BaseHTTPRequestHandler instantiated during request handling inside an action code? I need to access the rfile and wfile properties of a request handler instance. AFAIK, such a handler is instantiated by the framework during request lifetime. Update: I found that rfile is accessible thro...
How do I get an instance of BaseHTTPRequestHandler instantiated during request handling inside an action code?
I need to access the rfile and wfile properties of a request handler instance. AFAIK, such a handler is instantiated by the framework during request lifetime. Update: I found that rfile is accessible through request.environ['wsgi.input']. To access wfile I've do a hack with the additional line in Paste sources, httpser...
[ "Better do like this http://pythonpaste.org/webob/reference.html#body-app-iter\nIn pylons action:\n f = response.body_file\n f.write('hey')\n\nThe response.body_file is only like a file object, but not real stream.\nFor more details read http://www.python.org/dev/peps/pep-0333/#id22\n" ]
[ 1 ]
[]
[]
[ "pylons", "python" ]
stackoverflow_0003365660_pylons_python.txt
Q: python subprocess calling "internal" process Out of curiosity and trying to understand the subprocess module: Is it possible to do something like: import subprocess def myfun(arg): # do stuff arg = something; p = subprocess.Popen(["myfun","arg"]) without putting "myfun" in a file of its own? It seems like t...
python subprocess calling "internal" process
Out of curiosity and trying to understand the subprocess module: Is it possible to do something like: import subprocess def myfun(arg): # do stuff arg = something; p = subprocess.Popen(["myfun","arg"]) without putting "myfun" in a file of its own? It seems like this would in general be a scary thing to do if you...
[ "You can pass Popen a preexec_fn, which is a callable object executed in the child process before the command is exec'd. A more standard approach is to use the multiprocessing module, which requires a Python function instead of an external command.\n" ]
[ 4 ]
[]
[]
[ "python", "subprocess" ]
stackoverflow_0003373554_python_subprocess.txt
Q: Measuring rectangles at odd angles with a low resolution input matrix (Linear regression classification?) I'm trying to solve the following problem: Given an input of, say, 0000000000000000 0011111111110000 0011111111110000 0011111111110000 0000000000000000 0000000111111110 0000000111111110 0000000000000000 I nee...
Measuring rectangles at odd angles with a low resolution input matrix (Linear regression classification?)
I'm trying to solve the following problem: Given an input of, say, 0000000000000000 0011111111110000 0011111111110000 0011111111110000 0000000000000000 0000000111111110 0000000111111110 0000000000000000 I need to find the width and height of all rectangles in the field. The input is actually a single column at a time ...
[ "Collect the transition points (from a 1 to a 0 or vice-versa) as you're scanning, then figure the length and width either directly from there, or from the convex hull of each object. \nIf rectangles can overlap, then you'll have bigger issues.\n", "I'd take following steps:\n\nget all columns together in a matr...
[ 2, 1, 0 ]
[]
[]
[ "classification", "linear_regression", "python" ]
stackoverflow_0003372659_classification_linear_regression_python.txt
Q: Is there a JGraph alternative for Python? Which library can I use to develop an application for visual modeling with graphs? Is there a library for Python like JGraph for Java? Thank you! A: GraphViz is a powerful tool to make nice graphs and you have a python wrapper called PygraphViz that should answer your q...
Is there a JGraph alternative for Python?
Which library can I use to develop an application for visual modeling with graphs? Is there a library for Python like JGraph for Java? Thank you!
[ "GraphViz is a powerful tool to make nice graphs and you have a python wrapper called PygraphViz that should answer your question.\n", "I don't know from JGraph, but gnuplot has a Python wrapper.\n" ]
[ 2, 0 ]
[]
[]
[ "graph", "modeling", "python", "user_interface" ]
stackoverflow_0003373095_graph_modeling_python_user_interface.txt
Q: Line-wrapping problems with IPython shell If I have run a long line in IPython, and try and recall it (using the up-arrow) or backspace beyond the start of the current line, it displays incorrectly (all smushed into one line) For example, in the following session I wrote a long line [1], entered a somewhat-blank l...
Line-wrapping problems with IPython shell
If I have run a long line in IPython, and try and recall it (using the up-arrow) or backspace beyond the start of the current line, it displays incorrectly (all smushed into one line) For example, in the following session I wrote a long line [1], entered a somewhat-blank line [2], then up-arrowed twice to get the print...
[ "Aha! I had an old version of the Python readline module - installing the latest from http://ipython.scipy.org/dist/ and it works perfectly!\nsudo easy_install http://ipython.scipy.org/dist/readline-2.5.1-py2.5-macosx-10.5-i386.egg\n\n", "Got this problem on Snow Leopard. Installing a new version of readline from...
[ 12, 2, 1 ]
[]
[]
[ "ipython", "python", "terminal" ]
stackoverflow_0000670764_ipython_python_terminal.txt
Q: Building a compiler or interpreter using Python Right now I'm writing my PhD proposal to build a language processor for a new specification language for Java (cf. JML, or Spec# for C#) and need to nail down an implementation tool to start development. The research aspects of the language (syntax, semantics, theore...
Building a compiler or interpreter using Python
Right now I'm writing my PhD proposal to build a language processor for a new specification language for Java (cf. JML, or Spec# for C#) and need to nail down an implementation tool to start development. The research aspects of the language (syntax, semantics, theoretical results) are orthogonal to my choice of impleme...
[ "I personally can't stand antlr, I use lex/yacc as my parser generator. Here is a Python implementation http://www.dabeaz.com/ply/ that you could use.\nThat just deals with parsing though, that really doesn't even begin to construct your interpreter. For that, you'll probably be building it from the ground up - I...
[ 7, 1, 0 ]
[]
[]
[ "compiler_construction", "interpreter", "java", "programming_languages", "python" ]
stackoverflow_0003373817_compiler_construction_interpreter_java_programming_languages_python.txt
Q: HOWTO: Write Python API wrapper? I'd like to write a python library to wrap a REST-style API offered by a particular Web service. Does anyone know of any good learning resources for such work, preferably aimed at intermediate Python programmers? I'd like a good article on the subject, but I'd settle for nice, clea...
HOWTO: Write Python API wrapper?
I'd like to write a python library to wrap a REST-style API offered by a particular Web service. Does anyone know of any good learning resources for such work, preferably aimed at intermediate Python programmers? I'd like a good article on the subject, but I'd settle for nice, clear code examples. CLARIFICATION: What I...
[ "I can't point you to any article on how to do it, but I think there are a few libraries that can be good models on how to design your own.\nPyAws for example. I didn't see the source code so I can't tell you how good it is as code example, but the features and the usage examples in their website should be a useful...
[ 3, 2, 0, 0, 0 ]
[]
[]
[ "api", "python", "rest", "web_services" ]
stackoverflow_0000517237_api_python_rest_web_services.txt
Q: Global Variable Not Defined I'm calling two separate functions to determine what "P01" equals. The first one selects a random number, and discards random numbers already picked. The second one takes the result of the random number and picks a variable to make 'position' equal. I then say that 'P01' equals 'positio...
Global Variable Not Defined
I'm calling two separate functions to determine what "P01" equals. The first one selects a random number, and discards random numbers already picked. The second one takes the result of the random number and picks a variable to make 'position' equal. I then say that 'P01' equals 'position.' I've made 'position' a global...
[ "There is several problems in the code. Like you are not calling function if it is not followed by opening and closing parenthesis.\nie: not slotseeder but slotseeder()\n(That is the one that breaks the code)\nI would probably write your sample code as below:\n### Monster Statistics ####\n\ndefault_stats = dict(nam...
[ 5, 1, 0, 0 ]
[]
[]
[ "python", "random" ]
stackoverflow_0003373560_python_random.txt
Q: Python to recognize UNC path on cygwin All machines are on Windows Server 2003. If I only install cygwin on one of the machine and run my python script on it to manipulate files from all remote hosts. How can I access to those files via UNC path? A: Cygwin understands UNC pathnames that use two forward slashes (...
Python to recognize UNC path on cygwin
All machines are on Windows Server 2003. If I only install cygwin on one of the machine and run my python script on it to manipulate files from all remote hosts. How can I access to those files via UNC path?
[ "Cygwin understands UNC pathnames that use two forward slashes (as opposed to the two backslashes typical of Windows -- in fact, under Cygwin, you must use forward slashes instead of backslashes anywhere in the path). I assume that this support would be propagated through to Python running on top of Cygwin, but I ...
[ 4 ]
[]
[]
[ "cygwin", "python" ]
stackoverflow_0003374365_cygwin_python.txt
Q: Python and Excel: Overwriting an existing file always prompts, despite XlSaveConflictResolution value I'm using the Excel.Application COM object from a Python program to open a CSV file and save it as an Excel workbook. If the target file already exists, then I am prompted with this message: "A file named '...' a...
Python and Excel: Overwriting an existing file always prompts, despite XlSaveConflictResolution value
I'm using the Excel.Application COM object from a Python program to open a CSV file and save it as an Excel workbook. If the target file already exists, then I am prompted with this message: "A file named '...' already exists in this location. Do you want to replace it?" That message comes up despite the fact that I...
[ "Before saving the file set DisplayAlerts to False to suppress the warning dialog:\nxl.DisplayAlerts = False\n\nAfter the file is saved it is usually a good idea to set DisplayAlerts back to True: \n xl.DisplayAlerts = True\n\n" ]
[ 19 ]
[]
[]
[ "activex", "com", "excel", "excel_2007", "python" ]
stackoverflow_0003373955_activex_com_excel_excel_2007_python.txt
Q: (Python) Closure created when it wasn't expected I got an unexpected closure when creating a nested class. I suspect that this is something related to metaclasses, super, or both. It is definitely related to how closures get created. I am using python2.7. Here are five simplified examples that demonstrate the...
(Python) Closure created when it wasn't expected
I got an unexpected closure when creating a nested class. I suspect that this is something related to metaclasses, super, or both. It is definitely related to how closures get created. I am using python2.7. Here are five simplified examples that demonstrate the same problem that I am seeing (they all build off the...
[ "\nWhy does a closure get set for __init__?\n\nIt refers to a local variable (namely Subclass) in the enclosing function (namely setup).\n\nWhy doesn't the closure get set for other?\n\nBecause it doesn't refer to any local variables (or parameters) in any enclosing functions.\n\nWhy is the object in the closure ce...
[ 4 ]
[]
[]
[ "closures", "nested_class", "python", "super" ]
stackoverflow_0003374427_closures_nested_class_python_super.txt
Q: How does one put a link / url to the web-site's home page in Django? In Django templates, is there a variable in the context (e.g. {{ BASE\_URL }}, {{ ROOT\_URL }}, or {{ MEDIA\_URL }} that one can use to link to the home url of a project? I.e. if Django is running in the root of a project, the variable (let's cal...
How does one put a link / url to the web-site's home page in Django?
In Django templates, is there a variable in the context (e.g. {{ BASE\_URL }}, {{ ROOT\_URL }}, or {{ MEDIA\_URL }} that one can use to link to the home url of a project? I.e. if Django is running in the root of a project, the variable (let's call it R) {{ R }} in a template would be /. If the root url is a sub-folder ...
[ "You could give the URL configuration which you're using to handle the home page a name and use that:\nurls.py:\nfrom django.conf.urls.defaults import *\n\nurlpatterns = patterns('myproject.views',\n url(r'^$', 'index', name='index'),\n)\n\nTemplates:\n<a href=\"{% url index %}\">...\n\nUPDATE: Newer versions of...
[ 45, 13, 5, 2 ]
[]
[]
[ "django", "django_urls", "python" ]
stackoverflow_0000226528_django_django_urls_python.txt
Q: Why custom types accept ad-hoc attributes in Python (and built-ins don't)? I'd like to know why one is able to create a new attribute ("new" means "not previously defined in the class body") for an instance of a custom type, but is not able to do the same for a built-in type, like object itself. A code example: >...
Why custom types accept ad-hoc attributes in Python (and built-ins don't)?
I'd like to know why one is able to create a new attribute ("new" means "not previously defined in the class body") for an instance of a custom type, but is not able to do the same for a built-in type, like object itself. A code example: >>> class SomeClass(object): ... pass ... >>> sc = SomeClass() >>> sc.name =...
[ "Some objects don't have the __dict__ attribute (which is a dictionary that stores all the custom 'newly defined' attributes). You can emulate the same behaviour using the __slots__ variable (see python reference). When you are subclassing a class with __dict__, the __slots__ variable has no effect. And as you are ...
[ 6 ]
[]
[]
[ "attributes", "custom_type", "datamodel", "python" ]
stackoverflow_0003374502_attributes_custom_type_datamodel_python.txt
Q: split a file name How do i write a python script to split a file name eg LN0001_07272010_3.dat and to rename the file to LN0001_JY_07272010? also how do i place a '|' and the end of each line in this file(contents) each line is a record? A: fn = "LN0001_07272010_3.dat".split('_') new_fn = '{0}_JY_{1}'.format(fn...
split a file name
How do i write a python script to split a file name eg LN0001_07272010_3.dat and to rename the file to LN0001_JY_07272010? also how do i place a '|' and the end of each line in this file(contents) each line is a record?
[ "fn = \"LN0001_07272010_3.dat\".split('_')\nnew_fn = '{0}_JY_{1}'.format(fn[0], fn[1])\n\nUpdate forgot to add \"JY\" to new_fn\n", "filename=\"LN0001_07272010_3.dat\"\nnewfilename=filename.split(\"_\")[0]+\"_JY_\"+filename.split(\"_\")[1]\n\nlinearr=[]\nfor line in open(filename).readlines():\n linearr.appen...
[ 5, 3, 2, 0, 0 ]
[]
[]
[ "python", "string" ]
stackoverflow_0003373968_python_string.txt
Q: How to os.walk deep defaultdict for values? I have a very large defaultdict(dict) that looks something like this: data['w']['x']['y']['z']={'a':5,'b':10} I'm trying to do produce a report that lists the hierarchy of all keys navigated for a particular final dictionary. In other words, I am looking for its "full ...
How to os.walk deep defaultdict for values?
I have a very large defaultdict(dict) that looks something like this: data['w']['x']['y']['z']={'a':5,'b':10} I'm trying to do produce a report that lists the hierarchy of all keys navigated for a particular final dictionary. In other words, I am looking for its "full pathname" as if the last dictionary were the file...
[ "If possible, just flatten the path:\ndata['w:x:y:z'] = {'a':5, 'b':10}\n\nfor path, d in data.items():\n print '%s:%s' % (path, ':'.join(\"%s=%r\" % pair for pair in d.items()))\n\nIf the depth of the dict is exactly 4 in all cases, you can write this:\nfor w, wvals in data.items():\n for x, xvals in wvals.i...
[ 1 ]
[]
[]
[ "dictionary", "python", "search" ]
stackoverflow_0003374411_dictionary_python_search.txt
Q: Disable verify_exists on models.URLField at runtime? How can I temporarily turn off verify_exists on a models.URLField at runtime? I would like to skip the check on certain URLs (they block EC2 IPs from their firewall). I'm interfacing with the model through the ModelForm right now. A: class F(forms.Form): ...
Disable verify_exists on models.URLField at runtime?
How can I temporarily turn off verify_exists on a models.URLField at runtime? I would like to skip the check on certain URLs (they block EC2 IPs from their firewall). I'm interfacing with the model through the ModelForm right now.
[ " class F(forms.Form):\n url_field = forms.URLField(verify_exists = True)\n\nform = F({\"url_field\":\"http://blaghblagh.net\"})\nform.base_fields['url_field'].verify_exists = False\nform.is_valid() # returns True\n\n" ]
[ 0 ]
[]
[]
[ "django", "django_forms", "django_models", "python" ]
stackoverflow_0003374099_django_django_forms_django_models_python.txt
Q: modifying a python callable so it calls before() , actual function then after() I am not sure if this is the best way to have before and after functions be called around a function f1(). class ba(object): def __init__(self, call, before, after): self.call = call self.before = before sel...
modifying a python callable so it calls before() , actual function then after()
I am not sure if this is the best way to have before and after functions be called around a function f1(). class ba(object): def __init__(self, call, before, after): self.call = call self.before = before self.after = after def __call__(self, *args): self.before() r = sel...
[ "I'd use a decorator, like so:\nfrom functools import wraps\n\nclass withBeforeAfter(object):\n def __init__(self, before, after):\n self.before = before\n self.after = after\n def __call__(self, wrappedCall):\n @wraps(wrappedCall)\n def wrapCall(*args, **kwargs):\n try:...
[ 14, 3 ]
[]
[]
[ "callable", "python" ]
stackoverflow_0003373188_callable_python.txt
Q: python twisted tutorial/question Got a simple question regarding twisted. I can create a trivial basic test with a web server like apache, where http://foo.com/index.php instantiates the index.php for the "foo" site/app... I'm trying to figure out how the heck I can create a twisted server, where I run different b...
python twisted tutorial/question
Got a simple question regarding twisted. I can create a trivial basic test with a web server like apache, where http://foo.com/index.php instantiates the index.php for the "foo" site/app... I'm trying to figure out how the heck I can create a twisted server, where I run different backend functions based on the input! I...
[ "Have you read this?\nhttp://krondo.com/blog/?page_id=1327\n", "You may find http://twistedmatrix.com/documents/current/web/howto/web-in-60/index.html helpful.\n" ]
[ 3, 0 ]
[]
[]
[ "client", "python", "twisted" ]
stackoverflow_0003374481_client_python_twisted.txt
Q: how do you include modified 3rd party modules when writing setup.py files? I wrote a standalone script depends on a few modified modules. the directory structure looks like this: client setup.py tsclient __init__.py tsup utils.py mutagen __init__.py blah.py blah.py ... ...
how do you include modified 3rd party modules when writing setup.py files?
I wrote a standalone script depends on a few modified modules. the directory structure looks like this: client setup.py tsclient __init__.py tsup utils.py mutagen __init__.py blah.py blah.py ... colorama __init__.py blah.py blah.py ... currently, ...
[ "Unfortunately you do need to edit mutagen to make this work.\nFortunately Python 2.5 and later have syntax to support exactly what you're doing.\nSee http://docs.python.org/whatsnew/2.5.html#pep-328-absolute-and-relative-imports .\nSuppose mutagen currently says,\nfrom mutagen import _util\n\nIf you change it to s...
[ 2 ]
[]
[]
[ "python", "setuptools" ]
stackoverflow_0003373779_python_setuptools.txt
Q: .py to .exe, three questions I want to package a Python script so that it can run as a standalone program on Windows XP and later Windows versions. Now to do this I'm pretty sure I'll have to convert it to an .exe file. I know methods exist, what is the easiest/best method? Now this is where the question gets a l...
.py to .exe, three questions
I want to package a Python script so that it can run as a standalone program on Windows XP and later Windows versions. Now to do this I'm pretty sure I'll have to convert it to an .exe file. I know methods exist, what is the easiest/best method? Now this is where the question gets a little more advanced. I also have ...
[ "Take a look at py2exe. It's not perfect, but it will convert your script and all dependencies into an executable. I haven't used it in a while, but I believe it makes a directory of dependencies in the directory of the executable. I suspect that you could change the png to a relative path and put it in that direct...
[ 3, 0 ]
[]
[]
[ "exe", "module", "png", "python", "windows" ]
stackoverflow_0003374647_exe_module_png_python_windows.txt
Q: py2exe, problems I'm attempting to convert a .py file to a .exe file. However, I get a weird output. Output: usage: module1 [global_opts] cmd1 [cmd1_opts] [cmd2 [cmd2_opts] ...] or: module1 --help [cmd1 cmd2 ...] or: module1 --help-commands or: module1 cmd --help error: no commands supplied My code: fr...
py2exe, problems
I'm attempting to convert a .py file to a .exe file. However, I get a weird output. Output: usage: module1 [global_opts] cmd1 [cmd1_opts] [cmd2 [cmd2_opts] ...] or: module1 --help [cmd1 cmd2 ...] or: module1 --help-commands or: module1 cmd --help error: no commands supplied My code: from distutils.core impo...
[ "Useing Gui2exe can be smart,i use it to both console and gui.\nHere is a script i have used,and have worked ok.\nfrom distutils.core import setup\nimport py2exe\nimport sys\n\nif len(sys.argv) == 1:\n sys.argv.append(\"py2exe\")\n\nsetup( options = {\"py2exe\": {\"compressed\": 1, \"optimize\": 2, \"ascii\": 1,...
[ 1 ]
[]
[]
[ "py2exe", "python", "windows_7" ]
stackoverflow_0003374913_py2exe_python_windows_7.txt
Q: Are there any existing batch log file aggregation solutions? I wish to export from multiple nodes log files (in my case apache access and error logs) and aggregate that data in batch, as a scheduled job. I have seen multiple solutions that work with streaming data (i.e think scribe). I would like a tool that gi...
Are there any existing batch log file aggregation solutions?
I wish to export from multiple nodes log files (in my case apache access and error logs) and aggregate that data in batch, as a scheduled job. I have seen multiple solutions that work with streaming data (i.e think scribe). I would like a tool that gives me the flexibility to define the destination. This requiremen...
[ "we use http://mergelog.sourceforge.net/ to merge all our apache logs..\n", "take a look at Zomhg, its an aggregation/reporting system for log files using Hbase and Hdfs: http://github.com/zohmg/zohmg\n", "Scribe can meet your requirements, there's a version (link) of scribe that can aggregate logs from multi...
[ 1, 0, 0 ]
[ "PiCloud may help.\n\nThe PiCloud Platform gives you the freedom to develop your algorithms\n and software without sinking time into all of the plumbing that comes\n with provisioning, managing, and maintaining servers.\n\n" ]
[ -1 ]
[ "aggregation", "export", "hdfs", "logfiles", "python" ]
stackoverflow_0002358896_aggregation_export_hdfs_logfiles_python.txt
Q: Logical task for Python programmers. Make tuple of lists from list I need to make tuple of list with 2 items. For example if I have list range(10) I need to make tuple like this: [(0,1),(2,3),(4,5),(6,7),(8,9)] How can I implement that? A: Many different ways. Just to show off a few: As list comprehension, wher...
Logical task for Python programmers. Make tuple of lists from list
I need to make tuple of list with 2 items. For example if I have list range(10) I need to make tuple like this: [(0,1),(2,3),(4,5),(6,7),(8,9)] How can I implement that?
[ "Many different ways. Just to show off a few:\nAs list comprehension, where l is a sequence (i.e. integer indexes): [(l[i], l[i+1]) for i in range(0,len(l),2)]\nAs generator function, works for all iterables:\ndef some_meaningful_name(it):\n it = iter(it)\n while True:\n yield next(it), next(it)\n\nNai...
[ 3, 2, 0 ]
[]
[]
[ "list", "python" ]
stackoverflow_0003374955_list_python.txt
Q: Django template can't see CSS files I'm building a django app and I can't get the templates to see the CSS files... My settings.py file looks like: MEDIA_ROOT = os.path.join(os.path.abspath(os.path.dirname(__file__)), 'media') MEDIA_URL = '/media/' I've got the CSS files in /mysite/media/css/ and the template co...
Django template can't see CSS files
I'm building a django app and I can't get the templates to see the CSS files... My settings.py file looks like: MEDIA_ROOT = os.path.join(os.path.abspath(os.path.dirname(__file__)), 'media') MEDIA_URL = '/media/' I've got the CSS files in /mysite/media/css/ and the template code contains: <link rel="stylesheet" type=...
[ "in the \"development only\" block in your urls.py you need to change\n(r'^media/(?P<path>.*)$', 'django.views.static.serve',\n {'document_root': '/media'}),\n\nto...\n(r'^media/(?P<path>.*)$', 'django.views.static.serve',\n {'document_root': settings.MEDIA_ROOT}),\n\n", "ADMIN_MEDIA_PREFIX is set to \\medi...
[ 13, 5, 2, 1, 0 ]
[]
[]
[ "css", "django", "django_templates", "python" ]
stackoverflow_0001075753_css_django_django_templates_python.txt
Q: What is the search order for free variables in Python? Specifically, how are free variables bound at definition for methods of a class? It is probably something like this: enclosing function (temporary) scope => generate closure global (permanent) scope => generate no closure (just look it up when the method bod...
What is the search order for free variables in Python?
Specifically, how are free variables bound at definition for methods of a class? It is probably something like this: enclosing function (temporary) scope => generate closure global (permanent) scope => generate no closure (just look it up when the method body executes) raise UnboundLocalError() Here are two examples...
[ "Python assumes a variable is local if and only if it is assigned to, within the current code block. So\nspam = 0\ndef ham:\n print( spam )\n\nwill make spam a global variable, but\nspam = 0\ndef ham:\n spam = 0\n print( spam )\n\nwill make a separate variable, local to ham. A closure grabs all the variabl...
[ 2 ]
[]
[]
[ "closures", "python", "scope" ]
stackoverflow_0003375217_closures_python_scope.txt
Q: Python XML and XPath to sort things out Let's say I have an XML as follows. <a> <b> <c>A</c> </b> <bb> <c>B</c> </bb> <c> X </c> </a> I need to parse this XML into dictionary X for a/b/c and a/b'/c, but dictionary Y for a/c. dictionary X X[a_b_c] = A X[a_bb_c] = B dictionary T T[a_c] = X Q : I'd lik...
Python XML and XPath to sort things out
Let's say I have an XML as follows. <a> <b> <c>A</c> </b> <bb> <c>B</c> </bb> <c> X </c> </a> I need to parse this XML into dictionary X for a/b/c and a/b'/c, but dictionary Y for a/c. dictionary X X[a_b_c] = A X[a_bb_c] = B dictionary T T[a_c] = X Q : I'd like to make a mapping file for this in XML fil...
[ "Maybe you could do this with XSLT. This stylesheet:\n<xsl:stylesheet version=\"1.0\" xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\">\n <xsl:output method=\"text\"/>\n <xsl:key name=\"dict\" match=\"item\" use=\"@dict\"/>\n <xsl:key name=\"path\" match=\"*[not(*)]\" use=\"concat(name(../..),'/',\n ...
[ 1 ]
[]
[]
[ "python", "xml", "xpath" ]
stackoverflow_0003373028_python_xml_xpath.txt
Q: Voice recognition : voice driven control Few days ago I asked for a project idea for my B.tech Final year project. Unfortunately couldn't got any cool idea. Now I have got an idea which really pleases me and motivates me. I want to ask to intelligent guys out there is following thing is feasible in 5 months: The P...
Voice recognition : voice driven control
Few days ago I asked for a project idea for my B.tech Final year project. Unfortunately couldn't got any cool idea. Now I have got an idea which really pleases me and motivates me. I want to ask to intelligent guys out there is following thing is feasible in 5 months: The Project idea is : "A Voice Driven Controlling o...
[ "I think somebody beat you to it:\nhttp://code.google.com/p/dragonfly/\nnote that you can use the Microsoft Windows speech recognition engine or Nuance's Dragon NaturallySpeaking.\nGood luck\n" ]
[ 0 ]
[]
[]
[ "c#", "c++", "projects_and_solutions", "python", "voice_recognition" ]
stackoverflow_0003369158_c#_c++_projects_and_solutions_python_voice_recognition.txt
Q: Select element within a list/tuple Hey bit of a beginners question here, I have connected to an imap server using the imaplib and fetched a email, it returns the following: [('1 (BODY[HEADER.FIELDS (SUBJECT)] {62}', "Subject: Gmail is different. Here's what you need to know.\r\n\r\n"), ')'] My question is how do ...
Select element within a list/tuple
Hey bit of a beginners question here, I have connected to an imap server using the imaplib and fetched a email, it returns the following: [('1 (BODY[HEADER.FIELDS (SUBJECT)] {62}', "Subject: Gmail is different. Here's what you need to know.\r\n\r\n"), ')'] My question is how do I select just the subject element ("Subj...
[ "a[0][1]\n\nwhere a is the string.\n", " email=[('1 (BODY[HEADER.FIELDS (SUBJECT)] {62}', \"Subject: Gmail is different. Here's what you need to know.\\r\\n\\r\\n\"), ')']\n for subj in (subject for element in email for subject in element if subject.startswith(\"Subject\")):\n print subj\n\"\"\" Outp...
[ 4, 0 ]
[]
[]
[ "list", "python" ]
stackoverflow_0003375375_list_python.txt
Q: Writing binary data to stdout with IronPython I have two Python scripts which I am running on Windows with IronPython 2.6 on .NET 2.0. One outputs binary data and the other processes the data. I was hoping to be able to stream data from the first to the second using pipes. The problem I encountered here is that, w...
Writing binary data to stdout with IronPython
I have two Python scripts which I am running on Windows with IronPython 2.6 on .NET 2.0. One outputs binary data and the other processes the data. I was hoping to be able to stream data from the first to the second using pipes. The problem I encountered here is that, when run from the Windows command-line, sys.stdout u...
[ "sys.stdout is just a variable that points to the same thing as sys.__stdout__\nTherefore, just open up a file in binary mode, assign the file to sys.stdout and use it. If you ever need the real, normal stdout back again, you can get it with\nsys.stdout = sys.__stdout__\n\n" ]
[ 0 ]
[]
[]
[ "character_encoding", "ironpython", "python", "stdout" ]
stackoverflow_0003375111_character_encoding_ironpython_python_stdout.txt
Q: Call javascript functions in IE with Python/Com http://win32com.goermezer.de/content/view/170/291/ Tried the above. I am able to call Javascript functions declared in the html file. However, for javascript functions in external js files included in the html, I am not able to call those functions using the above me...
Call javascript functions in IE with Python/Com
http://win32com.goermezer.de/content/view/170/291/ Tried the above. I am able to call Javascript functions declared in the html file. However, for javascript functions in external js files included in the html, I am not able to call those functions using the above method. Any work arounds for this ?
[ "This sounds like a timing problem that is common with Javascript in the web page. AJAX programmers often need to tell the browser to wait until the page is fully loaded before executing their scripts.\nOne way to deal with that outside of the browser is to simply insert a time delay, i.e. call some innocuous funct...
[ 0 ]
[]
[]
[ "com", "python" ]
stackoverflow_0003366026_com_python.txt
Q: Having Problems with importing xlwt? I am using Eclipse with the PyDev plugin. I am using xlwt which is for writing to an excel sheet. I have the xlwt library in my src file. I have another python file called gene_sorter.py where i try to import xlwt. using import xlwt I keep gettting back this error: File "C:\D...
Having Problems with importing xlwt?
I am using Eclipse with the PyDev plugin. I am using xlwt which is for writing to an excel sheet. I have the xlwt library in my src file. I have another python file called gene_sorter.py where i try to import xlwt. using import xlwt I keep gettting back this error: File "C:\Documents and Settings\Ben Fossen\Pythonwor...
[ "\"New enough version of Python\" could well be \"too new\"; please edit your question to show the actual version number. In future, don't be coy; save the time and energy of everybody (including yourself) by including such essential information in your question.\nIf you are trying to run it under Python 3.1:\n\nDo...
[ 1 ]
[]
[]
[ "import", "python", "xlwt" ]
stackoverflow_0003375384_import_python_xlwt.txt
Q: communication between python programs I have a python program that is running as a daemon on Linux. How to send this daemon a signal from another python program? A: Use os.kill to send signals. The signals are defined in the signal module. You'll just need to get the pid of the daemon in some way. One more thi...
communication between python programs
I have a python program that is running as a daemon on Linux. How to send this daemon a signal from another python program?
[ "Use os.kill to send signals. The signals are defined in the signal module. You'll just need to get the pid of the daemon in some way.\nOne more thing - you can use the signal module to register signal handlers as well.\n", "If you need something more sophisticated than simple signals, consider using an RPC lib...
[ 4, 3, 2, 1 ]
[]
[]
[ "process", "python" ]
stackoverflow_0003363831_process_python.txt
Q: python: print values from a dictionary generic_drugs_mapping={'MORPHINE':[86], 'OXYCODONE':[87], 'OXYMORPHONE':[99], 'METHADONE':[82], 'BUPRENORPHINE':[28], 'HYDROMORPHONE':[54], ...
python: print values from a dictionary
generic_drugs_mapping={'MORPHINE':[86], 'OXYCODONE':[87], 'OXYMORPHONE':[99], 'METHADONE':[82], 'BUPRENORPHINE':[28], 'HYDROMORPHONE':[54], 'CODEINE':[37], 'HY...
[ "You have a bracket in the wrong place:\nprint generic_drugs_mapping['MORPHINE'][0]\n\nYour code is indexing the string 'MORPHINE', so it's equivalent to\nprint generic_drugs_mapping['M']\n\nSince 'M' is not a key in your dictionary, you won't get the results you expect.\n", "The list is the value stored under th...
[ 6, 2 ]
[]
[]
[ "dictionary", "python" ]
stackoverflow_0003375804_dictionary_python.txt
Q: python: comparing values string/integer i will be comparing two values like this:\ value1>value2 i know that value2 is always an integer, but sometimes value1 is None or a string, how do force the comparison ONLY if value1 is numerical? value1 is a decimal A: Python 3 try: value1 > value2 except TypeError: ...
python: comparing values string/integer
i will be comparing two values like this:\ value1>value2 i know that value2 is always an integer, but sometimes value1 is None or a string, how do force the comparison ONLY if value1 is numerical? value1 is a decimal
[ "Python 3\ntry:\n value1 > value2\nexcept TypeError:\n pass\n\nPython <3\nif isinstance( value2, int ):\n value1 > value2\n\nThis latter is unpythonic, because this type of comparison is unpythonic. You should filter your data first.\n", "try:\n int(value1) > value2\nexcept (TypeError, ValueError):\n ...
[ 2, 2, 2 ]
[]
[]
[ "python" ]
stackoverflow_0003375845_python.txt
Q: Python: upload images Can python upload images onto the internet and provide a URL for it? For example is it possible for python to upload an image onto photobucket or any other uploading image service and then retreive the URL for it? A: Certainly. You'll need to find an image hosting service with an API (hint:...
Python: upload images
Can python upload images onto the internet and provide a URL for it? For example is it possible for python to upload an image onto photobucket or any other uploading image service and then retreive the URL for it?
[ "Certainly. You'll need to find an image hosting service with an API (hint: Flickr), and then write some Python code to interact with it (hint: XML-RPC).\nPseudocode\nimport xmlrpclib\n\nwith open( \"...\" ) as imagelist:\n for image in imagelist:\n message = xmlrpclib.make_some_message_or_other\n ...
[ 2, 0 ]
[]
[]
[ "image", "python", "upload" ]
stackoverflow_0003375875_image_python_upload.txt
Q: python: accessing a list using a dictionary i read a csv into a variable called b now i am going through every row in it like this: for row in b: this dictionary gives me the positions of where these drugs are in the row: generic_drugs_mapping={'MORPHINE':[86], 'OXYCODONE':[87], ...
python: accessing a list using a dictionary
i read a csv into a variable called b now i am going through every row in it like this: for row in b: this dictionary gives me the positions of where these drugs are in the row: generic_drugs_mapping={'MORPHINE':[86], 'OXYCODONE':[87], 'OXYMORPHONE':[99], ...
[ "Yes, that should work, assuming those are 0-based indexes into row. Is there a reason the elements of the dictionary are lists?\n" ]
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0003376043_python.txt
Q: Append a value to a list and move all values over if i start off with : a=[1,2,4] and i want the result to be a=[1,3,2,4] how do i do this append? A: In [18]: a=[1,2,4] In [19]: a[1:1]=[3] In [20]: a Out[20]: [1, 3, 2, 4] or In [22]: a.insert(1,3) In [24]: a Out[24]: [1, 3, 2, 4] With the first (slice) no...
Append a value to a list and move all values over
if i start off with : a=[1,2,4] and i want the result to be a=[1,3,2,4] how do i do this append?
[ "In [18]: a=[1,2,4]\n\nIn [19]: a[1:1]=[3]\n\nIn [20]: a\nOut[20]: [1, 3, 2, 4]\n\nor\nIn [22]: a.insert(1,3)\n\nIn [24]: a\nOut[24]: [1, 3, 2, 4]\n\nWith the first (slice) notation, you can even insert multiple elements (similar to extend, but not necessarily at the end of the list):\nIn [26]: a[1:1]=[3,5]\n\nIn [...
[ 6, 4, 4 ]
[]
[]
[ "python" ]
stackoverflow_0003376160_python.txt
Q: Finding Regex Pattern after doing re.findall This is in continuation of my earlier question where I wanted to compile many patterns as one regular expression and after the discussion I did something like this REGEX_PATTERN = '|'.join(self.error_patterns.keys()) where self.error_patterns.keys() would be pattern ...
Finding Regex Pattern after doing re.findall
This is in continuation of my earlier question where I wanted to compile many patterns as one regular expression and after the discussion I did something like this REGEX_PATTERN = '|'.join(self.error_patterns.keys()) where self.error_patterns.keys() would be pattern like : error: : warning: cc1plus: undefine re...
[ "re.findall will return all portions of text that matched your expression.\nIf that is not sufficient to identify the pattern unambiguously, you can still do a second re.match/re.find against the individual subpatterns you have join()ed. At the time of applying your initial regular expression, the matcher is no lon...
[ 1, 1 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0003374456_python_regex.txt
Q: request.POST pylons, getting array like in php I have a dynamic form, i must bulid some post array to field witch some id. For example: <input type="checkbox" name="field[124][]" value="1"> <input type="checkbox" name="field[124][]" value="2"> In php i can simply get value and key. foreach($_POST as $key => $val...
request.POST pylons, getting array like in php
I have a dynamic form, i must bulid some post array to field witch some id. For example: <input type="checkbox" name="field[124][]" value="1"> <input type="checkbox" name="field[124][]" value="2"> In php i can simply get value and key. foreach($_POST as $key => $value){ if(is_array($value){ foreach($value as $key2 ...
[ "You can use .getall() of multidict object, for example:\nhtml:\n<input type=\"checkbox\" name=\"field[124][]\" value=\"1\">\n<input type=\"checkbox\" name=\"field[124][]\" value=\"2\">\n\ncontroller:\nvalues = request.POST.getall('field[124][]')\n# >>> values\n# [u'1', u'2']\n\n\nanother way to get this list is by...
[ 2 ]
[]
[]
[ "php", "pylons", "python" ]
stackoverflow_0003366074_php_pylons_python.txt
Q: Approximate session data from apache access.log - python How might one use the ip and timestamp from Apache's access log to approximate a "session" for a given visitor? A session would include all consecutive requests within a given period, say 60secs. I have a class to parse the log file, and follow an IP addres...
Approximate session data from apache access.log - python
How might one use the ip and timestamp from Apache's access log to approximate a "session" for a given visitor? A session would include all consecutive requests within a given period, say 60secs. I have a class to parse the log file, and follow an IP address through it (the log is in timestamp order, thankfully). The...
[ "I wrote you some code then did a fail and lost it =(.\nOne way, not necessarily the best, is to iterate through the lines, maintaining a dictionary of IP address -> list of lines in its session. For each line, if it's already in the dict just append it to the list; otherwise, make a new session for it. Then, withi...
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0003376218_python.txt
Q: How do I add a new column of data to a csv file I am reading a csv file into a variable data like this: def get_file(start_file): #opens original file, reads it to array with open(start_file,'rb') as f: data=list(csv.reader(f)) data is the entire csv file. How do I add an extra column to this data? A...
How do I add a new column of data to a csv file
I am reading a csv file into a variable data like this: def get_file(start_file): #opens original file, reads it to array with open(start_file,'rb') as f: data=list(csv.reader(f)) data is the entire csv file. How do I add an extra column to this data?
[ "data is a list of lists of strings, so...:\nfor row, itm in zip(data, column):\n row.append(str(itm))\n\nof course you need column to be the right length so you may want to check that, eg raise an exc if len(data) != len(column).\n", ".append a value to the end of each row in data, and then use a csv.writer to ...
[ 3, 3, 3 ]
[]
[]
[ "csv", "python" ]
stackoverflow_0003376236_csv_python.txt
Q: make a change to an element within a list within a list i am reading a csv file into a data: def get_file(start_file): #opens original file, reads it to array with open(start_file,'rb') as f: data=list(csv.reader(f)) i need to go through every row and add a value to row[1] like this. initially row[1] = 'Pea...
make a change to an element within a list within a list
i am reading a csv file into a data: def get_file(start_file): #opens original file, reads it to array with open(start_file,'rb') as f: data=list(csv.reader(f)) i need to go through every row and add a value to row[1] like this. initially row[1] = 'Peanut', i need to add 'Butter' so the result would be row[1]='...
[ "You want\nfor row in data:\n row[ 1 ] += \"Butter\"\n\nbut the right way to do this is not to iterate through every row of data again but to modify the way you generate data in the first place. Go look at my answer in your other question.\n\nCopy-paste from your previous question\ndef get_file( start_file )\n ...
[ 5, 0 ]
[]
[]
[ "csv", "list", "python" ]
stackoverflow_0003376299_csv_list_python.txt
Q: GAE/Django Templates (0.96) filters to get LENGTH of GqlQuery and filter it I pass the query with comments to my template: COMM = CommentModel.gql("ORDER BY created") doRender(self,CP.template,{'CP':CP,'COMM':COMM, 'authorize':authorize()}) And I want to output the number of comments as a result, and I t...
GAE/Django Templates (0.96) filters to get LENGTH of GqlQuery and filter it
I pass the query with comments to my template: COMM = CommentModel.gql("ORDER BY created") doRender(self,CP.template,{'CP':CP,'COMM':COMM, 'authorize':authorize()}) And I want to output the number of comments as a result, and I try to do things like that: <a href="...">{{ COMM|length }} comments</a> That...
[ "Call .fetch() on the query, returning a list of results, before passing it to the template. Any other solution - such as calling .count() - will result in executing the query multiple times, which wastes CPU and wall-clock time.\nLikewise, if you need to filter the query, you should do this in your own code, befor...
[ 3, 1, 0 ]
[]
[]
[ "django_templates", "google_app_engine", "python" ]
stackoverflow_0002533306_django_templates_google_app_engine_python.txt
Q: sqlachemy, says decimal is not defined? Trying to make a column of type decimal: Column('cost', DECIMAL) Erorr, name 'DECIMAL' is not defined. SqlAlch seems to support decimal, am I missing an import? BTW, how do I also create a longtext column? I'm using mysql. A: try import sqlalchemy.types.DECIMAL as DECIMAL...
sqlachemy, says decimal is not defined?
Trying to make a column of type decimal: Column('cost', DECIMAL) Erorr, name 'DECIMAL' is not defined. SqlAlch seems to support decimal, am I missing an import? BTW, how do I also create a longtext column? I'm using mysql.
[ "try\nimport sqlalchemy.types.DECIMAL as DECIMAL\n\n" ]
[ 3 ]
[]
[]
[ "mysql", "python", "sqlalchemy" ]
stackoverflow_0003376465_mysql_python_sqlalchemy.txt
Q: help on getting image src from a table cell using BeautifulSoup So I have a html page that has a form, and a table inside the form that has rows of products. I got to the point now where I am looping through the table rows, and in each loop I grab all the table cells. for tr in t.findAll('tr'): td = tr.findAll...
help on getting image src from a table cell using BeautifulSoup
So I have a html page that has a form, and a table inside the form that has rows of products. I got to the point now where I am looping through the table rows, and in each loop I grab all the table cells. for tr in t.findAll('tr'): td = tr.findAll('td') Now I want to grab the image src url from the first td. Html ...
[ "Use\ntd[0].a.img['src']\n\nI imagine your use of image for img in the question was just a transcription error, but the important point is that, in BeautifulSoup, in order to access a tag's HTML attributes you use indexing notation (like the ['src'] in my code snippet above), not dot-syntax -- the dot-syntax notati...
[ 6 ]
[]
[]
[ "beautifulsoup", "python" ]
stackoverflow_0003376507_beautifulsoup_python.txt
Q: how do I halt execution in a python script? Possible Duplicates: Programatically stop execution of python script? Terminating a Python script I want to print a value, and then halt execution of the script. Do I just use return? A: You can use return inside the main function in you have one, but this isn't guar...
how do I halt execution in a python script?
Possible Duplicates: Programatically stop execution of python script? Terminating a Python script I want to print a value, and then halt execution of the script. Do I just use return?
[ "You can use return inside the main function in you have one, but this isn't guaranteed to quit the script if there is more code after your call to main.\nThe simplest that nearly always works is sys.exit():\nimport sys\nsys.exit()\n\nOther possibilities:\n\nRaise an error which isn't caught.\nLet the execution poi...
[ 21, 7, 6 ]
[]
[]
[ "python" ]
stackoverflow_0003376534_python.txt
Q: How to get rid of spacing in SimpleDocTemplate(). Python. ReportLab Do someone know if it possible to delete default spancing when i'm making PDF document with SimpleDocTemplate(). I want it to print from corner to corner. response = HttpResponse(mimetype='application/pdf') response['Content-Disposition'] ...
How to get rid of spacing in SimpleDocTemplate(). Python. ReportLab
Do someone know if it possible to delete default spancing when i'm making PDF document with SimpleDocTemplate(). I want it to print from corner to corner. response = HttpResponse(mimetype='application/pdf') response['Content-Disposition'] = 'attachment; filename=somefilename.pdf' # Our container for 'Flowa...
[ "Try:\ndoc = SimpleDocTemplate(response, rightMargin=0, leftMargin=0, topMargin=0, bottomMargin=0)\n\n" ]
[ 6 ]
[]
[]
[ "django", "pdf_generation", "python" ]
stackoverflow_0003374296_django_pdf_generation_python.txt
Q: Store Information In MySQL Database with Python I am working on a huge project. I have been working on it for a while now, and decided to "up" the security on the way the software handles data. I already know how to encrypt and decrypt the data strings using DES encryption, but what I am not sure about is where to...
Store Information In MySQL Database with Python
I am working on a huge project. I have been working on it for a while now, and decided to "up" the security on the way the software handles data. I already know how to encrypt and decrypt the data strings using DES encryption, but what I am not sure about is where to put that encrypted data. I would like to store every...
[ "Here's an example of what the schema could look like:\nuser\n user_id (PK)\n username (char)\n password (char)\n security_question_id (FK)\n security_answer (char)\n email_address (char)\n\nsecurity_question\n security_question_id (PK)\n question (char)\n\nkeyword\n keyword_id (PK)\n ...
[ 2, 0 ]
[]
[]
[ "mysql", "python" ]
stackoverflow_0003376634_mysql_python.txt
Q: Using BeautifulSoup, how to guard against elements not being found? I am looping through table rows in a table, but the first 1 or 2 rows doesn't have the elements I am looking for (they are for table column headers etc.). So after say the 3rd table row, there are elements in the table cells (td) that have what I ...
Using BeautifulSoup, how to guard against elements not being found?
I am looping through table rows in a table, but the first 1 or 2 rows doesn't have the elements I am looking for (they are for table column headers etc.). So after say the 3rd table row, there are elements in the table cells (td) that have what I am looking for. e.g. td[0].a.img['src'] But calling this fails since the...
[ "Simplest and clearest, if you want your code \"in line\":\ntheimage = td[0].a.img\nif theimage is not None:\n use(theimage['src'])\n\nOr, preferably, wrap the None check in a tiny function of your own, e.g.:\ndef getsrc(image):\n return None if image is None else image['src']\n\nand use getsrc(td[0].a.img).\n",...
[ 5, 1 ]
[]
[]
[ "beautifulsoup", "python" ]
stackoverflow_0003376666_beautifulsoup_python.txt
Q: Object propert is an integer, have to use regex to clean input, looking for good style I have some text that looks like: California(2342) My object has a property that I need to assign the value 2342 to. I'm looking for input on how to go about doing this, and guarding against any potential for errors in the inpu...
Object propert is an integer, have to use regex to clean input, looking for good style
I have some text that looks like: California(2342) My object has a property that I need to assign the value 2342 to. I'm looking for input on how to go about doing this, and guarding against any potential for errors in the input. c = SomeClass() c.count = re.compile(r'(\d*)').groups[0] Does that look ok? Or should ...
[ "import re\n\npat = re.compile(r'\\w+\\((\\d+)\\)')\n\ns = 'California(2342)'\nmatch = pat.match(s)\nif match:\n c.count = match.group(1)\n print c.count\n # '2342'\nelse:\n c.count = '0' # or 0 if numeric\n\nIf you want a number back instead of a string just modify:\nvalue = int(match.group(1))\n\n" ]
[ 2 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0003376700_python_regex.txt
Q: Can someone please explain this bit of Python code? I started working in Python just recently and haven't fully learned all the nuts and bolts of it, but recently I came across this post that explains why python has closures, in there, there is a sample code that goes like this: y = 0 def foo(): x = [0] d...
Can someone please explain this bit of Python code?
I started working in Python just recently and haven't fully learned all the nuts and bolts of it, but recently I came across this post that explains why python has closures, in there, there is a sample code that goes like this: y = 0 def foo(): x = [0] def bar(): print x[0], y def change(z): ...
[ "Before the nonlocal keyword was added in Python 3 (and still today, if you're stuck on 2.* for whatever reason), a nested function just couldn't rebind a local barename of its outer function -- because, normally, an assignment statement to a barename, such as x = 23, means that x is a local name for the function c...
[ 9, 5, 4, 2 ]
[]
[]
[ "closures", "python" ]
stackoverflow_0003376643_closures_python.txt
Q: Width of widget In PyGTK what is the easiest way to figure out the dimensions of a widget? I know that it is easy to do with the gtk.Window object, but I can't find in the reference manual any way to get dimensions for the other objects. Any help is greatly appreciated thanks :D A: You may be looking for the get...
Width of widget
In PyGTK what is the easiest way to figure out the dimensions of a widget? I know that it is easy to do with the gtk.Window object, but I can't find in the reference manual any way to get dimensions for the other objects. Any help is greatly appreciated thanks :D
[ "You may be looking for the get_allocation method:\n\nThe get_allocation() method returns a\n gtk.gdk.Rectangle containing the\n bounds of the widget's allocation.\n\nor size_request:\n\nThe size_request() method returns the\n preferred size of a widget as a tuple\n containing its required width and\n height. ...
[ 1 ]
[]
[]
[ "gtk", "pygtk", "python" ]
stackoverflow_0003376791_gtk_pygtk_python.txt
Q: Captcha solution which can be used with App Engine? Is there a simple captcha solution which can be easily integrated with a form deployed using Google App Engine? I am using Python. A: Recaptcha. It does work with Python. http://www.google.com/recaptcha http://code.google.com/apis/recaptcha/docs/otherplatforms....
Captcha solution which can be used with App Engine?
Is there a simple captcha solution which can be easily integrated with a form deployed using Google App Engine? I am using Python.
[ "Recaptcha. It does work with Python.\nhttp://www.google.com/recaptcha\nhttp://code.google.com/apis/recaptcha/docs/otherplatforms.html\nhttp://pypi.python.org/pypi/recaptcha-client\n", "I didn't test, but I guess this can work: http://daily.profeth.de/2008/04/using-recaptcha-with-google-app-engine.html, he use re...
[ 5, 1 ]
[]
[]
[ "api", "captcha", "google_app_engine", "python" ]
stackoverflow_0003376797_api_captcha_google_app_engine_python.txt
Q: sqlachemy created mysql table, but I modified table now says 'unknown column url' I added a url column in my table, and now sqlalchemy is saying 'unknown column url'. Why isn't it updating the table? There must be a setting when I create the session? I am doing: Session = sessionmaker(bind=engine) Is there someth...
sqlachemy created mysql table, but I modified table now says 'unknown column url'
I added a url column in my table, and now sqlalchemy is saying 'unknown column url'. Why isn't it updating the table? There must be a setting when I create the session? I am doing: Session = sessionmaker(bind=engine) Is there something I am missing? I want it to update any table that doesn't have a property that I add...
[ "I'm not sure SQLAlchemy supports schema migration that well (atleast the last time I touched it, it wasn't there). \nA couple of options. \n\nDon't manually specify your tables. Use the autoload feature to have SQLAlchemy automatically read out the columns from your database. This will require tests to make sure t...
[ 1, 1 ]
[]
[]
[ "python", "sqlalchemy" ]
stackoverflow_0003376788_python_sqlalchemy.txt
Q: beautifulsoup, Find th with text 'price', then get price from next th My html looks like: <td> <table ..> <tr> <th ..>price</th> <th>$99.99</th> </tr> </table> </td> So I am in the current table cell, how would I get the 99.99 value? I have so far: td[3].findChild('th') But I ...
beautifulsoup, Find th with text 'price', then get price from next th
My html looks like: <td> <table ..> <tr> <th ..>price</th> <th>$99.99</th> </tr> </table> </td> So I am in the current table cell, how would I get the 99.99 value? I have so far: td[3].findChild('th') But I need to do: Find th with text 'price', then get next th tag's string value....
[ "Think about it in \"steps\"... given that some x is the root of the subtree you're considering,\nx.findAll(text='price')\n\nis the list of all items in that subtree containing text 'price'. The parents of those items then of course will be:\n[t.parent for t in x.findAll(text='price')]\n\nand if you only want to k...
[ 8, 0 ]
[]
[]
[ "beautifulsoup", "python" ]
stackoverflow_0003376803_beautifulsoup_python.txt
Q: Python - SqlAlchemy. How to relate tables from different modules or files? I have this class in one file and item class in another file in the same module. If they are in different modules or files when I define a new Channel, I got an error because Item is not in the same file. How can I solve this problem? If bo...
Python - SqlAlchemy. How to relate tables from different modules or files?
I have this class in one file and item class in another file in the same module. If they are in different modules or files when I define a new Channel, I got an error because Item is not in the same file. How can I solve this problem? If both classes are in the same file, I don't get any error. ChannelTest.py from Item...
[ "\n\"NoReferencedTableError: Could not find table 'items' with which to generate a foreign key\"\n\nAll your table definitions should share metadata object. \nSo you should do metadata = rdb.MetaData() in some separate module, and then use this metadata instance in ALL Table()'s.\n", "The string method should wor...
[ 1, 0 ]
[]
[]
[ "python", "sqlalchemy" ]
stackoverflow_0003357825_python_sqlalchemy.txt
Q: Having some trouble creating my Model in Pylons I've been reading the Pylons Book and, having got to the part about Models, realise it's out of date. So I then switched over to the official Pylons documentation for creating Models in Pylons 1.0 - http://pylonshq.com/docs/en/1.0/tutorials/quickwiki_tutorial/ I've f...
Having some trouble creating my Model in Pylons
I've been reading the Pylons Book and, having got to the part about Models, realise it's out of date. So I then switched over to the official Pylons documentation for creating Models in Pylons 1.0 - http://pylonshq.com/docs/en/1.0/tutorials/quickwiki_tutorial/ I've followed what they've got and it's still failing. ./bl...
[ "First, you should not declare two classes with same name. How is that supposed to work at all?\nSecond, you probably would want to read official SQLA docs, not Pylons. Pylons docs are a bit messy after upgrade, and still have a lot of 0.9.7 references.\nDeclarative extension is described here: http://www.sqlalchem...
[ 4 ]
[]
[]
[ "model", "pylons", "python", "sqlalchemy" ]
stackoverflow_0003377013_model_pylons_python_sqlalchemy.txt
Q: method factories which take class attributes as parameters I'm finding it useful to create "method factory functions" that wrap a parametrized object attribute in some logic. For example: """Fishing for answers. >>> one().number_fisher() 'one fish' >>> one().colour_fisher() 'red fish' >>> two().number_fisher() 't...
method factories which take class attributes as parameters
I'm finding it useful to create "method factory functions" that wrap a parametrized object attribute in some logic. For example: """Fishing for answers. >>> one().number_fisher() 'one fish' >>> one().colour_fisher() 'red fish' >>> two().number_fisher() 'two fish' >>> two().colour_fisher() 'blue fish' """ class one(o...
[ "\"One more level of indirection\" (sometimes proposed as programming's magic panacea;-) -- just like for typical decorators like property. E.g.:\ndef makefisher(fun):\n def fisher(self):\n return '{0} fish'.format(fun(self))\n return fisher\n\nclass one(object):\n def number(self): return self._number()\n ...
[ 2 ]
[]
[]
[ "factory_method", "polymorphism", "python" ]
stackoverflow_0003377014_factory_method_polymorphism_python.txt
Q: How do I set up rpy2? Hi I just download rpy2 and Python 2.6. When I try to run some of example code I found on the internet, I got this error. Can anyone explain why this is happening and how can I fix it? Thanks. import rpy2.robjects as RO Traceback (most recent call last): File "<pyshell#0>", line 1, in <mod...
How do I set up rpy2?
Hi I just download rpy2 and Python 2.6. When I try to run some of example code I found on the internet, I got this error. Can anyone explain why this is happening and how can I fix it? Thanks. import rpy2.robjects as RO Traceback (most recent call last): File "<pyshell#0>", line 1, in <module> import rpy2.robjec...
[ "\nThis might be because R.exe is nowhere\n in your Path\n\nThis sounds like a big clue. Check the value of %PATH% in your Windows environment. I'd expect this to contain the location of R.EXE (probably something like C:\\Programs\\R\\R-2.8.0\\bin).\n" ]
[ 1 ]
[]
[]
[ "python", "r" ]
stackoverflow_0003376867_python_r.txt
Q: Solving AttributeErrors in nested attributes I am writing a small mocking class to do some tests. But this class needs to support the idea of having nested attributes. This example should provide some insight to the problem: class Foo(object): def __init__(self): self.x = True From the above class, w...
Solving AttributeErrors in nested attributes
I am writing a small mocking class to do some tests. But this class needs to support the idea of having nested attributes. This example should provide some insight to the problem: class Foo(object): def __init__(self): self.x = True From the above class, we can have: f = Foo() f.x I know I can add attrib...
[ "You can \"mock anything\" by returning, on each attribute access, another instance of the \"mock anything\" class (which must also be callable, if you want to have the .z() part work;-).\nE.g.:\nclass MockAny(object):\n\n # mock special methods by making them noops\n def __init__(self, *a, **k): pass\n\n # or r...
[ 3, 1 ]
[]
[]
[ "nested_attributes", "python" ]
stackoverflow_0003376566_nested_attributes_python.txt
Q: tornado server not returning response with self.write I have a simple tornado server running like this: import json import suds from suds.client import Client import tornado.httpserver import tornado.ioloop import tornado.web class MainHandler(tornado.web.RequestHandler): def get(self): url = "http://...
tornado server not returning response with self.write
I have a simple tornado server running like this: import json import suds from suds.client import Client import tornado.httpserver import tornado.ioloop import tornado.web class MainHandler(tornado.web.RequestHandler): def get(self): url = "http://xx.xxx.xx.xxx/Service.asmx?WSDL" client = Client(ur...
[ "I finally figured out what was wrong: my app wasn't following the 'same domain origin' policy. So when the ajax request was being sent, the referrer header was from a different port than my tornado server. Naturally the server didn't return a response!\n" ]
[ 4 ]
[]
[]
[ "jquery", "python", "tornado" ]
stackoverflow_0003367944_jquery_python_tornado.txt
Q: how to check the neighbouring states in python The newPos gives me the position of pacman agent (like (3,5) ). newPos = successorGameState.getPacmanPosition() The oldfood gives me the remaining food available for pacman in the form of grid. We can access the grid via list like if we want to know if food is availa...
how to check the neighbouring states in python
The newPos gives me the position of pacman agent (like (3,5) ). newPos = successorGameState.getPacmanPosition() The oldfood gives me the remaining food available for pacman in the form of grid. We can access the grid via list like if we want to know if food is available at (3,4) then we do oldFood = currentGameState...
[ "Well, imagine this:\n...\n.P.\n.G.\n\nP is the pacman an G is a ghost. Checking with \"radius = 1\" is ghosts adjacent to the pacman. This check will find the ghost. But:\n....\n.P.G\n....\n....\n\nBut here a ghost won't be found with radius of 1, so radius of 2 is required.\n" ]
[ 2 ]
[]
[]
[ "python" ]
stackoverflow_0003377110_python.txt
Q: Memoization Handler Is it "good practice" to create a class like the one below that can handle the memoization process for you? The benefits of memoization are so great (in some cases, like this one, where it drops from 501003 to 1507 function calls and from 1.409 to 0.006 seconds of CPU time on my computer) that ...
Memoization Handler
Is it "good practice" to create a class like the one below that can handle the memoization process for you? The benefits of memoization are so great (in some cases, like this one, where it drops from 501003 to 1507 function calls and from 1.409 to 0.006 seconds of CPU time on my computer) that it seems a class like thi...
[ "You can memoize without having to resort to eval.\nA (very basic) memoizer:\ndef memoized(f):\n cache={}\n def ret(*args):\n if args in cache:\n return cache[args]\n else:\n answer=f(*args)\n cache[args]=answer\n return answer\n return ret\n\n@memo...
[ 14, 5 ]
[]
[]
[ "dynamic_programming", "memoization", "python" ]
stackoverflow_0003377258_dynamic_programming_memoization_python.txt
Q: Mac ports Mysql install I completed my install on Leopard with Mac Ports. I also installed Mysqld via Mac Ports for use with python. I set the password for mysql on mysql start. Everything seemed to be fine except when I invoke mysql-start from the command line now I get this: mysql-start *****Password: Starting M...
Mac ports Mysql install
I completed my install on Leopard with Mac Ports. I also installed Mysqld via Mac Ports for use with python. I set the password for mysql on mysql start. Everything seemed to be fine except when I invoke mysql-start from the command line now I get this: mysql-start *****Password: Starting MySQL . SUCCESS! demetrius-fo...
[ "The command for the client is normally mysql (see MySql docs) However in macports they have appended the major version number so try mysql5 \nThe python error is only a depreciation so can be ignored \n" ]
[ 0 ]
[]
[]
[ "django", "macports", "mysql", "python" ]
stackoverflow_0003376565_django_macports_mysql_python.txt
Q: Relating generically created Django objects with users I'm new to Python & Django. I want to allow users to create new objects, and for each object to be related to the currently logged in user. So, I thought I'd use the generic create_object method - only I can't work out how best to do this so it's simple and se...
Relating generically created Django objects with users
I'm new to Python & Django. I want to allow users to create new objects, and for each object to be related to the currently logged in user. So, I thought I'd use the generic create_object method - only I can't work out how best to do this so it's simple and secure. Here's my model: class Book(models.Model): user = ...
[ "I think it's not possible with generic view (I could think of some way to accomplish that, but that would be much more complicated than it's worth - using signals, globals and middleware). You should write your own view that will handle Book object creation using ModelForm. Read about it here and here (Django docs...
[ 2 ]
[]
[]
[ "django", "python" ]
stackoverflow_0003377421_django_python.txt
Q: Using a tuple as function arguments For this function I can use tuple elements as arguments: light_blue = .6, .8, .9 gradient.add_color_rgb(0, *light_blue) What if i have to add another argument after the tuple? light_blue = .6, .8, .9 alpha = .5 gradient.add_color_rgba(0, *light_blue, alpha) does not work. What...
Using a tuple as function arguments
For this function I can use tuple elements as arguments: light_blue = .6, .8, .9 gradient.add_color_rgb(0, *light_blue) What if i have to add another argument after the tuple? light_blue = .6, .8, .9 alpha = .5 gradient.add_color_rgba(0, *light_blue, alpha) does not work. What does work is gradient.add_color_rgba(0, ...
[ "You could call it like gradient.add_color_rgba(0, *light_blue, alpha=alpha) if you know parameter name for the alpha.\n", "You can simplify the expression slightly by making a tuple instead of a list containing light_blue and alpha e.g.\ngradient.add_color_rgba(0, *(light_blue + (alpha,)))\n\n" ]
[ 6, 2 ]
[]
[]
[ "python" ]
stackoverflow_0003377681_python.txt
Q: How do I efficiently fill a file with null data from python? I need to create files of arbitrary size that contain no data. The are potentially quite large. While I could just loop through and write a single null character until I've reached the file size, that seems ugly. with open(filename,'wb') as f: # what ...
How do I efficiently fill a file with null data from python?
I need to create files of arbitrary size that contain no data. The are potentially quite large. While I could just loop through and write a single null character until I've reached the file size, that seems ugly. with open(filename,'wb') as f: # what goes here? What is the efficient, pythonic way to do this?
[ "You can seek to a specific position and write a byte, and the OS will magically make the rest of the file appear.\nwith open(filename, \"wb\") as f:\n f.seek(999999)\n f.write(\"\\0\")\n\nYou need to write at least one byte for this to work.\n", "with open('zero', 'w') as f:\n f.seek(999999999)\n f.w...
[ 18, 8 ]
[]
[]
[ "file", "python" ]
stackoverflow_0003377891_file_python.txt
Q: find the neighbouring states around the agent I need to find the states that are next to my pacman agent. The current state is Tuple(3,5) which is given by numPos. I need to check the position that are around the pacman agent. I want to find the neighbouring states so that i can check it with the ghosts states and...
find the neighbouring states around the agent
I need to find the states that are next to my pacman agent. The current state is Tuple(3,5) which is given by numPos. I need to check the position that are around the pacman agent. I want to find the neighbouring states so that i can check it with the ghosts states and if they matches, that means , a ghost is present ...
[ "What is the problem? Your question (and the previous) one are quite unclear. \nWhat's wrong with this. \nx,y = numPos\npositions_to_search = [ (x-1, y),\n (x-1, y-1),\n (x, y-1),\n (x+1, y-1),\n (x+1, y),\n ...
[ 2, 2, 1 ]
[]
[]
[ "python" ]
stackoverflow_0003377303_python.txt
Q: passing C++ classes instances to python with boost::python I have a library which creates objects (instances of class A) and pass them to a python program which should be able to call their methods. Basically I have C++ class instances and I want to use them from python. Occasionally that object should be passed b...
passing C++ classes instances to python with boost::python
I have a library which creates objects (instances of class A) and pass them to a python program which should be able to call their methods. Basically I have C++ class instances and I want to use them from python. Occasionally that object should be passed back to C++ for some manipulations. I created the following wrapp...
[ "boost::python knows all about boost::shared_ptr, but you need to tell it that boost::shared_ptr<A> holds an instance of A, you do this by adding boost::shared_ptr<A> in the template argument list to class_, more information on this 'Held Type' is here in the boost documentation.\nTo prevent instances being created...
[ 14, 1 ]
[]
[]
[ "boost", "boost_python", "c++", "python" ]
stackoverflow_0003342216_boost_boost_python_c++_python.txt
Q: Using boost.python to import a method with opencv calls but failing due to symbols not being found after compilation So I don't have the code right now, as I am not home... but i used the boost library for python in C++ to allow python to access a function called something like loadImageIntoMainWindow(string filep...
Using boost.python to import a method with opencv calls but failing due to symbols not being found after compilation
So I don't have the code right now, as I am not home... but i used the boost library for python in C++ to allow python to access a function called something like loadImageIntoMainWindow(string filepath) in the C++ source code the method calls opencv methods that are imported at the top of the file, I included opencv in...
[ "Add the lines (editing /your/lib/path as appropriate...):\nlib cvlib : : <name>cv <search>/your/lib/path/lib ;\nlib cxcorelib : : <name>cxcore <search>/your/lib/path/lib ;\n\nto your Jamfile, and edit\npython-extension uTrackSpheresForPyInterface : uTrackSpheresForPyInterface.cpp ;\n\nso that it reads:\npython-ext...
[ 0 ]
[]
[]
[ "boost_python", "c++", "missing_symbols", "opencv", "python" ]
stackoverflow_0002502921_boost_python_c++_missing_symbols_opencv_python.txt
Q: Problem extracting text out of html file using python regex I'm working on a project that requires me to write some code to pull out some text from a html file in python. <tr> <td>Target binary file name:</td> <td class="right">Doc1.docx</td> </tr> ^Small portion of the html file that I'm interested in. #! /usr/b...
Problem extracting text out of html file using python regex
I'm working on a project that requires me to write some code to pull out some text from a html file in python. <tr> <td>Target binary file name:</td> <td class="right">Doc1.docx</td> </tr> ^Small portion of the html file that I'm interested in. #! /usr/bin/python import os import re if __name__ == '__main__': ...
[ "\nIs there something I'm missing out with regards to regex and html?\n\nYes. You're missing the fact that some HTML cannot be parsed with a simple regex.\n", "HTML as understood by browsers is waaaay too flexible for reg expressions. Attributes can pop up in any tag, and in any order, and in upper or lower cas...
[ 4, 0, 0 ]
[]
[]
[ "html", "python", "regex" ]
stackoverflow_0003378194_html_python_regex.txt
Q: name and value lookup collection, loaded from a dropdown list using beautifulsoup On my html page I have a dropdown list: <select name="somelist"> <option value="234234234239393">Some Text</option> </select> So do get this list I am doing: ddl = soup.findAll('select', name="somelist") if(ddl): ??? Now I ...
name and value lookup collection, loaded from a dropdown list using beautifulsoup
On my html page I have a dropdown list: <select name="somelist"> <option value="234234234239393">Some Text</option> </select> So do get this list I am doing: ddl = soup.findAll('select', name="somelist") if(ddl): ??? Now I need help with this collection/dictionary, I want to be able to lookup by both 'Some Te...
[ "Try the following to get started:\nstr = r'''\n<select name=\"somelist\">\n <option value=\"234234234239393\">Some Text</option>\n <option value=\"42\">Other text</option>\n</select>\n'''\n\nsoup = BeautifulSoup(str)\nselect_node = soup.findAll('select', attrs={'name': 'somelist'})\n\nif select_node:\n for ...
[ 5, 1, 0 ]
[]
[]
[ "beautifulsoup", "dictionary", "python" ]
stackoverflow_0003376817_beautifulsoup_dictionary_python.txt
Q: Python: what does "...".encode("utf8") fix? I wanted to url encode a python string and got exceptions with hebrew strings. I couldn't fix it and started doing some guess oriented programming. Finally, doing mystr = mystr.encode("utf8") before sending it to the url encoder saved the day. Can somebody explain what ...
Python: what does "...".encode("utf8") fix?
I wanted to url encode a python string and got exceptions with hebrew strings. I couldn't fix it and started doing some guess oriented programming. Finally, doing mystr = mystr.encode("utf8") before sending it to the url encoder saved the day. Can somebody explain what happened? What does .encode("utf8") do? My origin...
[ "\nMy original string was a unicode string anyways (i.e. prefixed by a u)\n\n...which is the problem. It wasn't a \"string\", as such, but a \"Unicode object\". It contains a sequence of Unicode code points. These code points must, of course, have some internal representation that Python knows about, but whatever t...
[ 13, 9, 4, 1, 0, 0 ]
[]
[]
[ "internationalization", "python", "unicode", "urlencode", "utf_8" ]
stackoverflow_0003291123_internationalization_python_unicode_urlencode_utf_8.txt
Q: How would you group up articles by context? - Natural Language I have lists of articles made of: title, subtitle and body. Now I need to parse all these articles and group them up under different context categories or sub categories based on their possible keywords. e.g. if the article is likely to be related to ...
How would you group up articles by context? - Natural Language
I have lists of articles made of: title, subtitle and body. Now I need to parse all these articles and group them up under different context categories or sub categories based on their possible keywords. e.g. if the article is likely to be related to sports cars then the article would be associated with the car or/and...
[ "The Natural Lanugage Toolkit but don't expect that there is a magic bullet in there which will keep you having to learn a fair bit about linguistics, as the problem you describe cannot be solved wholly mechanically.\n" ]
[ 1 ]
[]
[]
[ "data_mining", "nlp", "python" ]
stackoverflow_0003378908_data_mining_nlp_python.txt
Q: How to capture Python interpreter's and/or CMD.EXE's output from a Python script? Is it possible to capture Python interpreter's output from a Python script? Is it possible to capture Windows CMD's output from a Python script? If so, which librar(y|ies) should I look into? A: If you are talking about the python...
How to capture Python interpreter's and/or CMD.EXE's output from a Python script?
Is it possible to capture Python interpreter's output from a Python script? Is it possible to capture Windows CMD's output from a Python script? If so, which librar(y|ies) should I look into?
[ "If you are talking about the python interpreter or CMD.exe that is the 'parent' of your script then no, it isn't possible. In every POSIX-like system (now you're running Windows, it seems, and that might have some quirk I don't know about, YMMV) each process has three streams, standard input, standard output and s...
[ 10, 6, 3, 1, 0 ]
[]
[]
[ "cmd", "python", "windows" ]
stackoverflow_0000024931_cmd_python_windows.txt
Q: Deploying python app to Mac and Windows users I've written an app in python that depends on wxPython and some other python libraries. I know about pyexe for making python scripts executable on Windows, but what would be the easiest way to share this with my Mac using friends who wouldn't know how to install the re...
Deploying python app to Mac and Windows users
I've written an app in python that depends on wxPython and some other python libraries. I know about pyexe for making python scripts executable on Windows, but what would be the easiest way to share this with my Mac using friends who wouldn't know how to install the required dependencies? One option would be to bundle ...
[ "You could check out py2app, which is similar to py2exe\n", "\nHow do people usually deploy such apps?\n\n2 choices.\n\nWith instructions.\nAll bundled up.\n\nYou write simple instructions like this. Folks can follow these pretty reliably, unless they don't have enough privileges. Sometimes they need to sudo in...
[ 2, 0 ]
[]
[]
[ "deployment", "python" ]
stackoverflow_0003379032_deployment_python.txt
Q: call external python script in same window Im trying to call an external python script, and so far i was able to do so successfully using: os.system("START fileNameHere") However right now im running in the console, and i want the contents of the other python file to be shown in the same console. ATM it shows it ...
call external python script in same window
Im trying to call an external python script, and so far i was able to do so successfully using: os.system("START fileNameHere") However right now im running in the console, and i want the contents of the other python file to be shown in the same console. ATM it shows it in a separate console. Thanks in Advance.
[ "This outta do it.\nimport subprocess\n\np = subprocess.Popen('command', shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)\n for line in p.stdout.readlines():\n print line,\nretval = p.wait()\n\n" ]
[ 1 ]
[]
[]
[ "console", "external", "python" ]
stackoverflow_0003379151_console_external_python.txt
Q: Asynchronous api for obtaining GPS position in python for S60 I'm using positioning.position(). but this function is blocking. I want to be able to run another function while the GPS is being measured. thanks A: I'm not familiar with the S60, but if it supports threading here's an example of doing two functions ...
Asynchronous api for obtaining GPS position in python for S60
I'm using positioning.position(). but this function is blocking. I want to be able to run another function while the GPS is being measured. thanks
[ "I'm not familiar with the S60, but if it supports threading here's an example of doing two functions at once:\nimport threading\nimport time\n\ndef doit1():\n for i in range(10):\n time.sleep(.1)\n print 'doit1(%d)' % i\n\ndef doit2():\n for i in range(10):\n time.sleep(.2)\n prin...
[ 2 ]
[]
[]
[ "position", "pys60", "python" ]
stackoverflow_0003378922_position_pys60_python.txt
Q: Which is the most preferred language to start with dynamic languages After working for on JAVA for a long time now i feel like also learn some other language just for a change. This time i want to spend some time learning and reading one of the dynamic languages. Which is the most appropriate one that covers mos...
Which is the most preferred language to start with dynamic languages
After working for on JAVA for a long time now i feel like also learn some other language just for a change. This time i want to spend some time learning and reading one of the dynamic languages. Which is the most appropriate one that covers most of the features offered by dynamic languages and the syntax which probab...
[ "Python is always fun.Go for it.\n", "Javascript is by far the most useful of dynamic languages for real-world practical work - not only is it irreplaceable for \"client-side\" work on the user's browser, but Node.js is rapidly making it very interesting for server-side work, too. Sure, it has many issues, but a...
[ 7, 4, 3, 2, 2, 2, 0 ]
[]
[]
[ "dynamic_languages", "python", "ruby" ]
stackoverflow_0003379174_dynamic_languages_python_ruby.txt
Q: Why doesn't mydict.items().sort() work? When I try and sort my dictionary, I get an error: ''nonetype' object is not iterable. I am doing: for k,v in mydict.items().sort(): A: The sort method returns None (it has sorted the temporary list given by items(), but that's gone now). Use: for k, v in sorted(mydict.it...
Why doesn't mydict.items().sort() work?
When I try and sort my dictionary, I get an error: ''nonetype' object is not iterable. I am doing: for k,v in mydict.items().sort():
[ "The sort method returns None (it has sorted the temporary list given by items(), but that's gone now). Use:\nfor k, v in sorted(mydict.iteritems()):\n\nUsing .items() in lieu of .iteritems() is also OK (and needed if you're in Python 3) but, in Python 2 (where .items() makes and returns a list while .iteritems() ...
[ 12 ]
[]
[]
[ "dictionary", "python" ]
stackoverflow_0003379282_dictionary_python.txt
Q: ModelForm and error_css_class my problem is simple. Where the right place for a custom error_css_class value is when using ModelForm? I tried this: class ToolForm(ModelForm): error_css_class = 'wrong_list' class Meta: model = Tool widgets = { 'name' : TextInput(attrs={'class': 'small_input c...
ModelForm and error_css_class
my problem is simple. Where the right place for a custom error_css_class value is when using ModelForm? I tried this: class ToolForm(ModelForm): error_css_class = 'wrong_list' class Meta: model = Tool widgets = { 'name' : TextInput(attrs={'class': 'small_input corners'}), 'descript...
[ "You can define your own error list class by inherting from django's ErrorList. See the docs for details:\n\nCustomizing the error list format\n\nNote that you'll have to override the method to output the full HTML and can't just replace CSS class. You could call the base method and do a string replace on \"class...
[ 0 ]
[]
[]
[ "django", "django_forms", "python" ]
stackoverflow_0003379302_django_django_forms_python.txt
Q: ImageKit in Django I am implementing ImageKit in a Django app and I have everything set up properly to my knowledge. When I run the command $python manage.py ikflush main the command seems to run fine but nothing appears to happen. None of the images get resized or stored and cannot be accessed. main.models.py: c...
ImageKit in Django
I am implementing ImageKit in a Django app and I have everything set up properly to my knowledge. When I run the command $python manage.py ikflush main the command seems to run fine but nothing appears to happen. None of the images get resized or stored and cannot be accessed. main.models.py: class ProductImage(models...
[ "This may just be a formatting mistake in the question and not in your code. But IKOptions should be nested in your model class:\nclass ProductImage(models.Model):\n # fields, etc...\n class IKOptions:\n # ...\n\nAlso, before you run ikflush, did you add ImageKit to INSTALLED_APPS in your settings fil...
[ 1, 1 ]
[]
[]
[ "django", "django_imagekit", "imagekit", "python" ]
stackoverflow_0003366952_django_django_imagekit_imagekit_python.txt
Q: Django Fixtures Error: Unknown application I have a project w/ multiple apps. I am attempting to use the dumpdata command to create a fixture for each app. Calling dumpdata on a given app seems to work well. This prints the data to the console: python manage.py dumpdata myapp However, when I attempt to create a...
Django Fixtures Error: Unknown application
I have a project w/ multiple apps. I am attempting to use the dumpdata command to create a fixture for each app. Calling dumpdata on a given app seems to work well. This prints the data to the console: python manage.py dumpdata myapp However, when I attempt to create a json file containing the dumped data: python ma...
[ "You give the correct syntax in your first snippet. The argument after dumpdata is an application, not a file.\nIf you want to save that output to a file, you use standard redirection: \npython manage.py dumpdata myapp > apps/myapp/fixtures/initial_data.json\n\n" ]
[ 2 ]
[]
[]
[ "django", "fixtures", "python" ]
stackoverflow_0003379500_django_fixtures_python.txt
Q: min max algorithm in python In the minmax algorithm,How to determine when your function reaches the end of the tree and break the recursive calls. I have made a max function in which I am calling the min function. In the min function , what shud I do?? For max function, I am just returning the bestscore. def maxAg...
min max algorithm in python
In the minmax algorithm,How to determine when your function reaches the end of the tree and break the recursive calls. I have made a max function in which I am calling the min function. In the min function , what shud I do?? For max function, I am just returning the bestscore. def maxAgent(gameState, depth): if (...
[ "Usually you want to search until a certain recursion depth (e.g. n moves in advance, when playing chess). Therefore, you should pass the current recursion depth as a parameter. You may abort earlier when your results do not improve, if you can determine that with little effort.\n", "\nIn the minmax algorithm,How...
[ 3, 1, 1, 0 ]
[]
[]
[ "algorithm", "artificial_intelligence", "python" ]
stackoverflow_0003379616_algorithm_artificial_intelligence_python.txt
Q: Splitting a module with 8+ classes into a package with each class in its own file I have a module (tools.py) containing many classes. I'd like to extract these out into its own "whyteboard.tools" package, each class being inside its own file. However, I previously moved from having all my classes in one base direc...
Splitting a module with 8+ classes into a package with each class in its own file
I have a module (tools.py) containing many classes. I'd like to extract these out into its own "whyteboard.tools" package, each class being inside its own file. However, I previously moved from having all my classes in one base directory to being in a package below the root of my project, and had issues with loading in...
[ "I've typically seen the init.py in modules do something like:\nfrom whyteboard.tools.pen import *\n\nThis way you can always import from whyteboard.tools and reference any of the classes inside this module without knowing where they are located. You simply need to just know of the classes provided by the whyteboar...
[ 2, 1 ]
[]
[]
[ "extract", "package", "python" ]
stackoverflow_0003379662_extract_package_python.txt
Q: Can Python be good alternative for web app that would otherwise be done in Java EE? Can Python be a good alternative to a web app that would otherwise be developed with Java EE? If so, which Python web app framework(s) may be a good choice? Please see details about the app below. I've asked a few people individual...
Can Python be good alternative for web app that would otherwise be done in Java EE?
Can Python be a good alternative to a web app that would otherwise be developed with Java EE? If so, which Python web app framework(s) may be a good choice? Please see details about the app below. I've asked a few people individually about this, who have worked for a good amount of time on either or both of Java EE and...
[ "It's a very good alternative indeed. Your project sounds to me like it'll need quite a lot of custom programming, which in the Python world would point to basing your web app from Pylons ( http://pylonshq.com/ ). Pylons is mostly a glue layer, and you'll pick a template engine and ORM (try SQLAlchemy ( http://www....
[ 5, 3, 3, 2 ]
[]
[]
[ "jakarta_ee", "java", "python" ]
stackoverflow_0003379440_jakarta_ee_java_python.txt