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: How to speed up json decode and encode operations in Python? I've been using the json module in python 2.6 but is very slow. I'd like to use a faster implementation. I've seen cjson but seems the development is not coing on and the api is different from the json module. I have also read some comments about a way t...
How to speed up json decode and encode operations in Python?
I've been using the json module in python 2.6 but is very slow. I'd like to use a faster implementation. I've seen cjson but seems the development is not coing on and the api is different from the json module. I have also read some comments about a way to speed up json. Any ideas?
[ "The most recent versions of simplejson are considerably faster than the one built in to python 2.6, and have the same API. If you want your python code to continue working even when simplejson is not installed, try this:\ntry:\n import simplejson as json\nexcept ImportError:\n import json\n\nSee also:\nhttp...
[ 7, 1 ]
[]
[]
[ "json", "python", "python_2.6" ]
stackoverflow_0005158773_json_python_python_2.6.txt
Q: Python regex question I'm having some problems figuring out a solution to this problem. I want to read from a file on a per line basis and analyze whether that line has one of two characters (1 or 0). I then need to sum up the value of the line and also find the index value (location) of each of the "1" characte...
Python regex question
I'm having some problems figuring out a solution to this problem. I want to read from a file on a per line basis and analyze whether that line has one of two characters (1 or 0). I then need to sum up the value of the line and also find the index value (location) of each of the "1" character instances. so for exampl...
[ "Perhaps do it without regex:\nimport urllib\nurl='http://stackoverflow.com/questions/5158168/python-regex-question/5158341'\nf=urllib.urlopen(url)\nfor linenum,line in enumerate(f):\n print(line)\n locations=[pos for pos,char in enumerate(line) if char=='1']\n print('line {n}=(count:{c}, pos:{l})'.format(...
[ 4, 1, 0 ]
[]
[]
[ "for_loop", "multidimensional_array", "python" ]
stackoverflow_0005158168_for_loop_multidimensional_array_python.txt
Q: Why does Python's urlparse.parse_qs() split arguments on semicolon I'm writing a test script in Python to check the output of my PHP application and I've got a problem with Python's urlparse.parse_qs() function. GET string delimiter (AFAIK) is an ampersand. The function (as I understand) is supposed to split a GET...
Why does Python's urlparse.parse_qs() split arguments on semicolon
I'm writing a test script in Python to check the output of my PHP application and I've got a problem with Python's urlparse.parse_qs() function. GET string delimiter (AFAIK) is an ampersand. The function (as I understand) is supposed to split a GET string into Python dictionary, so that the output for count=2&offset=5&...
[ "';' is equivalent to '&'\nW3C recommends that all web servers support semicolon separators in the place of ampersand separators.\nSo use ',' instead.\n" ]
[ 13 ]
[]
[]
[ "get", "http", "python", "query_string" ]
stackoverflow_0005158565_get_http_python_query_string.txt
Q: HTTP Post from Android to Python (Apache Mod_Python) I want to send HTTP Post data from an Android application to a Python script (Apache with Mod_Python). I tested my Android client and send data successfully to a php script before. When I use a form and send data to my Python script it performs well (uploading o...
HTTP Post from Android to Python (Apache Mod_Python)
I want to send HTTP Post data from an Android application to a Python script (Apache with Mod_Python). I tested my Android client and send data successfully to a php script before. When I use a form and send data to my Python script it performs well (uploading or with the script below prompting 'No file uploaded'). I o...
[ "I found the error:\nIn my HTTP Post I used \"\\n\" as a new line character. PHP was fine with that, even if it is malformed. Mod_Python requires \"\\r\\n\".\n" ]
[ 1 ]
[]
[]
[ "android", "http_post", "mod_python", "python" ]
stackoverflow_0005158381_android_http_post_mod_python_python.txt
Q: Is there a way to create non-bordered transparent windows in Python? I am trying to make a widget-style application in Python, and I have tried searching around but I have not found a GUI toolkit that allows you to hide borders and remove the window background (fully transparent, only content rendered). Is there a...
Is there a way to create non-bordered transparent windows in Python?
I am trying to make a widget-style application in Python, and I have tried searching around but I have not found a GUI toolkit that allows you to hide borders and remove the window background (fully transparent, only content rendered). Is there a Python GUI toolkit with the following features?: No window borders. Comp...
[ "Yes, wxpython can do this. Look at the ShapedWindow example in the Demo application (available on the download page). \n", "It's been a little while since I've done things like that, but I would think that most GUI toolkits would allow you to do that. For example, GTK+ has Python bindings, and should support al...
[ 3, 1 ]
[]
[]
[ "python", "user_interface", "widget" ]
stackoverflow_0005158295_python_user_interface_widget.txt
Q: Unbinding a name referenced by an enclosing scope From the Python Language Reference (v 3.1, see here - http://docs.python.org/py3k/reference/executionmodel.html#naming-and-binding ): It is illegal to unbind a name referenced by an enclosing scope; the compiler will report a SyntaxError. But when I run the follo...
Unbinding a name referenced by an enclosing scope
From the Python Language Reference (v 3.1, see here - http://docs.python.org/py3k/reference/executionmodel.html#naming-and-binding ): It is illegal to unbind a name referenced by an enclosing scope; the compiler will report a SyntaxError. But when I run the following code: a = 3 def x(): global a del(a) print(a...
[ "I don't think that rule applies to the global scope. The global scope is always fully accessible.\nHere's an example:\n>>> def outer():\n... a=5\n... def inner():\n... nonlocal a\n... print(a)\n... del a\n...\nSyntaxError: can not delete variable 'a' referenced in nested scope\n\n",...
[ 4, 3 ]
[]
[]
[ "python", "syntax_error", "unbind" ]
stackoverflow_0005056074_python_syntax_error_unbind.txt
Q: Persisting Data from Threading I'm trying to write a 'market data engine' of sorts. So far I have a queue of threads, each thread will urllib to google finance and re the stock details out the page. Each thread will poll the page ever few seconds. From here, how can I persist the data in a way another class can ju...
Persisting Data from Threading
I'm trying to write a 'market data engine' of sorts. So far I have a queue of threads, each thread will urllib to google finance and re the stock details out the page. Each thread will poll the page ever few seconds. From here, how can I persist the data in a way another class can just poll it, without the problem of 2...
[ "You are correct that using a standard dict is not thread-safe (see here) and may cause you problems.\nA very nice way to handle this is to use the Queue class in the queue module in the standard library. It is thread-safe. Have the worker threads send updates to the main thread via the queue and have the main thre...
[ 4 ]
[]
[]
[ "multithreading", "python" ]
stackoverflow_0005159072_multithreading_python.txt
Q: I'm running 32-bit Windows on an x86-64 PC. Should I download the 32-bit or 64-bit Python installer? I have an Intel T9550 64-bit processor with 32-bit Windows Vista. I want to install Python 2.7.1 onto my PC. From the python.org website, which installer should I use: "Python 2.7.1 Windows Installer"? or "Python ...
I'm running 32-bit Windows on an x86-64 PC. Should I download the 32-bit or 64-bit Python installer?
I have an Intel T9550 64-bit processor with 32-bit Windows Vista. I want to install Python 2.7.1 onto my PC. From the python.org website, which installer should I use: "Python 2.7.1 Windows Installer"? or "Python 2.7.1 Windows X86-64 Installer"? The latter one is for x86-64. I don't understand if this bit refers to t...
[ "\n", "Even though you have a 64-bit processor, your OS is of a 32-bit flavour. The Windows installer for Python targets the OS it is built on, not just the processor. Since your OS is 32-bit, you can only install the regular 32-bit Python 2.7.1 Windows installer.\nNote that you can install both 32-bit (under a 3...
[ 6, 3, 1 ]
[]
[]
[ "32bit_64bit", "download", "installation", "python" ]
stackoverflow_0005158781_32bit_64bit_download_installation_python.txt
Q: How can I filter or limit the text being entered in a PyGTK text entry field? I want a text entry field (gtk.Entry) that accepts only hexadecimal characters as valid input from the user. A: Filtering may be done by connecting to the 'insert_text' signal and manipulating the entered text in the signal handler. He...
How can I filter or limit the text being entered in a PyGTK text entry field?
I want a text entry field (gtk.Entry) that accepts only hexadecimal characters as valid input from the user.
[ "Filtering may be done by connecting to the 'insert_text' signal and manipulating the entered text in the signal handler. Here is example code for validating Hex characters:\n#!/usr/bin/env python\nimport gtk, pygtk, gobject, string\n\nclass HexEntry(gtk.Entry):\n \"\"\"A PyGTK text entry field which allows only...
[ 9 ]
[]
[]
[ "pygtk", "python" ]
stackoverflow_0005159219_pygtk_python.txt
Q: is it possible to release the GIL before a C function that blocks and might call back into Python? I am wrapping a C function which performs a blocking operation (select) and then handles incoming messages. My understanding is that when a C function is going to block, the correct way to call it while allowing oth...
is it possible to release the GIL before a C function that blocks and might call back into Python?
I am wrapping a C function which performs a blocking operation (select) and then handles incoming messages. My understanding is that when a C function is going to block, the correct way to call it while allowing other threads to run is: Py_BEGIN_ALLOW_THREADS blocking_...
[ "I used these API functions several months ago, and my recollection is a bit hazy, but I believe this code will solve your problem. I am assuming version 2.x (3.x may be different):\nPyGILState_STATE gstate;\ngstate = PyGILState_Ensure();\n\n/* Make your call to PyEval_CallObject() here (and any other PY API calls...
[ 7, 1 ]
[]
[]
[ "gil", "python", "python_bindings", "python_multithreading" ]
stackoverflow_0005159040_gil_python_python_bindings_python_multithreading.txt
Q: Generate ranks based on data table The Background: I have been creating a script that based on input csv's that exist within an input directory, creates a 3 dimensional array to store the aggregated information. Each table within the array represents one of the pollution sources (eg one of the input csvs was Inci...
Generate ranks based on data table
The Background: I have been creating a script that based on input csv's that exist within an input directory, creates a 3 dimensional array to store the aggregated information. Each table within the array represents one of the pollution sources (eg one of the input csvs was Incinerators.csv, the created table will be ...
[ "For this I have created 2 functions\ndef sortTable(table, col):\n return sorted(table, key=itemgetter(col))\n\nAnd\ndef buildRankTable(totalTable, fieldList, wsidList, subList, subDict, wsidDict):\n ## build rankTable to mimic other templates\n rankTable = newTemplateTable(wsidList, fieldList)\n\n ## a...
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0005084720_python.txt
Q: Python Curses IRC/IM style updates How do I create a IRC/IM style update in a curses window. Where all lines are moved up by one and the bottom line is replaced with the provided text? So far I have managed to get a one line input box at the bottom and then one window above it with the height of the screen -1 but...
Python Curses IRC/IM style updates
How do I create a IRC/IM style update in a curses window. Where all lines are moved up by one and the bottom line is replaced with the provided text? So far I have managed to get a one line input box at the bottom and then one window above it with the height of the screen -1 but am unsure on inserting text. I am inser...
[ "I may have solved this myself after just trying loads of functions in window\nwDebug.move(0,0)\nwDebug.deleteln()\nwDebug.addstr(4, 0, msg)\nwDebug.refresh() \n\nIs this the correct/best way?\n" ]
[ 0 ]
[]
[]
[ "curses", "python" ]
stackoverflow_0005159125_curses_python.txt
Q: python library that is the inverse of urllib? urllib fetches data from urls right? is there a python library that can do the reverse of that and send data to urls instead (for example, to a site you are managing)? and if so, is that library compatible with apache? thanks. A: What does sending data to a URL mean?...
python library that is the inverse of urllib?
urllib fetches data from urls right? is there a python library that can do the reverse of that and send data to urls instead (for example, to a site you are managing)? and if so, is that library compatible with apache? thanks.
[ "What does sending data to a URL mean? The usual way to do that is just via an HTTP POST, and urllib (and urllib2) handle that just fine.\n", "urllib can send data associated with a request by using GET or POST.\nurllib2.urlopen(url, data) where data is a dict of key-values representing the data you're sending. S...
[ 6, 2 ]
[]
[]
[ "python", "urllib", "urllib2" ]
stackoverflow_0005159351_python_urllib_urllib2.txt
Q: Python: Spaced Data-to-CSV Data I think there is a simple Python solution, but I cannot seem to get there in an elegant manner. I am basically trying to take 3-columns of spaced data, truncate several rows off the top, and then re-store the 3-columns of data as a CSV file. Essentially separating the column fiel...
Python: Spaced Data-to-CSV Data
I think there is a simple Python solution, but I cannot seem to get there in an elegant manner. I am basically trying to take 3-columns of spaced data, truncate several rows off the top, and then re-store the 3-columns of data as a CSV file. Essentially separating the column fields by a single comma. Th column field...
[ "import csv\n\nwith open('list1.txt') as inf:\n data_list = []\n for line in inf:\n try:\n i, f1, f2 = line.strip().split()\n data_list.append((int(i), float(f1), float(f2)))\n except ValueError:\n pass # could not parse line\n\n# REPRODUCE THE LINES 1 THRU 5 OF...
[ 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0005158025_python.txt
Q: How to make a function repeat itself I have a python problem, I'm reading from XML and have two spread functions set up; one finds a location, than the other function finds a location inside the first one, and returns info. my problem is that i need this to continue down the page and find other occurrences of each...
How to make a function repeat itself
I have a python problem, I'm reading from XML and have two spread functions set up; one finds a location, than the other function finds a location inside the first one, and returns info. my problem is that i need this to continue down the page and find other occurrences of each. I'm not sure if thats a good explanation...
[ "Don't try and parse XML manually. There are plenty of good ways of doing it, including ElementTree in the standard library.\n", "lxml.etree makes this nice to work with.\nFor an XML document structured as so:\n<entry>\n <title>story 1</title>\n <text>this is the first earthquake story</text>\n <title>st...
[ 5, 1 ]
[]
[]
[ "python" ]
stackoverflow_0005159238_python.txt
Q: creating a 3d numpy array from a non-contigous set of contigous 2d slices Is it possible to use PyArray_NewFromDescr to create numpy array object from a set of contiguous 2d arrays, without copying the data? A: There's a slight inconsistency in your post; I'm assuming your title describes what you want. Looking ...
creating a 3d numpy array from a non-contigous set of contigous 2d slices
Is it possible to use PyArray_NewFromDescr to create numpy array object from a set of contiguous 2d arrays, without copying the data?
[ "There's a slight inconsistency in your post; I'm assuming your title describes what you want. Looking at the Python API docs, PyArray_NewFromDescr accepts just a single pointer to preallocated memory, so the answer is almost certainly no. It seems that you might be able to use the strides argument in a clever way ...
[ 1, 1 ]
[]
[]
[ "c++", "numpy", "python", "python_c_api" ]
stackoverflow_0005155597_c++_numpy_python_python_c_api.txt
Q: querying through wmi & win32.client objects with python Could someone shed some lights upon querying through wmi and win32.client objects? Anytime i try to query throught win32.client object i get this error: Error: '' object has no attribute 'UserName' though, i know (wmic class "Win32_ComputerSystem", wmiexp...
querying through wmi & win32.client objects with python
Could someone shed some lights upon querying through wmi and win32.client objects? Anytime i try to query throught win32.client object i get this error: Error: '' object has no attribute 'UserName' though, i know (wmic class "Win32_ComputerSystem", wmiexplorer etc.) the certain attribute belongs to the object i'm t...
[ "To find out about the \"keys\" and \"values\" in WMI query result, you can use \"Properties_\"\nfrom win32com.client import Dispatch, GetObject import win32con\nserver = Dispatch(\"WbemScripting.SWbemLocator\")\nc = server.ConnectServer(\"localhost\", \"root\\\\cimv2\") \np = c.ExecQuery(\"Select * from Win32_Oper...
[ 2, 1, 0, 0 ]
[]
[]
[ "python", "winapi" ]
stackoverflow_0000685351_python_winapi.txt
Q: Filling out paragraph text via urllib? Say I have a paragraph in a site I am managing and I want a python program to change the contents of that paragraph. Is this plausible with urllib? A: If you have access to any server-side scripting language, its easy. A: Quite possibly; it depends on how the site is desi...
Filling out paragraph text via urllib?
Say I have a paragraph in a site I am managing and I want a python program to change the contents of that paragraph. Is this plausible with urllib?
[ "If you have access to any server-side scripting language, its easy.\n", "Quite possibly; it depends on how the site is designed.\nIf the site is just a collection of static pages (ie .html files) then you would have to get a copy of the page, modify it, and upload the new version - most likely using sftp or WebD...
[ 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0005159674_python.txt
Q: Floating point precision in Python array I apologize for the really simple and dumb question; however, why is there a difference in precision displayed for these two cases? 1) >> test = numpy.array([0.22]) >> test2 = test[0] * 2 >> test2 0.44 2) >> test = numpy.array([0.24]) >> test2 = test[0] * 2 >> test2 0.479...
Floating point precision in Python array
I apologize for the really simple and dumb question; however, why is there a difference in precision displayed for these two cases? 1) >> test = numpy.array([0.22]) >> test2 = test[0] * 2 >> test2 0.44 2) >> test = numpy.array([0.24]) >> test2 = test[0] * 2 >> test2 0.47999999999999998 I'm using python2.6.6 on 64-bi...
[ "Because they are different numbers and different numbers have different rounding effects. \n(Practically any of the Related questions down the right-hand side will explain the cause of the rounding effects themselves.)\n\nOkay, more serious answer. It appears that numpy performs some transformation or calculation ...
[ 6 ]
[]
[]
[ "numpy", "precision", "python" ]
stackoverflow_0005160339_numpy_precision_python.txt
Q: how to count value returned from select query in python I want to count the total number of rows returned by query. I am able to retrieved rows returned by query but what if i need to work in case when no data exits. that is when query returns no va from database. the code i used to solve this problem is : try: ...
how to count value returned from select query in python
I want to count the total number of rows returned by query. I am able to retrieved rows returned by query but what if i need to work in case when no data exits. that is when query returns no va from database. the code i used to solve this problem is : try: cur.execute(query) id = cur.fetchone()[0] if(id...
[ "cur.fetchall() will give you a sequence of all the rows. You can look at the length of that sequence to see if any rows were returned. This works for small result sets, but may not be ideal for queries that return large amounts of data.\nAlternatively, you can look at cur.rowcount. Rowcount will return the number ...
[ 2 ]
[]
[]
[ "python" ]
stackoverflow_0005160455_python.txt
Q: Python MVC Framework vs .NET vs Rails (Middleware) I'm starting one new project, and I need to choose the best technology to maintain one Middleware Layer. This layer will offer REST and SOAP Webservices to several devices (mobile and web) I need Speed! I need easy setup and scalability Regards, Pedro A: I am a ...
Python MVC Framework vs .NET vs Rails (Middleware)
I'm starting one new project, and I need to choose the best technology to maintain one Middleware Layer. This layer will offer REST and SOAP Webservices to several devices (mobile and web) I need Speed! I need easy setup and scalability Regards, Pedro
[ "I am a Rails developer but I wouldnt recommend you Rails for your purpose, maybe Sinatra but Ruby in general is not known for its speed.\nConsidering your observations I would go for python, perhaps django is more a FrontEnd techonology. Give Tornado a try, even if you dont really need its main feature (asynchrono...
[ 1 ]
[]
[]
[ ".net", "middleware", "python", "ruby_on_rails", "scalability" ]
stackoverflow_0005160598_.net_middleware_python_ruby_on_rails_scalability.txt
Q: Check if a pixel (RGB or HSV) is contained in a color scale range, how I need to check if a pixel (RGB) is contained in the color scale ranging from very light pink to dark purple. Using the RGB scheme can I do a check like this: IF image [x, y] [R]> threshold and image [x, y] [G]> threshold image [x, y] [B]> thre...
Check if a pixel (RGB or HSV) is contained in a color scale range, how
I need to check if a pixel (RGB) is contained in the color scale ranging from very light pink to dark purple. Using the RGB scheme can I do a check like this: IF image [x, y] [R]> threshold and image [x, y] [G]> threshold image [x, y] [B]> threshold and \ image [x, y] [R] <threshold and image [x, y] [G] < threshol...
[ "You probably want to work in HSV, because it maps much more intuitively to human perception than RGB. If you get a human to mark colors as \"in range\" or \"out of range\", and map them in HSV, you'll be able to find a bound on the H, S, and V values that indicates in and out.\nThen you can use a simple range che...
[ 3, 3, 0 ]
[]
[]
[ "hsv", "image_processing", "python", "rgb" ]
stackoverflow_0005159290_hsv_image_processing_python_rgb.txt
Q: twisted reactor: priority and insights Two simple questions about twisted reactor: Is there a way to explicitly assign a priority while scheduling a task ? Is it possible to inspect the reactor in order to list all the pending tasks? A: No. The reactor does not implement priority-based scheduling; it just ru...
twisted reactor: priority and insights
Two simple questions about twisted reactor: Is there a way to explicitly assign a priority while scheduling a task ? Is it possible to inspect the reactor in order to list all the pending tasks?
[ "No. The reactor does not implement priority-based scheduling; it just runs events in whatever order they happen to come back from your multiplexing/timing mechanism, depending on the particular reactor implementation (it's slightly different for the different ones).\nImplementing a scheduling or fair queueing API...
[ 3 ]
[]
[]
[ "python", "reactor", "twisted" ]
stackoverflow_0005159259_python_reactor_twisted.txt
Q: Python problem with sockets I'm working on a simple project involving sockets. Kinda like telnet. I just want it to connect to port 80 and execute GET / Here is what I'm trying: import socket size = 100000 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) host = "localhost" port = 80 s.connect((host, port)) s...
Python problem with sockets
I'm working on a simple project involving sockets. Kinda like telnet. I just want it to connect to port 80 and execute GET / Here is what I'm trying: import socket size = 100000 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) host = "localhost" port = 80 s.connect((host, port)) stuff = "GET /" s.send(stuff) r = ...
[ "The HTTP spec says that you need two newlines ('\\r\\n' * 2) after the header. Try:\nstuff = 'GET /\\r\\n\\r\\n'\n\n", "You need at least a blank line after the GET /, so use stuff = \"GET /\\n\\n\". Read this example.\n", "your main problem is lacking a newline after \"GET /\". The HTTP protocol demands a ne...
[ 2, 1, 1 ]
[]
[]
[ "http", "python", "sockets" ]
stackoverflow_0005160673_http_python_sockets.txt
Q: How to update a plot with python and Matplotlib I have been bashing my head against the wall trying to update a graph using matplotlib with python and wxpython. I want to press a button and add data to a graph nested in a wx.notebook. Below is the code. Thanks for the help import wx import matplotlib as mpl imp...
How to update a plot with python and Matplotlib
I have been bashing my head against the wall trying to update a graph using matplotlib with python and wxpython. I want to press a button and add data to a graph nested in a wx.notebook. Below is the code. Thanks for the help import wx import matplotlib as mpl import matplotlib.pyplot as plt from matplotlib.backends...
[ "Using this example as a guide, perhaps try this:\nimport wx\nimport matplotlib as mpl\nmpl.use('WXAgg')\nimport matplotlib.pyplot as plt\nfrom matplotlib.backends.backend_wxagg import FigureCanvasWxAgg as Canvas\n\nclass Plot(wx.Panel):\n def __init__(self, parent, id = -1, dpi = None, **kwargs):\n wx.Pa...
[ 4 ]
[]
[]
[ "matplotlib", "python", "wxpython" ]
stackoverflow_0005160558_matplotlib_python_wxpython.txt
Q: Bash background color changing for accented character Basically, I'm using python to print out some information in the terminal and some of the text included accented characters, such as Thai language. When I use try this. #!/usr/bin/python #coding: UTF-8 #test.py import sys print "\033[41mลองดู\033[0m" #there i...
Bash background color changing for accented character
Basically, I'm using python to print out some information in the terminal and some of the text included accented characters, such as Thai language. When I use try this. #!/usr/bin/python #coding: UTF-8 #test.py import sys print "\033[41mลองดู\033[0m" #there is an accented character at the end. Therefore the whole se...
[ "The accent is considered outside of the cell for the purposes of text attributes. Output some spaces before resetting the attributes if you want the accent to appear with the background.\n" ]
[ 0 ]
[]
[]
[ "background", "bash", "colors", "python" ]
stackoverflow_0005160541_background_bash_colors_python.txt
Q: How do I package an unchanged C extension as part of my new Python package? I've released a new version of a Python package to pypi without changing the C extension. Since I have only changed the Python code, not the C code, how do I package the shared libraries I have compiled for several platforms without having...
How do I package an unchanged C extension as part of my new Python package?
I've released a new version of a Python package to pypi without changing the C extension. Since I have only changed the Python code, not the C code, how do I package the shared libraries I have compiled for several platforms without having to recompile?
[ "As an example for a library called 'somelib' with compiled libraries in two subdirectories, lib-i386 and lib-amd64:\nMANIFEST.in contains the following:\ninclude __init__.py\ninclude setup.py\ninclude somelib/*\ninclude somelib/lib-i386/*\ninclude somelib/lib-amd64/*\n\nsetup.py contains (I've omitted lines unesse...
[ 1 ]
[]
[]
[ "distutils", "packaging", "python" ]
stackoverflow_0005160222_distutils_packaging_python.txt
Q: use select() to listen on both tcp and udp message I only get the TCP message when I try this code: from socket import * from select import select def read_tcp(s): while True: client,addr = s.accept() data = client.recv(8000) client.close() print "Recv TCP:'%s'" % data def rea...
use select() to listen on both tcp and udp message
I only get the TCP message when I try this code: from socket import * from select import select def read_tcp(s): while True: client,addr = s.accept() data = client.recv(8000) client.close() print "Recv TCP:'%s'" % data def read_udp(s): while True: data,addr = s.recvfrom...
[ "\nGet rid of the 'while' loops in read_tcp() and read_udp(). The select() loop is the only loop you need: it will call the read_XXX() methods as often as required. The read_XXX() methods should handle exactly one event.\nYour read_tcp() method should be split into two parts: one to accept a socket and add it to th...
[ 6 ]
[]
[]
[ "python", "select", "sockets", "tcp", "udp" ]
stackoverflow_0005160980_python_select_sockets_tcp_udp.txt
Q: Exposing C++ library to Python + PIL I started using SWIG on a huge C++ library (made of of several inter-dependent static libs) to expose it to python. This library defines many primitive classes that are used throughout as parameters (images of different types for example). There is extensive use of STL, inherit...
Exposing C++ library to Python + PIL
I started using SWIG on a huge C++ library (made of of several inter-dependent static libs) to expose it to python. This library defines many primitive classes that are used throughout as parameters (images of different types for example). There is extensive use of STL, inheritance and templating in the lib as well. So...
[ "Have you considered looking into using Boost.Python?\n" ]
[ 1 ]
[]
[]
[ "c++", "python", "python_imaging_library" ]
stackoverflow_0005160308_c++_python_python_imaging_library.txt
Q: How to port this NetHack function to Python? I am trying to write a Python function which returns the same moon phase value as in the game NetHack. This is found in hacklib.c. I have tried to simply copy the corresponding function from the NetHack code but I don't believe I am getting the correct results. The func...
How to port this NetHack function to Python?
I am trying to write a Python function which returns the same moon phase value as in the game NetHack. This is found in hacklib.c. I have tried to simply copy the corresponding function from the NetHack code but I don't believe I am getting the correct results. The function which I have written is phase_of_the_moon(). ...
[ "The code as written is largely untestable - and you need to make it testable. So, you need the C code to be:\nint\nphase_of_the_moon() /* 0-7, with 0: new, 4: full */\n{\n register struct tm *lt = getlt();\n return testable_potm(lt);\n}\n\nstatic int\ntestable_potm(const struct tm *lt)\n{\n register ...
[ 5, 3, 2, 1, 1, 1, 0 ]
[]
[]
[ "c", "nethack", "porting", "python", "time" ]
stackoverflow_0000942328_c_nethack_porting_python_time.txt
Q: Django admin application for master/detail page Consider this simplified model in Django: class Item(models.Model): title = models.CharField(max_length=200) pub_date = models.DateTimeField() class ItemDetail(models.Model): item = models.ForeignKey(Item) name = models.CharField(max_length=200) ...
Django admin application for master/detail page
Consider this simplified model in Django: class Item(models.Model): title = models.CharField(max_length=200) pub_date = models.DateTimeField() class ItemDetail(models.Model): item = models.ForeignKey(Item) name = models.CharField(max_length=200) value = models.CharField(max_length=200) display_...
[ "That's actually the only direction django is good at dealing with relationships for -- the other way around is harder (directly editing the related parent from the child).\nTo get the format you want, look into ModelAdmin inlines:\nhttp://docs.djangoproject.com/en/dev/ref/contrib/admin/#django.contrib.admin.Inline...
[ 14 ]
[]
[]
[ "django", "django_admin", "python" ]
stackoverflow_0005161477_django_django_admin_python.txt
Q: Multi-threading different scripts I have aa few scripts written in python. I am trying to multi thread them. When Script A starts. I would like scripts B, C, and D to start. After A runs, I would A2 to run. After B runs, I would B2 to run, then B3. C and D have no follow up scripts. I have checked that the ...
Multi-threading different scripts
I have aa few scripts written in python. I am trying to multi thread them. When Script A starts. I would like scripts B, C, and D to start. After A runs, I would A2 to run. After B runs, I would B2 to run, then B3. C and D have no follow up scripts. I have checked that the scripts are independent of each other. ...
[ "Ok I'm still not sure where exactly your problem is, but that's the way I'd solve the problem:\n#Main.py\nfrom multiprocessing import Process\nimport ScriptA\n# import all other scripts as well\n\ndef handle_script_a(*args):\n print(\"Call one or several functions from Script A or calculate some stuff beforehan...
[ 2, 0 ]
[]
[]
[ "multithreading", "python" ]
stackoverflow_0005093164_multithreading_python.txt
Q: Reverse order of given numbers in python I am trying to reverse order of given numbers in python.The problem says that the first line of the standard input contains one integer t (t<1001) which is the number of numbers.In each of the next t lines there is one integer n (n<1001). Now I am trying to solve this using...
Reverse order of given numbers in python
I am trying to reverse order of given numbers in python.The problem says that the first line of the standard input contains one integer t (t<1001) which is the number of numbers.In each of the next t lines there is one integer n (n<1001). Now I am trying to solve this using recursion trick: def f(n,a): if n > 0: ...
[ "You probably don't want to print in the 'n == 0' case.\nTry indenting the 'print' inside the 'if'.\nI imagine your 'a' variable is getting re-used in the 'n == 0' case, causing your problem.\nAlso, is there a particular reason you don't just read the input into an list, then reverse that list? [I see you know how ...
[ 3, 0 ]
[]
[]
[ "python", "recursion" ]
stackoverflow_0005161372_python_recursion.txt
Q: Managing multiple settings.py files Possible Duplicate: How to manage local vs production settings in Django? I have managed to deploy successfully a Django project on Apache's Web Server with mod_wsgi. I would like some recommendations on how to manage multiple settings.py files. Right now I have one for develo...
Managing multiple settings.py files
Possible Duplicate: How to manage local vs production settings in Django? I have managed to deploy successfully a Django project on Apache's Web Server with mod_wsgi. I would like some recommendations on how to manage multiple settings.py files. Right now I have one for development and one totally different for prod...
[ "I use a settings module that is not a single file:\nsettings/\n __init__.py\n _base.py\n _servers.py\n development.py\n production.py\n testing.py\n\nThe __init__.py file is simple:\nfrom _servers import get_server_type\nexec(\"from %s import *\" % get_server_type())\n\nThe _base.py file contains...
[ 29, 9, 7, 2 ]
[]
[]
[ "apache", "deployment", "django", "python" ]
stackoverflow_0005159852_apache_deployment_django_python.txt
Q: shell_plus isn't autoloading all the apps it should be Below I'm showing what happens when I run ./manage.py shell_pus and what my settings.py file looks like. jason@buster:~/projects/mcifdjango$ ./manage.py shell_plus From 'auth' autoload: Permission, Group, User, Message From 'contenttypes' autoload: ContentType...
shell_plus isn't autoloading all the apps it should be
Below I'm showing what happens when I run ./manage.py shell_pus and what my settings.py file looks like. jason@buster:~/projects/mcifdjango$ ./manage.py shell_plus From 'auth' autoload: Permission, Group, User, Message From 'contenttypes' autoload: ContentType From 'sessions' autoload: Session From 'sites' autoload: Si...
[ "Django_extensions has no models to load, so it's not strange that no model is loaded. \nOTOS the Messages model that is being loaded in the 'auth' line is probably the one from contrib.messages. Explore the model class in the shell to verify its app_label. \nFor what matters your custom 'mcif' app, it probably has...
[ 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0005160812_django_python.txt
Q: Django: override the save() function of an abstract model I have tried to override the save() function on a model that is abstract, and am getting an error Manager isn't accessible via Entry instances So if possible, how do you override the save function on an abstract model. The model that extends from this is E...
Django: override the save() function of an abstract model
I have tried to override the save() function on a model that is abstract, and am getting an error Manager isn't accessible via Entry instances So if possible, how do you override the save function on an abstract model. The model that extends from this is Entry Here is my model Code: class EntryBlog(EntryAbstractClass)...
[ "self.__class__().objects should be self.__class__.objects. \nSee the Notes on retrieving objects: http://docs.djangoproject.com/en/dev/topics/db/queries/#retrieving-objects\n\nManagers are accessible only via model classes, rather than from model instances, to enforce a separation between \"table-level\" operation...
[ 5 ]
[]
[]
[ "django", "django_models", "python" ]
stackoverflow_0005161805_django_django_models_python.txt
Q: What does this mean in Python? I'm learning Python. I'm curious to know what this mean? count = 10**6 I try to print the variable "count" but gives me an error. Can someone give me a clue on this? Best Regards, A: ** in that context is exponentiation. A: ** is the exponentiation operator, so you are computing...
What does this mean in Python?
I'm learning Python. I'm curious to know what this mean? count = 10**6 I try to print the variable "count" but gives me an error. Can someone give me a clue on this? Best Regards,
[ "** in that context is exponentiation.\n", "** is the exponentiation operator, so you are computing 10 to the 6th power. The Python documentation tabulates the supported operators.\n", "It sounds like you might be using Python 3, but are using a tutorial designed for Python 2. In Python 3, print() is a function...
[ 5, 4, 2, 0 ]
[]
[]
[ "python" ]
stackoverflow_0005161904_python.txt
Q: Extending Python with a C++ shared object library using Cython So basically, I am attempting to write my own GUI wrapper in Python (Using GTK+, but I don't think that's relevant) for an API that is written in C++ and compiled by the user into a shared object file (in linux [*nix? I'm not quite sure how it works on...
Extending Python with a C++ shared object library using Cython
So basically, I am attempting to write my own GUI wrapper in Python (Using GTK+, but I don't think that's relevant) for an API that is written in C++ and compiled by the user into a shared object file (in linux [*nix? I'm not quite sure how it works on macs]) or a dll (in windows) that you should be able to reference t...
[ "You could do a file named \"yourmodule.pyx\", rename all the others files to pxi, and do:\ninclude \"other1.pxi\"\ninclude \"other2.pxi\"\n\nThen you'll have only one file to cythonize and compile: yourmodule.pyx.\n" ]
[ 0 ]
[]
[]
[ "c++", "cython", "python" ]
stackoverflow_0004838843_c++_cython_python.txt
Q: How to create test objects in tests? I'm creating unittests to a payment process. There is about 20 unit unittests to write -some positives cases and some negatives. example: payment_screen=PaymentScreen() and there I few conceptions. First - create a Payer object with giving attributes: payer=Payer(last_name,cou...
How to create test objects in tests?
I'm creating unittests to a payment process. There is about 20 unit unittests to write -some positives cases and some negatives. example: payment_screen=PaymentScreen() and there I few conceptions. First - create a Payer object with giving attributes: payer=Payer(last_name,country_code) country_code is important, bec...
[ "Maybe what you are looking for is some kind of mocking framework. Then when you test PaymentScreen, you can mock out Payer. For more about mocking frameworks for python look here: What is your favorite Python mocking library?.\n", "Hey.\nProbably answer with mocks is what you need in the first place, but I want ...
[ 0, 0 ]
[]
[]
[ "class_design", "python", "unit_testing" ]
stackoverflow_0005156663_class_design_python_unit_testing.txt
Q: Yet another producer/consumer problem in Twisted Python I am building a server which stores key/value data on top of Redis using Twisted Python. The server receives a JSON dictionary via HTTP, which is converted into a Python dictionary and put in a buffer. Everytime new data is stored, the server schedules a task...
Yet another producer/consumer problem in Twisted Python
I am building a server which stores key/value data on top of Redis using Twisted Python. The server receives a JSON dictionary via HTTP, which is converted into a Python dictionary and put in a buffer. Everytime new data is stored, the server schedules a task which pops one dictionary from the buffer and writes every t...
[ "The producer and consumer APIs in Twisted, IProducer and IConsumer, are about flow control. You don't seem to have any flow control here, you're just relaying messages from one protocol to another.\nSince there's no flow control, the buffer is just extra complexity. You could get rid of it by just passing the da...
[ 3 ]
[]
[]
[ "producer_consumer", "python", "redis", "twisted" ]
stackoverflow_0005157967_producer_consumer_python_redis_twisted.txt
Q: Compiling Pythonika on MacOS I'm compiling Pythonika on Snow Leopard and the errors I get suggest that I'm missing some standard flag, any idea what's missing? Another post suggests I need -lrt flag, but that's not available on MacOS cc -I/Applications/Mathematica.app/SystemFiles/Links/MathLink/DeveloperKit/Compil...
Compiling Pythonika on MacOS
I'm compiling Pythonika on Snow Leopard and the errors I get suggest that I'm missing some standard flag, any idea what's missing? Another post suggests I need -lrt flag, but that's not available on MacOS cc -I/Applications/Mathematica.app/SystemFiles/Links/MathLink/DeveloperKit/CompilerAdditions -I/Library/Frameworks/...
[ "Looks like you might need the following linker flags:\n-lstdc++ -framework CoreFoundation\n" ]
[ 4 ]
[]
[]
[ "c++", "mathlink", "python", "wolfram_mathematica" ]
stackoverflow_0005161006_c++_mathlink_python_wolfram_mathematica.txt
Q: Serialize a tuple of numpy arrays I have a couple of numpy matrices (3-dimensional to be exact) which are stored in tuples (a1,b1,c1) (a2,b2,c2) ... (an,bn,cn) I would like to serialize each tuple into a file that can be read back into Python on another machine (Linux => Windows, both are x86-64). What would be a...
Serialize a tuple of numpy arrays
I have a couple of numpy matrices (3-dimensional to be exact) which are stored in tuples (a1,b1,c1) (a2,b2,c2) ... (an,bn,cn) I would like to serialize each tuple into a file that can be read back into Python on another machine (Linux => Windows, both are x86-64). What would be a pythonic way to accomplish this?
[ "numpy.savez or numpy.savez_compressed is the way to go. I've heard, but never experienced issues with certain types of arrays not pickling well.\nI'm recalling this post (doesn't seem to have been much of an issue) as well as something about numpy.void not pickling. Likely not an issue, but there it is.\n", "P...
[ 6, 1, 1, 1 ]
[]
[]
[ "numpy", "python", "scipy", "serialization" ]
stackoverflow_0005162073_numpy_python_scipy_serialization.txt
Q: Checking against a list using if else statment I've gone through most of the related questions and none of them seem to give me the idea I need for my program. users = ["Block Harris", "Apple Mccoy", "Plays Terry", "Michael Strong", "Katie Blue"] nicknames = ["Block", ...
Checking against a list using if else statment
I've gone through most of the related questions and none of them seem to give me the idea I need for my program. users = ["Block Harris", "Apple Mccoy", "Plays Terry", "Michael Strong", "Katie Blue"] nicknames = ["Block", "Apple", "Plays", "Mi...
[ "You're setting \"FoundUser\" to \"True\" or \"False\" but then checking against a level in a list that is an Integer. It's always printing 2 because your 2nd item in the list is 1.\nSuggestion:\nInstead of forming lists that are only marginally related according to their ordering, you should come up with a class ...
[ 7, 2, 0 ]
[]
[]
[ "if_statement", "list", "python" ]
stackoverflow_0005162342_if_statement_list_python.txt
Q: Different results when invoking a python script from the command line or in the web server I am writing a python script to run on a apache web server. My first goal is to list the network interfaces that are available and, after, for each one, build a form to input some parameters of interest. My problem is that w...
Different results when invoking a python script from the command line or in the web server
I am writing a python script to run on a apache web server. My first goal is to list the network interfaces that are available and, after, for each one, build a form to input some parameters of interest. My problem is that when I run the following script from the command line I get the expected result (a formatted html...
[ "Probably different versions of python are being run.\nCheck if your ssh user and web server user (www) is running same python from same path.\n", "Try commenting out Popen and replace result with mock values. If Popen is causing the problem (as I suspect), you probably will want to obtain the values in a differ...
[ 0, 0 ]
[]
[]
[ "cgi", "forms", "python" ]
stackoverflow_0005162157_cgi_forms_python.txt
Q: Elegant way of reducing list by averaging? Is there a more elegant way of writing this function? def reduce(li): result=[0 for i in xrange((len(li)/2)+(len(li)%2))] for i,e in enumerate(li): result[int(i/2)] += e for i in range(len(result)): result[i] /= 2 if (len(li)%2 == 1): ...
Elegant way of reducing list by averaging?
Is there a more elegant way of writing this function? def reduce(li): result=[0 for i in xrange((len(li)/2)+(len(li)%2))] for i,e in enumerate(li): result[int(i/2)] += e for i in range(len(result)): result[i] /= 2 if (len(li)%2 == 1): result[len(result)-1] *= 2 return result ...
[ "what you actually want to do is to apply a moving average of 2 samples trough your list, mathematically you convolve a window of [.5,.5], then take just the even samples. To avoid dividing by two the last element of odd arrays, you should duplicate it, this does not affect even arrays.\nUsing numpy it gets pretty ...
[ 8, 2, 1, 0, 0 ]
[]
[]
[ "list", "python" ]
stackoverflow_0005162130_list_python.txt
Q: Create instance method in metaclass using partial in Python 3 Using metaclasses, I am trying to create an instance method by simplifying an existing instance method. The problem is that partial does not work with instance method. This is a simple example of what I try to achieve: from functools import partial cla...
Create instance method in metaclass using partial in Python 3
Using metaclasses, I am trying to create an instance method by simplifying an existing instance method. The problem is that partial does not work with instance method. This is a simple example of what I try to achieve: from functools import partial class Aclass(object): def __init__(self, value): self._va...
[ "Well, I am a bit unfamiliar with Python 3 method handling yet -\nthe simplest thing I could think of is rewriting partial so that it preserves the first argument from the original call, then inserts the \"partial\" parameters.\nIt worked with your example, but it needs testing with more complex patterns.\nfrom fun...
[ 5, 3, 1 ]
[]
[]
[ "methods", "partial", "python", "python_3.x" ]
stackoverflow_0005161095_methods_partial_python_python_3.x.txt
Q: Python list syntax help results=[key for key, value in adictionary if str(key).startswith('target') and value > 0 ] What am I trying to do here is select all the keys if the key in dictionary that beginswith target and its value is greater than 0. But looks there's a problem with this, help me~ A: results=...
Python list syntax help
results=[key for key, value in adictionary if str(key).startswith('target') and value > 0 ] What am I trying to do here is select all the keys if the key in dictionary that beginswith target and its value is greater than 0. But looks there's a problem with this, help me~
[ "results=[key for key, value in adictionary.items() if str(key).startswith('target') \n and value > 0 ]\n\n", "Missing items() ior iteritems() to your dict access. iteritems will not create a temp list which could be slightly faster.\nresults=[key for key, value in adictionary.iteritems() if str(key)....
[ 3, 2, 0, 0, 0 ]
[]
[]
[ "list", "python" ]
stackoverflow_0005162494_list_python.txt
Q: Upload image from webform in Python I am new to python and I am assigned the task of making an image uploade script from a webform in python. We are using Pylons. I have a form submitting to a page and am trying to run the follow but I am getting this error AttributeError: read My code is this: im = Image.o...
Upload image from webform in Python
I am new to python and I am assigned the task of making an image uploade script from a webform in python. We are using Pylons. I have a form submitting to a page and am trying to run the follow but I am getting this error AttributeError: read My code is this: im = Image.open(request.POST['image']) im = im.conv...
[ "I think you want to do this:\nim = Image.open(StringIO(request.POST['image']))\n\nsince the Image.open function takes a file-like object not a buffer. The StringIO packages turns a buffer into a file-like object.\n" ]
[ 1 ]
[]
[]
[ "pylons", "python", "python_imaging_library" ]
stackoverflow_0005162786_pylons_python_python_imaging_library.txt
Q: urllib2.urlopen returns 404 for page that browser can return Background: I'm working through the "Programming Collective Intelligence" book by Toby Segaran; specifically the Kayak API example from Chapter 5. I can navigate with my browser (Chrome) to the Kayak API results page (which is all XML) here:http://www.ka...
urllib2.urlopen returns 404 for page that browser can return
Background: I'm working through the "Programming Collective Intelligence" book by Toby Segaran; specifically the Kayak API example from Chapter 5. I can navigate with my browser (Chrome) to the Kayak API results page (which is all XML) here:http://www.kayak.com/s/basic/flight?searchid=[searchidhere]&c=999&apimode=1&sid...
[ "Most probable explanation is that your search has been invalidated (outdated). Chrome might display data from the cache, try refreshing the page in chrome and see if results are still there.\nAlternatively, web page might expect a previously saved cookie.\n", "If you try the above query in browser too, you will...
[ 0, 0, 0 ]
[]
[]
[ "debugging", "python", "urllib2" ]
stackoverflow_0005162655_debugging_python_urllib2.txt
Q: web.py memory leak Am I doing something wrong or does web.py leak memory? import web class Index: def GET(self): return 'hello web.py' app = web.application(('/*', 'Index'), globals()) app.run() Run the above file. Watch how much memory the task uses. Go to localhost:8080 in your browser. Close the browser ...
web.py memory leak
Am I doing something wrong or does web.py leak memory? import web class Index: def GET(self): return 'hello web.py' app = web.application(('/*', 'Index'), globals()) app.run() Run the above file. Watch how much memory the task uses. Go to localhost:8080 in your browser. Close the browser (to keep the page from g...
[ "After running your code and sending it thousands of requests (via another Python process using urllib2), I find that it grows by about 200k over the course of the first few hundred requests and then stops growing. That doesn't seem unreasonable, and it needn't indicate a memory leak. Remember that Python uses auto...
[ 4 ]
[]
[]
[ "memory_leaks", "python", "web.py", "web_applications" ]
stackoverflow_0005162688_memory_leaks_python_web.py_web_applications.txt
Q: AppEngine: Out of Blobstore and into S3? I'm uploading data to the blobstore. There should it stay only temporary and be uploaded from within my AppEngine app to Amazon S3. As it seems I can only get the data through a BlobDonwloadHandler as described at the Blobstore API: http://code.google.com/intl/de-DE/appengi...
AppEngine: Out of Blobstore and into S3?
I'm uploading data to the blobstore. There should it stay only temporary and be uploaded from within my AppEngine app to Amazon S3. As it seems I can only get the data through a BlobDonwloadHandler as described at the Blobstore API: http://code.google.com/intl/de-DE/appengine/docs/python/blobstore/overview.html#Serving...
[ "You can use a BlobReader to access that Blob and send that to S3.\nhttp://code.google.com/intl/de-DE/appengine/docs/python/blobstore/blobreaderclass.html\n" ]
[ 2 ]
[]
[]
[ "amazon_s3", "blobstore", "google_app_engine", "python" ]
stackoverflow_0005162660_amazon_s3_blobstore_google_app_engine_python.txt
Q: Label in a dialog window does not update every release of click of button Main Window (PyQt) I've designed in a GUI using QtDesigner (at eric4) I've just made a Qlabel as a placeholder which is intended to update with the latest ID that has access to a SQLite database which I'm building. I want it to setlabel to c...
Label in a dialog window does not update every release of click of button Main Window (PyQt)
I've designed in a GUI using QtDesigner (at eric4) I've just made a Qlabel as a placeholder which is intended to update with the latest ID that has access to a SQLite database which I'm building. I want it to setlabel to change to the next slot available in ID primary key so I made a class and def in a separate py file...
[ "Okay, I ended up finding the solution after taking some rest and sleeping.\nI just did some changing in the compiled UI form where these\nIDL = AccessMem()\nIDLabel = `IDL.LastRowID()`\n\nwere first at the topmost, I put it now inside the method of def retranslateUi and it now works.\n" ]
[ 0 ]
[]
[]
[ "pyqt", "python", "qt_designer", "sqlite" ]
stackoverflow_0005161037_pyqt_python_qt_designer_sqlite.txt
Q: ForeignKey model has no Manager (i.e., 'Foo' object has no attribute 'foo_set') I have searched around for an answer to this but can't find one. When using a ForeignKey, I am consistently getting an error telling me that 'Foo object has no attribute 'foo_set'. I am a bit new to Django/Python, so I'm sure there is ...
ForeignKey model has no Manager (i.e., 'Foo' object has no attribute 'foo_set')
I have searched around for an answer to this but can't find one. When using a ForeignKey, I am consistently getting an error telling me that 'Foo object has no attribute 'foo_set'. I am a bit new to Django/Python, so I'm sure there is a simple answer here, but I haven't been able to find it so far. Here's some code (to...
[ "The name that Django uses for a reverse foreign key manager is the name of the model that contains the foreign key, not the name of the model that the manager is on.\nIn your case, it will be:\nnewboard.hexes_set.create(col=c,row=r)\n\nI find it useful to use the manage.py shell command to import your models and i...
[ 2 ]
[]
[]
[ "django", "django_models", "foreign_keys", "python" ]
stackoverflow_0005162874_django_django_models_foreign_keys_python.txt
Q: C# or Python Pipe Blocked I'm trying to simply be able to pipe the standard output of my program (written in C#) to another program (e.g. python script). My code simply writes to standard output using Console.Write(), and that works just fine when I'm not piping. The listen command just uses Console.Write() to wri...
C# or Python Pipe Blocked
I'm trying to simply be able to pipe the standard output of my program (written in C#) to another program (e.g. python script). My code simply writes to standard output using Console.Write(), and that works just fine when I'm not piping. The listen command just uses Console.Write() to write data from a separate Thread ...
[ "Does your program write newlines or call flush on its standard output? Maybe it's buffered and that's why you can't see anything.\n", "You may want to look here and search for \"deadlock\".\nMaybe it will help.\n", "Your python program requires 2 EOF characters to terminate. Try this.\nimport sys\n\nline=sys.s...
[ 0, 0, 0 ]
[]
[]
[ "c#", "console_application", "pipe", "python", "stdin" ]
stackoverflow_0004520165_c#_console_application_pipe_python_stdin.txt
Q: Method to create a model instance based on a request object I have a model like this: class UserSubmission(models.Model): mantra = models.CharField(max_length=64) ip = models.CharField(max_length=15) # xxx.xxx.xxx.xxx I want to create a function like so: def create_submission(request, mantra): s = Use...
Method to create a model instance based on a request object
I have a model like this: class UserSubmission(models.Model): mantra = models.CharField(max_length=64) ip = models.CharField(max_length=15) # xxx.xxx.xxx.xxx I want to create a function like so: def create_submission(request, mantra): s = UserSubmission(mantra=mantra) ip_meta_entry = 'HTTP_X_REAL_IP' i...
[ "I tend to put functions that use request in views.py. Aside from error checking, your code should work fine.\ndef create_submission(request, mantra):\n ip_meta_entry = 'HTTP_X_REAL_IP' in request.META and 'HTTP_X_REAL_IP' or 'REMOTE_ADDR'\n s = UserSubmission(\n mantra=mantra,\n ip=request.MET...
[ 2 ]
[]
[]
[ "django", "django_managers", "django_models", "python" ]
stackoverflow_0005161841_django_django_managers_django_models_python.txt
Q: Matplotlib and Numpy Math I'm trying get some traction with Matplotlib and Numpy but it is not very easy. I'm doing a mini project to start dealing with Matplotlib and Numpy but I'm stuck... Here is the code: # Modules import datetime import numpy as np import matplotlib.finance as finance import matplotlib.mlab a...
Matplotlib and Numpy Math
I'm trying get some traction with Matplotlib and Numpy but it is not very easy. I'm doing a mini project to start dealing with Matplotlib and Numpy but I'm stuck... Here is the code: # Modules import datetime import numpy as np import matplotlib.finance as finance import matplotlib.mlab as mlab import matplotlib.pyplot...
[ "I agree with Josh, but wanted to add the matplotlib gallery: \nhttp://matplotlib.sourceforge.net/gallery.html\nMost of my plots start off directly copying something close to what I want, and then modifying it to fit my needs. The matplotlib gallery has many such examples.\n", "I would say that you don't necessa...
[ 5, 3, 2, 1 ]
[]
[]
[ "matplotlib", "numpy", "python", "stockquotes" ]
stackoverflow_0005155847_matplotlib_numpy_python_stockquotes.txt
Q: Extending c functionality of PIL I want to create functionality similar to PIL's Image.blend, using a different blending algorithm. To do this would I need to: (1) directly modify the PIL modules and compile my own custom PIL or (2) write a python c module which imports and extends PIL? I have unsuccessfully trie...
Extending c functionality of PIL
I want to create functionality similar to PIL's Image.blend, using a different blending algorithm. To do this would I need to: (1) directly modify the PIL modules and compile my own custom PIL or (2) write a python c module which imports and extends PIL? I have unsuccessfully tried: #include "_imaging.c" I also was t...
[ "Here's my implementation in NumPy. I have no unit tests, so I do not know if it contains bugs. I assume I'll hear from you if it fails. Explanation of what is going on is in the comments. It processes a 200x400 RGBA image in 0.07 seconds\nimport Image, numpy\n\ndef blend_images(upper=None, lower=None):\n # ...
[ 3 ]
[]
[]
[ "c", "python", "python_imaging_library" ]
stackoverflow_0005161510_c_python_python_imaging_library.txt
Q: Is there something like `ForeignKey` in Google App Engine's `webapp`? I'm using Google App Engine with their webapp framework. Is there something like Django's ForeigKey in webapp? i.e. I have a model and I want it to have a property/field that points at another model. Possible? A: There is a db.ReferencePropert...
Is there something like `ForeignKey` in Google App Engine's `webapp`?
I'm using Google App Engine with their webapp framework. Is there something like Django's ForeigKey in webapp? i.e. I have a model and I want it to have a property/field that points at another model. Possible?
[ "There is a db.ReferenceProperty. You need to be aware of two things when using it: automatic dereferencing (which is another datastore RPC call) and the entity being referenced is not required to exist (so you will need to manually check it).\nWhen using db.ReferenceProperty make sure you use Appstats to avoid fe...
[ 7, 4 ]
[]
[]
[ "foreign_keys", "google_app_engine", "python", "web_applications" ]
stackoverflow_0005157070_foreign_keys_google_app_engine_python_web_applications.txt
Q: Is there any good python library for generating and rendering text in image format? I'm developing a CMS like application where the user should be able to create the menu the way he wants. Ideally, each menu object wouldn't be a text with a background but rather an image of the text. I envision this in either of t...
Is there any good python library for generating and rendering text in image format?
I'm developing a CMS like application where the user should be able to create the menu the way he wants. Ideally, each menu object wouldn't be a text with a background but rather an image of the text. I envision this in either of these 2 ways: a) By rendering a font in a/several image file/s with every letter and a scr...
[ "We are using Imagemagick. \nhttp://www.imagemagick.org/Usage/text/#attributes\n\nThis will render a simple button with text:\nconvert -background white -fill dodgerblue -font Candice -strokewidth 2 -stroke blue -undercolor lightblue -size 165x70 -gravity center label:Anthony label_color.gif\n\nWrapping th...
[ 3, 2, 0, 0, 0 ]
[]
[]
[ "fonts", "imaging", "python", "render" ]
stackoverflow_0005163416_fonts_imaging_python_render.txt
Q: Easy Install for Python and Eclipse Library Paths Recently I found about this tool easy_install that help me to easy install additional python modules. The problem is that for each module it creates additional *.egg folder (sometime there is only an egg file?) (no source?) and I don't know how to setup eclipse pat...
Easy Install for Python and Eclipse Library Paths
Recently I found about this tool easy_install that help me to easy install additional python modules. The problem is that for each module it creates additional *.egg folder (sometime there is only an egg file?) (no source?) and I don't know how to setup eclipse paths. By default I have included C:\Python26\Lib\site-pac...
[ "I'm assuming that eclipse does not search the egg files for source. Eggs, like jar files in Java, are just zipfiles of python code with some included metadata.\nYou'll also note that in site-packages you've got easy-install.pth and setuptools.pth files. Those files are parsed by python and used to add other dire...
[ 2 ]
[]
[]
[ "easy_install", "eclipse", "python" ]
stackoverflow_0005163484_easy_install_eclipse_python.txt
Q: Django RSS add attribute into item Just a quick question that I have been having trouble with all day. Hopefully my google skills just havent failed me ;) I want to add an extra field to the <item>, something like: <item> <title></title> <myfield></myfield> </item> A: Although I dont like answering my ow...
Django RSS add attribute into item
Just a quick question that I have been having trouble with all day. Hopefully my google skills just havent failed me ;) I want to add an extra field to the <item>, something like: <item> <title></title> <myfield></myfield> </item>
[ "Although I dont like answering my own questions, I figured out how and its rather simple...once its demonstrated. Credit does not go to me, but I found this link\nfrom django.utils.feedgenerator import Rss201rev2Feed\nclass CustomFeedGenerator(Rss201rev2Feed):\n def add_item_elements(self, handler, item):\n ...
[ 6 ]
[]
[]
[ "django", "python", "rss" ]
stackoverflow_0005163637_django_python_rss.txt
Q: Apply function to 3 elements at a time in numpy I would like to apply a function to a monodimensional array 3 elements at a time, and output for each of them a single element. for example I have an array of 13 elements: a = np.arange(13)**2 and I want to apply a function, let's say np.std as an example. Here is t...
Apply function to 3 elements at a time in numpy
I would like to apply a function to a monodimensional array 3 elements at a time, and output for each of them a single element. for example I have an array of 13 elements: a = np.arange(13)**2 and I want to apply a function, let's say np.std as an example. Here is the equivalent list comprehension: [np.std(a[i:i+3]) f...
[ "The simplest way is to reshape it and apply the function along an axis.\nimport numpy as np\na = np.arange(12)**2\nb = a.reshape(4,3)\nprint np.std(b, axis=1)\n\n If you need a little better performance than that, you could try stride_tricks. Below is the same as above except using stride_tricks. I was wrong abo...
[ 5, 0, 0 ]
[]
[]
[ "numpy", "python" ]
stackoverflow_0005163974_numpy_python.txt
Q: Use smtpd.PureProxy with HTTP proxy I want to set up SMTP relay server which also needs to use HTTP proxy. I'm using Python. SMTP proxy: import smtpd import asyncore smtpd.PureProxy(('local host name', 1234), ('smtp server name', 25)) asyncore.loop() The issue is I need to use HTTP proxy in order to connect to SM...
Use smtpd.PureProxy with HTTP proxy
I want to set up SMTP relay server which also needs to use HTTP proxy. I'm using Python. SMTP proxy: import smtpd import asyncore smtpd.PureProxy(('local host name', 1234), ('smtp server name', 25)) asyncore.loop() The issue is I need to use HTTP proxy in order to connect to SMTP server. How can I specify it?
[ "Square peg in round hole. SMTP is a different protocol to HTTP, they are incompatible.\n", "I used desproxy to HTTP tunnel SMTP connection.\n" ]
[ 0, 0 ]
[]
[]
[ "http_proxy", "proxy", "python", "smtp" ]
stackoverflow_0005150192_http_proxy_proxy_python_smtp.txt
Q: How to grab a chunk of data from a file? I want to grab a chunk of data from a file. I know the start line and the end line. I wrote the code but its incomplete and I don't know how to solve it further. file = open(filename,'r') end_line='### Leave a comment!' star_line = 'Kill the master' for line in fil...
How to grab a chunk of data from a file?
I want to grab a chunk of data from a file. I know the start line and the end line. I wrote the code but its incomplete and I don't know how to solve it further. file = open(filename,'r') end_line='### Leave a comment!' star_line = 'Kill the master' for line in file: if star_line in line: ...
[ "startmarker = \"ohai\"\nendmarker = \"meheer?\"\nmarking = False\nresult = []\n\nwith open(\"somefile\") as f:\n for line in f:\n if line.startswith(startmarker): marking = True\n elif line.startswith(endmarker): marking = False\n\n if marking: result.append(line)\n\nif len(result) > 1:\n print \"\".joi...
[ 1, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0005163781_python.txt
Q: How to escape unicode syntax (u'foo') in JSON string? I'm passing a JSON String from the server to a Django template. When I assign the JSON String to a jQuery variable, I'm getting unicode syntax. Py: # Call Facebook Graph API to get list of Friends. result = facebook.GraphAPI( user.access_token).get...
How to escape unicode syntax (u'foo') in JSON string?
I'm passing a JSON String from the server to a Django template. When I assign the JSON String to a jQuery variable, I'm getting unicode syntax. Py: # Call Facebook Graph API to get list of Friends. result = facebook.GraphAPI( user.access_token).get_connections('me', 'friends') friends = result["data"] j...
[ "You need to convert friends to JSON on the server side. You're seeing the Python representation, which looks like kind of like JSON sometimes but isn't.\n", "As Brian Goldman points out, the friends variable isn't a JSON string, like you say, but a Python object, which looks enough like JSON when printed out to ...
[ 4, 2, 1 ]
[]
[]
[ "jquery", "json", "python", "unicode" ]
stackoverflow_0005145037_jquery_json_python_unicode.txt
Q: Python - MySql access for inserting data into db I have created a Django application.Now i am trying to populate some data into SQL database tabel EmployeeDetails, using normal python script. But i am not able to insert data into db. I guess its because my db is not connecting with this external python script. I a...
Python - MySql access for inserting data into db
I have created a Django application.Now i am trying to populate some data into SQL database tabel EmployeeDetails, using normal python script. But i am not able to insert data into db. I guess its because my db is not connecting with this external python script. I am new with Python, so please help me to solve this.Thi...
[ "\nDon't import MySQLdb. Use Django instead.\nDon't bother connecting to the database directly. Use Django instead.\nIf you are going to create objects from your models, you need to import those. They will take care of importing all of the necessary Django modules, if you have written them correctly.\nModel.objects...
[ 3, 0 ]
[]
[]
[ "database", "django", "django_models", "mysql", "python" ]
stackoverflow_0005164221_database_django_django_models_mysql_python.txt
Q: Error running Python apps in Ubuntu This is the first time I've tried Python. I followed this guide, and want make this app running in Ubtuntu 10 server. I used easy_install virtualenv and followed the rest of the setup steps. But, I got errors in step 8: (mirosubs-env)root@makserver:/usr/local/src/mirosubs# pyt...
Error running Python apps in Ubuntu
This is the first time I've tried Python. I followed this guide, and want make this app running in Ubtuntu 10 server. I used easy_install virtualenv and followed the rest of the setup steps. But, I got errors in step 8: (mirosubs-env)root@makserver:/usr/local/src/mirosubs# python manage.py syncdb Error: No module nam...
[ "Seems like either you forgot to install some additional Python modules or your documentation doesn't mention them. You need to do:\nsudo easy_install South\nsudo easy_install sorl-thumbnail\n\nOf course, you may encounter further problems, but that should solve your immediate issue.\n" ]
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0005163760_python.txt
Q: Py2app build runs perfectly when run from command line or the executable in the pkg, but not when the app is double clicked I have a program that I'm trying to distribute with py2app. When I run the program from the command line, it works without any problems. It also works if I go into the package that py2app cre...
Py2app build runs perfectly when run from command line or the executable in the pkg, but not when the app is double clicked
I have a program that I'm trying to distribute with py2app. When I run the program from the command line, it works without any problems. It also works if I go into the package that py2app creates and find the exec inside the package contents and run it from there. There are not any errors in the output during the build...
[ "Check the Console (Applications > Utilities). All stack traces from py2app applications get printed there.\nI had this problem today, and my solution was that there was something broken with argv_emulation in py2app itself, so I had to set it to False in the OPTIONS dict. It's set to True by default.\n" ]
[ 5 ]
[]
[]
[ "macos", "py2app", "python" ]
stackoverflow_0005128999_macos_py2app_python.txt
Q: Python Struct Unpack I have this little problem that has been bugging me for the past hour or so. string = b'-' t = struct.pack(">h%ds" % len(string), len(string), string) print(t) the result of this pack is b'\x00\x01-' The problem I'm having is that I can't figure out how to unpack the result b'\x00\x01-' so th...
Python Struct Unpack
I have this little problem that has been bugging me for the past hour or so. string = b'-' t = struct.pack(">h%ds" % len(string), len(string), string) print(t) the result of this pack is b'\x00\x01-' The problem I'm having is that I can't figure out how to unpack the result b'\x00\x01-' so that it's just '-', Yes. I k...
[ "Normally you wouldn't use struct.pack to put a length header and the value together. Instead you would just do struct.pack(\">h\", len(data)), send that over the line (for example in network protocol) and then send the data. No need to create a new bytes buffer.\nIn your case, you could simply do:\ndataLength, = s...
[ 5, 3, 1, 0, 0 ]
[]
[]
[ "python", "struct" ]
stackoverflow_0005161917_python_struct.txt
Q: Help! Django media widget did not appear been scratching my head. I've followed the examples to use a jquery datepicker for my datefield in my form. Here are my code (note:indentation are correct in my code): from django import forms from django.contrib.admin.widgets import FilteredSelectMultiple from myproject.c...
Help! Django media widget did not appear
been scratching my head. I've followed the examples to use a jquery datepicker for my datefield in my form. Here are my code (note:indentation are correct in my code): from django import forms from django.contrib.admin.widgets import FilteredSelectMultiple from myproject.customUsers.models import SchoolClass#,Student ...
[ "Ah, thanks to @seitaridis, I managed to find out where my error was. I did not specify the doctype, and ` wasn't allowed. Gosh, I am embarrassed by such a simple mistake. \n", "Try adding the following to the top of your custom widgets file.\nfrom django import forms\n\n" ]
[ 1, 0 ]
[ "Could the problem be because you've given the CalendarWidget class instead of an instance in the widget keyword argument?\nTry changing:\ndeadline = forms.DateField(widget=CalendarWidget)\n\nto\ndeadline = forms.DateField(widget=CalendarWidget())\n\n" ]
[ -1 ]
[ "django", "django_forms", "python" ]
stackoverflow_0005069606_django_django_forms_python.txt
Q: What defines floating point precision in python? I learnt of the "exactly equal to" operator in Erlang, which compares not only values, but also data types of numbers, and I was curious about how things work in Python and its lone "equals to" operator. So after making sure that >>> 1 == 1.0 True I wondered abou...
What defines floating point precision in python?
I learnt of the "exactly equal to" operator in Erlang, which compares not only values, but also data types of numbers, and I was curious about how things work in Python and its lone "equals to" operator. So after making sure that >>> 1 == 1.0 True I wondered about the floating point precision, and got to this >>> 0....
[ "Please check with the Python documentation:\nhttp://docs.python.org/tutorial/floatingpoint.html\n", "It's a peril of using floating-point numbers.\nIf you need precision at this deep a level, use the Decimal type.\nMore here: http://docs.python.org/library/decimal.html\n" ]
[ 9, 2 ]
[]
[]
[ "floating_point", "precision", "python" ]
stackoverflow_0005164882_floating_point_precision_python.txt
Q: RegexpTokenize Japanese sentences - python I'm trying to split the japanese sentences up using RegexpTokenizer but it is returning null sets. can someone tell me why? and how to get split the japanese sentences up? #!/usr/bin/python # -*- encoding: utf-8 -*- import nltk import os, sys, re, glob from nltk.tokeniz...
RegexpTokenize Japanese sentences - python
I'm trying to split the japanese sentences up using RegexpTokenizer but it is returning null sets. can someone tell me why? and how to get split the japanese sentences up? #!/usr/bin/python # -*- encoding: utf-8 -*- import nltk import os, sys, re, glob from nltk.tokenize import RegexpTokenizer jp_sent_tokenizer = nl...
[ "I think you're just missing a unicode u:\nprint jp_sent_tokenizer.tokenize (u'の各宣言を実行しておく必要があることに注意しよう。これ以下の節では、各スクリプト例の前にこれらがすでに宣言されていることを前提とする。')\n\n" ]
[ 3 ]
[]
[]
[ "nlp", "nltk", "python" ]
stackoverflow_0005164782_nlp_nltk_python.txt
Q: many to many problem django how in django find list of post related with special many to many field? for example catagory have title post have many to many relation to catagory how find all post from category title A: From the category objects you can retrieve the related objects using the automatically created...
many to many problem django
how in django find list of post related with special many to many field? for example catagory have title post have many to many relation to catagory how find all post from category title
[ "From the category objects you can retrieve the related objects using the automatically created field post_set, if the post model is named Post.\nThis is a bit tricky to find in the documentation because it is in a dedicated section, see here:\nhttp://docs.djangoproject.com/en/dev/topics/db/queries/#many-to-many-re...
[ 1, 1, 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0005164307_django_python.txt
Q: How can I extend Image class? I want to extend "Image" class in PIL. #module Image def open(file): ... class Image: def method1:... def method2:... #module myOriginal from Image import Image class ExtendedImage(Image): def method3:... #module test import myOriginal im = myOriginal.open("picture.jpg")...
How can I extend Image class?
I want to extend "Image" class in PIL. #module Image def open(file): ... class Image: def method1:... def method2:... #module myOriginal from Image import Image class ExtendedImage(Image): def method3:... #module test import myOriginal im = myOriginal.open("picture.jpg") RESULT: Error.myOriginal has no a...
[ "According to Fredrik Lundh, the author of PIL:\n\nthe Image class isn't designed to be\n subclassed by application code. if\n you want custom behaviour, use a\n delegating wrapper.\n\nmyOriginal.py:\nTo delegate individual methods:\nclass ExtendedImage(object):\n def __init__(self,img):\n self._img=i...
[ 11 ]
[]
[]
[ "inheritance", "python", "python_imaging_library" ]
stackoverflow_0005165317_inheritance_python_python_imaging_library.txt
Q: Python logging HTTPHandler Broken pipe error with django I'm having a few problems with using the HTTPHandler of the python logging to push messages to a customer django app. I have a separate daemon that is part of my infrastructure that I would like for it to push logs to django so I've kinda got everything all ...
Python logging HTTPHandler Broken pipe error with django
I'm having a few problems with using the HTTPHandler of the python logging to push messages to a customer django app. I have a separate daemon that is part of my infrastructure that I would like for it to push logs to django so I've kinda got everything all in one place. I'm using: Ubuntu 10.04 Django 1.2.4 PostgreSQL ...
[ "It may be that the exception is causing a transaction to roll back and undo your changes. Are you using TransactionMiddleware? You could try the transaction.autocommit decorator on your view.\nIf the \"broken pipe\" error keeps happening, it's worth finding out why. The HTTPHandler does a normal POST and waits for...
[ 0 ]
[]
[]
[ "django", "httphandler", "logging", "python" ]
stackoverflow_0005164125_django_httphandler_logging_python.txt
Q: Create dictionaries of objects in python I've created a dict of objects (creditcards): class CreditCard: def __init__(self,number,expire_date_month,expire_date_year,CVC): self.number=number self.expire_date_month=expire_date_month self.expire_date_year=expire_date_year self.CVC...
Create dictionaries of objects in python
I've created a dict of objects (creditcards): class CreditCard: def __init__(self,number,expire_date_month,expire_date_year,CVC): self.number=number self.expire_date_month=expire_date_month self.expire_date_year=expire_date_year self.CVC=CVC credit_cards={CreditCard('10000000000000...
[ "I think there are two things that are wrong with your code.\n\nIf you want the CreditCard object to be retrieved by its associated string ('VISA' in this case), you should make the string the key and the object the value and not the other way around. Your dict should look like this,\ncredit_cards={'VISA':CreditCar...
[ 8 ]
[]
[]
[ "dictionary", "python" ]
stackoverflow_0005165761_dictionary_python.txt
Q: How to return a function pointer from CPython to Python then call a C function with ctypes? I have CPython function: void my_cfunc(int arg) { printf("Hello from C; arg=%d\n", arg); } PyObject *get_fptr(PyObject * /*self*/, PyObject * /*args*/) { return PyCObject_FromVoidPtr(my_cfunc, NULL); } Then later, i...
How to return a function pointer from CPython to Python then call a C function with ctypes?
I have CPython function: void my_cfunc(int arg) { printf("Hello from C; arg=%d\n", arg); } PyObject *get_fptr(PyObject * /*self*/, PyObject * /*args*/) { return PyCObject_FromVoidPtr(my_cfunc, NULL); } Then later, in Python I have: import mymodule ptr = mymodule.get_fptr() # will return a PyCObject wrapping th...
[ "First of all, I don't understand why you'd want to return a C function pointer from a Python extension only to call it from Python (via ctypes), while the logical thing would be to call the C function via the Python extension (unless I'm missing something).\nSecond, it does not look like ctypes supports PyCObject ...
[ 1 ]
[]
[]
[ "casting", "ctypes", "function", "pointers", "python" ]
stackoverflow_0005158766_casting_ctypes_function_pointers_python.txt
Q: python argparse subcommand with dependency and conflict I want to use argparse to build a tool with subcommand. The possible syntax could be /tool.py download --from 1234 --interval 60 /tool.py download --build 1432 /tool.py clean --numbers 10 So I want to use argparse to implement: ensure '--from' and '--inter...
python argparse subcommand with dependency and conflict
I want to use argparse to build a tool with subcommand. The possible syntax could be /tool.py download --from 1234 --interval 60 /tool.py download --build 1432 /tool.py clean --numbers 10 So I want to use argparse to implement: ensure '--from' and '--interval' are always together used ensure '--build' is never used ...
[ "You could use custom actions for this:\nimport argparse\nimport sys\n\n\nclass VerifyNoBuild(argparse.Action):\n def __call__(self, parser, args, values, option_string=None):\n # print 'No: {n} {v} {o}'.format(n=args, v=values, o=option_string)\n if args.build is not None:\n parser.erro...
[ 6 ]
[]
[]
[ "argparse", "python" ]
stackoverflow_0005165415_argparse_python.txt
Q: How do I figure out why Python is throwing this non-descriptive error in Windows 7 64 bit I'm making graphs using scipy on python 2.7 on Windows 7 64 bit. I installed it from http://www.lfd.uci.edu/~gohlke/pythonlibs/. When running scripts, I'm periodically getting error boxes that say: Title: Microsoft Visual ...
How do I figure out why Python is throwing this non-descriptive error in Windows 7 64 bit
I'm making graphs using scipy on python 2.7 on Windows 7 64 bit. I installed it from http://www.lfd.uci.edu/~gohlke/pythonlibs/. When running scripts, I'm periodically getting error boxes that say: Title: Microsoft Visual C++ Runtime Library Message: Runtime Error! Program: C:\Python27\pythonw.exe This applicatio...
[ "You could consider installing Visual Studio, and build and install Python and SciPy with debug symbols. When Python subsequently crashes, if I'm not completely mistaken Windows should be giving you the option of debugging it in Visual Studio.\nOtherwise, I'd ask for assistance on one of the SciPy mailing lists.\n"...
[ 0 ]
[]
[]
[ "python", "python_2.7", "scipy" ]
stackoverflow_0004779625_python_python_2.7_scipy.txt
Q: Wrapping a function which returns a pointer to a python object with ctypes I've got some code which compiles a C function to create a numpy generic function with it using PyUFunc_FromFuncAndData. I've written some cython to create the ufunc but I'd like to do it with ctypes if possible since I'm intending to distr...
Wrapping a function which returns a pointer to a python object with ctypes
I've got some code which compiles a C function to create a numpy generic function with it using PyUFunc_FromFuncAndData. I've written some cython to create the ufunc but I'd like to do it with ctypes if possible since I'm intending to distribute it and I'd like to avoid users the compile step. The problem is that PyUFu...
[ "Set restype of that function to ctypes.py_object. The following example uses a call to python C-API but it works the same for anything else.\nimport ctypes\nclass Foo(object):\n bar='baz'\n\nfoo=ctypes.py_object(Foo)\nprint 'Memory adress of Foo.bar object:',\nprint ctypes.pythonapi.PyObject_GetAttrString(foo,'...
[ 3 ]
[]
[]
[ "ctypes", "cython", "numpy", "python" ]
stackoverflow_0004716433_ctypes_cython_numpy_python.txt
Q: Run multiprocess I'm trying to run tests in parallel using nose. I have setup a nose.cfg file to contain the following: [nosetests] verbosity=2 processes=2 I need to be able to run the programatically using either nose.main() or nose.run(). Whats the best way to do this? How do I select the test location? A: Yo...
Run multiprocess
I'm trying to run tests in parallel using nose. I have setup a nose.cfg file to contain the following: [nosetests] verbosity=2 processes=2 I need to be able to run the programatically using either nose.main() or nose.run(). Whats the best way to do this? How do I select the test location?
[ "You should invoke nose in Python code like this:\nnose.run(defaultTest=test_location)\n\nThat'll run nose on tests beneath test_location (typically a directory).\n" ]
[ 0 ]
[]
[]
[ "nose", "python", "python_nose", "unit_testing" ]
stackoverflow_0004466077_nose_python_python_nose_unit_testing.txt
Q: Reuse existing objects for immutable objects? In Python, how is it possible to reuse existing equal immutable objects (like is done for str)? Can this be done just by defining a __hash__ method, or does it require more complicated measures? A: If you want to create via the class constructor and have it return a ...
Reuse existing objects for immutable objects?
In Python, how is it possible to reuse existing equal immutable objects (like is done for str)? Can this be done just by defining a __hash__ method, or does it require more complicated measures?
[ "If you want to create via the class constructor and have it return a previously created object then you will need to provide a __new__ method (because by the time you get to __init__ the object has already been created).\nHere is a simple example - if the value used to initialise has been seen before then a previo...
[ 17, 4, 3 ]
[]
[]
[ "immutability", "python" ]
stackoverflow_0005161424_immutability_python.txt
Q: Unique items in python list I am trying to make a unique collection of dates in a Python list. Only add a date to the collection if it not already present in the collection. timestamps = [] timestamps = [ '2011-02-22', '2011-02-05', '2011-02-04', '2010-12-14', '2010-12-13', '2010-12-12', '2010-12-11', '2...
Unique items in python list
I am trying to make a unique collection of dates in a Python list. Only add a date to the collection if it not already present in the collection. timestamps = [] timestamps = [ '2011-02-22', '2011-02-05', '2011-02-04', '2010-12-14', '2010-12-13', '2010-12-12', '2010-12-11', '2010-12-07', '2010-12-02', '2010-1...
[ "You can use sets for this.\ndate = \"2010-11-22\"\ntimestamps = set(['2011-02-22', '2011-02-05', '2011-02-04', '2010-12-14', '2010-12-13', '2010-12-12', '2010-12-11', '2010-12-07', '2010-12-02', '2010-11-30', '2010-11-26', '2010-11-23', '2010-11-22', '2010-11-16'])\n#then you can just update it like so\ntimestamps...
[ 14, 2, 1 ]
[]
[]
[ "python" ]
stackoverflow_0005166569_python.txt
Q: Problem in downloading the file using sharepoint copy.asmx I am trying to download the file from the document using sharepoint webservices called copy.asmx. its onlt 100 kb file size. But its not downloading the file. The web services iteself return empty stream (out byte[] Stream) in the web service response. is ...
Problem in downloading the file using sharepoint copy.asmx
I am trying to download the file from the document using sharepoint webservices called copy.asmx. its onlt 100 kb file size. But its not downloading the file. The web services iteself return empty stream (out byte[] Stream) in the web service response. is that any memory issue. Also it returning like "download_document...
[ "Please try below function. you need to pass FileURL(Full web url for document), Title(Pass name you want to give for downloaded file.)\npublic string DownLoadfiletolocal(string FileURL, string Title)\n{\n\n//Copy.Copy is a webservice object that I consumed.\n\nCopy.Copy CopyObj = new Copy.Copy();\nCopyObj.Url = Si...
[ 0 ]
[]
[]
[ "download", "python", "sharepoint", "web_services" ]
stackoverflow_0005166581_download_python_sharepoint_web_services.txt
Q: Python: Get Windows username of user viewing page? Is there a way in Python/Django to get the username of the currently logged-in Windows user, from an app that is not running locally? UPDATE: sorry, to clarify, by this I mean the Windows username of the user viewing the web page, not the user running the server. ...
Python: Get Windows username of user viewing page?
Is there a way in Python/Django to get the username of the currently logged-in Windows user, from an app that is not running locally? UPDATE: sorry, to clarify, by this I mean the Windows username of the user viewing the web page, not the user running the server. I've tried both: current_user = os.environ.get("USERNAM...
[ "Three ways, none of which work.\n\nUse the Ident (AUTH) protocol. It's technically cross-platform.\n...except there are exactly zero Ident servers for Windows that are able to return the real user name instead of a static string.\nEdit: Apparently Retina Scan Identd can do this. (Awesome.)\nRequire HTTP NTLM or Ne...
[ 2 ]
[]
[]
[ "django_authentication", "python", "windows_authentication" ]
stackoverflow_0005166901_django_authentication_python_windows_authentication.txt
Q: Trouble with Tornado and JavaScript Libraries I'm trying to write a simple python web application using the Tornado web server and am having trouble using the JavaScript libraries I need. I wanted to use the Protovis JavaScript plotting library, so I added the following 'Hello World' code snippet to my template.ht...
Trouble with Tornado and JavaScript Libraries
I'm trying to write a simple python web application using the Tornado web server and am having trouble using the JavaScript libraries I need. I wanted to use the Protovis JavaScript plotting library, so I added the following 'Hello World' code snippet to my template.html: <script type="text/javascript" src="/protovis-d...
[ "You should read the documentation about static files.\nIn particular, the standard way is to:\n\nCreate a 'static' directory in the root of your application\nAdd the following to your application settings: \n\"static_path\": os.path.join(os.path.dirname(file), \"static\")\nPut the protovis-d3.2.js in your static ...
[ 12 ]
[]
[]
[ "javascript", "protovis", "python", "templates", "tornado" ]
stackoverflow_0005167109_javascript_protovis_python_templates_tornado.txt
Q: Turkish character problem in post data I have two applications running on diffrent servers with diffrent DB's. I need to post some data from one to another, so ,i use post method. I concatenate related info into a string, then POST it... My data is something like: 26AU223/AHMET DEMİROĞLU/18439586958/0//2000-07-31/...
Turkish character problem in post data
I have two applications running on diffrent servers with diffrent DB's. I need to post some data from one to another, so ,i use post method. I concatenate related info into a string, then POST it... My data is something like: 26AU223/AHMET DEMİROĞLU/18439586958/0//2000-07-31/2000-06-11/42.00/0 For turkish characters, ...
[ "With Python 2.x, this is obviously wrong:\nvar1 = '26AU223/AHMET DEMİROĞLU/18439586958/0//2000-07-31/2000-06-11/42.00/0'\nvar1.encode('iso8859_9')\n\nPython 2 has a bad design flaw in that it allows you to .encode() byte strings (str type). You must have a Unicode string, and then encode that before POSTing it. An...
[ 1, 1, 0 ]
[]
[]
[ "character_encoding", "python" ]
stackoverflow_0005166036_character_encoding_python.txt
Q: Why does os.path.getsize() return a negative number for a 10gb file? I am using the function os.path.getsize() which gives the size of the file in bytes. As my one file size is 10gb it give me size in negative(bytes). so can anyone give me any idea why this happen? This is my code: import os ospathsize = os.path.g...
Why does os.path.getsize() return a negative number for a 10gb file?
I am using the function os.path.getsize() which gives the size of the file in bytes. As my one file size is 10gb it give me size in negative(bytes). so can anyone give me any idea why this happen? This is my code: import os ospathsize = os.path.getsize('/home/user/Desktop/test1.nrg') print (ospathsize)
[ "Your Linux kernel obviously has large file support, since ls -l works correctly. Thus, it's your Python installation that is lacking the support. (Are you using your distribution's Python package? What distribution is it?)\nThe documentation on POSIX large file support in Python states that Python should typica...
[ 10, 1 ]
[]
[]
[ "file_io", "linux", "python" ]
stackoverflow_0005167120_file_io_linux_python.txt
Q: continuous writing to a text file and ensuring that a new file is create each time I'm writing to a text file using the code below. the setup is: read '\n'-terminated data off of the serial port. create a text file containing only one line of text. _ import serial ser = serial.Serial ( 2 , baudrate = 57600 , ti...
continuous writing to a text file and ensuring that a new file is create each time
I'm writing to a text file using the code below. the setup is: read '\n'-terminated data off of the serial port. create a text file containing only one line of text. _ import serial ser = serial.Serial ( 2 , baudrate = 57600 , timeout = 1 ) AngleText = open ("data.txt" , "w") while True: line = ser.readline()....
[ "One solution is to move the open and close statements inside the loop so that each time you get data you overwrite the file. For example:\nimport serial\n\nser = serial.Serial ( 2 , baudrate = 57600 , timeout = 1 )\nwhile True:\n\n line = ser.readline().strip('^\\n\\r')\n print line\n AngleText = open (\"...
[ 6 ]
[]
[]
[ "python" ]
stackoverflow_0005167459_python.txt
Q: Web Python instead of addslashes i am familiar with php. but new to python. in php i will use addslashes() and stripslashes() method. instead of this what solution is there in python for avoiding sql conflicts. A: The solution is parameterized statements, where you will do something like this: db.execute('SELECT...
Web Python instead of addslashes
i am familiar with php. but new to python. in php i will use addslashes() and stripslashes() method. instead of this what solution is there in python for avoiding sql conflicts.
[ "The solution is parameterized statements, where you will do something like this:\ndb.execute('SELECT * FROM users WHERE username=:user;', {'user': 'john'})\n\nYour SQL client library will handle the quoting and escaping for you. The exact details depend on the library you use (for example, if your RDBMS is Postgre...
[ 4 ]
[]
[]
[ "php", "python", "sql_injection" ]
stackoverflow_0005167761_php_python_sql_injection.txt
Q: Error Code 203 on GAE I keep getting this error 12-21 09:32AM 10.043 /matrix 500 334696ms 147411cpu_ms 147411api_cpu_ms 0kb AppEngine-Google; (+http://code.google.com/appengine) 0.1.0.2 - - [21/Dec/2010:09:37:44 -0800] "POST /matrix HTTP/1.1" 500 0 "AppEngine-Google; (+http://code.google.com/appengine)" "ms=334...
Error Code 203 on GAE
I keep getting this error 12-21 09:32AM 10.043 /matrix 500 334696ms 147411cpu_ms 147411api_cpu_ms 0kb AppEngine-Google; (+http://code.google.com/appengine) 0.1.0.2 - - [21/Dec/2010:09:37:44 -0800] "POST /matrix HTTP/1.1" 500 0 "AppEngine-Google; (+http://code.google.com/appengine)" "ms=334696 cpu_ms=147412 api_cpu_m...
[ "You have probably hit the request time limit.\nIf you use the \"logger\" module then you should be able to see the print outs by clicking on login to appspot, click on \"Logs\" and set \"Logs with minimum severity\" to \"Debug\".\n" ]
[ 1 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0004505472_google_app_engine_python.txt
Q: ValueError: invalid literal for int() with base 10: i am getting this value error, when i try to insert some data to django model. My python script is : from task.employeeDetails.models import EmployeeDetails def dumpdata(): userName = "John" designation = 'Software Engineer' employeeID = 2312 ...
ValueError: invalid literal for int() with base 10:
i am getting this value error, when i try to insert some data to django model. My python script is : from task.employeeDetails.models import EmployeeDetails def dumpdata(): userName = "John" designation = 'Software Engineer' employeeID = 2312 contactNumber = 9495321257 project = 'AOL' dateO...
[ "Don't use positional arguments, use keywords to specify which field is being populated with what data.\nEmployeeDetails(userName=userName, designation=designation) #etc\n\nAlso, if you are going to call save() anyways, you can use EmployeeDetails.objects.create(...)\n", "I am no Django expert, but try replacing\...
[ 7, 5 ]
[]
[]
[ "django", "django_models", "django_views", "python" ]
stackoverflow_0005168035_django_django_models_django_views_python.txt
Q: Creating old fashion console form using Python How can I write a console form looking like the one seen on the screenshot using python. This means that I can write something like print(x=6, y=2, "z/VM ONLINE") This code should place the text almost in the upper left corner as seen on the screenshot. Importantly ...
Creating old fashion console form using Python
How can I write a console form looking like the one seen on the screenshot using python. This means that I can write something like print(x=6, y=2, "z/VM ONLINE") This code should place the text almost in the upper left corner as seen on the screenshot. Importantly the output text should never make all the other text...
[ "The Python curses module is made for this purpose.\n", "You need to learn (in great depth) the precise capabilities of the terminal you wish to use. Specific bytes will cause the character to move left, right, up and down - or maybe not, depending on the capabilities of the terminal emulator you are using.\nIf y...
[ 4, 2 ]
[]
[]
[ "command_line_interface", "command_prompt", "python" ]
stackoverflow_0005168069_command_line_interface_command_prompt_python.txt
Q: Best way to save availability of user over days of week in python/django I want to store users preferences for day(s) of week he might be available. e.g. A user can be available on saturday, sunday but not on other days. Currently I am using array of 7 checkboxes(values=1,2,...7) so that user can select individual...
Best way to save availability of user over days of week in python/django
I want to store users preferences for day(s) of week he might be available. e.g. A user can be available on saturday, sunday but not on other days. Currently I am using array of 7 checkboxes(values=1,2,...7) so that user can select individual days of his availability. Now the first question is how can i store this in d...
[ "1st - good solution, I'm doing mine similarly. \n2nd - you should think of assigning each day power of 2, that way it'll be easy to convert those numbers to binary using bin() and easy to compare you'll just do &.\n>>> mon, tue, wed, thu, fri, sat, sun = (pow(2, i) for i in range(7)) \n>>> bin(mon)\n'0b1'\n>>> bin...
[ 3, 2, 1, 1, 1, 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0005168207_django_python.txt
Q: Can Python be embedded in HTML like PHP and JSP? Is there a way of writing Python embedded in HTML like I do with PHP or JSP? A: Use a template engine, such as: Jinja2 (based on Django's templating) mako Cog Cheetah The python wiki also has an article on this topic, with many more suggestions. A: There is......
Can Python be embedded in HTML like PHP and JSP?
Is there a way of writing Python embedded in HTML like I do with PHP or JSP?
[ "Use a template engine, such as:\n\nJinja2 (based on Django's templating)\nmako\nCog\nCheetah\n\nThe python wiki also has an article on this topic, with many more suggestions.\n", "There is... But you're highly suggested to use a templating engine, or some other means of separating the presentation from the busi...
[ 23, 7, 2, 1, 0 ]
[]
[]
[ "html", "python" ]
stackoverflow_0005168588_html_python.txt
Q: OpenCV / Array should be CvMat or IplImage / Releasing a capture object Edit : Array should be CvMat or IplImage is not an error message specific to this issue, that's the only most relevant error message i got. I'm trying to make an *.exe out of an application using opencv. I'm using Python 2.6 and openCV 2.1. I...
OpenCV / Array should be CvMat or IplImage / Releasing a capture object
Edit : Array should be CvMat or IplImage is not an error message specific to this issue, that's the only most relevant error message i got. I'm trying to make an *.exe out of an application using opencv. I'm using Python 2.6 and openCV 2.1. I can run part of the *.exe, i'm having a menu from where i can choose to proc...
[ "It was not related to the packagers.\nThe problem was that I wasn't closing the webcam capture, several processes of my app were actually running in the background.\nThe doc is talking about ReleaseCapture but this function is apparently not in the python bindings, calling :\ndel(self.cam)\ndid the job just well, ...
[ 4 ]
[]
[]
[ "camera", "capture", "opencv", "python", "release" ]
stackoverflow_0005140230_camera_capture_opencv_python_release.txt
Q: How to stop myself overwriting Python functions when coding? A source of constant headache when tracking down bugs in my Python code are seemingly innocuous snippets like this: list = ['a', 'b', 'c', 'c'] list(set(list)) This fails because I've overwritten the function list() with the variable list. A contrived...
How to stop myself overwriting Python functions when coding?
A source of constant headache when tracking down bugs in my Python code are seemingly innocuous snippets like this: list = ['a', 'b', 'c', 'c'] list(set(list)) This fails because I've overwritten the function list() with the variable list. A contrived example obviously, but the point is Python happily lets me overwr...
[ "You should use Pylint. If you are using Eclipse + PyDev, you can configure it to run automatically within the IDE and highlight this issue (and many many others).\n", "Tools like PyChecker may be valuable for you. See also this SO discussion.\n", "Use a syntax-highlighting text editor that will highlight keywo...
[ 9, 3, 3, 2, 0 ]
[]
[]
[ "built_in", "function", "python" ]
stackoverflow_0005168830_built_in_function_python.txt
Q: Problems with GAE + django 1.2 I upgraded to django 1.2 and I now get this error message which looks related to i18n. Can you tell what I should do? thanks global name '_' is not defined Traceback (most recent call last): File "/base/python_runtime/python_lib/versions/1/google/appengine/ext/webapp/__init__.py", ...
Problems with GAE + django 1.2
I upgraded to django 1.2 and I now get this error message which looks related to i18n. Can you tell what I should do? thanks global name '_' is not defined Traceback (most recent call last): File "/base/python_runtime/python_lib/versions/1/google/appengine/ext/webapp/__init__.py", line 515, in __call__ handler.ge...
[ "Looks like you are missing\nfrom django.utils.translation import gettext_lazy as _\n\nbut I have no idea why it worked in previous version.\n", "Found this at Old Django 1.0 manual (App Engine's default version is 0.98 I think).\nHere's the answer:\n\nSTANDARD TRANSLATION:\nPython’s standard library gettext modu...
[ 2, 2 ]
[]
[]
[ "django", "escaping", "google_app_engine", "html", "python" ]
stackoverflow_0005168224_django_escaping_google_app_engine_html_python.txt
Q: Using variables in Stored procedures with Python and MySQL How would I setup a stored procedure in MySQL to use external variables. I have written SP before, but not with extenal inputs. With connection string coming from pyODBC. Then, using python how would I call that Sp and input that variable? cursor.execu...
Using variables in Stored procedures with Python and MySQL
How would I setup a stored procedure in MySQL to use external variables. I have written SP before, but not with extenal inputs. With connection string coming from pyODBC. Then, using python how would I call that Sp and input that variable? cursor.execute('Call d.MySP' ????)
[ "Assuming you are using MySQLdb, according to the docs, the call would be:\ncursor.callproc('d.MySP',args)\n\nA peek under the hood shows how the variables are set and the CALL statement is made:\ndef callproc(self, procname, args=()):\n from types import UnicodeType\n db = self._get_db()\n charset = db.ch...
[ 2 ]
[]
[]
[ "mysql", "python", "stored_procedures" ]
stackoverflow_0005169302_mysql_python_stored_procedures.txt
Q: Is there any preferable way to get user/group information from an Active Directory domain in Python? For a Django application that I'm working on, I wanted to allow group membership to be determined by Active Directory group. After a while of digging through the pywin32 documentation, I came up with this: >>> imp...
Is there any preferable way to get user/group information from an Active Directory domain in Python?
For a Django application that I'm working on, I wanted to allow group membership to be determined by Active Directory group. After a while of digging through the pywin32 documentation, I came up with this: >>> import win32net >>> win32net.NetUserGetGroups('domain_name.com', 'username') [(u'Domain Users', 7), ...] I s...
[ "AD's LDAP interface has quite a few 'quirks' that make it more difficult to use than it might appear on the surface, and it tends to lag significantly behind on features. When I worked with it, I mostly dealt with authentication, but it's probably the same no matter what you're doing. There's a lot of weirdness ...
[ 3, 2, 1 ]
[]
[]
[ "active_directory", "ldap", "python", "pywin32", "winapi" ]
stackoverflow_0000654520_active_directory_ldap_python_pywin32_winapi.txt