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: Image preview with Reportlab? I'm generating some pdf's with Reportlab and Django using a web interface. The pdf's are always going to be a single page. I'd like to generate a png or jpg image of the generated page and return that to the browser for the user to preview before saving the final pdf and delivering it...
Image preview with Reportlab?
I'm generating some pdf's with Reportlab and Django using a web interface. The pdf's are always going to be a single page. I'd like to generate a png or jpg image of the generated page and return that to the browser for the user to preview before saving the final pdf and delivering it to the end user. Is there anyway t...
[ "This answer explains that you can use ghostscript to convert pdf to png. Depending of the requirements of your app (traffic, response time, nb of pdfs ...) it may or may not be a solution for you.\nThis is just an idea, but may be you can generate the preview image in parallel using PIL ImageDraw and get rid of th...
[ 0 ]
[]
[]
[ "django", "pdf", "preview", "python", "reportlab" ]
stackoverflow_0004122026_django_pdf_preview_python_reportlab.txt
Q: How to dynamically change a property? My problem is quite simple, I have a string that contains a path to a property, and I want to change that property through the string. str = "someClass.property" data = 123 ''' I don't know what str contains, as it is created by a user I know that I could do this, but it smell...
How to dynamically change a property?
My problem is quite simple, I have a string that contains a path to a property, and I want to change that property through the string. str = "someClass.property" data = 123 ''' I don't know what str contains, as it is created by a user I know that I could do this, but it smells like bad practice, in PHP it's a criminal...
[ "You could use setattr:\nsetattr(someClass, property, data)\n\nNote that this is still dangerous if done without any user validation as your user could change the definition of existing attributes that they should not be able to modify.\nA safer alternative is to use a dict as a key-value store and put the user-def...
[ 3, 0 ]
[]
[]
[ "exec", "python" ]
stackoverflow_0004122102_exec_python.txt
Q: Get Data from OpenGL glReadPixels(using Pyglet) I'm using Pyglet(and OpenGL) in Python on an application, I'm trying to use glReadPixels to get the RGBA values for a set of pixels. It's my understanding that OpenGL returns the data as packed integers, since that's how they are stored on the hardware. However for...
Get Data from OpenGL glReadPixels(using Pyglet)
I'm using Pyglet(and OpenGL) in Python on an application, I'm trying to use glReadPixels to get the RGBA values for a set of pixels. It's my understanding that OpenGL returns the data as packed integers, since that's how they are stored on the hardware. However for obvious reasons I'd like to get it into a normal for...
[ "You must first create an array of the correct type, then pass it to glReadPixels:\na = (GLuint * 1)(0)\nglReadPixels(x, y, 1, 1, GL_RGB, GL_UNSIGNED_INT, a)\n\nTo test this, insert the following in the Pyglet \"opengl.py\" example:\n@window.event\ndef on_mouse_press(x, y, button, modifiers):\n a = (GLuint * 1)(...
[ 4, 2, 1, 0, 0 ]
[]
[]
[ "glreadpixels", "graphics", "opengl", "pyglet", "python" ]
stackoverflow_0000367684_glreadpixels_graphics_opengl_pyglet_python.txt
Q: Is there a way to make Mercurial give me a more verbose error message? I'm having trouble with my hooks running on a remote server while the Mercurial process is running locally. The error message is not very informative, but I'm pretty sure it's a Python path issue. I get the error when I try to commit a changese...
Is there a way to make Mercurial give me a more verbose error message?
I'm having trouble with my hooks running on a remote server while the Mercurial process is running locally. The error message is not very informative, but I'm pretty sure it's a Python path issue. I get the error when I try to commit a changeset. Is there anyway to get a complete stack trace? None of the following outp...
[ "Modify your hook script to catch exceptions (wrap it in a try...except block) and within the except clause, use the traceback module to format a full-length traceback and write it out to stderr/stdout?\n" ]
[ 1 ]
[]
[]
[ "mercurial", "python" ]
stackoverflow_0004122392_mercurial_python.txt
Q: If users are uploading images, and I need to do a lot of resizing/uploading, how should I set up my queue? When the user POSTS to my server, should I store the picture in the body of the queue, and then have the "worker" servers pull it out and resize/upload to S3? The reason I'm using a queue is because resizing/...
If users are uploading images, and I need to do a lot of resizing/uploading, how should I set up my queue?
When the user POSTS to my server, should I store the picture in the body of the queue, and then have the "worker" servers pull it out and resize/upload to S3? The reason I'm using a queue is because resizing/uploading 20 images to S3 takes a long time.
[ "Amazon's Simple Queue Service may be used to maintain communication between your worker and frontend servers, but keep in mind that it only supports messages up to 64kb, meaning it won't be possible to keep the images in the queue. This is probably best, filesystems are designed to maintain large files, queue imp...
[ 1 ]
[]
[]
[ "amazon_s3", "data_structures", "distributed", "python", "queue" ]
stackoverflow_0004122504_amazon_s3_data_structures_distributed_python_queue.txt
Q: Displaying list in Java as elegant as in Python In Python it is pretty easy to display an iterable as comma separated list: >>> iterable = ["a", "b", "c"] >>> ", ".join(iterable) 'a, b, c' Is there a Java way that comes close to this conciseness? (Notice that there is no "," at the end.) A: Here are the version...
Displaying list in Java as elegant as in Python
In Python it is pretty easy to display an iterable as comma separated list: >>> iterable = ["a", "b", "c"] >>> ", ".join(iterable) 'a, b, c' Is there a Java way that comes close to this conciseness? (Notice that there is no "," at the end.)
[ "Here are the versions using Guava and Commons / Lang that Michael referred to:\nList<String> items = Arrays.asList(\"a\",\"b\",\"c\");\n\n// Using Guava\nString guavaVersion = Joiner.on(\", \").join(items);\n\n// Using Commons / Lang\nString commonsLangVersion = StringUtils.join(items, \", \");\n\n// both versions...
[ 19, 5 ]
[]
[]
[ "iterator", "java", "join", "list", "python" ]
stackoverflow_0004122517_iterator_java_join_list_python.txt
Q: Apply a list of decorators to a callable? Given a list of decorator methods, how would one apply those to a callable? For example, since: @foo @bar def baz(): pass ...is the same as: def baz(): pass baz = foo(bar(baz))) ...one would assume that with a list of decorators ([foo, bar]) they could be applie...
Apply a list of decorators to a callable?
Given a list of decorator methods, how would one apply those to a callable? For example, since: @foo @bar def baz(): pass ...is the same as: def baz(): pass baz = foo(bar(baz))) ...one would assume that with a list of decorators ([foo, bar]) they could be applied to baz dynamically.
[ "With yet another decorator!\ndef yad(decorators):\n def decorator(f):\n for d in reversed(decorators):\n f = d(f)\n return f\n return decorator\n\nexample usage\n list_of_decorators = [foo, bar]\n\n@yad(list_of_decorators)\ndef foo():\n print 'foo'\n\nWithout the decorator syntax,...
[ 14, 2 ]
[]
[]
[ "decorator", "python" ]
stackoverflow_0004122815_decorator_python.txt
Q: Csv blank rows problem with Excel I have a csv file which contains rows from a sqlite3 database. I wrote the rows to the csv file using python. When I open the csv file with Ms Excel, a blank row appears below every row, but the file on notepad is fine(without any blanks). Does anyone know why this is happenning a...
Csv blank rows problem with Excel
I have a csv file which contains rows from a sqlite3 database. I wrote the rows to the csv file using python. When I open the csv file with Ms Excel, a blank row appears below every row, but the file on notepad is fine(without any blanks). Does anyone know why this is happenning and how I can fix it? Edit: I used the s...
[ "You're using open('file.csv', 'w')--try open('file.csv', 'wb'). \nThe Python csv module requires output files be opened in binary mode. \n", "the first that comes into my mind (just an idea) is that you might have used \"\\r\\n\" as row delimiter (which is shown as one linebrak in notepad) but excel expects to g...
[ 34, 0 ]
[]
[]
[ "csv", "excel", "python" ]
stackoverflow_0004122794_csv_excel_python.txt
Q: why "return 100 if i < 10 else pass" is not valid in python? All; def foo(i): return 100 if i < 10 else pass return 200 if i < 20 else pass return 1 Why this not works in python? I suppose this code may works same as: def foo(i): if i < 10: return 100 elif i < 20: return 200 ...
why "return 100 if i < 10 else pass" is not valid in python?
All; def foo(i): return 100 if i < 10 else pass return 200 if i < 20 else pass return 1 Why this not works in python? I suppose this code may works same as: def foo(i): if i < 10: return 100 elif i < 20: return 200 else: return 1 Thanks!
[ "In the documentation you will see that the \"ternary operator\" should be like this:\nconditional_expression ::= or_test [\"if\" or_test \"else\" expression]\nexpression ::= conditional_expression | lambda_expr\n\nand pass is a statement not an expression\n", "\nreturn 100 if i < 10 else pass\n\nyo...
[ 19, 10, 10, 2, 0 ]
[]
[]
[ "if_statement", "python" ]
stackoverflow_0004122764_if_statement_python.txt
Q: Python regular expression: decimal part of float How can I accomplish the following transformations with a regular expression in Python? 0.44 -> 44 0.7867 -> 78 1.00 -> 100 A: Parse the input as a floating point number then multiply it by 100 and truncate to an integer: result = int(float(s) * 100) A: def twod...
Python regular expression: decimal part of float
How can I accomplish the following transformations with a regular expression in Python? 0.44 -> 44 0.7867 -> 78 1.00 -> 100
[ "Parse the input as a floating point number then multiply it by 100 and truncate to an integer:\nresult = int(float(s) * 100)\n\n", "def twodigitint(x):\n return int(100*float(x))\n\n(or use round instead of int if you really want 0.7867->79)\n", "How about *100 and convert to int\nt = lambda x: int (x*100)\n...
[ 6, 0, 0 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0004123094_python_regex.txt
Q: Getting the root (head) of a DiGraph in networkx (Python) I'm trying to use networkx to do some graph representation in a project, and I'm not sure how to do a few things that should be simple. I created a directed graph with a bunch of nodes and edges, such that there is only one root element in this graph. Now, ...
Getting the root (head) of a DiGraph in networkx (Python)
I'm trying to use networkx to do some graph representation in a project, and I'm not sure how to do a few things that should be simple. I created a directed graph with a bunch of nodes and edges, such that there is only one root element in this graph. Now, what I'd like to do is start at the root, and then iterate thro...
[ "If by having \"one root element\" you mean your directed graph is a rooted tree, then the root will be the only node with zero in-degree. \nYou can find that node in linear time (in the number of nodes) with:\nIn [1]: import networkx as nx\n\nIn [2]: G=nx.balanced_tree(2,3,create_using=nx.DiGraph()) # tree rooted...
[ 66 ]
[]
[]
[ "directed_graph", "networkx", "python" ]
stackoverflow_0004122390_directed_graph_networkx_python.txt
Q: Is there any function that returns the out edges of a node? I am using python with networkx package. I need to find the nodes connected to out edges of a given node. I know there is a function networkx.DiGraph.out_edges but it returns out edges for the entire graph. A: I'm not a networkx expert, but have you tri...
Is there any function that returns the out edges of a node?
I am using python with networkx package. I need to find the nodes connected to out edges of a given node. I know there is a function networkx.DiGraph.out_edges but it returns out edges for the entire graph.
[ "I'm not a networkx expert, but have you tried networkx.DiGraph.out_edges, specifying the source node?\n\nDiGraph.out_edges(nbunch=None, data=False)\n\nReturn a list of edges.\nEdges are returned as tuples with optional data in the order (node,\n neighbor, data).\n\nIf you just want the out edges for a single node...
[ 6, 6 ]
[]
[]
[ "networkx", "python" ]
stackoverflow_0002191687_networkx_python.txt
Q: Looping seems to not follow sequence I feel like I'm missing something obvious here! seq = {'a': ['1'], 'aa': ['2'], 'aaa': ['3'], 'aaaa': ['4'], 'aaaaa': ['5']} for s in seq: print(s) outputs: a aa aaaa aaaaa aaa Whereas surely it should output: a aa aaa aaaa aaaaa What's going wrong here? A: Dictionarie...
Looping seems to not follow sequence
I feel like I'm missing something obvious here! seq = {'a': ['1'], 'aa': ['2'], 'aaa': ['3'], 'aaaa': ['4'], 'aaaaa': ['5']} for s in seq: print(s) outputs: a aa aaaa aaaaa aaa Whereas surely it should output: a aa aaa aaaa aaaaa What's going wrong here?
[ "Dictionaries are not ordered. If you need to rely on the ordering, you need an OrderedDict - there's one in the collections module in Python 2.7, or you can use one of the many recipes around.\n", "Standard Python dictionaries are not ordered: there is no guarantee on which order the keys will be returned.\nIf y...
[ 15, 5, 1 ]
[]
[]
[ "dictionary", "for_loop", "list", "python" ]
stackoverflow_0004123266_dictionary_for_loop_list_python.txt
Q: How to open mutiple frames via thread in tkinter? I tried to open mutiple frames by mutiple threads. Here is my code. ''' This is the module for test and studying. Author:Roger Date: 2010/10/10 Python version: 2.6.5 ''' import threading, Tkinter class Application(Tkinter.Frame): def __init__(self, master=Non...
How to open mutiple frames via thread in tkinter?
I tried to open mutiple frames by mutiple threads. Here is my code. ''' This is the module for test and studying. Author:Roger Date: 2010/10/10 Python version: 2.6.5 ''' import threading, Tkinter class Application(Tkinter.Frame): def __init__(self, master=None): Tkinter.Frame.__init__(self, master) ...
[ "I don't think you can do what you want. Generally speaking, there's no need to run multiple frames and multiple event loops. You can have multiple frames within a single thread and within a single event loop.\n" ]
[ 1 ]
[]
[]
[ "python", "tkinter" ]
stackoverflow_0004123409_python_tkinter.txt
Q: lambda push to a list then invoking - output is not as expected All: def a(p): return p+1 def gen(func, k=100): l= [] for x in range(k): temp = ("%s_with_parameter_%s" %(func.__name__, x), lambda: func(x)) # maybe this will be more clear to explain my quetion: # i want to g...
lambda push to a list then invoking - output is not as expected
All: def a(p): return p+1 def gen(func, k=100): l= [] for x in range(k): temp = ("%s_with_parameter_%s" %(func.__name__, x), lambda: func(x)) # maybe this will be more clear to explain my quetion: # i want to get list/dict which can bind self-defined string and function together...
[ "As other answers have noted, the lambdas are using the last value of x because they're closed over it and so see any changes made to it. The trick is to bind them to the value.\nYou can do this by writing them as \nlambda x=x: func(x)\n\nThis binds the value of x that is current when the lambda is created to the d...
[ 6, 3, 2, 0, 0 ]
[]
[]
[ "lambda", "python" ]
stackoverflow_0004123174_lambda_python.txt
Q: python versions on winXP I asked this question on superuser, and got the tumbleweed badge for it (13 views in 10 days), so I figured here might be the right place. There are several versions of python installed in my windows machine. I want to be able to switch easily between the versions being used as default. I ...
python versions on winXP
I asked this question on superuser, and got the tumbleweed badge for it (13 views in 10 days), so I figured here might be the right place. There are several versions of python installed in my windows machine. I want to be able to switch easily between the versions being used as default. I experimented and used winexplo...
[ "If HKEY_CLASSES_ROOT\\.py is Python.File then you have to look into HKEY_CLASSES_ROOT\\Python.File\\shell. Then lookup the subkey named like its value, e.g. if the shell key has the value open go to HKEY_CLASSES_ROOT\\Python.File\\shell\\open. That's where the association is stored. If the shell key has no value, ...
[ 1 ]
[]
[]
[ "associations", "python", "windows" ]
stackoverflow_0004123009_associations_python_windows.txt
Q: searching a wsgi testing plugin in python i was wondering what you'r using to test your python wsgi apps and which one is the most updated and easiest to setup. im on appengine python and i would like to start writing tests for my handlers. i've see gaeunit and nose-gae and if there are some more out there and wha...
searching a wsgi testing plugin in python
i was wondering what you'r using to test your python wsgi apps and which one is the most updated and easiest to setup. im on appengine python and i would like to start writing tests for my handlers. i've see gaeunit and nose-gae and if there are some more out there and what you think about them.
[ "I use webtest with nose-gae. While it doesn't emulate javascript, it is a great way to exercise each handler in your app, and has nice support for forms too.\nFor more detail testing of each edge case, I would factor our utilities / model related logic from the handlers and write tests for those separately. But ...
[ 2 ]
[]
[]
[ "httpwebrequest", "python", "testing", "wsgi" ]
stackoverflow_0004124071_httpwebrequest_python_testing_wsgi.txt
Q: Python: multiple possible values for function arguments I've inherited some Python code that looks like this: name = 'London' code = '0.1' notes = 'Capital of England' ev = model.City(key=key, code=code, name=name or code, notes=notes) In the spirit of learning, I'd like to know what's going on with the name or c...
Python: multiple possible values for function arguments
I've inherited some Python code that looks like this: name = 'London' code = '0.1' notes = 'Capital of England' ev = model.City(key=key, code=code, name=name or code, notes=notes) In the spirit of learning, I'd like to know what's going on with the name or code argument. Is this saying 'Use name if it's not null, othe...
[ "Almost. It says use name if it does not evaluate to false. Things that evaluate to false include, but are not limited to:\n\nFalse\nempty sequences ((), [], \"\")\nempty mappings ({})\n0\nNone\n\nEdit Added the link provided by SilentGhost in his comment to the answer.\n", "In python, the or operator returns the...
[ 13, 7, 1, 1, 0, 0 ]
[]
[]
[ "boolean_expression", "python" ]
stackoverflow_0004124787_boolean_expression_python.txt
Q: Python serialize lexical closures? Is there a way to serialize a lexical closure in Python using the standard library? pickle and marshal appear not to work with lexical closures. I don't really care about the details of binary vs. string serialization, etc., it just has to work. For example: def foo(bar, baz) ...
Python serialize lexical closures?
Is there a way to serialize a lexical closure in Python using the standard library? pickle and marshal appear not to work with lexical closures. I don't really care about the details of binary vs. string serialization, etc., it just has to work. For example: def foo(bar, baz) : def closure(waldo) : retur...
[ "PiCloud has released an open-source (LGPL) pickler which can handle function closure and a whole lot more useful stuff. It can be used independently of their cloud computing infrastructure - it's just a normal pickler. The whole shebang is documented here, and you can download the code via 'pip install cloud'. A...
[ 20, 18, 1, 1, 0 ]
[]
[]
[ "closures", "python", "serialization" ]
stackoverflow_0000573569_closures_python_serialization.txt
Q: How do I get case-insensitive queries on non-ASCII with python and sqlite3? There are some obvious tips and resources about this, but I can't find any direct examples. http://www.sqlite.org/faq.html#q18 says one can override the NOCASE collation, and the like, lower, and upper functions. I've done so, in a Django ...
How do I get case-insensitive queries on non-ASCII with python and sqlite3?
There are some obvious tips and resources about this, but I can't find any direct examples. http://www.sqlite.org/faq.html#q18 says one can override the NOCASE collation, and the like, lower, and upper functions. I've done so, in a Django testcase, but in my test none of them are actually called. from django.test impor...
[ "It seems to work fine outside django:\nSo maybe you have a django problem? Are you sure the table fields were created using the NOCASE collation?\nimport sqlite3\n\ndef NOCASE(a, b):\n print 'comparing %r with %r...' % (a, b)\n return cmp(a.lower(), b.lower())\n\ncon = sqlite3.connect('')\n\ncur = con.cursor...
[ 2 ]
[]
[]
[ "django", "python", "sqlite", "unicode" ]
stackoverflow_0004124557_django_python_sqlite_unicode.txt
Q: python getpass encoding Imagine I have the following code: # -*- coding: utf-8 -*- from getpass import getpass #print u'Введите пароль!'.encode('cp866') passwd = getpass (u'Введите пароль!'.encode('cp866')) This is for asking user to enter his password in Windows console (thus encoding is 'cp866'). The u...
python getpass encoding
Imagine I have the following code: # -*- coding: utf-8 -*- from getpass import getpass #print u'Введите пароль!'.encode('cp866') passwd = getpass (u'Введите пароль!'.encode('cp866')) This is for asking user to enter his password in Windows console (thus encoding is 'cp866'). The user sees the following prompt...
[ "putch() might be doing its own translation from your ANSI codepage (cp1251) to your OEM codepage (cp866). Try encoding with cp1251 instead.\n", "The state of unicode is really embarassing in Python in my experience. From time to time I encounter these type of problems in several libraries suffering from UTF myop...
[ 1, 0 ]
[]
[]
[ "encoding", "python", "windows" ]
stackoverflow_0004124711_encoding_python_windows.txt
Q: How do I check if a module/class/methods has changed and log the changes? I am trying to compare two modules/classes/method and to find out if the class/method has have changed. We allow users to change classes/methods, and after processing, we make those changes persistent, without overwriting the older classes/...
How do I check if a module/class/methods has changed and log the changes?
I am trying to compare two modules/classes/method and to find out if the class/method has have changed. We allow users to change classes/methods, and after processing, we make those changes persistent, without overwriting the older classes/methods. However, before we commit the new classes, we need to establish if the...
[ "You should be using a version control program to help manage development. This is one of the specific d=features you get from vc program is the ability to track changes. You can do diffs between current source code and previous check-ins to test if there were any changes.\n", "\nif i have many methods, what i ...
[ 1, 0 ]
[]
[]
[ "code_analysis", "comparison", "python", "unit_testing" ]
stackoverflow_0004125282_code_analysis_comparison_python_unit_testing.txt
Q: Python: Permission issue when installing an egg Tried installing South sitewide with easy_install. However I'm having permission issues: drwxr-x--- 2 root root 4096 Nov 8 10:23 South-0.7.2-py2.6.egg-info I then tried installing it with pip but received the same results. I am assuming I could fix this by just...
Python: Permission issue when installing an egg
Tried installing South sitewide with easy_install. However I'm having permission issues: drwxr-x--- 2 root root 4096 Nov 8 10:23 South-0.7.2-py2.6.egg-info I then tried installing it with pip but received the same results. I am assuming I could fix this by just changing the permissions. However, am I doing someth...
[ "It could be your user and/or root have a specific umask which creates files with those permissions such as 0027.\n% umask\n027\n% sudo touch /tmp/foo\n% ls -l /tmp/foo\n-rw-r----- 1 root wheel 0 Nov 8 08:19 /tmp/foo\n% umask 002\n% touch /tmp/bar\n% ls -al /tmp/bar\n-rw-r--r-- 1 root wheel 0 Nov 8 08:23 /t...
[ 6 ]
[]
[]
[ "distribute", "egg", "python", "setuptools" ]
stackoverflow_0004125237_distribute_egg_python_setuptools.txt
Q: Django template instructions leave space Instructions like {% block %} and {% load %} leave empty newline after themselves. How can one turn off this feature ? A: Spaceless works. It doesn't remove space inside HTML tags within it (but that's a feature, so it doesn't remove all spaces in say a paragraph of text...
Django template instructions leave space
Instructions like {% block %} and {% load %} leave empty newline after themselves. How can one turn off this feature ?
[ "Spaceless works. It doesn't remove space inside HTML tags within it (but that's a feature, so it doesn't remove all spaces in say a paragraph of text). Do you have a new line before spaceless? Can you give a failing example, tell us your django version (not that it should be relevant?) \nE.g., I have code like...
[ 4, 2, 2 ]
[]
[]
[ "django", "python", "templates" ]
stackoverflow_0004122718_django_python_templates.txt
Q: Appending tuples to lists What's the proper syntax for adding a recomposed tuple to a list? For example, if I had two lists: >>> a = [(1,2,3),(4,5,6)] >>> b = [(0,0)] Then I would expect the following to work: >>> b.append((a[0][0],a[0,2])) Traceback (most recent call last): File "<stdin>", line 1, in <module> ...
Appending tuples to lists
What's the proper syntax for adding a recomposed tuple to a list? For example, if I had two lists: >>> a = [(1,2,3),(4,5,6)] >>> b = [(0,0)] Then I would expect the following to work: >>> b.append((a[0][0],a[0,2])) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: list indices must be...
[ "you have try to do this: \n(a[0][0],a[0,2])\n ^^^\n\nthis is like doing:\n(a[0][0],a[(0,2)])\n\nwhich like the error said : list indices must be integers, not tuple\nif i'm not mistaken, i think you wanted to do:\nb.append((a[0][0],a[0][2]))\n\n", "Your problem is this:\nb.append((a[0][0],a[0,2]))\n...
[ 4, 1, 1, 0 ]
[]
[]
[ "list", "python", "tuples" ]
stackoverflow_0004126227_list_python_tuples.txt
Q: Regular expression in python How i can write a regular expression for validate a "right Human Name": My definition of human name (in this case): I need validate Hispanic names: Something like Maria, John, jon, Andrés will be valid, but something like 'NNNNNatalia' doesn't I mean this is valid: Diego Diego A. Dieg...
Regular expression in python
How i can write a regular expression for validate a "right Human Name": My definition of human name (in this case): I need validate Hispanic names: Something like Maria, John, jon, Andrés will be valid, but something like 'NNNNNatalia' doesn't I mean this is valid: Diego Diego A. Diego A. Sanabria This is not valid...
[ "This is way beyond the scope of regular expressions. You'll need a Dictionary of names, and possibly an algorithm to check for things which aren't in your dictionary but are names (do some research into Markov Chains for a start). You'll then need some Natural Language Processing algorithms to parse the syntax for...
[ 6, 3 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0004126249_python_regex.txt
Q: Scheduling Tasks I run MAC OS X. So I have completed a python script that essentially parses a few sites online, and uploads a particular file to an online server. Essentially, I wish to run this script automatically from my computer about 20 times a day. Is there a solution to schedule this script to run at fi...
Scheduling Tasks
I run MAC OS X. So I have completed a python script that essentially parses a few sites online, and uploads a particular file to an online server. Essentially, I wish to run this script automatically from my computer about 20 times a day. Is there a solution to schedule this script to run at fixed time points everyd...
[ "The OS provides a tool called 'cron' that's for exactly this purpose. You shouldn't need to modify your script at all to make use of it. \nAt a terminal command prompt, type man cron for more info.\n", "You can check also launchd, it's the OS X replacement of cron (you can still use cron but it's kind of depreca...
[ 4, 1 ]
[]
[]
[ "python", "scheduled_tasks" ]
stackoverflow_0004126041_python_scheduled_tasks.txt
Q: python 2.7 __init__ behavior on self I have a python question that I'm sure is pretty simple - please feel free to disabuse me of any sort of bad practice while you're at it. I have the following code: class User(dict,BaseDBI): def __init__(self,uid=None,username=None): self['uid']=str(uuid()) ...
python 2.7 __init__ behavior on self
I have a python question that I'm sure is pretty simple - please feel free to disabuse me of any sort of bad practice while you're at it. I have the following code: class User(dict,BaseDBI): def __init__(self,uid=None,username=None): self['uid']=str(uuid()) if uid == None and username is not No...
[ "python variables are references. when you assign to self, you are replacing that reference but not altering the object which is returned by __init__.\nThe easiest thing may be to simply use the dict.update method to copy all key/value pairs into self. This should 'just work' since you're already inheriting from di...
[ 2, 0, 0 ]
[]
[]
[ "initialization", "python" ]
stackoverflow_0004126517_initialization_python.txt
Q: How to upload zope site on my ftp? Hey, I'd like to know how to upload my zope site on my ftp. I have a domain, and I like to upload it, like a upload normal files on my ftp. Thanks. A: You can upload zope the same way you would upload anything else, but it's not suitable for deploying on many shared webhosts a...
How to upload zope site on my ftp?
Hey, I'd like to know how to upload my zope site on my ftp. I have a domain, and I like to upload it, like a upload normal files on my ftp. Thanks.
[ "You can upload zope the same way you would upload anything else, but it's not suitable for deploying on many shared webhosts as many of them would not like you running the zope process due to the ammount of resources it can consume\nYou are best off trying to find a webhost that supports zope or to use a VPS\n" ]
[ 2 ]
[]
[]
[ "frameworks", "python", "zope", "zope.interface" ]
stackoverflow_0004126247_frameworks_python_zope_zope.interface.txt
Q: Multiplying transformation matrix to a vector I have done a series of transformations using glMultMatrix. How do I multiply a vector (nX, nY, nZ, 1) to the matrix I have from the transformation? How do I get that matrix to multiply with a vector? pyglet.gl.lib.GLException: invalid operation I am getting above e...
Multiplying transformation matrix to a vector
I have done a series of transformations using glMultMatrix. How do I multiply a vector (nX, nY, nZ, 1) to the matrix I have from the transformation? How do I get that matrix to multiply with a vector? pyglet.gl.lib.GLException: invalid operation I am getting above error if I use glMultMatrix. I need to call this mul...
[ "If I'm reading your question right, you want something that returns the result of a Matrix-vector product between the current ModelView/Projection matrix and a vector you specify.\nIn that case, OpenGL can't do the multiplication for you. Instead, you need to extract the current matrix and do the multiplication yo...
[ 0 ]
[]
[]
[ "opengl", "python" ]
stackoverflow_0004102872_opengl_python.txt
Q: Simple python re lookahead help I have three sample twiki names: names = [ "JohnDoe", "JaneMcAdams", "BillyBobThorton" ] I want to get the following back: * John Doe * Jane McAdams * BillyBob Thorton Now I have this which busts them apart on the cap (That's a good thing). re.findall('[A-Z][^A-Z]*', nam...
Simple python re lookahead help
I have three sample twiki names: names = [ "JohnDoe", "JaneMcAdams", "BillyBobThorton" ] I want to get the following back: * John Doe * Jane McAdams * BillyBob Thorton Now I have this which busts them apart on the cap (That's a good thing). re.findall('[A-Z][^A-Z]*', name) How do I ignore "Mc" as a split? ...
[ "I would recommend against using a regex here. I doubt Mc is the only name particle you need to match. Did you think about Mac, O, Van, Von, De? \nI suggest to break them as you say you currently do and build the first name and last name manually.\nBonus. Regex:\nre.findall('(?:Mc|Mac|O|Van|Von|De)?[A-Z][^A-Z]*', ...
[ 3 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0004126729_python_regex.txt
Q: Creating a list from a CSV file using Python I have a Python script so far that does what I it to... Opens the CSV Defined by the user, splits the file into different Predefined "pools" and remakes them again into their own files, with proper headers. My only problem is I want to change the Pool list from a static...
Creating a list from a CSV file using Python
I have a Python script so far that does what I it to... Opens the CSV Defined by the user, splits the file into different Predefined "pools" and remakes them again into their own files, with proper headers. My only problem is I want to change the Pool list from a static to a variable; and having some issues. The pool ...
[ "If I am understanding correctly what you want to achieve here this could be as solution:\nimport csv\nimport time\nimport tkFileDialog\n\nfilename = tkFileDialog.askopenfilename(defaultextension = \".csv\")\n\nreader = csv.reader(open(filename, \"rb\"), delimiter = ',')\n\nheadders = reader.next()\n\npool_dict = {...
[ 4, 2, 0 ]
[]
[]
[ "csv", "python" ]
stackoverflow_0004126423_csv_python.txt
Q: (Python) gaierror: [Errno 11004] getaddrinfo failed from Tkinter import * import tkMessageBox, socket root = Tk() root.title("pynet v1.0") root.config(bg='black') root.resizable(0,0) text = Text() text1 = Text() text1.config(width=15, height=1) text1.config(bg="white", fg="red") text1.pack() def Info(): ...
(Python) gaierror: [Errno 11004] getaddrinfo failed
from Tkinter import * import tkMessageBox, socket root = Tk() root.title("pynet v1.0") root.config(bg='black') root.resizable(0,0) text = Text() text1 = Text() text1.config(width=15, height=1) text1.config(bg="white", fg="red") text1.pack() def Info(): targetip = socket.gethostbyname_ex(text1.get("1.0", ...
[ "My guess is because you are using a hostname that has a trailing newline. At the time I write this answer, your code shows:\ndef Info():\n targetip = socket.gethostbyname_ex(text1.get(\"1.0\", END))\n text.insert(END, targetip)\n\nWhen you use the index END you get the extra newline that is added by the text...
[ 2, 1 ]
[]
[]
[ "python", "tkinter" ]
stackoverflow_0004126023_python_tkinter.txt
Q: Ambiguous tab completion not working in iPython on Windows I am running IPython on Windows 7 x64 with pyreadline installed. If I start a new session and type: import numpy nu<TAB> Then nu autocompletes to numpy. However, if I start a new session and try this: import numpy n<TAB> Then nothing happens. I would ...
Ambiguous tab completion not working in iPython on Windows
I am running IPython on Windows 7 x64 with pyreadline installed. If I start a new session and type: import numpy nu<TAB> Then nu autocompletes to numpy. However, if I start a new session and try this: import numpy n<TAB> Then nothing happens. I would expect it to cycle through all of the possible completions. I'm...
[ "You have to copy config file for pyreadline to your HOME folder (C:\\Users\\< username >).\nOpen Command line and execute that:\ncopy \"C:\\Program Files (x86)\\Python26\\Lib\\site-packages\\pyreadline\\configuration\\pyreadlineconfig.ini\" %HOMEPATH%\n\n", "Just installed python 2.6 and numpy, ipython and so on...
[ 9, 6 ]
[]
[]
[ "ipython", "python", "tab_completion" ]
stackoverflow_0003771837_ipython_python_tab_completion.txt
Q: [Python]How to deal with a string ending with one backslash? I'm getting some content from Twitter API, and I have a little problem, indeed I sometimes get a tweet ending with only one backslash. More precisely, I'm using simplejson to parse Twitter stream. How can I escape this backslash ? From what I have read, ...
[Python]How to deal with a string ending with one backslash?
I'm getting some content from Twitter API, and I have a little problem, indeed I sometimes get a tweet ending with only one backslash. More precisely, I'm using simplejson to parse Twitter stream. How can I escape this backslash ? From what I have read, such raw string shouldn't exist ... Even if I add one backslash (w...
[ "Prepending the string with r (stands for \"raw\") will escape all characters inside the string. For example:\nprint r'\\b\\n\\\\'\nwill output\n\\b\\n\\\\\nHave I understood the question correctly?\n", "I guess you are looking a method similar to stripslashes in PHP. So, here you go:\nPython version of PHP's str...
[ 1, 1, 1, 0 ]
[]
[]
[ "backslash", "escaping", "python", "string" ]
stackoverflow_0004121751_backslash_escaping_python_string.txt
Q: Solving statistics question using Python I'm really lost. How can I approach this problem? Beginning with $1 of capital, you choose a fixed proportion p of your capital to bet on a fair coin tossed repeatedly for 1000 times. Your returns is doubled if the toss lands head and you lose your it lands tail. For exampl...
Solving statistics question using Python
I'm really lost. How can I approach this problem? Beginning with $1 of capital, you choose a fixed proportion p of your capital to bet on a fair coin tossed repeatedly for 1000 times. Your returns is doubled if the toss lands head and you lose your it lands tail. For example, if p=0.25 and for the first toss your bet $...
[ "Do you have any experience with python? If not, read the tutorial.\nTo solve your problem, you should first write down some kind of pseudo-code. Your first attempt can be very general, and then you should go into more detail about specific operations, until in the end you actually go and implement it. Think about ...
[ 1, 1, 0 ]
[]
[]
[ "python", "statistics" ]
stackoverflow_0004124568_python_statistics.txt
Q: Sandboxed AND stackless python? I need a scripting language for describing very complicated workflows. These workflows need to be paused whenever user input is required, and resumed after it is given (could be months later). Seems like serializable continuations from Stackless would be a good fit. Users also ne...
Sandboxed AND stackless python?
I need a scripting language for describing very complicated workflows. These workflows need to be paused whenever user input is required, and resumed after it is given (could be months later). Seems like serializable continuations from Stackless would be a good fit. Users also need to be able to edit the workflows t...
[ "Your serialization requirement will be difficult in most languages with native co-routine libraries. You might need to implement co-routines in another way to allow for object graph serialization. \nLua has the Pluto library, which CAN persist threads (co-routines): http://lua-users.org/wiki/PlutoLibrary\nAs far a...
[ 2 ]
[]
[]
[ "continuations", "jit", "pypy", "python", "python_stackless" ]
stackoverflow_0004126863_continuations_jit_pypy_python_python_stackless.txt
Q: WTforms: Error "field not present" Hi I have a form class which looks like below:- class UserCreateForm(wtf.Form): name=wtf.TextField('Name',validators=[validators.Required(),username_check]) email=wtf.TextField('Email') userimage=wtf.FileField(u'Upload Image',validators=[checkfile]) The custom valid...
WTforms: Error "field not present"
Hi I have a form class which looks like below:- class UserCreateForm(wtf.Form): name=wtf.TextField('Name',validators=[validators.Required(),username_check]) email=wtf.TextField('Email') userimage=wtf.FileField(u'Upload Image',validators=[checkfile]) The custom validator function " checkfile" looks like th...
[ "Solved this finally , had to replace field.data in the validator with field.file and then access its attributes using field.file.filename.\n" ]
[ 7 ]
[]
[]
[ "flask", "flask_wtforms", "forms", "python", "wtforms" ]
stackoverflow_0004058308_flask_flask_wtforms_forms_python_wtforms.txt
Q: Python import module results in NameError I'm having a module import issue. using python 2.6 on ubuntu 10.10 I have a class that subclasses the daemon at http://www.jejik.com/articles/2007/02/a_simple_unix_linux_daemon_in_python/ . I created a python package with a module containing code that imports some models ...
Python import module results in NameError
I'm having a module import issue. using python 2.6 on ubuntu 10.10 I have a class that subclasses the daemon at http://www.jejik.com/articles/2007/02/a_simple_unix_linux_daemon_in_python/ . I created a python package with a module containing code that imports some models from a django project. The code works when used...
[ "With from my_module.core.daemon import Daemon you do not actually bind the loaded module my_module to a variable. Use import my_module\njust before or after your other imports to do that.\nExplained in code:\n>>> from xml import dom\n>>> xml\nTraceback (most recent call last):\n File \"<stdin>\", line 1, in <modu...
[ 0, 0, 0 ]
[]
[]
[ "django", "import", "module", "nameerror", "python" ]
stackoverflow_0003992175_django_import_module_nameerror_python.txt
Q: Transforming the string representation of a dictionary into a real dictionary I am working on an image processing script. I need to let the user specify how to remap some classes in an image via a text file. The syntax in this file should be simple and self-evident. What I thought of doing is to get the user to wr...
Transforming the string representation of a dictionary into a real dictionary
I am working on an image processing script. I need to let the user specify how to remap some classes in an image via a text file. The syntax in this file should be simple and self-evident. What I thought of doing is to get the user to write the string version of a dictionary: 125:126, 126:126, 127:128, 128:128 and the...
[ "You can use ast.literal_eval:\n>>> import ast\n>>> ast.literal_eval('{' + s + '}')\n{128: 128, 125: 126, 126: 126, 127: 128}\n\nNote that this requires Python 2.6 or newer.\nAn alternative is to split the string on ',' and then split each piece on ':' and construct a dict from that:\n>>> dict(map(int, x.split(':')...
[ 11 ]
[]
[]
[ "dictionary", "numpy", "python", "string" ]
stackoverflow_0004127344_dictionary_numpy_python_string.txt
Q: Gtk IconView select multiple without Ctrl? Is it possible to make Gtk IconView (in pygtk) allow selection of multiple icons without the Ctrl key being pressed? I basically want the behaviour of Ctrl being held down even when it is not held down. A: Overriding this kind of behaviour might confuse users. But if y...
Gtk IconView select multiple without Ctrl?
Is it possible to make Gtk IconView (in pygtk) allow selection of multiple icons without the Ctrl key being pressed? I basically want the behaviour of Ctrl being held down even when it is not held down.
[ "Overriding this kind of behaviour might confuse users. But if you really want to, there are two possibilities that I can see:\nEither make the IconView believe Ctrl is always pressed:\ndef force_ctrl(iv, ev): ev.state |= gtk.gdk.CONTROL_MASK\niconview.connect('key-press-event', force_ctrl)\niconview.connect('butto...
[ 2 ]
[]
[]
[ "gtk", "pygtk", "python" ]
stackoverflow_0004120097_gtk_pygtk_python.txt
Q: How do I get Cyrillic in the output, Python? how do I get Cyrillic instead of u'... the code is like this def openfile(filename): with codecs.open(filename, encoding="utf-8") as F: raw = F.read() do stuff... print some_text prints >>>[u'.', u',', u':', u'\u0432', u'<', u'>', u'(', u')', u'\u0437', u...
How do I get Cyrillic in the output, Python?
how do I get Cyrillic instead of u'... the code is like this def openfile(filename): with codecs.open(filename, encoding="utf-8") as F: raw = F.read() do stuff... print some_text prints >>>[u'.', u',', u':', u'\u0432', u'<', u'>', u'(', u')', u'\u0437', u'\u0456']
[ "It looks like some_text is a list of unicode objects. When you print such a list, it prints the reprs of the elements inside the list. So instead try:\nprint(u''.join(some_text))\n\nThe join method concatenates the elements of some_text, with an empty space, u'', in between the elements. The result is one unicode ...
[ 4, 3, 0 ]
[]
[]
[ "encode", "python", "utf_8" ]
stackoverflow_0004127496_encode_python_utf_8.txt
Q: Genshi: if/else How do I do a simple if/else in the Genshi templating language? I've found this ticket, which seems to suggest that Genshi doesn't support if/else, but it doesn't really explain what it supports instead. I basically just want something like this: <py:if test="c.row.currency"> ${c.row.currency.u...
Genshi: if/else
How do I do a simple if/else in the Genshi templating language? I've found this ticket, which seems to suggest that Genshi doesn't support if/else, but it doesn't really explain what it supports instead. I basically just want something like this: <py:if test="c.row.currency"> ${c.row.currency.upper()} <py:else> ...
[ "Currently, you can not if do else constructs in Genshi, and as far as I'm aware, there are no plans to add it. Instead, like you mentioned, use py:choose. The following is how you use py:choose as a type of if/else construct:\n<py:choose ...>\n <py:when test=\"...\">\n ${c.row.currency.upper()}\n </py:when>\n...
[ 8 ]
[]
[]
[ "genshi", "pylons", "python" ]
stackoverflow_0004127626_genshi_pylons_python.txt
Q: Is there any possible point to reloading a Python module immediately? Is there any conceivable point to reloading these modules immediately after importing them? This is the code that I was reviewing which made me wonder: import time import sys import os import string import pp import numpy import nrrd reload(nrr...
Is there any possible point to reloading a Python module immediately?
Is there any conceivable point to reloading these modules immediately after importing them? This is the code that I was reviewing which made me wonder: import time import sys import os import string import pp import numpy import nrrd reload(nrrd) import smooth as sm reload(sm) import TensorEval2C as tensPP reload(tens...
[ "It is possible that this does cause something to happen; the obvious example is side-effects that happen on import. For instance, a module could log to a file the time and date of every time it is imported.\nThere is probably no good reason for this, however.\n", "I note that the standard modules are just import...
[ 6, 6, 1, 0 ]
[]
[]
[ "import", "python", "reload" ]
stackoverflow_0004127647_import_python_reload.txt
Q: How do I exclude files from a search that may be in use or being copied to in python? I'm new to python so this might end up having a simple solution. At my house, I have 3 computers that are relevant to this situation: - File Server (linux) - My main PC (windows) - Girlfriend's MacBook Pro My file server is runn...
How do I exclude files from a search that may be in use or being copied to in python?
I'm new to python so this might end up having a simple solution. At my house, I have 3 computers that are relevant to this situation: - File Server (linux) - My main PC (windows) - Girlfriend's MacBook Pro My file server is running ubuntu and samba. I've installed python 3.1 and I've written my code in 3.1. I've creat...
[ "You can try taking an exclusive write lock on the file before moving it. This can be done with the fcntl module:\nhttp://docs.python.org/library/fcntl.html\nBarring that, you can us the lsof utility to see files which the system has open. That requires more drudgery. \nNote that os.rename() will work on the same f...
[ 0, 0, 0 ]
[]
[]
[ "linux", "macos", "python", "samba", "windows" ]
stackoverflow_0004110666_linux_macos_python_samba_windows.txt
Q: re.findall() - additional criteria I have a part number like this: part_number = '18-TX25-37 DMDFC PS' When I do >>> re.findall(r'\w+', part_number) ... ['18', 'TX25', '37', 'DMDFC', 'PS'] Some part numbers may have a dot such as '18-TX25-37.25 DMDFC PS' and my regex returns '37', '25' etc. How can I make it no...
re.findall() - additional criteria
I have a part number like this: part_number = '18-TX25-37 DMDFC PS' When I do >>> re.findall(r'\w+', part_number) ... ['18', 'TX25', '37', 'DMDFC', 'PS'] Some part numbers may have a dot such as '18-TX25-37.25 DMDFC PS' and my regex returns '37', '25' etc. How can I make it not to split at the dot and return '37.25'...
[ "\\w is a character class, which is a shortcut for [a-zA-Z0-9_] (that is: letters, digits, and underscores). In other words, your regular expression is searching for all groups of one or more (letters, digits, or underscores). Naturally then, when the regex engine sees . in the string it doesn't include it as part ...
[ 3 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0004128332_python_regex.txt
Q: Most efficient way to print strings in Python? So according to the optimization tips at http://wiki.python.org/moin/PythonSpeed/PerformanceTips , joining strings should be done with out = "<html>%(head)s%(prologue)s%(query)s%(tail)s</html>" % locals() and not out = "<html>" + head + prologue + query + tail + "<...
Most efficient way to print strings in Python?
So according to the optimization tips at http://wiki.python.org/moin/PythonSpeed/PerformanceTips , joining strings should be done with out = "<html>%(head)s%(prologue)s%(query)s%(tail)s</html>" % locals() and not out = "<html>" + head + prologue + query + tail + "</html>" My question is, is this the same for if I wa...
[ "String concatenation has been improved for the (fairly common) case where there is only one reference to the string. See PyString_ConcatAndDel in stringobject.c\nSo usually concatenation in a loop is linear since there is only ever one reference of the string\nHere is a simple experiment to demonstrate the behavio...
[ 6, 5, 2 ]
[]
[]
[ "performance", "printing", "profiling", "python", "string" ]
stackoverflow_0004128392_performance_printing_profiling_python_string.txt
Q: Google Protocol Buffers, HDF5, NumPy comparison (transferring data) I need help to make decision. I have a need to transfer some data in my application and have to make a choice between these 3 technologies. I've read about all technologies a little bit (tutorials, documentation) but still can't decide... How do t...
Google Protocol Buffers, HDF5, NumPy comparison (transferring data)
I need help to make decision. I have a need to transfer some data in my application and have to make a choice between these 3 technologies. I've read about all technologies a little bit (tutorials, documentation) but still can't decide... How do they compare? I need support of metadata (capability to receive file and r...
[ "There does seem to be a slight contradiction in your question - you want to be able to store Python objects, but you also want C/C++ access. I think that regardless of which choice you go with, you will need to convert your fancy Python data structures into more static structures such as arrays.\nIf you need cros...
[ 13, 4 ]
[]
[]
[ "hdf5", "numpy", "python" ]
stackoverflow_0004125855_hdf5_numpy_python.txt
Q: python izip which cycles through all iterables until the longest finishes This turned out not to be a trivial task for me and I couldn't find any receipt so maybe you can point me to one or you have a ready, proper and well-tuned solution for that? Proper meaning works also for iterators that do not know own lengt...
python izip which cycles through all iterables until the longest finishes
This turned out not to be a trivial task for me and I couldn't find any receipt so maybe you can point me to one or you have a ready, proper and well-tuned solution for that? Proper meaning works also for iterators that do not know own length (without __len__) and works for exhaustible iterators (e.g. chained iterators...
[ "A simple approach which might work for you, depending on your requirement is:\nimport itertools\n\ndef izip_cycle(*colls):\n maxlen = max(len(c) if hasattr(c,'__len__') else 0 for c in colls)\n g = itertools.izip(*[itertools.cycle(c) for c in colls])\n\n for _ in range(maxlen):\n yield g.next()\n\n...
[ 1, 1, 0 ]
[]
[]
[ "iterator", "python" ]
stackoverflow_0004125825_iterator_python.txt
Q: Sqlite statement syntax error What's wrong with this SQL statement? I'm getting a SQLError: near "?": syntax error. 'select all counts from table as table where offset in ?' The ? has a binding of numbers with a list in it: (1,2,4). A: Just guessing that the language you're using is Python... No matter the lang...
Sqlite statement syntax error
What's wrong with this SQL statement? I'm getting a SQLError: near "?": syntax error. 'select all counts from table as table where offset in ?' The ? has a binding of numbers with a list in it: (1,2,4).
[ "Just guessing that the language you're using is Python...\nNo matter the language the principle is the same:\nYou need to dynamically create the appropriate number of placeholders.\n>>> import sqlite3\n>>> conn = sqlite3.connect(':memory:')\n>>> c = conn.cursor()\n>>> c.execute('create table test (id int)')\n<sqli...
[ 1, 1, 0 ]
[]
[]
[ "python", "sqlite" ]
stackoverflow_0004127993_python_sqlite.txt
Q: User-defined text fields in django admin Django (and database) newbie here. I'm trying to figure out a way to enable the creation of n custom text fields for a table (let's call it Book) using the admin interface. I would like a way for the user to define new text fields through the admin interface (instead of def...
User-defined text fields in django admin
Django (and database) newbie here. I'm trying to figure out a way to enable the creation of n custom text fields for a table (let's call it Book) using the admin interface. I would like a way for the user to define new text fields through the admin interface (instead of defining fields like CustomField1, CustomField2, ...
[ "Where you might run into problems is because Django will not recreate tables or columns based on changing model declarations. This means you're unable to add fields to a table at run-time without running the generated sql on your database manually. What you'll need, instead, is a way of defining custom fields, and...
[ 2, 0 ]
[]
[]
[ "database", "database_design", "django", "python", "relational_database" ]
stackoverflow_0004128454_database_database_design_django_python_relational_database.txt
Q: Python: Adding excel file to an access database I am using pyodbc to access an access (accdb) file. I want to add an excel workbook into the access database programatically, but cannot find an API to do so. Here is my current code: import pyodbc DBFile = r'C:\Documents and Settings\IA.accdb' conn = pyodbc.connect(...
Python: Adding excel file to an access database
I am using pyodbc to access an access (accdb) file. I want to add an excel workbook into the access database programatically, but cannot find an API to do so. Here is my current code: import pyodbc DBFile = r'C:\Documents and Settings\IA.accdb' conn = pyodbc.connect('DRIVER={Microsoft Access Driver (*.mdb, *.accdb)};DB...
[ "It seems like you got to a certain point and gave up.\nDon't give up! :-)\nYou've made the connection to the Excel spreadsheet, now you need to read it*.\ncurs1 = conn1.cursor()\n# the following returns list of tuples\nexcel_results = curs1.execute('select [a_column]\n from [Sheet1$]'...
[ 3 ]
[]
[]
[ "excel", "ms_access", "pyodbc", "python" ]
stackoverflow_0004128334_excel_ms_access_pyodbc_python.txt
Q: Difficulties with distribute - am new to Python packaging and am trying to work out which flags I need to get something uploaded properly into PyPi. distribute seems to building things them deleting them straight away. How do I stop that from happening? Here is the traceback: tim@falcon:~/Code/slate$ python setup....
Difficulties with distribute -
am new to Python packaging and am trying to work out which flags I need to get something uploaded properly into PyPi. distribute seems to building things them deleting them straight away. How do I stop that from happening? Here is the traceback: tim@falcon:~/Code/slate$ python setup.py sdist running sdist running egg_i...
[ "This message seems to indicate that the script removed a temporary directory created to do your package... The .tar.gz file is not removed. Check your dist directory for it.\nTo upload you can probably use distutils-documented way:\npython setup.py sdist upload\n\nSome good reads:\n\nDistutils -- Official document...
[ 2 ]
[]
[]
[ "distutils", "python" ]
stackoverflow_0004128914_distutils_python.txt
Q: How to build/compile C++, Java and Python projects? Let's say I have a bunch of small targets in different programming languages (C++, Java, Python, etc), with inter programming language dependencies (Java project depends on a C++, Python depends on C++). How can one build/compile them? I tried scons and more rece...
How to build/compile C++, Java and Python projects?
Let's say I have a bunch of small targets in different programming languages (C++, Java, Python, etc), with inter programming language dependencies (Java project depends on a C++, Python depends on C++). How can one build/compile them? I tried scons and more recently gyp. I don't remember what issues I had with scons. ...
[ "I would pick one of the more configurable build tools like ant or maven, as a starting point.\nAnt is highly configurable, and worst case you can use it to exec another build process (like, make, or whatever you normally use for C++).\nMaven also has a number of plugins natively supported for other languages besid...
[ 2, 0 ]
[]
[]
[ "build", "c++", "java", "python", "scons" ]
stackoverflow_0004128555_build_c++_java_python_scons.txt
Q: Finding which array contributes the maximum value for classification Given 2 2x2 Numpy arrays, each element having a value between 0 and 1, I would like to find the one array of the 2 that has the maximum value, and do that comparison element-wise. For example, given: A = [[.6 .2] [.3 .4]] and B = [[.4 .5] [.7 .1]...
Finding which array contributes the maximum value for classification
Given 2 2x2 Numpy arrays, each element having a value between 0 and 1, I would like to find the one array of the 2 that has the maximum value, and do that comparison element-wise. For example, given: A = [[.6 .2] [.3 .4]] and B = [[.4 .5] [.7 .1]], I would like something like: [[A B] [A B]] back. Ideally, the output wi...
[ "If you have a combined array of 10 of your 2x2 matrices like the one randomly generated by\na = numpy.random.randn(10, 2, 2)\n\nyou can get the desired indices by\na.argmax(axis=0)\n\n" ]
[ 3 ]
[]
[]
[ "numpy", "python" ]
stackoverflow_0004129149_numpy_python.txt
Q: Is there a Django App/Plugin that will do notifications for me? Such as Twitter's drop down notifications whenever something happens. Whenever a user finishes registration, the notification will drop down and say, "Thank you" A: Would django flash message be sufficient for you? A: Why not use django.contrib.me...
Is there a Django App/Plugin that will do notifications for me?
Such as Twitter's drop down notifications whenever something happens. Whenever a user finishes registration, the notification will drop down and say, "Thank you"
[ "Would django flash message be sufficient for you?\n", "Why not use django.contrib.messages if you're using Django >= 1.2?\nRead this Django Advent article on django.contrib.messages. It seems like it should do what you want.\n" ]
[ 1, 0 ]
[]
[]
[ "django", "javascript", "plugins", "python" ]
stackoverflow_0004129104_django_javascript_plugins_python.txt
Q: How to create a raw socket(customised TCP header) using dpkt? i m writing a code for port scanner so i need to send a raw packet. i searched and found out that using dpkt library would be better but i didnt find any documentation that would help. So please anyone could help may explaining how to create a packet wi...
How to create a raw socket(customised TCP header) using dpkt?
i m writing a code for port scanner so i need to send a raw packet. i searched and found out that using dpkt library would be better but i didnt find any documentation that would help. So please anyone could help may explaining how to create a packet with customized TCP header i.e set the flags of tcp header as require...
[ "Well, this is a bit old but I'll answer anyway since I've been looking to do the same. The dpkt documentation is basically non-existant. The only thing they give you is some samples and Jon Oberheide, the co-developer, wrote some tutorials for it. So if you want to use dpkt it isn't difficult you can figure it ...
[ 1 ]
[]
[]
[ "packet", "python" ]
stackoverflow_0004033776_packet_python.txt
Q: How can I remote debug a Python script running on Linux from Windows using PyScripter? I have a Python script (running Python v2.6 or v2.7) that runs on Linux and also AIX. I'd like to be able to debug this script from Windows. I'd like to use PyScripter if possible. If it is not possible to use PyScripter, what ...
How can I remote debug a Python script running on Linux from Windows using PyScripter?
I have a Python script (running Python v2.6 or v2.7) that runs on Linux and also AIX. I'd like to be able to debug this script from Windows. I'd like to use PyScripter if possible. If it is not possible to use PyScripter, what other combination of IDE + debugger would you recommend? I would prefer something easy to s...
[ "Currently it is not possible to debug a script on a remote machine from PyScripter. This is a planned feature thought. You may be able to use winpdb. \nUpdate: PyScripter 3.5 supports running/debugging scripts running remotely at Linux and Windows machines. Please have a look at this blog post for details. Ha...
[ 1 ]
[]
[]
[ "debugging", "pyscripter", "python", "remote_debugging" ]
stackoverflow_0004127790_debugging_pyscripter_python_remote_debugging.txt
Q: PyScripter - cannot termiate Run with KeyboardInterrupt I write alot of small apps where I use try: print "always does this until I Ctrl+C" Except KeyboardInterrupt: print "finish program" I've just began to move away from using IDLE and booted up PyScripter. However CTRL+C no longer works. Is it possible...
PyScripter - cannot termiate Run with KeyboardInterrupt
I write alot of small apps where I use try: print "always does this until I Ctrl+C" Except KeyboardInterrupt: print "finish program" I've just began to move away from using IDLE and booted up PyScripter. However CTRL+C no longer works. Is it possible to still send in a KeyboardInterrupt while using the built-...
[ "In PyScripter if you just want to terminate a running program you can always re-initialize the remote engine:\n\nApplication Run Menu > Python Engine > Reinitialize Python Engine or \nInterpreter context menu > Python Engine > Reinitialize Python Engine or\nKeyboard shortcut CTRL-F2\n\nSource, Psyscripter Author\n...
[ 6, 0 ]
[]
[]
[ "keyboardinterrupt", "pyscripter", "python" ]
stackoverflow_0002246885_keyboardinterrupt_pyscripter_python.txt
Q: Store user's name on Google App Engine, without calling get_current_user every time? I have a Google App Engine site, with multiple pages that are rendered using templates. I'd like to have a hello, user!-type greeting on the header of every page. I can call users.get_current_user().nickname()(or something like) o...
Store user's name on Google App Engine, without calling get_current_user every time?
I have a Google App Engine site, with multiple pages that are rendered using templates. I'd like to have a hello, user!-type greeting on the header of every page. I can call users.get_current_user().nickname()(or something like) on every handler and add that to the template values dictionary, but I was wondering if the...
[ "I don't know of a built-in way to access that from a template, but I agree with you that I certainly wouldn't want to have to re-type the code in every handler.\nIf all your views are children of one main handler then you can stick the code in that main handler and be done with it, e.g.:\nclass BaseHandler(webapp....
[ 1 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0004129475_google_app_engine_python.txt
Q: Writing a "table" from Python3 How does one write both multiple strings and multiple variable outputs on one line in a file to output? I know that write() only accepts one argument, though ideally this is what I'm trying to achieve: write('Temperature is', X , 'and pressure is', Y) The result would be a table. C...
Writing a "table" from Python3
How does one write both multiple strings and multiple variable outputs on one line in a file to output? I know that write() only accepts one argument, though ideally this is what I'm trying to achieve: write('Temperature is', X , 'and pressure is', Y) The result would be a table. Can you help?
[ "write('Temperature is {0} and pressure is {1})'.format(X,Y))\n\nIf you want more control over the output you can do something like this:\nX = 12.3\nY = 1.23\nwrite('Temperature is {0:.1f} and pressure is {1:.2f})'.format(X,Y))\n# writes 'Temperature is 12.3 and pressure is 1.2'\n\nDocumentation and examples here: ...
[ 2, 2 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0004129624_python_python_3.x.txt
Q: Is this the correct way of doing/handling url rewrite in App Engine/ Python? I'm not sure if this is effective or not. It works, but sometimes i feel...weird about it. Can you please tell me if this is a good way or not? I threw the code on pastebin, because i think it's a bit too much to put here: http://pastebi...
Is this the correct way of doing/handling url rewrite in App Engine/ Python?
I'm not sure if this is effective or not. It works, but sometimes i feel...weird about it. Can you please tell me if this is a good way or not? I threw the code on pastebin, because i think it's a bit too much to put here: http://pastebin.com/662TiQLq EDIT I edited the title to make it more objective.
[ "I'm just guessing that the questioner is asking about creating a dictionary of functions in the __ init __ function of the handlers, and then using this dict in the \"get\" function to look up specific functions. If this is the question, then IMHO a clearer approach would be to set up separate handlers for each d...
[ 2 ]
[]
[]
[ "google_app_engine", "python", "url_rewriting" ]
stackoverflow_0004117051_google_app_engine_python_url_rewriting.txt
Q: Is there a DotNetOpenAuth equivalent that runs on a LAMP stack? I really love the way the StackExchange family of sites allow someone to log in using their OpenID or OAuth provider, which has been open-sourced as DotNetOpenAuth. This is absolutely wonderful, but I am unable to use it on a *AMP stack. Is there a...
Is there a DotNetOpenAuth equivalent that runs on a LAMP stack?
I really love the way the StackExchange family of sites allow someone to log in using their OpenID or OAuth provider, which has been open-sourced as DotNetOpenAuth. This is absolutely wonderful, but I am unable to use it on a *AMP stack. Is there anything analogous that runs in PHP, Perl, Python or Ruby?
[ "For Perl there's Net::OAuth, and there looks to be an as-yet-unreleased Catalyst::Controller::OAuth, but what the status of that last one is is unknown (other than the OAuth code page says they're \"working on\" it).\n", "Try Catalyst::Plugin::Authentication::Credential::OpenID - OpenID credential for Catalyst::...
[ 1, 0, 0 ]
[]
[]
[ "dotnetopenauth", "perl", "php", "python", "ruby" ]
stackoverflow_0003865286_dotnetopenauth_perl_php_python_ruby.txt
Q: Configuring up and down arrows to scroll history in Python shell I installed Python 2.7 on my mac from source. Before, I could use the arrow keys to scroll through my history. Now, I get this: >>> print 'stupid' 'stupid' >>> ^[[A # This is my feeble attempt at scrolling up. Scrolling still works if I use Python 2...
Configuring up and down arrows to scroll history in Python shell
I installed Python 2.7 on my mac from source. Before, I could use the arrow keys to scroll through my history. Now, I get this: >>> print 'stupid' 'stupid' >>> ^[[A # This is my feeble attempt at scrolling up. Scrolling still works if I use Python 2.6 Is there a config file for this or is this something that I have to...
[ "You forgot to install readline or libedit before building.\n" ]
[ 3 ]
[]
[]
[ "python" ]
stackoverflow_0004129955_python.txt
Q: Why aren't anonymous (C)Python objects deallocated immediately? I noticed something about CPython's object deallocation which piqued my curiosity. Let's say I define a type that prints a message from its tp_dealloc function: static void pyfoo_Bar_dealloc(pyfoo_Bar* self) { PySys_WriteStdout("Bar freed\n");...
Why aren't anonymous (C)Python objects deallocated immediately?
I noticed something about CPython's object deallocation which piqued my curiosity. Let's say I define a type that prints a message from its tp_dealloc function: static void pyfoo_Bar_dealloc(pyfoo_Bar* self) { PySys_WriteStdout("Bar freed\n"); self->ob_type->tp_free((PyObject*)self); } I've also done th...
[ "Because after you called pyfoo.Bar() the object is still accessible using the special object _\nThis works with pure Python, by the way:\nclass X:\n def __del__(self):\n print 'deleted'\n\nAnd later:\n >>>a = X()\n >>>a = None\n deleted\n >>>X()\n <__main__.X instance at 0x7f391bb066c8> \n >>> _\n <__mai...
[ 9, 3 ]
[]
[]
[ "garbage_collection", "python" ]
stackoverflow_0004129950_garbage_collection_python.txt
Q: How do I queue FTP commands in Twisted? I'm writing an FTP client using Twisted that downloads a lot of files and I'm trying to do it pretty intelligently. However, I've been having the problem that I'll download several files very quickly (sometimes ~20 per batch, sometimes ~250) and then the downloading will han...
How do I queue FTP commands in Twisted?
I'm writing an FTP client using Twisted that downloads a lot of files and I'm trying to do it pretty intelligently. However, I've been having the problem that I'll download several files very quickly (sometimes ~20 per batch, sometimes ~250) and then the downloading will hang, only to eventually have connections time o...
[ "I would suggest using queueCommand, as you suggested I'd suspect the semaphore you're using is probably causing you issues. I believe using queueCommand will limit your FTPClient to a single active connection (though I'm just speculating), so you may want to think about creating a few FTPClient instances and passi...
[ 1 ]
[]
[]
[ "ftp", "ftp_client", "python", "twisted" ]
stackoverflow_0004129291_ftp_ftp_client_python_twisted.txt
Q: python -regex matching a word list I have a python script which has probably 100 or so regex lines each line matching certain words. The script obviously consumes up to 100% cpu each time it is run (I basically pass a sentence to it and it will return any matched words found). I want to combine these into around 4...
python -regex matching a word list
I have a python script which has probably 100 or so regex lines each line matching certain words. The script obviously consumes up to 100% cpu each time it is run (I basically pass a sentence to it and it will return any matched words found). I want to combine these into around 4 or 5 different "compiled" regex parsers...
[ "Your algorithm here is basically O(N*M*L) (where N is the length of the sentence, M is the number of words you're looking for, and L is the longest word you're looking for) for each sentence. Using a regex won't speed this up any more than just using find. The only thing it does give you is the ability to match pa...
[ 4 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0004130134_python_regex.txt
Q: Python threading flow control in concise way I want to upload a file to two ftp sites. After both finishing, I need to delete the file. In case not to block the main function running, both ftp and deletion functions will be implemented by threading, which means there will be 3 threads running in background simulta...
Python threading flow control in concise way
I want to upload a file to two ftp sites. After both finishing, I need to delete the file. In case not to block the main function running, both ftp and deletion functions will be implemented by threading, which means there will be 3 threads running in background simultaneously. An easy problem becomes complicated becau...
[ "Use a semaphore.\nIn your parent handler create a semaphore of 0 and hand it off to the threads.\nimport threading\n\nsem = threading.Semaphore(0)\n\nhostThread = threading.Thread(target=uploadToHost, args=(sem,))\nbackupThread = threading.Thread(target=uploadToBackup, args=(sem,))\n\nsem.acquire() # Wait for one ...
[ 0 ]
[]
[]
[ "multithreading", "mutex", "python" ]
stackoverflow_0004130475_multithreading_mutex_python.txt
Q: App Engine _ah login page not working locally Whenever i click on the link created by users.create_login_url(), i get an error (shown below). When deployed, the thing works, but doesn't work locally. What is wrong? Here's the code: import random import os from google.appengine.api import users from google.appengi...
App Engine _ah login page not working locally
Whenever i click on the link created by users.create_login_url(), i get an error (shown below). When deployed, the thing works, but doesn't work locally. What is wrong? Here's the code: import random import os from google.appengine.api import users from google.appengine.ext import webapp, db from google.appengine.ext....
[ "You are using Python 2.7 that is not supported by Google App Engine (issue here).\nYou need to downgrade to Python 2.5 to make it work.\n", "I fixed this problem on Fedora 14 w/ Python 2.7 by commenting out the following:\n# logging.debug('Executing CGI with env:\\n%s', pprint.pformat(env))\n\non line 2312 of de...
[ 1, 1, 0 ]
[]
[]
[ "authentication", "google_app_engine", "python" ]
stackoverflow_0004115374_authentication_google_app_engine_python.txt
Q: self.response.out.write() - how to use it properly? I have a class that doesn't extend webapp.RequestHandler, and I can't use self.response.out.write(), I get: AttributeError: Fetcher instance has no attribute 'response' If I extend webapp.RequestHandler (I thought it would work), I get: AttributeError: 'Fetc...
self.response.out.write() - how to use it properly?
I have a class that doesn't extend webapp.RequestHandler, and I can't use self.response.out.write(), I get: AttributeError: Fetcher instance has no attribute 'response' If I extend webapp.RequestHandler (I thought it would work), I get: AttributeError: 'Fetcher' object has no attribute 'response' How can I use th...
[ "You're not routing to Fetcher when you initialize a WSGIApplication. Rather, you create an instance manually in other handlers. Thus, App Engine will not initialize your request and response properties. You can manually do so in from the handlers you route to, such as MainHandler and ViewQuoteHandler. E.g.:\nf...
[ 2 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0004131013_google_app_engine_python.txt
Q: setting ftp service via web with python sorry if my english bad... anyone can tell me how to setting ftp service via web using python... i want my site can control the ftp service like sinology diskstation.. like enable/disable ftp service, control how many connection, add or remove user, etc. i use linux and pyth...
setting ftp service via web with python
sorry if my english bad... anyone can tell me how to setting ftp service via web using python... i want my site can control the ftp service like sinology diskstation.. like enable/disable ftp service, control how many connection, add or remove user, etc. i use linux and python+django or just give me where to find the a...
[ "You can try this: http://code.google.com/p/pyftpdlib/\nFilezilla can be controlled by command lines. The users and other parameters can be edited in the Server XML file.\n" ]
[ 0 ]
[]
[]
[ "ftp", "linux", "python" ]
stackoverflow_0004131003_ftp_linux_python.txt
Q: What are the best uses for the Django Admin app? On the website, it says this: One of the most powerful parts of Django is the automatic admin interface. It reads metadata in your model to provide a powerful and production-ready interface that content producers can immediately use to start adding con...
What are the best uses for the Django Admin app?
On the website, it says this: One of the most powerful parts of Django is the automatic admin interface. It reads metadata in your model to provide a powerful and production-ready interface that content producers can immediately use to start adding content to the site. In this document, we discuss how t...
[ "Let's say you create a model called Entry. IE an extremely simple blog. You write a view to show all the entries on the front page. Now how do you put those entries on the webpage? How do you edit them?\nEnter the admin. You register your model with the admin, create a superuser and log in to your running webapp. ...
[ 2, 1 ]
[]
[]
[ "admin", "django", "python" ]
stackoverflow_0004131120_admin_django_python.txt
Q: Handling and securing server functions in an ajax request..python Hi I am trying to secure a server function being used for an Ajax request, so that the function is not accessed for any sort of malicious activity. I have done the following till now:- I am checking whether a valid session is present while the func...
Handling and securing server functions in an ajax request..python
Hi I am trying to secure a server function being used for an Ajax request, so that the function is not accessed for any sort of malicious activity. I have done the following till now:- I am checking whether a valid session is present while the function is being called. I am using POST rather than GET I look for specif...
[ "No any special secure actions required. Consider ajax request as any other client request.\n" ]
[ 2 ]
[]
[]
[ "ajax", "dojo", "flask", "python" ]
stackoverflow_0004131327_ajax_dojo_flask_python.txt
Q: boolean 'and' in Python Can somebody explain the reasoning behind the following tests ?? >>> 1 and True True >>> {'foo': 'Foo'} and True True >>> {} and True {} >>> A: Python doesn't have a boolean and or boolean or. Its and and or operators are coalescing, which means that they return the first non-true or true...
boolean 'and' in Python
Can somebody explain the reasoning behind the following tests ?? >>> 1 and True True >>> {'foo': 'Foo'} and True True >>> {} and True {} >>>
[ "Python doesn't have a boolean and or boolean or. Its and and or operators are coalescing, which means that they return the first non-true or true operand, or the second operand.\n", "In the context of Boolean operations, and also when expressions are used by control flow statements, the following values are inte...
[ 8, 5 ]
[]
[]
[ "boolean", "python" ]
stackoverflow_0004131468_boolean_python.txt
Q: python_select with fink-installed python? How do I use python_select with fink installed python? It won't find it and I don't want to go through the whole process of installing python using macports. I got python_select from macports though. It reports: Available versions: current none python26-apple I used fi...
python_select with fink-installed python?
How do I use python_select with fink installed python? It won't find it and I don't want to go through the whole process of installing python using macports. I got python_select from macports though. It reports: Available versions: current none python26-apple I used fink to install python in: /sw/bin/python2.7
[ "I see the following in my machine:\nAvailable versions:\ncurrent none python26 python26-apple\n\nI guess it is looking up the python versions that are available in path. Since, MacPorts go to /opt; Fink goes to /sw. Is fink on your path? What is contained in $PATH.\n\nI would suggest that you use macports. python_...
[ 1 ]
[]
[]
[ "fink", "python" ]
stackoverflow_0004131016_fink_python.txt
Q: What version of Python should I use if I'm a new to Python? I am now on the road to learn Python (not the first time I wanted to get this done) now I am standing in front of a decision which I am not able to make so easily Which Version should I use?! I found that question was asked about a year ago and Python 2.6...
What version of Python should I use if I'm a new to Python?
I am now on the road to learn Python (not the first time I wanted to get this done) now I am standing in front of a decision which I am not able to make so easily Which Version should I use?! I found that question was asked about a year ago and Python 2.6 was chosen (more or less) now whats the status quo now ?! I am r...
[ "For writing admin scripts, I would recommend the current Python 3.x variant and http://diveintopython3.org. As you already know how to program, you will pick up the differences between 3.x and 2.x rather easily in case you should need a 2.x-only library.\nFor your purposes, the major difference between 2.x and 3.x...
[ 4, 3, 1, 0, 0 ]
[]
[]
[ "linux", "macos", "python", "windows" ]
stackoverflow_0004131648_linux_macos_python_windows.txt
Q: Persistent objects and __repr__ What would be the best way to handle the __repr__() function for an object that is made persistent? For example, one that is representing a row in a database (relational or object). According to Python docs, __repr__() should return a string that would re-create the object with eval...
Persistent objects and __repr__
What would be the best way to handle the __repr__() function for an object that is made persistent? For example, one that is representing a row in a database (relational or object). According to Python docs, __repr__() should return a string that would re-create the object with eval() such that (roughly) eval(repr(obj)...
[ "\nrepr should return a string that would\n re-create the object with eval\n\nThat is legal for simple types like int or string or float, but not usable for multi-column DB object with say 15+ columns\nFor example if I had a class representing price, it would be reasonable to make the __repr__ show the main charac...
[ 1, 0 ]
[]
[]
[ "persistence", "python", "repr" ]
stackoverflow_0004131768_persistence_python_repr.txt
Q: How upload folder by FTP using cURL? I need to create FTP-uploader, i am using pycurl and python, but i dont know how to make folder with cURL on ftp's host. Help me please. A: You can use the curl option while uploading a file : --ftp-create-dirs http://curl.haxx.se/docs/manpage.html#--ftp-create-dirs Ex: c...
How upload folder by FTP using cURL?
I need to create FTP-uploader, i am using pycurl and python, but i dont know how to make folder with cURL on ftp's host. Help me please.
[ "You can use the curl option while uploading a file : --ftp-create-dirs\n\nhttp://curl.haxx.se/docs/manpage.html#--ftp-create-dirs\n\nEx: \ncurl --ftp-create-dirs -T uploadfilename -u username:password ftp://sitename.com/directory/myfile\n\n" ]
[ 17 ]
[]
[]
[ "curl", "ftp", "pycurl", "python" ]
stackoverflow_0004131782_curl_ftp_pycurl_python.txt
Q: Filter models by ManyToMany relationship with Django User Given this model: from django.db import models from django.contrib.auth.admin import User # Create your models here. class Plan(models.Model): editors = models.ManyToManyField(User) in which every plan can have more than one editor (User), how can I r...
Filter models by ManyToMany relationship with Django User
Given this model: from django.db import models from django.contrib.auth.admin import User # Create your models here. class Plan(models.Model): editors = models.ManyToManyField(User) in which every plan can have more than one editor (User), how can I retrieve all plans for which a particular user is one of the edi...
[ "You just use the normal equals here.\nPlan.objects.filter(editors=request.user)\n\n" ]
[ 2 ]
[]
[]
[ "django", "python" ]
stackoverflow_0004131836_django_python.txt
Q: Regex to find out fields which are having non ascii character in python i have data of thousand records which i read line by line . Each line has some fields and their value but field names contain a non ascii character, below is the example of such a record : | | | X:720 | N°22...
Regex to find out fields which are having non ascii character in python
i have data of thousand records which i read line by line . Each line has some fields and their value but field names contain a non ascii character, below is the example of such a record : | | | X:720 | N°227: Done where X and N°(non ascii character) are fieldnames and 720,227 and "...
[ "Sometimes regex is good for such thing, sometimes split() and other string method will be easier. It is up to you to chose:\n#!/usr/bin/env python\n# -*- coding: utf8 -*-\n\nimport re\nRE_TXT = re.compile(r'\\|\\s*X:(\\S+)\\s*\\|\\s*N\\D*(\\d+):\\s*(.*)$')\ntxt = '| | | X:720 | ...
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0004131632_python.txt
Q: How to avoid a seemingly unavoidable divide by zero Ok, so I'm doing the power method in python. Basically, the equation revolves around multiplying a matrix A by a vector (y) like this: for i in range(0, 100): y = mult(matrix,y) y = scalarMult(y, 1.0/y[0][0]) Then you multiply the vector y by 1/(the fi...
How to avoid a seemingly unavoidable divide by zero
Ok, so I'm doing the power method in python. Basically, the equation revolves around multiplying a matrix A by a vector (y) like this: for i in range(0, 100): y = mult(matrix,y) y = scalarMult(y, 1.0/y[0][0]) Then you multiply the vector y by 1/(the first element in y). Now, if the matrix is sparse or has a...
[ "Instead of dividing by first element of the vector you can divide by one of its norms. \nFor example if you use second norm, the length of the vector will always be 1. \nnorm = sum(e**2 for e in y)**0.5\n\nNorm of the vector is only zero when vector is 0 (has all elements 0), so division by 0 should not happen. \n...
[ 3 ]
[]
[]
[ "math", "python" ]
stackoverflow_0004131809_math_python.txt
Q: Python threading, queuing, asyncing... What does it all mean? I've been experimenting with threading recently in Python and was curious when to use what. For example, when should I use multithreading over multiprocessing? What would be a scenario when I should be using asynchronous IO rather than threading? I most...
Python threading, queuing, asyncing... What does it all mean?
I've been experimenting with threading recently in Python and was curious when to use what. For example, when should I use multithreading over multiprocessing? What would be a scenario when I should be using asynchronous IO rather than threading? I mostly understand what each does (I think) but I can't see any benefits...
[ "What you want talk about is not specific to python only it's about multiprocessing vs threading in general i think you can find in google lot of argument from the two side the ones that prefer threading and the others that prefer multiprocessing.\nBut for python multi-threading is limited (if you're using CPython)...
[ 2, 0 ]
[]
[]
[ "asynchronous", "multiprocessing", "multithreading", "python" ]
stackoverflow_0004132179_asynchronous_multiprocessing_multithreading_python.txt
Q: How to use thread in Django I want to check users' subscribed dates for certain period. And send mail to users whose subscription is finishing (ex. reminds two days). I think the best way is using thread and timer to check dates. But I have no idea how to call this function. I don't want to make a separate program...
How to use thread in Django
I want to check users' subscribed dates for certain period. And send mail to users whose subscription is finishing (ex. reminds two days). I think the best way is using thread and timer to check dates. But I have no idea how to call this function. I don't want to make a separate program or shell. I want to combine this...
[ "That's case for manage.py command called periodically from cron. Oficial doc about creating those commands. Here bit more helpful.\nIf you want something simpler then django-command-extensions has commands for managing django jobs.\n", "if you need more then only this one asynchronous job have a look at celery.\...
[ 3, 2, 1 ]
[]
[]
[ "django", "multithreading", "python" ]
stackoverflow_0002583567_django_multithreading_python.txt
Q: Python based build tools I've been lately looking at build systems and I can't find anything close to what I want. I consider too low end, I don't like the syntax of bjam and CMake, and I really don't like that they are only for C/C++. Ant and NAnt are also too language oriented. I really like the idea of a build ...
Python based build tools
I've been lately looking at build systems and I can't find anything close to what I want. I consider too low end, I don't like the syntax of bjam and CMake, and I really don't like that they are only for C/C++. Ant and NAnt are also too language oriented. I really like the idea of a build tool that uses a real programm...
[ "I used Scons and it is good and you can really do everything with it because just Python code so what missing you write in Python - it is easy.\nSome say it has problem with very big projects, I didn't have very big projects to run it so I don't know.\n" ]
[ 3 ]
[]
[]
[ "build", "build_process", "c++", "makefile", "python" ]
stackoverflow_0004132066_build_build_process_c++_makefile_python.txt
Q: Python: Replace function to edit files I have a results.txt file which looks like this: [["12 - 22 - 30 - 31 - 34 - 39 - 36"], ["13 - 21 - 28 - 37 - 39 - 45 - 6"], ["2 - 22 - 32 - 33 - 37 - 45 - 11"], ["3 - 5 - 11 - 16 - 41 - 48 - 32"], ["2 - 3 - 14 - 29 - 35 - 42 12"], ["14 - 30 - 31 - 36 - 44 - 47 26"]] I want ...
Python: Replace function to edit files
I have a results.txt file which looks like this: [["12 - 22 - 30 - 31 - 34 - 39 - 36"], ["13 - 21 - 28 - 37 - 39 - 45 - 6"], ["2 - 22 - 32 - 33 - 37 - 45 - 11"], ["3 - 5 - 11 - 16 - 41 - 48 - 32"], ["2 - 3 - 14 - 29 - 35 - 42 12"], ["14 - 30 - 31 - 36 - 44 - 47 26"]] I want to replace the " - " in the results.txt file...
[ "for i in read:\n # the string.replace() function don't do the change at place\n # it's return a new string with the new changes.\n a = i.replace(\" - \",\",\") \n output.write(a)\n\n", "String methods return a new string. Write that out instead.\noutput.write(i.replace(\" - \",\",\"))\n\n", "i.rep...
[ 6, 5, 4 ]
[]
[]
[ "file", "python", "replace" ]
stackoverflow_0004132715_file_python_replace.txt
Q: Is there 64-bit version pymongo? When i install pymongo using easy_install with 64-bit python, exception happens. But it works with 32-bit python. It seems only 32-bit python is supported. So i want to know whether 64-bit pymongo exists? Thanks. --- more details --- running install running bdist_egg running e...
Is there 64-bit version pymongo?
When i install pymongo using easy_install with 64-bit python, exception happens. But it works with 32-bit python. It seems only 32-bit python is supported. So i want to know whether 64-bit pymongo exists? Thanks. --- more details --- running install running bdist_egg running egg_info writing pymongo.egg-info\PKG-I...
[ "Run vcvarsall.bat first, then install pymongo.\n" ]
[ 0 ]
[]
[]
[ "mongodb", "pymongo", "python" ]
stackoverflow_0004132500_mongodb_pymongo_python.txt
Q: python service restart (when compiled to exe) I have a service, as follows: """ The most basic (working) CherryPy 3.1 Windows service possible. Requires Mark Hammond's pywin32 package. """ import cherrypy import win32serviceutil import win32service import sys import __builtin__ __builtin__.theService = None cla...
python service restart (when compiled to exe)
I have a service, as follows: """ The most basic (working) CherryPy 3.1 Windows service possible. Requires Mark Hammond's pywin32 package. """ import cherrypy import win32serviceutil import win32service import sys import __builtin__ __builtin__.theService = None class HelloWorld: """ Sample request handler class...
[ "A non programming-related option:\nA windows service can be configured for recovery. Select the recovery tag of the service properties window. You can select to Restart the Service after the first, second or subsequent failures.\nA simple idea - why don't you drop the sys.exit() call? This way the service just con...
[ 4, 2 ]
[]
[]
[ "python", "restart", "windows_services" ]
stackoverflow_0001031705_python_restart_windows_services.txt
Q: Excel Vlookup in Python How do I implement the Excel VLOOKUP worksheet function in Python. Any idea? A: If you are using xlrd to read your Excel XLS file: Get the key column values that need to be searched on: key_values = sheet.col_values(KEY_COLX, start_rowx=START_ROWX, end_rowx=END_ROWX) # UPPER_CASE variable...
Excel Vlookup in Python
How do I implement the Excel VLOOKUP worksheet function in Python. Any idea?
[ "If you are using xlrd to read your Excel XLS file:\nGet the key column values that need to be searched on:\nkey_values = sheet.col_values(KEY_COLX, start_rowx=START_ROWX, end_rowx=END_ROWX)\n# UPPER_CASE variables (KEY_COLX etc) are part of your problem description.\nSearch those values to find what you are lookin...
[ 2 ]
[]
[]
[ "excel", "python" ]
stackoverflow_0004132060_excel_python.txt
Q: Where are some good places to reach great Django developers? Are there communities where expert Django developers (ideally looking for jobs) like to hang out? Stackoverflow excluded :) A: I'm partial to the #django channel on Freenode's IRC server. A few big names in the Django community hang around there. ( ir...
Where are some good places to reach great Django developers?
Are there communities where expert Django developers (ideally looking for jobs) like to hang out? Stackoverflow excluded :)
[ "I'm partial to the #django channel on Freenode's IRC server. A few big names in the Django community hang around there. ( irc://irc.freenode.net/#django since SO's Markdown processor doesn't like irc:// in URLs)\n", "You can checkout djangogigs. And hang out on #django and #django-dev on freenode.\n", "http://...
[ 3, 2, 2 ]
[]
[]
[ "django", "python" ]
stackoverflow_0004131096_django_python.txt
Q: How to mix serializers I need to json serialize loads of data in django, and I need to use both django.utils.simplejson and django.core.serializers. The problem is that I can't mix them. I need something like this: simplejson.dumps({ 'money': money.quantity, 'items_left': item.quantity 'transport': ser...
How to mix serializers
I need to json serialize loads of data in django, and I need to use both django.utils.simplejson and django.core.serializers. The problem is that I can't mix them. I need something like this: simplejson.dumps({ 'money': money.quantity, 'items_left': item.quantity 'transport': serializers.serialize([transpor...
[ "Use .values() in your query in order to generate a dict instead of a model instance, then just nest that dictionary in the outer dictionary.\n" ]
[ 1 ]
[]
[]
[ "django", "json", "python", "serialization" ]
stackoverflow_0004133600_django_json_python_serialization.txt
Q: Massive Python set of integers using too much memory Setup Python 2.6 Ubuntu x64 I have a set of unique integers with values between 1 and 50 million. New integers are added at random e.g. numberset.add(random.randint(1, 50000000)). I need to be able to quickly add new integers and quickly check if an integer is...
Massive Python set of integers using too much memory
Setup Python 2.6 Ubuntu x64 I have a set of unique integers with values between 1 and 50 million. New integers are added at random e.g. numberset.add(random.randint(1, 50000000)). I need to be able to quickly add new integers and quickly check if an integer is already present. Problem After a while, the set grows too...
[ "Use a bit-array.This will reduce the need for huge space requirement.\nRealted SO Question:\n\nPython equivalent to Java's BitSet\n\n", "You can avoid dependencies on 3rd-party bit-array modules by writing your own -- the functionality required is rather minimal:\nimport array\n\nBITS_PER_ITEM = array.array('I')...
[ 5, 5, 2, 1, 1, 0 ]
[]
[]
[ "memory_management", "python", "set" ]
stackoverflow_0004132207_memory_management_python_set.txt
Q: Is there a good NumPy clone for Jython? I'm a relatively new convert to Python. I've written some code to grab/graph data from various sources to automate some weekly reports and forecasts. I've been intrigued by the Jython concept, and would like to port some Python code that I've written to Jython. In order t...
Is there a good NumPy clone for Jython?
I'm a relatively new convert to Python. I've written some code to grab/graph data from various sources to automate some weekly reports and forecasts. I've been intrigued by the Jython concept, and would like to port some Python code that I've written to Jython. In order to do this quickly, I need a NumPy clone for J...
[ "I can't find anything that's a clone of numpy, but there's a long list of Java numerics packages here - these should all be usable from Jython. Which one meets your requirements depends on what you're doing with numpy, I guess.\n", "Wilberforce is essentially corrrect. \nHowever, I suggest looking at the Apache ...
[ 12, 10, 2, 1 ]
[]
[]
[ "java", "jython", "numpy", "python" ]
stackoverflow_0000316410_java_jython_numpy_python.txt
Q: Problem getting started with GeoDjango As soon as I add "from django.contrib.gis.db import models" instead of "from django.db import models", Django stops recognizing the app and gives this error: Error: App with label location could not be found. Are you sure your INSTALLED_APPS setting is correct? The error goe...
Problem getting started with GeoDjango
As soon as I add "from django.contrib.gis.db import models" instead of "from django.db import models", Django stops recognizing the app and gives this error: Error: App with label location could not be found. Are you sure your INSTALLED_APPS setting is correct? The error goes away as soon as I comment out "from django...
[ "If you have location on your INSTALLED_APPS and are getting this error, most likely you don't have the location app in your PYTHONPATH.\n", "I had encountered the same issue using Postgres 8.4\nLinks to psycopg2 and GeoDjango given on GeoDjango installation instructions page rely on Postgres 8.3,\nSo, if you use...
[ 0, 0, 0 ]
[]
[]
[ "django", "django_models", "geodjango", "python" ]
stackoverflow_0001734147_django_django_models_geodjango_python.txt
Q: Python: pip installs sub-packages in root dir I have such structure: setup.py package __init__.py sub_package ___init__.py sub_package2 __init__.py If I install package via setup.py install, then it works as appreciated (by copying whole package to site-packages dir): site_packages ...
Python: pip installs sub-packages in root dir
I have such structure: setup.py package __init__.py sub_package ___init__.py sub_package2 __init__.py If I install package via setup.py install, then it works as appreciated (by copying whole package to site-packages dir): site_packages package sub_package sub_package2 ...
[ "NOTE: This answer is not valid anymore, it's only kept for historical reasons, the right answer right now is to use setuptools, more info https://mail.python.org/pipermail/distutils-sig/2013-March/020126.html\n\nFirst of all i will recommend to drop setuptools :\n\nAnd use either distutils (which is the standard m...
[ 7 ]
[]
[]
[ "distutils", "pip", "python", "setuptools" ]
stackoverflow_0004134209_distutils_pip_python_setuptools.txt
Q: Modifying an advanced-indexed subset of a NumPy recarray in place I have a recarray with a couple columns that I use for selecting a subset. Something like >>> x array([ ('label1',True,3), ('label2',True,2), ('label1',False,4)], dtype=[('status', '|S16'), ('select', '|b1'), ('someda...
Modifying an advanced-indexed subset of a NumPy recarray in place
I have a recarray with a couple columns that I use for selecting a subset. Something like >>> x array([ ('label1',True,3), ('label2',True,2), ('label1',False,4)], dtype=[('status', '|S16'), ('select', '|b1'), ('somedata', '<i4')]) Data is selected from this array using an approach simil...
[ "The kind of modifications you mention in the comments to my first answer can be done with the numpy.place() function:\n\n>>> import numpy\n>>> x = numpy.array([(\"label1\",True,3), (\"label2\",False,2), (\"label1\",True,4)],\n... dtype=[(\"status\", \"|S16\"), (\"select\", \"|b1\"), (\"somedata\", \">> mask = ...
[ 3, 2 ]
[]
[]
[ "arrays", "indexing", "numpy", "python" ]
stackoverflow_0004111514_arrays_indexing_numpy_python.txt
Q: Count the number of elements of same value in Python Possible Duplicate: How to count the frequency of the elements in a list? I wish to count the number of elements of same value in a list and return a dict as such: > a = map(int,[x**0.5 for x in range(20)]) > a > [0, 1, 1, 1, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3...
Count the number of elements of same value in Python
Possible Duplicate: How to count the frequency of the elements in a list? I wish to count the number of elements of same value in a list and return a dict as such: > a = map(int,[x**0.5 for x in range(20)]) > a > [0, 1, 1, 1, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4] > number_of_elements_by_value(a) > {0:1, ...
[ "This is a good way if you don't have collections.Counter available\nfrom collections import defaultdict\nd = defaultdict(int)\na = map(int, [x**0.5 for x in range(20)])\nfor i in a:\n d[i] += 1\n\nprint d\n\n", "Use a Counter:\n>>> from collections import Counter\n\n>>> a = map(int,[x**0.5 for x in range(20)]...
[ 8, 7, 4, 0 ]
[]
[]
[ "counter", "histogram", "python" ]
stackoverflow_0004131982_counter_histogram_python.txt
Q: Remove duplicate nodes in an XML I'm generating an XML file using Python and markup.py ....it was all working out but due to recent changes in the script, I'm now getting duplicated values in the nodes due to the checks I put in place. Here's a sample of the output (they are vehicle records): <?xml version='1.0' ...
Remove duplicate nodes in an XML
I'm generating an XML file using Python and markup.py ....it was all working out but due to recent changes in the script, I'm now getting duplicated values in the nodes due to the checks I put in place. Here's a sample of the output (they are vehicle records): <?xml version='1.0' encoding='UTF-8' ?> <datafeed> <vehicl...
[ "There are no real \"duplicates\" in XML. Every node is different by definition. But I understand you that you want to get rid of all duplicate features in your interpretion.\nYou can do this by simply parsing that tree, putting the features (the values of the nodes) in a set (to get rid of duplicates) and writing ...
[ 1 ]
[]
[]
[ "python", "xml" ]
stackoverflow_0004134531_python_xml.txt
Q: Recommended IDE for developing Pylons apps I have been reading through this wonderful website regarding the recommended Python IDEs and have narrowed it down to either WingIDE KomodoIDE which you guys will recommend for the purpose of developing Pylons apps? I know that most questions have been asked pertaining ...
Recommended IDE for developing Pylons apps
I have been reading through this wonderful website regarding the recommended Python IDEs and have narrowed it down to either WingIDE KomodoIDE which you guys will recommend for the purpose of developing Pylons apps? I know that most questions have been asked pertaining to Python IDEs but how about Python web framewor...
[ "Did you try Eclipse with PyDev plugin? Which is FREE plus works for any OS.\nScreenshots at the PyDev website.\n\n(source: sourceforge.net) \n", "+1 for WingIDE, It supports debugging pylons app. \n", "Netbeans has implemented beta support of python development. It unfortunately doesn't specifically support an...
[ 13, 3, 1, 1, 1, 1, 0, 0, 0 ]
[]
[]
[ "ide", "pylons", "python" ]
stackoverflow_0001065964_ide_pylons_python.txt
Q: How can i access the file-selection in Path Finder via py-appscript? Using the filemanager Path Finder on mac os x, i wanna retrieve the selected files/folders with python by using py-appscript. py-appscript is a high-level event bridge that allows you to control scriptable Mac OS X applications from Python. In ap...
How can i access the file-selection in Path Finder via py-appscript?
Using the filemanager Path Finder on mac os x, i wanna retrieve the selected files/folders with python by using py-appscript. py-appscript is a high-level event bridge that allows you to control scriptable Mac OS X applications from Python. In applescript it would be something like tell application "Path Finder" set ...
[ "I'm not familiar with Pathfinder, but if it has its own file URL type (or maybe it's a POSIX path?), then there is presumably a delimiter of some kind that separates the levels of file hierarchy in the path. To convert between one and the other, you need to work with Applescript's text item delimiters. Something a...
[ 0, 0 ]
[]
[]
[ "applescript", "macos", "path_finding", "python", "sourceforge_appscript" ]
stackoverflow_0004122750_applescript_macos_path_finding_python_sourceforge_appscript.txt
Q: Python, MySQL and a weird error I have a bug that I don't know how to fix or even reproduce: query = "SELECT id, name FROM names ORDER BY id" results = database.execute(query) where the class Database contains: def execute(self, query): cursor = self.db.cursor() try: cursor.execute(query) ...
Python, MySQL and a weird error
I have a bug that I don't know how to fix or even reproduce: query = "SELECT id, name FROM names ORDER BY id" results = database.execute(query) where the class Database contains: def execute(self, query): cursor = self.db.cursor() try: cursor.execute(query) return cursor.fetchall() except:...
[ "try this in your traceback it's for debugging:\nexcept ProgrammingError as ex:\n if cursor:\n print \"\\n\".join(cursor.messages) \n # You can show only the last error like this.\n # print cursor.messages[-1]\n else:\n print \"\\n\".join(self.db.messages)\n # Same here you ...
[ 3 ]
[]
[]
[ "mysql", "python" ]
stackoverflow_0004134635_mysql_python.txt