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:
Retrieve image to display from google datastore
models.py
class Badge(db.Model):
user = db.ReferenceProperty(User, collection_name='user_badges')
skill = db.ReferenceProperty(Skill, collection_name='skill_badges')
points = db.FloatProperty(required=True)
class Skill(db.Model):
skill_id = db.StringProperty()
name ... | Retrieve image to display from google datastore | models.py
class Badge(db.Model):
user = db.ReferenceProperty(User, collection_name='user_badges')
skill = db.ReferenceProperty(Skill, collection_name='skill_badges')
points = db.FloatProperty(required=True)
class Skill(db.Model):
skill_id = db.StringProperty()
name = db.StringProperty()
description = db.StringProperty... | [
"You can't embed a picture directly into a template; HTML does not work that way. You will need to embed an <img> tag with a src attribute that gives a URL that your application will answer to serve the URL. I only use the Templates part of Django, so if you are using the full-stack, you will have to translate some... | [
4,
0,
0
] | [] | [] | [
"django",
"google_app_engine",
"google_cloud_datastore",
"python"
] | stackoverflow_0005329567_django_google_app_engine_google_cloud_datastore_python.txt |
Q:
how to show mime data using python cgi in windows+apache
I met a problem while using python(2.6) cgi to show a mime data in windows(apache).
For example, to show a image, here is my code:
image.py
#!E:/program files/Python26/python.exe
# -*- coding: UTF-8 -*-
data = open('logo.png','rb').read()
print 'Content-Typ... | how to show mime data using python cgi in windows+apache | I met a problem while using python(2.6) cgi to show a mime data in windows(apache).
For example, to show a image, here is my code:
image.py
#!E:/program files/Python26/python.exe
# -*- coding: UTF-8 -*-
data = open('logo.png','rb').read()
print 'Content-Type:image/png;Content-Disposition:attachment;filename=logo.png\n... | [
"One newline between each header. Two newlines between the headers and the body. And watch your line endings.\nprint 'Content-Type:image/png'\nprint 'Content-Disposition:attachment;filename=logo.png'\nprint\n\n",
"Now I know how to solve this problem: \n\nFor windows+IIS:\nWhile adding the application mapping(IIS... | [
2,
0
] | [] | [] | [
"apache",
"cgi",
"mime",
"python",
"windows"
] | stackoverflow_0004332293_apache_cgi_mime_python_windows.txt |
Q:
TDD in python 3.1
I'm a C++ programmer who works via TDD. I am now learning python 3 and wish to continue with TDD. At the moment in C++, I give all my classes an interface and create mocked versions of them. I then pass pointers to these interfaces around in my code.
I'd like to know what libraries I should use i... | TDD in python 3.1 | I'm a C++ programmer who works via TDD. I am now learning python 3 and wish to continue with TDD. At the moment in C++, I give all my classes an interface and create mocked versions of them. I then pass pointers to these interfaces around in my code.
I'd like to know what libraries I should use in order to effectively ... | [
"I've never found the need for anything except that which python provides.\nBecause of Python's Duck typing, it is very, very easy to create Mock objects with a minimal implementation, and read out what is in them afterwards to check your assertions.\nI find the unittest module works just fine for me too.\n",
"Th... | [
6,
1,
0
] | [] | [] | [
"mocking",
"python",
"python_3.x",
"tdd"
] | stackoverflow_0005310770_mocking_python_python_3.x_tdd.txt |
Q:
Python OOP __Add__ matrices together (Looping Problem)
class Matrix:
def __init__(self, data):
self.data = data
def __repr__(self):
return repr(self.data)
def __add__(self, other):
data = []
for j in range(len(self.data)):
for k in range(len(self.data[0])):
data.appen... | Python OOP __Add__ matrices together (Looping Problem) | class Matrix:
def __init__(self, data):
self.data = data
def __repr__(self):
return repr(self.data)
def __add__(self, other):
data = []
for j in range(len(self.data)):
for k in range(len(self.data[0])):
data.append([self.data[k] + other.data[k]])
data.append([self.... | [
"How about this:\nclass Matrix:\n def __init__(self, data):\n self.data = data\n\n def __repr__(self):\n return repr(self.data) \n\n def __add__(self, other):\n data = []\n\n for j in range(len(self.data)):\n data.append([])\n for k in range(len(self.data[0])):\n data[j].app... | [
1,
0
] | [] | [] | [
"addition",
"class",
"matrix",
"oop",
"python"
] | stackoverflow_0005328684_addition_class_matrix_oop_python.txt |
Q:
django autoconverting datetime property
my datetime property is saving in mysql in this format 2011-03-17 00:00:00 but after fetchind the data with filter function it is giving March 17,2011 midnight but i have not say to do any this type of task. My question is how can i insist django to stic to show same value w... | django autoconverting datetime property | my datetime property is saving in mysql in this format 2011-03-17 00:00:00 but after fetchind the data with filter function it is giving March 17,2011 midnight but i have not say to do any this type of task. My question is how can i insist django to stic to show same value what is saved in MYSQL.
| [
"you'll want to use the datetime format, django's DateTimeField[1] really is a wrapper for datetime.datetime. \nin the templates you can use the date[2] filter to apply the format you want for example: \n{{ item.date|date:\"Y-m-d H:i:s\" }}\n\nThis should print out 2011-03-17 00:00:00 in the template. In views us... | [
1,
0
] | [] | [] | [
"django",
"mysql",
"python"
] | stackoverflow_0005335845_django_mysql_python.txt |
Q:
PostgreSql and Python
I am using python and postgresql. I have a table with 6 column. One id and 5 entries. I want to copy the id and most repeated entry in 5 entries to a new table.
I have done this:
import psycopg2
connection=psycopg2.connect("dbname=homedb user=ria")
cursor=connection.cursor()
l_dict= {'licence... | PostgreSql and Python | I am using python and postgresql. I have a table with 6 column. One id and 5 entries. I want to copy the id and most repeated entry in 5 entries to a new table.
I have done this:
import psycopg2
connection=psycopg2.connect("dbname=homedb user=ria")
cursor=connection.cursor()
l_dict= {'licence_id':1}
cursor.execute("SEL... | [
"p is a tuple so you can create a new execute with the INSERT statement passing the tuple (or part): \ncursor.execute(\"INSERT INTO new_table (x, ...) VALUES (%s, ...)\", p)\n\nwhere:\n\n(x, ....) contains the column names \n(%s, ...) %s is repeated for each column\n\n"
] | [
1
] | [] | [] | [
"database",
"postgresql",
"psycopg2",
"python"
] | stackoverflow_0005335938_database_postgresql_psycopg2_python.txt |
Q:
Video Streaming using Python
Is there any library (or) application available in Python to support Video Streaming? It has to read the file and needs to stream over the web.
A:
Check out Flumotion
It's a streaming media server implemented in Python.
| Video Streaming using Python | Is there any library (or) application available in Python to support Video Streaming? It has to read the file and needs to stream over the web.
| [
"Check out Flumotion\nIt's a streaming media server implemented in Python.\n"
] | [
5
] | [] | [] | [
"python",
"video_streaming"
] | stackoverflow_0005336643_python_video_streaming.txt |
Q:
How to open a file with chinese name in python
I am trying to open a file in "w" mode with "open()" function in python.
The filename is : 仿宋人笔意.jpg.
The open function fails with this filename but succeeds with normal files.
How can I open a file with names which are not in English in python?
My code is as follows:... | How to open a file with chinese name in python | I am trying to open a file in "w" mode with "open()" function in python.
The filename is : 仿宋人笔意.jpg.
The open function fails with this filename but succeeds with normal files.
How can I open a file with names which are not in English in python?
My code is as follows:
try:
filename = urllib.quote(filename.encode('u... | [
"#!/usr/bin/python\n# -*- coding: UTF-8 -*-\nimport codecs\nf=codecs.open(u'仿宋人笔意.txt','r','utf-8')\nprint f.read()\nf.close()\n\nworked just fine here\n",
"If you're having a problem it seems more likely to do with your operating system or terminal configuration than Python itself; it worked ok for me even witho... | [
5,
3,
0,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0005336375_python.txt |
Q:
how to get the Variable name in this file using python
this is the a.txt:
attackUp = [10, 15]
defenceUp = [10, 15]
magicUp = [10, 15]
attType = [1, 1]
weightDown = [10, 15]
#装饰器数据
accAttackSword = [100, 100]
accAttackSaber = [100, 100]
accAttackAx = [100, 100]
accAttackHa... | how to get the Variable name in this file using python | this is the a.txt:
attackUp = [10, 15]
defenceUp = [10, 15]
magicUp = [10, 15]
attType = [1, 1]
weightDown = [10, 15]
#装饰器数据
accAttackSword = [100, 100]
accAttackSaber = [100, 100]
accAttackAx = [100, 100]
accAttackHammer = [100, 100]
accAttackSpear = [100, 100]
accAttac... | [
"Provided that you remove the self.* \"variables\" from your file (Python does not know how to make sense of them), you can get a dictionary that contains what you want with:\nimport a # This supposes that your file is named a.py instead of a.txt\n\nvar_dict = vars(a)\n\nprint var_dict['accDefencePhy'] # Yields [... | [
1,
0
] | [] | [] | [
"dictionary",
"python"
] | stackoverflow_0005334725_dictionary_python.txt |
Q:
pyobjc indexed accessor method with range
I'm trying to implement an indexed accessor method for my model class in Python, as per the KVC guide. I want to use the optional ranged method, to load multiple objects at once for performance reasons. The method takes a pointer to a C-array buffer which my method needs t... | pyobjc indexed accessor method with range | I'm trying to implement an indexed accessor method for my model class in Python, as per the KVC guide. I want to use the optional ranged method, to load multiple objects at once for performance reasons. The method takes a pointer to a C-array buffer which my method needs to copy the objects into. I've tried something l... | [
"You were close. The correct decorator for this method is:\n@objc.signature('v@:o^@{_NSRange=QQ}')\n\nNSRange is not an object, but a struct, and can't be specified simply as @; you need to include the members1.\nUnfortunately, this is not the end of it. After a whole lot of experimentation and poring over the PyOb... | [
2
] | [] | [] | [
"cocoa",
"key_value_coding",
"pyobjc",
"python"
] | stackoverflow_0001376463_cocoa_key_value_coding_pyobjc_python.txt |
Q:
Sorting a filtered list in ascending/descending order in django
I have created an Employee management system using Django. I have done a filtering method in it and is based on a choice selected from a drop down menu and a text input. the filtering is working fine. On the first page it gives the entire employee lis... | Sorting a filtered list in ascending/descending order in django | I have created an Employee management system using Django. I have done a filtering method in it and is based on a choice selected from a drop down menu and a text input. the filtering is working fine. On the first page it gives the entire employee list which can be shown in both ascending and descending order. On the s... | [
"I'm not sure I get the question, but if you want to apply the sorting to the filtered objects, you might want to add some sort of caching (different from django's builtin caching), that stores the filtered queryset and sort that. Or you can pass the filter option around using django's session management and redo t... | [
1,
1
] | [] | [] | [
"django",
"django_models",
"django_templates",
"django_views",
"python"
] | stackoverflow_0005334889_django_django_models_django_templates_django_views_python.txt |
Q:
set default datetime format in python
How to set default datetime format in python because i have multiple tuples to send via template on client side. This is not good approach to set each object's value to specified format. I want to set a datetime format on server side and these converted values will be shown to... | set default datetime format in python | How to set default datetime format in python because i have multiple tuples to send via template on client side. This is not good approach to set each object's value to specified format. I want to set a datetime format on server side and these converted values will be shown to client. I tried
datetime.strftime("%Y-%m-%... | [
"strftime is a method of datetime objects - it doesn't set a default representation, which seems to be what you suggest. For example, you might call it like this:\n>>> import datetime\n>>> now = datetime.datetime.now()\n>>> now.strftime(\"%Y-%m-%d %X\")\n'2011-03-17 10:14:12'\n\nIf you need to do this a lot, it wo... | [
5,
2
] | [] | [] | [
"django",
"mysql",
"python"
] | stackoverflow_0005336805_django_mysql_python.txt |
Q:
Django override default functionalities
In django/django/contrib/auth/forms.py how to override the default method
and include the same in the users module ?
So my intention is that i want to change the username field length to 64 characters but this would not be correct to do this in django directories,because whe... | Django override default functionalities | In django/django/contrib/auth/forms.py how to override the default method
and include the same in the users module ?
So my intention is that i want to change the username field length to 64 characters but this would not be correct to do this in django directories,because whenever new version is downloaded this file has... | [
"@Deniz Dogan: You also have to convince login view to use the custom form:\nlogin(request, authentication_form=MyAuthenticationForm)\n\n",
"If I understand you correctly, you may be able to change it by sub-classing AuthenticationForm into e.g. MyAuthenticationForm:\nclass MyAuthenticationForm(AuthenticationForm... | [
1,
0
] | [] | [] | [
"django",
"django_models",
"django_views",
"python"
] | stackoverflow_0004124245_django_django_models_django_views_python.txt |
Q:
SWIG pass stream from python to C++
C++
I have some logger class in C++. This logger is heavily used in my library. The logger allows to set standart STL stream to use as output stream.
Python
Python library which uses "above SWIG wrapped C++ library" heavily uses python standard logging with StreamHandler. Somet... | SWIG pass stream from python to C++ | C++
I have some logger class in C++. This logger is heavily used in my library. The logger allows to set standart STL stream to use as output stream.
Python
Python library which uses "above SWIG wrapped C++ library" heavily uses python standard logging with StreamHandler. Something like:
logger = logging.getLogger("... | [
"Technically, you need to implement a swig typemap (in) that converts the python stream object into an std::ostream. However, I fear that this is highly non-trivial. \n"
] | [
1
] | [] | [] | [
"c++",
"iostream",
"python",
"stream",
"swig"
] | stackoverflow_0004892808_c++_iostream_python_stream_swig.txt |
Q:
Boost.Python call by reference : TypeError: No to_python (by-value) converter found for C++ type:
I'm trying to expose my C++ Classes to Python using Boost.Python. Here is a simplyfied version of what i'm trying to do:
I have a class A deriving from boost::noncopyable and a second class B with a method that takes ... | Boost.Python call by reference : TypeError: No to_python (by-value) converter found for C++ type: | I'm trying to expose my C++ Classes to Python using Boost.Python. Here is a simplyfied version of what i'm trying to do:
I have a class A deriving from boost::noncopyable and a second class B with a method that takes a reference to A as an argument.
class A : boost::noncopyable { /*...*/ };
class B {
public:
vir... | [
"Change B.do_something(a); to B.do_something(boost::ref(a));.\nSee Calling Python Functions and Methods in the boost manual.\n"
] | [
19
] | [] | [] | [
"boost",
"boost_python",
"c++",
"python"
] | stackoverflow_0005336942_boost_boost_python_c++_python.txt |
Q:
What is the minimal subset of file methods I need to implement to get the full python file interface?
Python has the marvelous collections module that has tools to allow you to implement a full dict (for example) from a minimal set of methods. Is there a similar thing for the file interface in Python? If not, what... | What is the minimal subset of file methods I need to implement to get the full python file interface? | Python has the marvelous collections module that has tools to allow you to implement a full dict (for example) from a minimal set of methods. Is there a similar thing for the file interface in Python? If not, what would you recommend as a minimal set of methods to implement for a file-like object for duck-typing purpos... | [
"The with statement requires a context manager:\nhttp://docs.python.org/library/stdtypes.html#typecontextmanager\nThe file type is fully defined:\nhttp://docs.python.org/library/stdtypes.html#file-objects \nSeems pretty simple.\nThe documentation lists the methods and attributes of a file and a context manager. I... | [
3,
2,
2
] | [] | [] | [
"python"
] | stackoverflow_0005335017_python.txt |
Q:
How to Access a image from another directory? python
I have a python script say "foo_1.py" which resides in folder x and another script foo_2.py which resides in folder y.
Folders x and y are in folder z.
I called a method which belongs to foo_2.py which generates an image in folder y (say img1.png).
Now what I ... | How to Access a image from another directory? python | I have a python script say "foo_1.py" which resides in folder x and another script foo_2.py which resides in folder y.
Folders x and y are in folder z.
I called a method which belongs to foo_2.py which generates an image in folder y (say img1.png).
Now what I want is to access this img1.png from foo_1.py. How is it ... | [
"sys.path[0] gives you the directory where the current script resides:\nimport sys, os\nscript_dir = sys.path[0]\nimg_path = os.path.join(script_dir, '../y/img1.png')\n\n",
"img_file = open('../y/img1.png')\n\n",
"What has this to do with Python? Either use an absolute path or a relative path using the wellknow... | [
6,
1,
1
] | [] | [] | [
"python"
] | stackoverflow_0005337682_python.txt |
Q:
Execute Multi-threading process
I'm writing a code for a simple chat client in python. I have the GUI, a php server to store strings and other data. I want to make my code capable of updating the chat (conversation Text field) each 1 second.
I post a bit of pseudo-code:
Initialize Gui
Setup Users
UserX write messa... | Execute Multi-threading process | I'm writing a code for a simple chat client in python. I have the GUI, a php server to store strings and other data. I want to make my code capable of updating the chat (conversation Text field) each 1 second.
I post a bit of pseudo-code:
Initialize Gui
Setup Users
UserX write messageX
messageX sent to server
At this ... | [
"You did not mention which GUI toolkit you are using; from mainloop() I guess it's Tk.\nThe answer to this question explains how to set up a recurring event. Multithreading is not required.\n",
"You need to detach the way you fetch for new messages from the main thread of your applications. That can be easily don... | [
0,
0
] | [] | [] | [
"multithreading",
"parallel_processing",
"python"
] | stackoverflow_0005333387_multithreading_parallel_processing_python.txt |
Q:
Python @ (at) prefix in top level module code - What does it stand for?
Possible Duplicate:
What does the @ symbol do in Python
I thought it would be a good idea to as this question here since google outright ignores the @ character in a query.
What does the @ before an earlier declared function name do when use... | Python @ (at) prefix in top level module code - What does it stand for? |
Possible Duplicate:
What does the @ symbol do in Python
I thought it would be a good idea to as this question here since google outright ignores the @ character in a query.
What does the @ before an earlier declared function name do when used in the top level of a document, multiple times, just before def´s?
Example... | [
"Those are decorators\n... and yes they're present in Python 3, see ... Python 3 primer, Part 2: Advanced topics\n"
] | [
6
] | [] | [] | [
"python",
"python_3.x"
] | stackoverflow_0005337890_python_python_3.x.txt |
Q:
What is the defacto standard for sharing variables between programs in different languages?
I've never had formal training in this area so I'm wondering what do they teach in school (if they do).
Say you have two programs in written in two different languages: C++ and Python or some other combination and you want ... | What is the defacto standard for sharing variables between programs in different languages? | I've never had formal training in this area so I'm wondering what do they teach in school (if they do).
Say you have two programs in written in two different languages: C++ and Python or some other combination and you want to share a constantly updated variable on the same machine, what would you use and why? The infor... | [
"Well you can write XML and use some basic message queuing (like rabbitMQ) to pass messages around\n",
"Don't know if this will be helpful, but I'm also a student, and this is what I think you mean.\nI've used marshalling to get a java class and import it into a C# program.\nWith marshalling you use xml to transf... | [
2,
2,
1,
0,
0
] | [] | [] | [
"buffer",
"c++",
"memory",
"python",
"udp"
] | stackoverflow_0005329573_buffer_c++_memory_python_udp.txt |
Q:
Minimize window using Xlib in python
How to minimize a window using Xlib in python?
A:
I haven't used Xlib before
But you may try that
window.right = -100
use negative number as the same of minimize
| Minimize window using Xlib in python | How to minimize a window using Xlib in python?
| [
"I haven't used Xlib before\nBut you may try that\nwindow.right = -100\nuse negative number as the same of minimize\n"
] | [
0
] | [] | [] | [
"python"
] | stackoverflow_0005336583_python.txt |
Q:
python programming
: N^N
Write a function called exactly NtoN() which takes a number (integer or float) as its sole parameter and returns the value of that number raised to the power of itself.
A:
def NtoN(n):
return n**n
Intentionally made CW
| python programming | : N^N
Write a function called exactly NtoN() which takes a number (integer or float) as its sole parameter and returns the value of that number raised to the power of itself.
| [
"def NtoN(n):\n return n**n \n\nIntentionally made CW\n"
] | [
2
] | [] | [] | [
"python"
] | stackoverflow_0005338273_python.txt |
Q:
Python 2.6: How to access base class descriptor field hidden by derived class?
I have a descriptor storing data in host object's dictionary.
And I have fields of this descriptor in class hierarchy with the same name:
class ADescriptor(object):
def __init__(self, keyname='descr'):
self.keyname = keyname... | Python 2.6: How to access base class descriptor field hidden by derived class? | I have a descriptor storing data in host object's dictionary.
And I have fields of this descriptor in class hierarchy with the same name:
class ADescriptor(object):
def __init__(self, keyname='descr'):
self.keyname = keyname
def __get__(self, obj, objtype):
return getattr(obj, self.keyname, 819... | [
"Surely A.f.__set__(b,'a') would work if A.__dict__['f'].__set__(b,'a') works?\nAnd then even A.f.b = 'a' aught to work, although you might have to specify it as a property if my memory serves me. \n\nSee the history to see a massive brainfart...\n>>> class ADescriptor(object):\n def __init__(self, keyname='desc... | [
1
] | [] | [] | [
"descriptor",
"python",
"super"
] | stackoverflow_0005336147_descriptor_python_super.txt |
Q:
Is there a Python module to detect month or day in string?
Is there a Python module to parse month or day references in a given string?
A:
You could try using dateutil.parser, e.g.:
>>> from dateutil import parser
>>> parser.parse("There's a date 09-21 in here", fuzzy=True)
datetime.datetime(2011, 9, 21, 0, 0)
... | Is there a Python module to detect month or day in string? | Is there a Python module to parse month or day references in a given string?
| [
"You could try using dateutil.parser, e.g.:\n>>> from dateutil import parser\n>>> parser.parse(\"There's a date 09-21 in here\", fuzzy=True)\ndatetime.datetime(2011, 9, 21, 0, 0)\n\n... with the fuzzy=True option. The documentation is here.\n",
"Are any other characters in the string or just numbers which says t... | [
26,
0
] | [] | [] | [
"date",
"python"
] | stackoverflow_0005336447_date_python.txt |
Q:
How do I create a pip requirements file for a tarball on my local filesystem?
Tell me if what I'm trying to do doesn't make sense.
I want to create a virtual environment that, among other things, includes MySQLDb 1.2.3. This library is distributed as a gzipped tarball (.tgz) file. I want to install everything—in... | How do I create a pip requirements file for a tarball on my local filesystem? | Tell me if what I'm trying to do doesn't make sense.
I want to create a virtual environment that, among other things, includes MySQLDb 1.2.3. This library is distributed as a gzipped tarball (.tgz) file. I want to install everything—including tarballs on my local filesystem—from a requirements file in requirements/ap... | [
"You can use absolute/relative paths in requirements files e.g.:\n--extra-index-url=http://example.com\nmy-apps/apps1.tar.gz\n# put apps2-1.0.1.tar.gz to http://example.com/apps2/\napps2\n\n",
"You have to add -f file:/absolute/path/to/the/directory/that/contains/your/downloaded/tarball/ to your call to pip.\nThe... | [
7,
2
] | [] | [] | [
"pip",
"python",
"requirements.txt",
"virtualenv"
] | stackoverflow_0004771620_pip_python_requirements.txt_virtualenv.txt |
Q:
How to draw probabilistic distributions with numpy/matplotlib?
I want to draw probabilistic functions (like the binomial distribution), but i don't find a function that returns the probability for given parameters. To write it myself i need binomial coefficients (I could write that myself), for which I haven't fou... | How to draw probabilistic distributions with numpy/matplotlib? | I want to draw probabilistic functions (like the binomial distribution), but i don't find a function that returns the probability for given parameters. To write it myself i need binomial coefficients (I could write that myself), for which I haven't found a function either. Is there a 'short and/or easy' to do this?
To ... | [
"scipy.stats.binom.pmf gives the probability mass function for the binomial distribution. You could compute it for a range and plot it. for example, for 10 trials, and p = 0.1, you could do\nimport scipy, scipy.stats\nx = scipy.linspace(0,10,11)\npmf = scipy.stats.binom.pmf(x,10,0.1)\nimport pylab\npylab.plot(x,pmf... | [
13
] | [] | [] | [
"matplotlib",
"numpy",
"python"
] | stackoverflow_0005338944_matplotlib_numpy_python.txt |
Q:
Does Python have something similar to .net c# PInvoke?
Do CPython has something similar to .net c# PInvoke?
For example I have some.dll or some.so and would like to register some functions from it on runtime and start using those in my program.
In C# you can do:
// Marshal.cs
using System;
using System.Runtime.Int... | Does Python have something similar to .net c# PInvoke? | Do CPython has something similar to .net c# PInvoke?
For example I have some.dll or some.so and would like to register some functions from it on runtime and start using those in my program.
In C# you can do:
// Marshal.cs
using System;
using System.Runtime.InteropServices;
namespace CSharpIterators
{
class MainCla... | [
"You can call functions from DLLs using Python's ctypes module.\n",
"Another option is to use tools like swig in order to create a Python interface to C/C++ code:\nhttp://www.swig.org/\nThe syntax for creating the wrappers is very similar to C plus some preprocessing directives.\n"
] | [
6,
0
] | [] | [] | [
"pinvoke",
"python"
] | stackoverflow_0005338228_pinvoke_python.txt |
Q:
Postgresql table update
I updated a database table using postgresql from python
My code was
import psycopg2
connection=psycopg2.connect("dbname=homedb user=ria")
cursor=connection.cursor()
l_dict= {'licence_id':1}
cursor.execute("SELECT * FROM im_entry.usr_table")
rows=cursor.fetchall()
for row in rows:
i=i+1... | Postgresql table update | I updated a database table using postgresql from python
My code was
import psycopg2
connection=psycopg2.connect("dbname=homedb user=ria")
cursor=connection.cursor()
l_dict= {'licence_id':1}
cursor.execute("SELECT * FROM im_entry.usr_table")
rows=cursor.fetchall()
for row in rows:
i=i+1
p = findmax(row)
#prin... | [
"You're probably not committing the transaction, i.e. you need a connection.commit() after all your updates.\nThere are various different settings you can make to the isolation level, e.g. autocommit, so you don't need to issue commits yourself. See, for example, How do I do database transactions with psycopg2/pyt... | [
7
] | [] | [] | [
"database",
"postgresql",
"psycopg",
"python"
] | stackoverflow_0005339139_database_postgresql_psycopg_python.txt |
Q:
Please help me design a database schema for this:
I'm designing a python application which works with a database. I'm planning to use sqlite.
There are 15000 objects, and each object has a few attributes. every day I need to add some data for each object.(Maybe create a column with the date as its name).
However, ... | Please help me design a database schema for this: | I'm designing a python application which works with a database. I'm planning to use sqlite.
There are 15000 objects, and each object has a few attributes. every day I need to add some data for each object.(Maybe create a column with the date as its name).
However, I would like to easily delete the data which is too old... | [
"It'll probably be easiest to separate your data into two tables like so:\nCREATE TABLE object(\n id INTEGER PRIMARY KEY,\n ...\n);\n\nCREATE TABLE extra_data(\n objectid INTEGER,\n date DATETIME,\n ...\n FOREIGN KEY(objectid) REFERENCES object(id)\n);\n\nThis way when you need to del... | [
1,
0,
0
] | [] | [] | [
"data_modeling",
"python",
"sqlite"
] | stackoverflow_0005335330_data_modeling_python_sqlite.txt |
Q:
How to make it shorter (Pythonic)?
I have to check a lot of worlds if they are in string... code looks like:
if "string_1" in var_string or "string_2" in var_string or "string_3" in var_string or "string_n" in var_string:
do_something()
how to make it more readable and more clear?
A:
This is one way:
words... | How to make it shorter (Pythonic)? | I have to check a lot of worlds if they are in string... code looks like:
if "string_1" in var_string or "string_2" in var_string or "string_3" in var_string or "string_n" in var_string:
do_something()
how to make it more readable and more clear?
| [
"This is one way:\nwords = ['string_1', 'string_2', ...]\n\nif any(word in var_string for word in words):\n do_something()\n\nReference: any()\nUpdate:\nFor completeness, if you want to execute the function only if all words are contained in the string, you can use all() instead of any().\nAlso note that this co... | [
35,
2,
2,
1,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0003600834_python.txt |
Q:
Easy way to delete elements from a list in Python
Possible Duplicate:
Removing an element from a list based on a predicate
Supposing I have a list and i want to delete from it elements that respect a condition,, how can i implement this easier?
I tried with:
for i in range (len(list)):
if [condition]:
... | Easy way to delete elements from a list in Python |
Possible Duplicate:
Removing an element from a list based on a predicate
Supposing I have a list and i want to delete from it elements that respect a condition,, how can i implement this easier?
I tried with:
for i in range (len(list)):
if [condition]:
del(list[i]);
Obviously it does not work...the... | [
"How about using a list comprehension:\nmylist = [x for x in mylist if not condition]\n\n",
"The simplest way is to create a copy of the list using filter:\nlist_removed = filter(lambda item: not condition(item), list)\n\n",
"I recommend @Space_C0wb0y's solution; however, for completeness I want to point out th... | [
12,
4,
1,
0
] | [] | [] | [
"list",
"python"
] | stackoverflow_0005339333_list_python.txt |
Q:
Reading binary file in python
I wrote a python script to create a binary file of integers.
import struct
pos = [7623, 3015, 3231, 3829]
inh = open('test.bin', 'wb')
for e in pos:
inh.write(struct.pack('i', e))
inh.close()
It worked well, then I tried to read the 'test.bin' file using the below code... | Reading binary file in python | I wrote a python script to create a binary file of integers.
import struct
pos = [7623, 3015, 3231, 3829]
inh = open('test.bin', 'wb')
for e in pos:
inh.write(struct.pack('i', e))
inh.close()
It worked well, then I tried to read the 'test.bin' file using the below code.
import struct
inh = open('test.... | [
"for rec in inh: reads one line at a time -- not what you want for a binary file. Read 4 bytes at a time (with a while loop and inh.read(4)) instead (or read everything into memory with a single .read() call, then unpack successive 4-byte slices). The second approach is simplest and most practical as long as the ... | [
8,
5,
1,
1,
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0002274503_python.txt |
Q:
Python database connection
In python is it possible to add connection timeout in the below code,if possible then please help me
connectionString = "Provider=SQLOLEDB.1;Data Source="+options.server+";Initial Catalog="+options.database+";Integrated Security=SSPI"
Connection = win32com.client.Dispatch('ADODB.Records... | Python database connection | In python is it possible to add connection timeout in the below code,if possible then please help me
connectionString = "Provider=SQLOLEDB.1;Data Source="+options.server+";Initial Catalog="+options.database+";Integrated Security=SSPI"
Connection = win32com.client.Dispatch('ADODB.Recordset')
Connection.ActiveConnection... | [
"Read a generic example here: http://programming-guides.com/python/timeout-a-function\n",
"I think you have to actively create (and open) the connection:\nconn = win32com.client.Dispatch('ADODB.Connection')\nconn.CommandTimeout = 3600\nconn.Open(connection_string)\n\nAnd then you can do stuff like:\nrs = win32com... | [
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0005338404_python.txt |
Q:
django point definition
my models:
class Mod(models.model)
name = models.CharField(max_length = 255)
co_x = models.DecimalField(max_digits = 11, decimal_places = 8)
co_y = models.DecimalField(max_digits = 11, decimal_places = 8)
my views:
def closedPoint(request):
location_name = str(request.POST.... | django point definition | my models:
class Mod(models.model)
name = models.CharField(max_length = 255)
co_x = models.DecimalField(max_digits = 11, decimal_places = 8)
co_y = models.DecimalField(max_digits = 11, decimal_places = 8)
my views:
def closedPoint(request):
location_name = str(request.POST.get("lo", default=""))
no... | [
"Ok, so it's now clear your error message comes from initializing a Point class with None. \nThat is your first critical problem. \nJudging by the error message, my guess is that poi_s is initialized with None, None as Mod() is an unsaved instance with no values and those are the invalid parameters.\nsk = Mod() # u... | [
1
] | [] | [] | [
"geodjango",
"openlayers",
"python"
] | stackoverflow_0005327684_geodjango_openlayers_python.txt |
Q:
M2Crypto, Encrypt and Sign at once?
This might be something obvious that I'm missing.
I would like to have my host encrypt a message to a client using the client's public key, and also have that message signed using the hosts private key.
It seems like an obvious scenario, but perhaps my concept is simply wrong. ... | M2Crypto, Encrypt and Sign at once? | This might be something obvious that I'm missing.
I would like to have my host encrypt a message to a client using the client's public key, and also have that message signed using the hosts private key.
It seems like an obvious scenario, but perhaps my concept is simply wrong. I think that you should be able to do wit... | [
"It sounds like you're looking for a hybrid cryptosystem which takes care of encryption and signature together, using appropriate crypto primitives to allow it to work whatever the size of the data, and encapsulating all the components of the cryptogram in one place. PGP, HTTPS and DHIES are good examples. While it... | [
1
] | [] | [] | [
"cryptography",
"m2crypto",
"python",
"rsa"
] | stackoverflow_0005279102_cryptography_m2crypto_python_rsa.txt |
Q:
PyCharm module name conflicts
I have a module named 'io' in my package: mypackage.io. This causes a conflict with the Python built-in io package. Thus, whenever I use PyCharm to perform debugging of my code, since pydev helper uses gzip (which in turns uses io), I encounter a module ImportError. The problem is par... | PyCharm module name conflicts | I have a module named 'io' in my package: mypackage.io. This causes a conflict with the Python built-in io package. Thus, whenever I use PyCharm to perform debugging of my code, since pydev helper uses gzip (which in turns uses io), I encounter a module ImportError. The problem is partly due to PyCharm automatically ad... | [
"You basically have two options:\n\nRename your custom package\nExplicitly use mypackage.io.foo instead of io.foo\n\nGenerally speaking, its bad form to map a custom package atop a built-in unless you are intentionally changing that default builtin's behavior. Any short-term game will be offset by many, long-term ... | [
3
] | [] | [] | [
"import",
"path",
"pycharm",
"python"
] | stackoverflow_0005332794_import_path_pycharm_python.txt |
Q:
How can I put Pyramid in front of a PHP website using the same webserver?
The scenario is: I current have an old website that runs on PHP. Over time, that code has become hacked up and messy. It's due for a rewrite. However, I don't have time to do that rewrite yet. But I'd like to plan for it in the future.
What ... | How can I put Pyramid in front of a PHP website using the same webserver? | The scenario is: I current have an old website that runs on PHP. Over time, that code has become hacked up and messy. It's due for a rewrite. However, I don't have time to do that rewrite yet. But I'd like to plan for it in the future.
What I need to do now is add a 'welcome' type page to the website. I'd like to code ... | [
"I am not sure about Apache configuration, but you could use wphp, a wsgi middleware for serving php.\nhttp://pythonpaste.org/wphp/\n",
"Use recipes for using AddHandler described in:\nhttp://code.google.com/p/modwsgi/wiki/ConfigurationGuidelines#The_Apache_Alias_Directive\nApply the AddHandler and the rewrite ru... | [
0,
0
] | [] | [] | [
"apache",
"mod_wsgi",
"php",
"pyramid",
"python"
] | stackoverflow_0005337279_apache_mod_wsgi_php_pyramid_python.txt |
Q:
SQLAlchemy IntegrityError
I'm having a problem using SQLAlchemy with PySide(PyQt). I'm trying to pop-up a QtGui.QDialog, but when I do this SQLAlchemy throws an exception:
Traceback (most recent call last):
File "C:\Python27\lib\site-packages\preo\preodb\dbviewandmodel.py", line 32, in rowCount
return len(s... | SQLAlchemy IntegrityError | I'm having a problem using SQLAlchemy with PySide(PyQt). I'm trying to pop-up a QtGui.QDialog, but when I do this SQLAlchemy throws an exception:
Traceback (most recent call last):
File "C:\Python27\lib\site-packages\preo\preodb\dbviewandmodel.py", line 32, in rowCount
return len(self.rows())
File "C:\Pyth... | [
"I've managed to make this problem go away, but it's still not really clear to me why SQLAlchemy was trying to insert rows in my database - that really bothers me, but it's not happening anymore.\nAt any rate, what was, I think, happening, was related to my SQLAlchemy data model and the way I was accessing it, here... | [
0
] | [] | [] | [
"pyqt",
"pyside",
"python",
"python_elixir",
"sqlalchemy"
] | stackoverflow_0005333170_pyqt_pyside_python_python_elixir_sqlalchemy.txt |
Q:
python, google app engine, and twitter: my program is not working right
I made this silly little app that uses twitters api and scans through the last 'x' tweets, finds tiny URL's, find out what URL that the tiny URL is pointing to, accumulates the frequency of top level domains that have been tweeted about, and o... | python, google app engine, and twitter: my program is not working right | I made this silly little app that uses twitters api and scans through the last 'x' tweets, finds tiny URL's, find out what URL that the tiny URL is pointing to, accumulates the frequency of top level domains that have been tweeted about, and outputs a html tagcloud page based on the frequencies.
But it doesn't work qui... | [
"I'm not sure about the crashes, but try putting each request in its own thread - assuming that webapp.RequestHandler is thread-safe and non-blocking on IO this should save you a lot of time as you can process lots of requests at the same time. IO-bound situations such as this are one of the most useful cases for ... | [
1
] | [] | [] | [
"python"
] | stackoverflow_0005340715_python.txt |
Q:
For list unless empty in python
I've been writing a lot of constructs like this the past couple of days:
list = get_list()
if list:
for i in list:
pass # do something with the list
else:
pass # do something if the list was empty
Lot of junk and I assign the list to a real variable (keeping it in m... | For list unless empty in python | I've been writing a lot of constructs like this the past couple of days:
list = get_list()
if list:
for i in list:
pass # do something with the list
else:
pass # do something if the list was empty
Lot of junk and I assign the list to a real variable (keeping it in memory longer than needed). Python has... | [
"Based on the other answers, I think the cleanest solutions are\n#Handles None return from get_list\nfor item in get_list() or []: \n pass #do something\n\nor the comprehension equiv\nresult = [item*item for item in get_list() or []]\n\n",
"Use a list comprehension:\ndef do_something(x):\n return x**2\n\nlist... | [
76,
10,
5,
3,
2,
1,
0
] | [] | [] | [
"for_loop",
"python"
] | stackoverflow_0001531402_for_loop_python.txt |
Q:
Unicode exception in twisted
On my production server I have periodically happening unicode error but not on my desktop. It appears in logs:
2011-03-17 13:14:53+0000 [GameProtocol,941,95.78.43.17] <unicode instance at 0x9e304a0 with str error:
Traceback (most recent call last):
File "/usr/local/lib/pytho... | Unicode exception in twisted | On my production server I have periodically happening unicode error but not on my desktop. It appears in logs:
2011-03-17 13:14:53+0000 [GameProtocol,941,95.78.43.17] <unicode instance at 0x9e304a0 with str error:
Traceback (most recent call last):
File "/usr/local/lib/python2.6/dist-packages/twisted/python/... | [
"]It's not safe to log unicode with the Twisted logging system. Here's the minimal example that produces the exception you're seeing:\nPython 2.6.4 (r264:75706, Dec 7 2009, 18:43:55)\n[GCC 4.4.1] on linux2\nType \"help\", \"copyright\", \"credits\" or \"license\" for more information.\n>>> from twisted.python imp... | [
5
] | [] | [] | [
"python",
"twisted"
] | stackoverflow_0005340003_python_twisted.txt |
Q:
How do I install IMDbPY on Windows?
I would like to start using IMDbPY but I can't find a Windows installer on their site. What is the most simple way to install it? Is there a way to install it using my Python interpreter?
A:
Windows installer
Python installer - run python -O setup.py install
| How do I install IMDbPY on Windows? | I would like to start using IMDbPY but I can't find a Windows installer on their site. What is the most simple way to install it? Is there a way to install it using my Python interpreter?
| [
"Windows installer\nPython installer - run python -O setup.py install\n"
] | [
6
] | [] | [] | [
"imdb",
"python",
"windows"
] | stackoverflow_0005341218_imdb_python_windows.txt |
Q:
Storing an inverted index
I am working on a project on Info Retrieval.
I have made a Full Inverted Index using Hadoop/Python.
Hadoop outputs the index as (word,documentlist) pairs which are written on the file.
For a quick access, I have created a dictionary(hashtable) using the above file.
My question is, how do... | Storing an inverted index | I am working on a project on Info Retrieval.
I have made a Full Inverted Index using Hadoop/Python.
Hadoop outputs the index as (word,documentlist) pairs which are written on the file.
For a quick access, I have created a dictionary(hashtable) using the above file.
My question is, how do I store such an index on disk ... | [
"shelve\n\nAt present I am storing the dictionary using python pickle module and loading from it but it brings the whole of index into memory at once (or does it?).\n\nYes it does bring it all in.\nIs that a problem? If it's not an actual problem, then stick with it.\nIf it's a problem, what kind of problem do you... | [
5,
1,
0,
0,
0,
0
] | [] | [] | [
"information_retrieval",
"inverted_index",
"python"
] | stackoverflow_0003687715_information_retrieval_inverted_index_python.txt |
Q:
login into adword without use api
There is a way to login into adwords without use api, in order to parsing it to get informations about: campaings, keywords clicks and so on...
something like:
url = 'https://www.google.com/accounts/ClientLogin'
data = [('Email', 'foo@gmail.com'), ('Passwd', 'secret'),
('... | login into adword without use api | There is a way to login into adwords without use api, in order to parsing it to get informations about: campaings, keywords clicks and so on...
something like:
url = 'https://www.google.com/accounts/ClientLogin'
data = [('Email', 'foo@gmail.com'), ('Passwd', 'secret'),
('accountType', 'GOOGLE'), ('service', 'a... | [
"I am a GUI test automation programmer, and som my experience is highly relevant to this question. I create tests designed to interact with a system, as a user would, at the request of my employer, who develop the software I am trying to test. This is an extremely complicated process even if you have to hand the en... | [
2
] | [] | [] | [
"google_ads_api",
"python",
"urllib"
] | stackoverflow_0005334792_google_ads_api_python_urllib.txt |
Q:
How do I convert config file to dict in Python?
server 192.168.10.10 443 {
protocol TCP
_server 192.168.10.1 443 {
weight 1
SSL_GET {
url {
path /
}
connect_timeout 3
}
}
}
A:
Have you got a full specification for the config... | How do I convert config file to dict in Python? | server 192.168.10.10 443 {
protocol TCP
_server 192.168.10.1 443 {
weight 1
SSL_GET {
url {
path /
}
connect_timeout 3
}
}
}
| [
"Have you got a full specification for the configuration files?\nI am going to guess that what you posted is an example of one, however it's very easy to produce a naive parser that works on one example but not others using different features.\nAlso the dictionary structure that it is useful to get out of your pars... | [
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0005337364_python.txt |
Q:
Is it possible to change the Python interpreter version DreamPie is using?
I have both Python 3.1 and Python 2.7 installed on my system. I'm usually using Python 3.1 but sometimes I need to use Python 2.7.
The Python shell I'm using is DreamPie which supports both 3.1 and 2.7. By default, it's using Python 3.1.
Is... | Is it possible to change the Python interpreter version DreamPie is using? | I have both Python 3.1 and Python 2.7 installed on my system. I'm usually using Python 3.1 but sometimes I need to use Python 2.7.
The Python shell I'm using is DreamPie which supports both 3.1 and 2.7. By default, it's using Python 3.1.
Is it possible to tell DreamPie "Please use 2.7 for now" and later return to 3.1 b... | [
"Given the path to your python2 executable...\ndreampie /path/to/python2.x\n\n"
] | [
6
] | [] | [] | [
"python",
"python_3.x",
"shell"
] | stackoverflow_0005341606_python_python_3.x_shell.txt |
Q:
How to Filter specific values against specific words from text file and store it in list?
Possible Duplicate:
How to Filter specific values against specific words from text file and store it in list ?
I have a text file abc.txt and it is like this:
we 2 rt 3 re 3 tr vh kn mo
we 3 rt 5 re 5 tr yh kn me
we 4 rt 6 ... | How to Filter specific values against specific words from text file and store it in list? |
Possible Duplicate:
How to Filter specific values against specific words from text file and store it in list ?
I have a text file abc.txt and it is like this:
we 2 rt 3 re 3 tr vh kn mo
we 3 rt 5 re 5 tr yh kn me
we 4 rt 6 re 33 tr ph kn m3
we 5 rt 9 re 34 tr oh kn me
we 6 rt 8 re 32 tr kh kn md
I want the values a... | [
"words = []\nf = open('abc.txt')\nfor line in f.readlines():\n if 'tr' in line:\n linewords = line.split()\n ind = linewords.index('tr')\n words.append(linewords[ind + 1])\n\nAlso, if you're certain that the data is well formed, you can use awk:\nawk '/tr/ {print $8}' abc.txt\n\n"
] | [
4
] | [] | [] | [
"filtering",
"python"
] | stackoverflow_0005341764_filtering_python.txt |
Q:
for loop in python
I just started with python..
I got an error with for loop..
What is the problem ??
Traceback (most recent call last):
File "userentry.py", line 34, in <module>
userentry(p,i)
File "userentry.py", line 26, in userentry
for cl in len(mylist):
TypeError: 'int' object is not iterable... | for loop in python | I just started with python..
I got an error with for loop..
What is the problem ??
Traceback (most recent call last):
File "userentry.py", line 34, in <module>
userentry(p,i)
File "userentry.py", line 26, in userentry
for cl in len(mylist):
TypeError: 'int' object is not iterable
Please help me
| [
"You can just iterate over the list, you don't iterate over the length of the list.\nfor cl in mylist:\n # do stuff\n\nIf you need to keep track of the index of the current item, use enumerate:\nfor idx, item in enumerate(mylist):\n # idx = index of current item\n # item = current item\n\nWhen you try to d... | [
8,
0,
0
] | [] | [] | [
"for_loop",
"loops",
"python"
] | stackoverflow_0005341794_for_loop_loops_python.txt |
Q:
Scrapy, python, Xpath how to match respective items in html
I am new to Xpath, trying to scrapy website with below format:
<div class="top">
<a> tittle_name </a>
<div class="middle"> listed_date </div>
<div class="middle"> listed_value </div>
</div>
<div class="top">
<a> tittle_name </a>
<div c... | Scrapy, python, Xpath how to match respective items in html | I am new to Xpath, trying to scrapy website with below format:
<div class="top">
<a> tittle_name </a>
<div class="middle"> listed_date </div>
<div class="middle"> listed_value </div>
</div>
<div class="top">
<a> tittle_name </a>
<div class="middle"> listed_date </div>
</div>
<div class="top">
<a... | [
"Do note that those XPath expressions are absolute:\n/a//text()\n\n//div[@class=\\'middle\\']\n\nYou would need relative XPath expression like these:\na\n\ndiv[@class=\\'middle\\']\n\nSecond. It's not a good idea to select text nodes in a mixed content model like (X)HTML. You should extract the string value with th... | [
1,
0
] | [] | [] | [
"python",
"scrapy",
"xpath"
] | stackoverflow_0005341086_python_scrapy_xpath.txt |
Q:
Filling numpy array using [:,:] crashes python?
Greetings,
I have come across an interesting error and was wondering if anyone knew the cause.
I create several numpy arrays of dtype object and wish to initialize them with empty strings, so I did the following to create them:
txtInputs=empty((7,12), dtype=object)
t... | Filling numpy array using [:,:] crashes python? | Greetings,
I have come across an interesting error and was wondering if anyone knew the cause.
I create several numpy arrays of dtype object and wish to initialize them with empty strings, so I did the following to create them:
txtInputs=empty((7,12), dtype=object)
txtInputs[:, :]=''
repeated...
How they are used aft... | [
"This error does not occur with numpy 1.5.1. We were fixing quite a few bugs around the time of numpy 1.0.4, particularly with the object and string dtypes. This is probably one of them. The bug has apparently been fixed since then.\n"
] | [
4
] | [] | [] | [
"arrays",
"crash",
"numpy",
"python",
"string"
] | stackoverflow_0005340739_arrays_crash_numpy_python_string.txt |
Q:
Memory not deallocated - PyQt4
It might be the bindings (SIP) or even python, but I have a problem with Qt (pyqt4).
I have a QTabWidget, and inside it I put widgets one can close.
I have a widget that allocates about 400mb of memory. I have not set a parent, and I call deleteLater() on close but nothing happens. E... | Memory not deallocated - PyQt4 | It might be the bindings (SIP) or even python, but I have a problem with Qt (pyqt4).
I have a QTabWidget, and inside it I put widgets one can close.
I have a widget that allocates about 400mb of memory. I have not set a parent, and I call deleteLater() on close but nothing happens. Even calling the python's gc does not... | [
"I had this - somewhere you have an reference to your widget, and that reference has been counted... the only way to delete that widget is to make sure that there are no remaining references so python can garbage-collect it.\nAt least you don't end up with a dangling reference like C++, which can lead to some nasty... | [
3
] | [] | [] | [
"garbage_collection",
"pyqt4",
"python",
"qt"
] | stackoverflow_0005341954_garbage_collection_pyqt4_python_qt.txt |
Q:
Problems with regex matching
I'm currently learning Python and I'm trying to make a small scraper but I'm running in to problems with Beautiful Soup and regex.
I am trying to match all links in a site that has the following html:
<td>
<a href="/l1234/Place+Number+1">Place Number 1 </a>
</td>
<td width="100">
... | Problems with regex matching | I'm currently learning Python and I'm trying to make a small scraper but I'm running in to problems with Beautiful Soup and regex.
I am trying to match all links in a site that has the following html:
<td>
<a href="/l1234/Place+Number+1">Place Number 1 </a>
</td>
<td width="100">
California </td>
<td>
<a h... | [
"Shouldn't you be trying to do the regex match on href and not id?\nfor tag in soup.findAll('a', href = re.compile('l[0-9]*')):\n print tag['href']\n\n",
"I would suggest\nfor tag in soup.findAll('a', href = re.compile('^/l[0-9]+/.*$')):\n print tag['href']\n\nfor avoiding tags looking like but not exactly ... | [
4,
2,
1
] | [] | [] | [
"beautifulsoup",
"python",
"regex"
] | stackoverflow_0005341849_beautifulsoup_python_regex.txt |
Q:
What's the pythonic way of using a source url to create a new url with different path and scheme?
Say I have a url that or may not be HTTPS, and who's host name I don't control, but follows a format like:
http://example.com/special/content [OR]
https://example.com/special/content
Using Python what would be ... | What's the pythonic way of using a source url to create a new url with different path and scheme? | Say I have a url that or may not be HTTPS, and who's host name I don't control, but follows a format like:
http://example.com/special/content [OR]
https://example.com/special/content
Using Python what would be the pythonic way of changing scheme to https and path to /something/else
My current approach is:
from u... | [
"You are so close. Use urlparse.urlparse() to split it up, take the parts you care about, and then use urlparse.urlunparse() to put it back together.\n"
] | [
4
] | [] | [] | [
"python"
] | stackoverflow_0005342114_python.txt |
Q:
How can I identify an element from a list within another list
I have been trying to make a block of code that finds the index of the largest bid for each item. Then I was going to use the index as a way to identify the person who paid that much moneys name. However no matter what i try I can't link the person and ... | How can I identify an element from a list within another list | I have been trying to make a block of code that finds the index of the largest bid for each item. Then I was going to use the index as a way to identify the person who paid that much moneys name. However no matter what i try I can't link the person and what they have gained from the auction together. Here is the code I... | [
"You can use other structure for your bids. Instead of using different lists synchronized by index, you can use dictionary and python tuples. Maybe something like this:\nitems_bids = { \n item1: [ (bidder1, amount), (some_other_bidder, amount), ... ],\n item2: [ (bidder1, amount), (some_other_bidder, amount), .... | [
1,
1,
0
] | [] | [] | [
"nested",
"nested_lists",
"python"
] | stackoverflow_0005341799_nested_nested_lists_python.txt |
Q:
is it possible to Insert a python tuple in a postgresql database
is it possible to Insert a python tuple in a postgresql database
A:
Yes, it is. Probably the easiest way is to serialise it using e.g. marshal, pickle or json and store it in a text field.
Another approach is to use Postgres' multitude of data typ... | is it possible to Insert a python tuple in a postgresql database | is it possible to Insert a python tuple in a postgresql database
| [
"Yes, it is. Probably the easiest way is to serialise it using e.g. marshal, pickle or json and store it in a text field.\nAnother approach is to use Postgres' multitude of data types e.g. array type.\nFinally, if the number of elements and their types of each tuple is fixed, then you may just create this many colu... | [
3,
2,
1,
1
] | [] | [] | [
"database",
"postgresql",
"python"
] | stackoverflow_0005342359_database_postgresql_python.txt |
Q:
Call handler initially in python
I have a datatable which may contain some data at the time of start of application.
My datatable is showing data when one request has been sent to the server, because initially view.py is not being called.
How can I ensure that views.py is called at application start so that my t... | Call handler initially in python | I have a datatable which may contain some data at the time of start of application.
My datatable is showing data when one request has been sent to the server, because initially view.py is not being called.
How can I ensure that views.py is called at application start so that my template can pick up the values.
I am ... | [
"If you are finding that views.py is not used, you may have done something funky with your app. I would suggest that you read the manual before trying to write an application in django, rather than posting garbled messages on a Q&A website. Until you know more or less what you're doing, you're not going to know how... | [
0,
0
] | [] | [] | [
"django",
"mysql",
"python"
] | stackoverflow_0005337939_django_mysql_python.txt |
Q:
How to Filter specific values against specific words from text file and store it in list?
Like i have a text file abc.txt and it is like this
we 2 rt 3 re 3 tr vh kn mo
we 3 rt 5 re 5 tr yh kn me
we 4 rt 6 re 33 tr ph kn m3
we 5 rt 9 re 34 tr oh kn me
we 6 rt 8 re 32 tr kh kn md
now i want the values against the ... | How to Filter specific values against specific words from text file and store it in list? | Like i have a text file abc.txt and it is like this
we 2 rt 3 re 3 tr vh kn mo
we 3 rt 5 re 5 tr yh kn me
we 4 rt 6 re 33 tr ph kn m3
we 5 rt 9 re 34 tr oh kn me
we 6 rt 8 re 32 tr kh kn md
now i want the values against the tr and after filtering it should get this result
[vh,yh,ph,oh,kh]
can anyone tell how to do ... | [
"mylist = [line.split()[7] for line in myfile] \n\nshould work if it's always the 8th column.\nIf the position of tr is variable, you could do\nmylist = []\nfor line in myfile:\n items = line.split()\n mylist.append(items[items.index(\"tr\")+1])\n\n",
"You can split the lines as before tr and after tr and o... | [
2,
2,
1,
0,
0,
0,
0
] | [] | [] | [
"filtering",
"python"
] | stackoverflow_0005340953_filtering_python.txt |
Q:
Is is possible to access VB .net APIs in Python
I am new to programming in Python, I was wondering if there is a way to access VB .net APIs using Python.
Please let me know
thanks in advance.
VG
A:
Python for .NET
Python for .NET is a package that gives Python programmers nearly seamless integration with the .NE... | Is is possible to access VB .net APIs in Python | I am new to programming in Python, I was wondering if there is a way to access VB .net APIs using Python.
Please let me know
thanks in advance.
VG
| [
"Python for .NET\nPython for .NET is a package that gives Python programmers nearly seamless integration with the .NET Common Language Runtime (CLR) and provides a powerful application scripting tool for .NET developers. \nUsing this package you can script .NET applications or build entire applications in Python, u... | [
6
] | [] | [] | [
"python",
"vb.net"
] | stackoverflow_0005342504_python_vb.net.txt |
Q:
How to store folders/files tree
I design a multi-threaded application that will monitor and handle files in selected folders (according to user preference).
What is the best way to store information on the files ?
(e.g. User add xxx directory, I need to go over the directory and add all the files and sub dir to my... | How to store folders/files tree | I design a multi-threaded application that will monitor and handle files in selected folders (according to user preference).
What is the best way to store information on the files ?
(e.g. User add xxx directory, I need to go over the directory and add all the files and sub dir to my application)
I was considering my ow... | [
"SQLite is a nice solution, as the database wrapper will handle locking of reads and writes (within the database) for you. You can even use a column as your file's read/write lock.\n",
"It depends on your environment, size and type of project, etc.\nThe EASIEST way is to use the pickle.\nFor example the data is i... | [
2,
0
] | [] | [] | [
"python"
] | stackoverflow_0005342430_python.txt |
Q:
cursor.execute("INSERT INTO im_entry.test ("+entrym+") VALUES ('"+p+"');")
entrym='entry'
entrym=entrym+ str(idx)
cursor.execute("INSERT INTO im_entry.test ("+entrym+") VALUES ('"+p+"');")
I am using a query like this, where entry1, entry2 etc. are my database tables. The program doesn't show any errors... | cursor.execute("INSERT INTO im_entry.test ("+entrym+") VALUES ('"+p+"');") | entrym='entry'
entrym=entrym+ str(idx)
cursor.execute("INSERT INTO im_entry.test ("+entrym+") VALUES ('"+p+"');")
I am using a query like this, where entry1, entry2 etc. are my database tables. The program doesn't show any errors, but the p value does not get inserted in the db. What is wrong here? Please he... | [
"By default, psycopg2 starts transactions for you automatically, which means that you have to tell it to commit. Note that commit is a method of the connection, not the cursor.\nconn = psycopg2.connection('...')\ncur = conn.cursor()\ncur.execute(\"...\")\nconn.commit()\n\nThe intent is that you can group multiple s... | [
14
] | [] | [] | [
"database",
"postgresql",
"python"
] | stackoverflow_0005342698_database_postgresql_python.txt |
Q:
display an object's attributes in python
I would like to display the attributes of a give object and was wondering if there was a python function for it.
For example if I had an object from the following class:
class Antibody():
def __init__(self,toSend):
self.raw = toSend
self.pdbcode = ''
... | display an object's attributes in python | I would like to display the attributes of a give object and was wondering if there was a python function for it.
For example if I had an object from the following class:
class Antibody():
def __init__(self,toSend):
self.raw = toSend
self.pdbcode = ''
self.year = ''
Could I get an output t... | [
"Try dir(self). It will include all attributes, not only \"data\".\n",
"The following method prints ['self.pdbcode', 'self.raw', 'self.year'] for an instance of your class:\nclass Antibody():\n ...\n def get_fields(self):\n ret = []\n for nm in dir(self):\n if not nm.startswith('__'... | [
15,
8,
1,
0
] | [] | [] | [
"list",
"oop",
"python"
] | stackoverflow_0005340042_list_oop_python.txt |
Q:
Can I retrieve IMDb's movie recommendations for a given movie using IMDbPY?
I'm using IMDbPY to retrieve all kinds of data about movies. For example, if I have a movie object of "Pulp Fiction (1994)" then I can get the name of its (first) director like this:
>>> pulp_fiction['director'][0]['name']
u'Quentin Ta... | Can I retrieve IMDb's movie recommendations for a given movie using IMDbPY? | I'm using IMDbPY to retrieve all kinds of data about movies. For example, if I have a movie object of "Pulp Fiction (1994)" then I can get the name of its (first) director like this:
>>> pulp_fiction['director'][0]['name']
u'Quentin Tarantino'
Or the name of the third actor:
>>> pulp_fiction['cast'][2]['name']
... | [
"Looking in the source, I found something:\nhttp://bitbucket.org/alberanid/imdbpy/src/579c50b280f9/imdb/parser/http/init.py\ncheck def get_movie_recommendations(self, movieID)\nI haven't tried it, but it looks like it might be doing what you are looking for.\n"
] | [
9
] | [] | [] | [
"imdb",
"python"
] | stackoverflow_0005342329_imdb_python.txt |
Q:
How and where to execute the python bulkloader command to upload .CSV file to Google App engine?
How and where to execute the python bulkloader command to upload a .CSV file to Google App engine ?
I am trying to upload a simple CSV file (2 column: tag, value, 7000
lines) into my datastore google app engine using ... | How and where to execute the python bulkloader command to upload .CSV file to Google App engine? | How and where to execute the python bulkloader command to upload a .CSV file to Google App engine ?
I am trying to upload a simple CSV file (2 column: tag, value, 7000
lines) into my datastore google app engine using the bulkloader.
I read the topic at: http://code.google.com/intl/fr-FR/appengine/docs/python/tools/up... | [
"I run it from the command line, in the same directory as the app.yaml of my project.\nSince appcfg.py is on my system path I can use the following command on MacOS (including the trailing dot):\nappcfg.py create_bulkloader_config --filename=bulkloader.yaml .\nThen the bulkloader.yaml will be created in that folder... | [
2,
0
] | [] | [] | [
"bulkloader",
"google_app_engine",
"python"
] | stackoverflow_0005342665_bulkloader_google_app_engine_python.txt |
Q:
TypeError: can only concatenate list (not "int") to list
I'm trying to do something usefull with some itens in list in the following code:
IPS=['10.254.243.83','10.254.243.82']
def commands(cmd):
command = Popen(cmd, shell=True, stdout=PIPE)
command_strip = command.stdout.read().strip()
print command_... | TypeError: can only concatenate list (not "int") to list | I'm trying to do something usefull with some itens in list in the following code:
IPS=['10.254.243.83','10.254.243.82']
def commands(cmd):
command = Popen(cmd, shell=True, stdout=PIPE)
command_strip = command.stdout.read().strip()
print command_strip
def main():
for ip in IPS:
ping = call('pin... | [
"You pass the return value of\ncall('ping -c 3 %s' % ip, shell=True)\n\nas cmd argument to your commands() function. The mentioned return value is an integer, which does not make any sense as a command, so trying to execute this integer using Popen() fails as expected.\n",
"Have you tried replacing\nping = call(... | [
4,
3
] | [] | [] | [
"python"
] | stackoverflow_0005343155_python.txt |
Q:
What is the best way to communicate between Python softwares running on the same computer?
I used MailSlots with Delphi for my softwares when I needed dialogs between them (on MS Windows on the same coputer).
Now I need to do the same things but with Python and on MS Windows but also on Linux.
So : what is the bes... | What is the best way to communicate between Python softwares running on the same computer? | I used MailSlots with Delphi for my softwares when I needed dialogs between them (on MS Windows on the same coputer).
Now I need to do the same things but with Python and on MS Windows but also on Linux.
So : what is the best way to communicate between Python written software running on the same computer ?
For some fir... | [
"On Linux you could use DBus, which has bindings for Python, and actually allows communication between processes even in different languages.\nUnfortunately this would not be portable. I don't know what would be suitable on a Windows environment.\n",
"The multiprocessing module has Listeners and Clients: \"It bas... | [
2,
2,
0
] | [] | [] | [
"pipe",
"python"
] | stackoverflow_0005343264_pipe_python.txt |
Q:
Pylibnet constants
i am introducing myself in the pylibnet library, I want to ask you how i can get the constants imported in this code.
import libnet
from libnet.constants import *
I try help(libnet) but there are nor any answers to my problem.
Thank you!!
A:
Have you tried dir(libnet.constants) ?
Also libnet.... | Pylibnet constants | i am introducing myself in the pylibnet library, I want to ask you how i can get the constants imported in this code.
import libnet
from libnet.constants import *
I try help(libnet) but there are nor any answers to my problem.
Thank you!!
| [
"Have you tried dir(libnet.constants) ?\nAlso libnet.constants.__dict__ should work.\nTo cut down on the noise a bit you could do \n[x for x in libnet.constants.__dict__ if x[:2] != '__' and not callable(libnet.constants.__dict__[x])]\n\n"
] | [
1
] | [] | [] | [
"libnet",
"python"
] | stackoverflow_0005343032_libnet_python.txt |
Q:
How does encoding in email subjects work? (Django/ Python)
I am sending email with EmailMessage object to Gmail box.
The subject of an email looks something like this:
u"You got a letter from Daėrius ęėįęėįęįėęįę---reply3_433441"
When i receive an email, looking at the message info i can see that Subject line look... | How does encoding in email subjects work? (Django/ Python) | I am sending email with EmailMessage object to Gmail box.
The subject of an email looks something like this:
u"You got a letter from Daėrius ęėįęėįęįėęįę---reply3_433441"
When i receive an email, looking at the message info i can see that Subject line looks like this:
Subject: =?utf-8?b?WW91IGdvdCBhIGxldHRlciBmcm9tIERh... | [
"See RFC 2047 for a complete description of the format of internationalized email headers. The basic format is \"=?\" charset \"?\" encoding \"?\" encoded-text \"?=\". So in your case, you have a base-64 encoded UTF-8 string.\nYou can use the email.header.decode_header and str.decode functions to decode it and ge... | [
4,
3,
0
] | [] | [] | [
"django",
"email",
"encoding",
"python"
] | stackoverflow_0005343191_django_email_encoding_python.txt |
Q:
Python Threading Over a Counter
I have a function that needs to be called N times. I would like T threads to execute the function in parallel. How would you model this in python?
A:
And now, for some alternative fun :)
import threading
from itertools import repeat
from multiprocessing.pool import ThreadPool # ... | Python Threading Over a Counter | I have a function that needs to be called N times. I would like T threads to execute the function in parallel. How would you model this in python?
| [
"And now, for some alternative fun :)\nimport threading\nfrom itertools import repeat\nfrom multiprocessing.pool import ThreadPool # this is a THREAD POOL! undocumented :)\n\n\ndef execute_me():\n print threading.current_thread().name, 'python is fun'\n\n\ntp = ThreadPool(processes=4)\nprint tp.map(lambda x: x... | [
3,
1,
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0005343387_python.txt |
Q:
How to save a ForeignKey without retrieving the foreign object instance?
I have a model in which I want to save a new instance (row). I have the primary key for the ForeignKey but I do not have the object itself (suppose it came from somewhere). Is there any way to save it without raw SQL and without having to get... | How to save a ForeignKey without retrieving the foreign object instance? | I have a model in which I want to save a new instance (row). I have the primary key for the ForeignKey but I do not have the object itself (suppose it came from somewhere). Is there any way to save it without raw SQL and without having to get the instance?
Here is the model:
class UserLocale(models.Model):
user = ... | [
"You can just use the id field underlying the ForeignKey object:\nUserLocale.objects.create(user=user_instance, locale_id=locale)\n\n(I presume the reference to Locale in your last line should actually have been UserLocale).\n",
"def save_locale(user_instance, locale_name):\n user_locale = UserLocale()\n us... | [
5,
0
] | [] | [] | [
"django",
"django_models",
"python"
] | stackoverflow_0005343755_django_django_models_python.txt |
Q:
How to turn the result (in python) of itertools.permutations("0123456789") into list of strings
In Python, I am using list(itertools.permutations("0123456789")), and I am receiving (I as expected) a list of tuples of singled character strings.
Is there a way to turn that result into a list of strings, without iter... | How to turn the result (in python) of itertools.permutations("0123456789") into list of strings | In Python, I am using list(itertools.permutations("0123456789")), and I am receiving (I as expected) a list of tuples of singled character strings.
Is there a way to turn that result into a list of strings, without iterating over all 3628800 items?
| [
"If you want to do it without iterating over the whole list but rather lazily doing it as needed, you can use itertools.imap:\nitertools.imap(lambda x: \"\".join(x), itertools.permutations(\"0123456789\"))\n\n(note that I'm not using list() on the result of permutations here so it's as lazy as possible)\nOr, as poi... | [
5,
1
] | [] | [] | [
"list",
"permutation",
"python",
"python_itertools",
"string"
] | stackoverflow_0005343877_list_permutation_python_python_itertools_string.txt |
Q:
How to split my strings with re.split?
I'm beginning my adventure with regular expressions.
I'm interested in splitting specially formatted strings. If a letter is not inside parentheses it should become a different element of output list. Letters grouped inside parentheses should be put together.
Samples:
my stri... | How to split my strings with re.split? | I'm beginning my adventure with regular expressions.
I'm interested in splitting specially formatted strings. If a letter is not inside parentheses it should become a different element of output list. Letters grouped inside parentheses should be put together.
Samples:
my string => wanted list
"ab(hpl)x" => ['a', 'b', ... | [
"This cannot be done with re.split, as it would require splitting on zero length matches.\nFrom http://docs.python.org/library/re.html#re.split:\n\nNote that split will never split a string on an empty pattern match.\n\nHere is an alternative:\nre.findall(r'(\\w+(?=\\))|\\w)', your_string)\n\nAnd an example:\n>>> f... | [
5,
1
] | [] | [] | [
"python",
"regex",
"split"
] | stackoverflow_0005343294_python_regex_split.txt |
Q:
How to install NLTK on my webserver
Ok I edited my question since I now have a host that does support ssh.
How can i install the nltk module for python using ssh?
I tried contacting support but they can't seem to help me. You guys any ideas? How can I install modules in general on my webserver? what's the hosting... | How to install NLTK on my webserver | Ok I edited my question since I now have a host that does support ssh.
How can i install the nltk module for python using ssh?
I tried contacting support but they can't seem to help me. You guys any ideas? How can I install modules in general on my webserver? what's the hosting's equivalent of sudo python setup.py ins... | [
"You will need shell access (though not necessarily root access) to properly install a Python module.\nHowever, since you're able to execute Python code on the remote, you might be able to set up a script that you can run through a web browser that runs python setup.py install --home=DIR for NLTK on the remote, whe... | [
1,
1
] | [] | [] | [
"nltk",
"python"
] | stackoverflow_0005341957_nltk_python.txt |
Q:
Problem creating CFloat64 ENVI files with GDAL 1.6.1
I'm trying to write ENVI CFloat64 files with GDAL:
import numpy
from osgeo import gdal
from osgeo.gdalconst import GDT_CFloat64
a = numpy.zeros((1000, 1000), dtype='complex64')
driver = gdal.GetDriverByName("ENVI")
outfile = driver.Create("test.bin", 1000, 1000... | Problem creating CFloat64 ENVI files with GDAL 1.6.1 | I'm trying to write ENVI CFloat64 files with GDAL:
import numpy
from osgeo import gdal
from osgeo.gdalconst import GDT_CFloat64
a = numpy.zeros((1000, 1000), dtype='complex64')
driver = gdal.GetDriverByName("ENVI")
outfile = driver.Create("test.bin", 1000, 1000, 1, GDT_CFloat64)
outfile.GetRasterBand(1).WriteArray(a, ... | [
"In a nutshell, when driver.Create(...) or gdal.Open(...), etc return None, it's gdal's way of raising an IOError or indicating than the given driver name is invalid. (Or potentially indicating that another sort of error occured, but those two seem the most likely)\n(I'll skip the rant about how much I dislike gdal... | [
1,
1
] | [] | [] | [
"gdal",
"image_processing",
"numpy",
"python"
] | stackoverflow_0005006911_gdal_image_processing_numpy_python.txt |
Q:
Yapsy minimal example
Can anyone provide a minimal working example using the Yapsy plugin framework?
A:
Here's a very simple example. It has three files:
plugins\plugin1.py - the plugin. This has to contain a class inherited from IPlugin.
plugins\plugin1.yapsy-plugin - information about the plugin.
yapsy-exam... | Yapsy minimal example | Can anyone provide a minimal working example using the Yapsy plugin framework?
| [
"Here's a very simple example. It has three files:\n\nplugins\\plugin1.py - the plugin. This has to contain a class inherited from IPlugin.\nplugins\\plugin1.yapsy-plugin - information about the plugin.\nyapsy-example.py - the main script. This just loads all the plugins it can find in the \"plugins\" directory,... | [
46
] | [] | [] | [
"plugins",
"python"
] | stackoverflow_0005333128_plugins_python.txt |
Q:
Is there way to construct a Q object, that represents a EmptyQueryset, i.e. that always returns an empty result?
In django I want to retrieve objects from the database depending on the attributes of some other objects. If one of the other objects doesn't exist, it should not influence the result of the query. The ... | Is there way to construct a Q object, that represents a EmptyQueryset, i.e. that always returns an empty result? | In django I want to retrieve objects from the database depending on the attributes of some other objects. If one of the other objects doesn't exist, it should not influence the result of the query. The code is like this:
from django.db.models import Q
try:
objectA = MyModel.objects.get(id = idA)
qA = Q(foo = ob... | [
"qList = []\ntry:\n objectA = ...\n qList.append(Q(foo=objectA.bar))\nexcept ...:\n ...\n ...\n\nresult = MyOtherMdel.objects.filter(reduce(operator.or_, qList),\n **other_filter_conditions)\n\n",
"\nFor Querysets there is the none() method, which always returns the EmptyQueryset. Is there something similar f... | [
3,
0
] | [] | [] | [
"django",
"django_q",
"python"
] | stackoverflow_0005341998_django_django_q_python.txt |
Q:
Amazon Linux AMI EC2 - librrd.so.2 dependency issue
I am attemping to install OpsCenter for Cassandra, and using the the standard REHL image. I can't figure out how to get this to work. Another version of EPEL perhaps?
yum install opscenter....
Error: Package: python26-rrdtool-1.2.27-1.i386 (opscenter)
... | Amazon Linux AMI EC2 - librrd.so.2 dependency issue | I am attemping to install OpsCenter for Cassandra, and using the the standard REHL image. I can't figure out how to get this to work. Another version of EPEL perhaps?
yum install opscenter....
Error: Package: python26-rrdtool-1.2.27-1.i386 (opscenter)
Requires: librrd.so.2
| [
"FYI:\nftp://194.199.20.114/linux/EPEL/5/i386/rrdtool-1.2.27-3.el5.i386.rpm\nWorked after rpm install and fixed dep issue.\n",
"Try installing rrdtool via yum, that should contain librrd.so.2 and correct your issue.\n"
] | [
1,
0
] | [] | [] | [
"cassandra",
"centos",
"linux",
"python",
"yum"
] | stackoverflow_0005344641_cassandra_centos_linux_python_yum.txt |
Q:
Editing Windows registry, from Python, Under Linux
I am looking for a Python API (or a C API as I am willing to bind) for editing Windows registries from XP to 7 from within a Linux system.
The Windows target will be a mounted volume under Linux.
I would be willing to code a library if none exists. Therefore, any ... | Editing Windows registry, from Python, Under Linux | I am looking for a Python API (or a C API as I am willing to bind) for editing Windows registries from XP to 7 from within a Linux system.
The Windows target will be a mounted volume under Linux.
I would be willing to code a library if none exists. Therefore, any docs or internals on the registry would be handy too.
An... | [
"OK, so you're after a hive file editor?\nI wrote a winregistry module that does this (for both NT and win9x hives). It's not really ready for the public but worked quite well with the data I was using at the time. I'm not sure what state I left it in and I haven't tested it with Win7 hives, but maybe we could get ... | [
7,
1,
0,
0
] | [] | [] | [
"linux",
"python",
"registry",
"windows"
] | stackoverflow_0001666690_linux_python_registry_windows.txt |
Q:
How to exit a loop of Python Multiprocessing?
I have a multiprocessing code that search database records for a certain condition, when it reaches the end of the database the loop must stop, how can I do that? Here is the code:
import psycopg2
from multiprocessing import Pool
conn = psycopg2.connect(a database)
qu... | How to exit a loop of Python Multiprocessing? | I have a multiprocessing code that search database records for a certain condition, when it reaches the end of the database the loop must stop, how can I do that? Here is the code:
import psycopg2
from multiprocessing import Pool
conn = psycopg2.connect(a database)
query=conn.cursor()
query.execute(some query)
def sc... | [
"Move your query / cursor over as the iterable and let multiprocessing distribute the work for you.\nimport psycopg2\nfrom multiprocessing import Pool\n\n\ndef scanfile(row):\n #do something with row...\n\n\nif __name__ == '__main__':\n conn = psycopg2.connect(a database)\n query = conn.cursor()\n query... | [
1
] | [] | [] | [
"multiprocessing",
"python"
] | stackoverflow_0005344099_multiprocessing_python.txt |
Q:
Oriented forest TAoCP - Algorithm in python
I try to implement Algorithm O (Oriented forests) from Donald E. Knuth: 'The Art of Computer Programming - Volume 4, Fascile 4, Generating All Trees' on page 24.
My Python solution is:
def generate_oriented_forest(n):
"""Algorithm O from Knuth TAoCP, Fascicle 4, p. 2... | Oriented forest TAoCP - Algorithm in python | I try to implement Algorithm O (Oriented forests) from Donald E. Knuth: 'The Art of Computer Programming - Volume 4, Fascile 4, Generating All Trees' on page 24.
My Python solution is:
def generate_oriented_forest(n):
"""Algorithm O from Knuth TAoCP, Fascicle 4, p. 25. """
p = range(-1, n)
while True:
... | [
"Congratulations!\nIt sure looks like you just found an error in TAOCP. As you no doubt know, there's a reward of one hexadecimal dollar (drawn on the Bank of San Seriffe) for the first finder of such errors. I've got one, and I can tell you, it's a hell of thing to put on your wall. \nIt certainly appears to me ... | [
2,
0,
0,
0,
0
] | [] | [] | [
"algorithm",
"python",
"taocp"
] | stackoverflow_0001633833_algorithm_python_taocp.txt |
Q:
Translate 8 queens problem from python to java : need help
I just begin to learn java (today),
To exercise me, I would like to translate the following "8 Queens" algorithm written in python into Java :
BOARD_SIZE = 8
def under_attack(col, queens):
left = right = col
for r, c in reversed(queens):
l... | Translate 8 queens problem from python to java : need help | I just begin to learn java (today),
To exercise me, I would like to translate the following "8 Queens" algorithm written in python into Java :
BOARD_SIZE = 8
def under_attack(col, queens):
left = right = col
for r, c in reversed(queens):
left, right = left-1, right+1
if c in (left, col, right):... | [
"The correction needed to your code to run identicaly to the python program is the following. At the begining of the solve() function instead of:\n if ( n==0 ) {\n return new_solutions;\n }\n\nyou should write:\n if ( n==0 ) {\n ArrayList<Integer[]> empty = new ArrayList<Integer[]>();\n ... | [
1
] | [] | [] | [
"java",
"python"
] | stackoverflow_0005319052_java_python.txt |
Q:
Embed Audio, Video in Python GUI
I am working on a project that requires me to display some live video feeds from networked cameras and play some unrelated streamed OR stored audio files as well.
All the filepaths are stored in a MySQL database (although I could use something other than MySQL if that'll make thing... | Embed Audio, Video in Python GUI | I am working on a project that requires me to display some live video feeds from networked cameras and play some unrelated streamed OR stored audio files as well.
All the filepaths are stored in a MySQL database (although I could use something other than MySQL if that'll make things easier).
My question is this: what P... | [
"The module Phonon from PyQt\n"
] | [
2
] | [] | [] | [
"audio",
"python",
"user_interface",
"video",
"video_streaming"
] | stackoverflow_0005344927_audio_python_user_interface_video_video_streaming.txt |
Q:
Speed up the creation of pathname
I've 2 folders. The first (called A) contains same images named in the form: subject_incrementalNumber.jpg (where incrementalNumber goes from 0 to X).
Then I process each image contained in folder A and extract some pieces from it, then save each piece in folder B with the name: s... | Speed up the creation of pathname | I've 2 folders. The first (called A) contains same images named in the form: subject_incrementalNumber.jpg (where incrementalNumber goes from 0 to X).
Then I process each image contained in folder A and extract some pieces from it, then save each piece in folder B with the name: subject(the same of the original image c... | [
"As specified, this is indeed a hard problem with no magic shortcuts. In order to find the minimum available number you need to use trial and error, exactly as you are doing. Whilst the implementation could be speeded up, there is a fundamental limitation in the algorithm.\nI think I would relax the constraints to ... | [
1,
0
] | [] | [] | [
"performance",
"python"
] | stackoverflow_0005292535_performance_python.txt |
Q:
Cassandra low performance?
I have to choose Cassandra or MongoDB(or another nosql database, I accept suggestions) for a project with a lot of inserts(1M/day).
So I create a small test to measure the write performance. Here's the code to insert in Cassandra:
import time
import os
import random
import string
import ... | Cassandra low performance? | I have to choose Cassandra or MongoDB(or another nosql database, I accept suggestions) for a project with a lot of inserts(1M/day).
So I create a small test to measure the write performance. Here's the code to insert in Cassandra:
import time
import os
import random
import string
import pycassa
def get_random_string(s... | [
"There is no equivalent to Mongo's unsafe mode in Cassandra. (We used to have one, but we took it out, because it's just a Bad Idea.)\nThe other main problem is that you're doing single-threaded inserts. Cassandra is designed for high concurrency; you need to use a multithreaded test. See the graph at the bottom... | [
12,
4,
2,
1,
1
] | [] | [] | [
"cassandra",
"mongodb",
"nosql",
"python"
] | stackoverflow_0004804630_cassandra_mongodb_nosql_python.txt |
Q:
Iterating Lists in Python, Ruby, Haskell (or whatever)
Update: I realize that I put the question very badly. Here's a second run.
Consider the following function:
myList = []
optimumList = []
def findOptimumListItems():
n = 5
for i in range (n + 1):
for j in range (n + 1 - i):
myList.... | Iterating Lists in Python, Ruby, Haskell (or whatever) | Update: I realize that I put the question very badly. Here's a second run.
Consider the following function:
myList = []
optimumList = []
def findOptimumListItems():
n = 5
for i in range (n + 1):
for j in range (n + 1 - i):
myList.append((i, j, n-i-j))
for i in myList:
win = 0.... | [
"Second Update: Great -- now I understand exactly what you want. This does the same thing as the code in your most recent edit:\ndef optimize(myList):\n score_tup = lambda tup_a, tup_b: sum(1.0 if a > b else 0.5 if a == b else 0 for a, b in zip(tup_a, tup_b))\n scores = ((tup_a, [score_tup(tup_a, tup_b) for t... | [
4,
4,
1,
0,
0
] | [] | [] | [
"functional_programming",
"haskell",
"python",
"ruby"
] | stackoverflow_0005333147_functional_programming_haskell_python_ruby.txt |
Q:
How to set GET parameters with PyCurl?
I'm trying to make a GET request for a REST api using PycURL. I am able to successful make a request if I do not pass any parameters. I am also able to make a POST request by doing the following:
curl.setopt(pycurl.POSTFIELDS, post_data)
I want to make a get request that in... | How to set GET parameters with PyCurl? | I'm trying to make a GET request for a REST api using PycURL. I am able to successful make a request if I do not pass any parameters. I am also able to make a POST request by doing the following:
curl.setopt(pycurl.POSTFIELDS, post_data)
I want to make a get request that includes login parameters. If I try to use the... | [
"Just like a normal URL on the browser, GET parameters are encoded and appended after a ? to the URL. Using python's urllib.urlencode, you can do:\nimport urllib\nimport pycurl\n\nurl = 'http://www.google.com/search'\nparams = {'q': 'stackoverflow answers'}\n\nc = pycurl.Curl()\nc.setopt(c.URL, url + '?' + urllib.u... | [
15,
1
] | [] | [] | [
"get",
"pycurl",
"python",
"rest"
] | stackoverflow_0005345599_get_pycurl_python_rest.txt |
Q:
python copy files to a network location on Windows without mapping a drive
I am running python in a non interactive session on windows and therefore I cannot map a network drive.
Most of what I have researched on here and through google everyone suggests mapping a network drive and copying the files that way.
On l... | python copy files to a network location on Windows without mapping a drive | I am running python in a non interactive session on windows and therefore I cannot map a network drive.
Most of what I have researched on here and through google everyone suggests mapping a network drive and copying the files that way.
On linux I would facilitate this with an smbmount but unfortunately the software I a... | [
"Personally, I've never had difficulties getting Python to simply recognize \\\\\\\\<server>\\\\path\\\\to\\\\directory\\\\. The annoying part is that for every \"\\\" in the win. path, there needs to be 2 in python.\n",
"First get access to the network share with \"NET USE\" - without Drive letter, like:\nwinCMD... | [
31,
11
] | [] | [] | [
"copy",
"file",
"networking",
"python",
"unc"
] | stackoverflow_0005224541_copy_file_networking_python_unc.txt |
Q:
How to add a default time (but not date) to a DateTimeField in DJango?
I have a DateTimeField on a model. In the forms for that model, I use the SplitDateTimeWidget. I want to enable users to enter just a date, and have my code define a default time (like 2 p.m.) if one is not entered.
Is there a simple way to do ... | How to add a default time (but not date) to a DateTimeField in DJango? | I have a DateTimeField on a model. In the forms for that model, I use the SplitDateTimeWidget. I want to enable users to enter just a date, and have my code define a default time (like 2 p.m.) if one is not entered.
Is there a simple way to do this? Since this is needed for multiple forms, I would like to have a way th... | [
"You may be able to do this by subclassing DateTimeField and over-riding the clean() method.\n",
"I tend to do these types of defaults in the models save() method or when the pre_save signal is called. \n"
] | [
1,
0
] | [] | [] | [
"datetime",
"default",
"django",
"forms",
"python"
] | stackoverflow_0005341448_datetime_default_django_forms_python.txt |
Q:
for loop to a list comprehension
Hey all,
I have some code to read certain lines from a file, and wanted to know if it would run faster as a list comprehension or a generator expression/function. And if it does run faster, how would the code look? Still learning Python. Thanks for your help
input = open('C:/.../li... | for loop to a list comprehension | Hey all,
I have some code to read certain lines from a file, and wanted to know if it would run faster as a list comprehension or a generator expression/function. And if it does run faster, how would the code look? Still learning Python. Thanks for your help
input = open('C:/.../list.txt', 'r')
output = open('C:/.../ou... | [
"No need for a list comprehension.\noutput.write(''.join(itertools.islice(inputfile, 2, 4))\n\n",
"If you want to do it with a generator:\noutput.writelines(line for line in input if 2 < int(line) < 5)\n\n",
"Not faster, but if you want to use a list comprehension:\n output.writelines([line for (x, line) in ... | [
6,
2,
1,
0,
0,
0
] | [] | [] | [
"list_comprehension",
"python"
] | stackoverflow_0005344191_list_comprehension_python.txt |
Q:
Django autocategorize in m2m field
I have done a pre_save signal in my django/satchmo inherited model Product called JPiece and I have another model inheritance from satchmo Category called JewelCategory. The pre_save signal makes the JPiece objects get the category list and add those categories that fit the Jpiec... | Django autocategorize in m2m field | I have done a pre_save signal in my django/satchmo inherited model Product called JPiece and I have another model inheritance from satchmo Category called JewelCategory. The pre_save signal makes the JPiece objects get the category list and add those categories that fit the Jpiece description to the relation, that is d... | [
"If you use pre_save, it's called before save(), meaning you can't define m2m relationships since the model doesn't have an ID.\nUse post_save.\n# this works because the ID does exist\np = Jpiece.objects.get(pk=3) \np.save()\n\nUpdate, check out the comment here: Django - How to save m2m data via post_save signal? ... | [
1
] | [] | [] | [
"django",
"django_admin",
"django_signals",
"python"
] | stackoverflow_0005345557_django_django_admin_django_signals_python.txt |
Q:
Python parsing xml directly from web address
Hey. I tried to find a way but i can't. I have set up a xml.sax parser in python and it works perfect when i read a local file (for example calendar.xml), but i need to read a xml file from a web address.
I figured it would work if i do this:
toursxml='http://api.song... | Python parsing xml directly from web address | Hey. I tried to find a way but i can't. I have set up a xml.sax parser in python and it works perfect when i read a local file (for example calendar.xml), but i need to read a xml file from a web address.
I figured it would work if i do this:
toursxml='http://api.songkick.com/api/3.0/artists/mbid:'+mbid+'/calendar.xm... | [
"First, your example is mixed up. Please don't reuse variables.\ntoursurl= urllib2.urlopen(toursxml)\ntoursurl_string= toursurl.read()\nparser.parseString( toursurl_string )\n\nReads the entire file into a string, named toursurl_string.\nTo parse a string, you use the parseString(toursurl_string) method. \nhttp:/... | [
3,
2
] | [] | [] | [
"parsing",
"python",
"urllib",
"xml"
] | stackoverflow_0005345858_parsing_python_urllib_xml.txt |
Q:
Does Python's random module have a substitute for numpy.random.exponential?
I've been using Numpy's numpy.random.exponential function for a while. I now see that Python's random module has many functions that I didn't know about. Does it have something that replaces numpy.random.exponential? It would be nice to dr... | Does Python's random module have a substitute for numpy.random.exponential? | I've been using Numpy's numpy.random.exponential function for a while. I now see that Python's random module has many functions that I didn't know about. Does it have something that replaces numpy.random.exponential? It would be nice to drop the numpy requirement from my project.
| [
"If anything about random.expovariate() does not suit your needs, it's also easy to roll your own version:\ndef exponential(beta):\n return -beta * math.log(1.0 - random.random())\n\nIt seems a bit of an overkill to have a dependency on NumPy just for this functionality.\nNote that this function accepts the mean... | [
4,
3
] | [] | [] | [
"exponential_distribution",
"numpy",
"python",
"random"
] | stackoverflow_0005346008_exponential_distribution_numpy_python_random.txt |
Q:
Problem running python from crontab - "invalid Python installation"
I have python 2.7 installed on my linux box, and I'm trying to schedule a python script via crontab. The script works fine from the command line, however when running via cron I get:
Traceback (most recent call last):
File "/usr/local/lib/python... | Problem running python from crontab - "invalid Python installation" | I have python 2.7 installed on my linux box, and I'm trying to schedule a python script via crontab. The script works fine from the command line, however when running via cron I get:
Traceback (most recent call last):
File "/usr/local/lib/python2.7/site.py", line 553, in <module>
main()
File "/usr/local/lib/pyt... | [
"You probably just have 2 versions installed, one of which is broken. If your cron is just directly calling python instead of a specific path, your PATH probably contains /usr/bin before /usr/local/bin (which is typical) - so in your cron, specify which python to use, or remove the existing one in /usr/bin and sym... | [
3,
2,
2
] | [] | [] | [
"crontab",
"linux",
"python",
"ubuntu"
] | stackoverflow_0005345934_crontab_linux_python_ubuntu.txt |
Q:
Why do I get so many warnings and some errors when using IMDbPY?
I'm using IMDbPY to retrieve data from IMDb. I'm getting the right results and everything looks OK except one thing: No matter what I do, I get warnings. The results are fine, but they appear only after a long list of warnings and sometimes errors.
F... | Why do I get so many warnings and some errors when using IMDbPY? | I'm using IMDbPY to retrieve data from IMDb. I'm getting the right results and everything looks OK except one thing: No matter what I do, I get warnings. The results are fine, but they appear only after a long list of warnings and sometimes errors.
For example: The following code is supposed to print Resevior Dogs (199... | [
"Well, this is pretty self-explanatory:\n\nunable to use \"lxml\": No module named lxml.html\n\nCan you do this to check if the module exists?\n\nIn Terminal or Command Prompt, run python.\nPost the output of the first line (e.g. Python 2.6.6 (r266...).\nIn the shell, type in import lxml.\nNext, try import lxml.htm... | [
2
] | [] | [] | [
"imdb",
"python",
"warnings"
] | stackoverflow_0005346144_imdb_python_warnings.txt |
Q:
Python CannotSendRequest
I receive a CannotSendRequest in my oauth library (Django socialauth) when I try to connect to Twitter.
Traceback:
File "/Library/Python/2.6/site-packages/django/core/handlers/base.py" in get_response
100. response = callback(request, *callback_args, **callback_kwargs)
... | Python CannotSendRequest | I receive a CannotSendRequest in my oauth library (Django socialauth) when I try to connect to Twitter.
Traceback:
File "/Library/Python/2.6/site-packages/django/core/handlers/base.py" in get_response
100. response = callback(request, *callback_args, **callback_kwargs)
File "/Users/me/webfaction/pro... | [
"The post you linked to says this error happens when you reuse connections that have thrown an exception and didn't make it to the getresponse() stage.\nIndeed, connection.request(\"GET\", \"/\") x 2 throws the error. \nThe solution suggested is to re-create the connection every time. Is that what you want to do? N... | [
5
] | [] | [] | [
"django",
"python"
] | stackoverflow_0005346434_django_python.txt |
Q:
Why does filtering data in Django break my code?
I've got a rather strange problem - which is caused by the following line of code:
userlist = twitter_user.objects.filter(enabled=True)
If I comment out this line, the code works fine, however when uncomment it, I get the following error message:
Traceback (most ... | Why does filtering data in Django break my code? | I've got a rather strange problem - which is caused by the following line of code:
userlist = twitter_user.objects.filter(enabled=True)
If I comment out this line, the code works fine, however when uncomment it, I get the following error message:
Traceback (most recent call last):
File "script.py", line 33, in <mo... | [
"For whatever reason django is having trouble importing tweetgrab. \nI would suggest 2 things (assuming tweetgrab is an app inside your project):\n\nMake sure the parent directory of your project is on your python path.\nStart importing apps / set them in INSTALLED_APPS as myproject.app. That way you won't run into... | [
1
] | [] | [] | [
"django",
"django_models",
"models",
"python"
] | stackoverflow_0005346197_django_django_models_models_python.txt |
Q:
Python, logging: use custom handler with dictionary configuration?
this is about the logging module on Python 3.2 (GNU/Linux x86_64): is it possible to set a custom handler with dictionary configuration?
This is the code I'm trying:
import logging
import logging.config
class CustomHandler(logging.StreamHandler):
... | Python, logging: use custom handler with dictionary configuration? | this is about the logging module on Python 3.2 (GNU/Linux x86_64): is it possible to set a custom handler with dictionary configuration?
This is the code I'm trying:
import logging
import logging.config
class CustomHandler(logging.StreamHandler):
pass
logconfig = {
'version': 1,
'handlers': {
'con... | [
"You need to tell it where to find the CustomHandler class. The string should contain the module (and possibly package) where it can be found. If you are running this script directly, you can use __main__.CustomHandler. Otherwise, use your_module.CustomHandler, Where you replace your_module with the name of the... | [
17
] | [] | [] | [
"configuration",
"dictionary",
"handler",
"logging",
"python"
] | stackoverflow_0005346661_configuration_dictionary_handler_logging_python.txt |
Q:
Using Google App Engine Queues service with Django
I am trying to use Google App Engine queues API, I am having problems on testing this. It seems that in some part of the process the CSRF it's not working.
as I understand the api executes the task calling the url and making and http request in background.
The com... | Using Google App Engine Queues service with Django | I am trying to use Google App Engine queues API, I am having problems on testing this. It seems that in some part of the process the CSRF it's not working.
as I understand the api executes the task calling the url and making and http request in background.
The complete url is the API is calling is → http://localhost.lo... | [
"If you have the CsrfViewMiddleware enabled, Django will require a csrf_token in all POSTs to your views.\nDjango provides a decorator, @csrf_exempt, that you should place on your task queue views. This turns off the middleware just for those views.\nAlternatively, you can avoid using CsrfViewMiddleware altogether ... | [
5,
3,
1
] | [] | [] | [
"django",
"google_app_engine",
"python",
"task_queue"
] | stackoverflow_0004806520_django_google_app_engine_python_task_queue.txt |
Q:
How to preallocate a list of lists?
I am creating a list of lists using this code:
zeroArray = [0]*Np
zeroMatrix = []
for i in range(Np):
zeroMatrix.append(zeroArray[:])
Is there a more efficient way to do this? I'm hoping for something along the lines of zeroArray = [0]*Np; zeroMat = zeroArray*Np but can't ... | How to preallocate a list of lists? | I am creating a list of lists using this code:
zeroArray = [0]*Np
zeroMatrix = []
for i in range(Np):
zeroMatrix.append(zeroArray[:])
Is there a more efficient way to do this? I'm hoping for something along the lines of zeroArray = [0]*Np; zeroMat = zeroArray*Np but can't find anything similar.
| [
"Maybe you should consider using NumPy. It seems like you're doing numerical work, which is what it's made for. This is the fastest so far, not including the import statement:\nimport numpy\nNp = 80\nzeroMatrix = numpy.zeros((Np, Np))\n\nTimes:\n>python -m timeit -s \"import numpy; Np = 80\" \"zeroMatrix = numpy.ze... | [
11,
10,
5,
2
] | [] | [] | [
"python"
] | stackoverflow_0005347108_python.txt |
Q:
log incoming ip addresses in web.py
I'd like to log the IP addresses of machines that access my web.py application. How can I access this data within the web.py framework? I'm happy to send the address to my own logger.
A:
Use web.ctx['ip'] to get the remote ip address. Here is a link which explains what's in ... | log incoming ip addresses in web.py | I'd like to log the IP addresses of machines that access my web.py application. How can I access this data within the web.py framework? I'm happy to send the address to my own logger.
| [
"Use web.ctx['ip'] to get the remote ip address. Here is a link which explains what's in the context.\n"
] | [
5
] | [] | [] | [
"python",
"web.py"
] | stackoverflow_0005347484_python_web.py.txt |
Q:
adding sys.stdout.write output to a variable
Is there a way to add the output of sys.stdout.write to a variable? Or is there a better way to do what I am doing in jython:
I have a web address("www.example.com/whateverpage.html") and I want to create a variable which I get my script to click into so the end result... | adding sys.stdout.write output to a variable | Is there a way to add the output of sys.stdout.write to a variable? Or is there a better way to do what I am doing in jython:
I have a web address("www.example.com/whateverpage.html") and I want to create a variable which I get my script to click into so the end result must be:
HtmlAnchor[<a href="www.example.com/wha... | [
"Maybe you want pageAnchor = ''.join(['HtmlAnchor[<a href=\"',PageLink,'\">]'])\nOr simply 'HtmlAnchor[<a href=\"' + PageLink + '\">]'\nBut it's far from clear, to me, what you're trying to accomplish.\n",
"Try something simpler, format strings :)\n>>> addr=\"www.example.com\"\n>>> s = \"HtmlAnchor[<a href=\\\"%s... | [
3,
1
] | [] | [] | [
"jython",
"parsing",
"python"
] | stackoverflow_0005347583_jython_parsing_python.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.