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: Google App Engine dev_appserver can't find PIL (I've installed it) I recently upgraded my Google App Engine launcher on my Mac, running OSX 10.5.8, and afterwards my projects that work with images stopped working locally. It seems to be the same problem that I had when first using GAE locally to work with images, ...
Google App Engine dev_appserver can't find PIL (I've installed it)
I recently upgraded my Google App Engine launcher on my Mac, running OSX 10.5.8, and afterwards my projects that work with images stopped working locally. It seems to be the same problem that I had when first using GAE locally to work with images, before I installed PIL. Here is the error I get: SystemError: Parent mo...
[ "You may be suffering from the problems I was explaining here, specifically, I think...:\n\nYou need to find another way to extend Python sys.path's\n appropriately. The simplest way is to\n make a file named PIL.pth with a\n single-line content:\n/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/s...
[ 4 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0002813742_google_app_engine_python.txt
Q: Windows 7 Task Scheduler Very new to this, and I have no idea where to start. I want to schedule a python script using Task Scheduler in Windows 7. When I add a "New Action", I place the following command as the script/program : c:\python25\python.exe As the argument, I add the full path to the location of my pyt...
Windows 7 Task Scheduler
Very new to this, and I have no idea where to start. I want to schedule a python script using Task Scheduler in Windows 7. When I add a "New Action", I place the following command as the script/program : c:\python25\python.exe As the argument, I add the full path to the location of my python script path\script.py Here...
[ "Not sure how to do it properly through the GUI, but see here for a nice solution involving the schtasks command.\n" ]
[ 2 ]
[]
[]
[ "python", "scheduled_tasks" ]
stackoverflow_0002815820_python_scheduled_tasks.txt
Q: python-xmpp and looping through list of recipients to receive and IM message I can't figure out the problem and want some input as to whether my Python code is incorrect, or if this is an issue or design limitation of Python XMPP library. I'm new to Python by the way. Here's snippets of code in question below. Wha...
python-xmpp and looping through list of recipients to receive and IM message
I can't figure out the problem and want some input as to whether my Python code is incorrect, or if this is an issue or design limitation of Python XMPP library. I'm new to Python by the way. Here's snippets of code in question below. What I'd like to do is read in a text file of IM recipients, one recipient per line, ...
[ "Never mind, found the problem. One has to watch out for the newline characters at the end of a line for the elements in a list returned by file.readlines(), so I had to strip it out with .rstrip('\\n') on the element when sending out message.\n" ]
[ 2 ]
[]
[]
[ "python", "xmpp", "xmpppy" ]
stackoverflow_0002815851_python_xmpp_xmpppy.txt
Q: Why doesn't this work? take = raw_input('Please enter the string of numbers that compose code\n\n\t') y = str(take) l = [] for i in xrange(0, len(y), 3): l.append(str(y[i:i+3])) b = len(l) a = 0 while(a!=b): c = l[a].replace('444', ' ') c = l[a].replace('111', 'a') c = l[a].replace('112', 'b') c =...
Why doesn't this work?
take = raw_input('Please enter the string of numbers that compose code\n\n\t') y = str(take) l = [] for i in xrange(0, len(y), 3): l.append(str(y[i:i+3])) b = len(l) a = 0 while(a!=b): c = l[a].replace('444', ' ') c = l[a].replace('111', 'a') c = l[a].replace('112', 'b') c = l[a].replace('113', 'c') ...
[ "It's not immediately obvious to me what you are trying to do, but maybe you mean this?\nc = ''\nwhile(a!=b):\n c += l[a].replace('444', ' ') \\\n .replace('111', 'a') \\\n .replace('112', 'b') \\\n .replace('113', 'c') \\\n .replace('114', 'd')...
[ 2, 0, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0002814982_python.txt
Q: Can I start up terminal, make it open the python interactive shell and run a few python statements with the same command in os x? I often do this to prepare for some django debugging: Open up a terminal window in os x (10.6) start the python interpreter run these commands in python: from django.core.management im...
Can I start up terminal, make it open the python interactive shell and run a few python statements with the same command in os x?
I often do this to prepare for some django debugging: Open up a terminal window in os x (10.6) start the python interpreter run these commands in python: from django.core.management import setup_environ import settings setup_environ(settings) Is it possible to automate these actions and make a shortcut that I can d...
[ "If you use django you should consider running the command python manage.py shell to debug django applications.\nEven better, try the shell_plus command from the excellent django command extension add-on.\n", "You can use the PYTHONSTARTUP environment variable to your advantage here if you want to throw that in a...
[ 2, 0 ]
[]
[]
[ "macos", "python", "shell", "terminal" ]
stackoverflow_0002816749_macos_python_shell_terminal.txt
Q: JQuery getJSON Callback Returning Null Data I have a getJSON call that is called back correctly, but the data variable is null. The python code posted below is executed by the getJSON call to the demandURL. Any ideas? javascript: var demandURL = "/demand/washington/"; $.getJSON(demandURL, function(data) { con...
JQuery getJSON Callback Returning Null Data
I have a getJSON call that is called back correctly, but the data variable is null. The python code posted below is executed by the getJSON call to the demandURL. Any ideas? javascript: var demandURL = "/demand/washington/"; $.getJSON(demandURL, function(data) { console.log(data); }); python: data = {"demand_cou...
[ "Switch out your getJSON with an ajax call so you can have a look at the error message. Try something like this:\n$.ajax({\n url: url,\n dataType: 'json',\n data: data,\n success: function(data) {\n console.log(data);\n },\n error: function(XMLHttpRequest, textStatus, errorThrown) {\n console.log(textSt...
[ 0 ]
[]
[]
[ "getjson", "javascript", "jquery", "null", "python" ]
stackoverflow_0002815171_getjson_javascript_jquery_null_python.txt
Q: Store value of os.system or os.popen I want to grep the error's out of a log file and save the value as an error. When I use: errors = os.system("cat log.txt | grep 'ERROR' | wc -l") I get the return code that the command worked or not. When I use: errors = os.popen("cat log.txt | grep 'ERROR' | wc -l") I get wh...
Store value of os.system or os.popen
I want to grep the error's out of a log file and save the value as an error. When I use: errors = os.system("cat log.txt | grep 'ERROR' | wc -l") I get the return code that the command worked or not. When I use: errors = os.popen("cat log.txt | grep 'ERROR' | wc -l") I get what the command is trying to do. When I run...
[ "popen is deprecated. Use subprocess instead. For example, in your case:\np1 = Popen([\"cat\", \"log.txt\"], stdout=PIPE)\np2 = Popen([\"grep\", \"ERROR\"], stdin=p1.stdout, stdout=PIPE)\noutput = p2.communicate()[0]\n\n", "First open a pipe using popen as you did.\np = os.popen(\"cat log.txt | grep 'ERROR' | wc ...
[ 6, 2, 1, 0 ]
[]
[]
[ "bash", "operating_system", "python" ]
stackoverflow_0002817416_bash_operating_system_python.txt
Q: OpenSSL signing and Google App Engine Is there a way to sign values with a PEM formatted private key in Google App Engine (Python)? For example in PHP it could be achieved like this: $key = openssl_pkey_get_private($privateKey); openssl_sign($strToBeSigned, $signature, $key); echo "signature: ".base64_encode($sign...
OpenSSL signing and Google App Engine
Is there a way to sign values with a PEM formatted private key in Google App Engine (Python)? For example in PHP it could be achieved like this: $key = openssl_pkey_get_private($privateKey); openssl_sign($strToBeSigned, $signature, $key); echo "signature: ".base64_encode($signature); Is there a way to do the same thin...
[ "Try taking a look at this question's answers, and the link to the google group discussion to see if that helps.\nSigning a string with RSA private key on Google App Engine Python SDK\n" ]
[ 1 ]
[]
[]
[ "cryptography", "google_app_engine", "openssl", "python" ]
stackoverflow_0002813571_cryptography_google_app_engine_openssl_python.txt
Q: In Python, urllib2 giving error I tried running this, >>> urllib2.urlopen('http://tycho.usno.navy.mil/cgi-bin/timer.pl') But it is giving error like this, can anyone tell me a solution ? Traceback (most recent call last): File "<pyshell#11>", line 1, in <module> urllib2.urlopen('http://tycho.usno.navy.mil/c...
In Python, urllib2 giving error
I tried running this, >>> urllib2.urlopen('http://tycho.usno.navy.mil/cgi-bin/timer.pl') But it is giving error like this, can anyone tell me a solution ? Traceback (most recent call last): File "<pyshell#11>", line 1, in <module> urllib2.urlopen('http://tycho.usno.navy.mil/cgi-bin/timer.pl') File "C:\Python26...
[ "Double check domain is accessible or not.\nI am getting 504 Gateway Timeout error here for domain - tycho.usno.navy.mil , at the moment.\nLooks like the site is down, also downforeveryoneorjustme.com says that \n\nIt's not just you!\n http://tycho.usno.navy.mil looks down\n from here.\n\nThats why getaddrinfo i...
[ 4, 0 ]
[]
[]
[ "python", "urllib2" ]
stackoverflow_0002818098_python_urllib2.txt
Q: Dynamically calling functions - Python I have a list of functions... e.g. def filter_bunnies(pets): ... def filter_turtles(pets): ... def filter_narwhals(pets): ... Is there a way to call these functions by using a string representing their name? e.g. 'filter_bunnies', 'filter_turtles', 'filter_narwhals' A: A...
Dynamically calling functions - Python
I have a list of functions... e.g. def filter_bunnies(pets): ... def filter_turtles(pets): ... def filter_narwhals(pets): ... Is there a way to call these functions by using a string representing their name? e.g. 'filter_bunnies', 'filter_turtles', 'filter_narwhals'
[ "Are your function a part of an object? If so you could use getattr function:\n>> class A:\n def filter_bunnies(self, pets):\n print('bunnies')\n\n>>> getattr(A(), 'filter_bunnies')(1)\nbunnies\n\n", "Yes, you can use:\nglobals()['filter_bunnies']()\n\nto call 'filter_bunnies'.\n", "You can use the bu...
[ 11, 4, 2, 2, 0, 0, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0002818490_python.txt
Q: Cascading Dropdown List I am working on a web app and trying to code a form with two dropdown lists. The list in the second dropdown will be dependent on the selection from the first one. The task itself isn’t too complicated except that once the first selection is made, I need to make a database call to pull th...
Cascading Dropdown List
I am working on a web app and trying to code a form with two dropdown lists. The list in the second dropdown will be dependent on the selection from the first one. The task itself isn’t too complicated except that once the first selection is made, I need to make a database call to pull the data for the second dropdow...
[ "you will have to use a combination of Ajax and javascript here. Onchange event of your select drop down call a javascript function. This javascript function will make a ajax request to a python script that will actually make a database hit and return you a response in a javascript variable. With this javascript va...
[ 1, 0 ]
[]
[]
[ "html", "javascript", "python", "rest", "zope" ]
stackoverflow_0002776415_html_javascript_python_rest_zope.txt
Q: Django urls conf So now I am still at the Django tutorial part 3: http://docs.djangoproject.com/en/1.1/intro/tutorial03/#intro-tutorial03 Trying to set up the urls.py with this piece of code provided by the tutorial from django.conf.urls.defaults import * from django.contrib import admin admin.autodiscover() url...
Django urls conf
So now I am still at the Django tutorial part 3: http://docs.djangoproject.com/en/1.1/intro/tutorial03/#intro-tutorial03 Trying to set up the urls.py with this piece of code provided by the tutorial from django.conf.urls.defaults import * from django.contrib import admin admin.autodiscover() urlpatterns = patterns(''...
[ "It's just that django does not seem to find the function vote inside your module views.\n" ]
[ 2 ]
[]
[]
[ "django", "django_urls", "python", "views" ]
stackoverflow_0002818959_django_django_urls_python_views.txt
Q: How to remove debugging from outputting with nosetests I am using nosetests to test several scripts. But when I run nosetests it prints out the logging. I know it stores logging info into sys.stderr. Does anyone know how to stop this from outputting to the screen? I just want the test results to output like when y...
How to remove debugging from outputting with nosetests
I am using nosetests to test several scripts. But when I run nosetests it prints out the logging. I know it stores logging info into sys.stderr. Does anyone know how to stop this from outputting to the screen? I just want the test results to output like when you run unittest normally. Thanks for any help
[ "Found the answer,\nnosetests test* --nologcapture --nocapture\n\nRun this in the command line.\nThanks\n" ]
[ 6 ]
[]
[]
[ "logging", "nosetests", "python", "stderr" ]
stackoverflow_0002818766_logging_nosetests_python_stderr.txt
Q: Json unicode decoding in python's simplejson I can't decode json strings like this: "\u0e4f\u0361\u032f\u0e4f" >>> import simplejson >>> simplejson.loads('"\u0e4f\u0361\u032f\u0e4f"', encoding='utf8') u'\u0e4f\u0361\u032f\u0e4f' However php json_decode works fine: json_decode('"\u0e4f\u0361\u032f\u0e4f"'); What ...
Json unicode decoding in python's simplejson
I can't decode json strings like this: "\u0e4f\u0361\u032f\u0e4f" >>> import simplejson >>> simplejson.loads('"\u0e4f\u0361\u032f\u0e4f"', encoding='utf8') u'\u0e4f\u0361\u032f\u0e4f' However php json_decode works fine: json_decode('"\u0e4f\u0361\u032f\u0e4f"'); What am I doing wrong?
[ "Nothing. The Python REPL prints the repr() of the string, not the string itself.\n>>> print u'\\u0e4f\\u0361\\u032f\\u0e4f'\n๏̯͡๏\n\n" ]
[ 2 ]
[]
[]
[ "json", "python", "simplejson" ]
stackoverflow_0002819092_json_python_simplejson.txt
Q: Quickbooks integration: IPP/IDS: can these by used for actual data exchange? Poking around options for integrating an online app with Quickbooks, I've made a lot of headway with QBWC, but it's fairly ugly. From an end user perspective the usability of QBWC is pretty low. Intuit is now pushing Intuit Partner Platfo...
Quickbooks integration: IPP/IDS: can these by used for actual data exchange?
Poking around options for integrating an online app with Quickbooks, I've made a lot of headway with QBWC, but it's fairly ugly. From an end user perspective the usability of QBWC is pretty low. Intuit is now pushing Intuit Partner Platform (IPP) and Intuit Data Services (IDS). I can't quite figure out what these are a...
[ "\nIs IPP limited to using Flex, or can it work with existing web apps?\n\nIt is not limited to Flex. You can use IPP/IDS from any web application, as long as you federate your application (allow logins using SAML via workplace.intuit.com). \nThere are two \"types\" of IPP applications:\n\nNative apps Native applic...
[ 7 ]
[]
[]
[ "python", "qbwc", "quickbooks" ]
stackoverflow_0002786122_python_qbwc_quickbooks.txt
Q: django threadedcomments I would like to setup a comment systems on my site, using django threadedcomments, and I follow all the steps in the Tutorial, however, I get the following error: No module named newforms.util I am not sure what causing this issue, here is my configuration: #settings.py INSTALLED_APPS = ( ...
django threadedcomments
I would like to setup a comment systems on my site, using django threadedcomments, and I follow all the steps in the Tutorial, however, I get the following error: No module named newforms.util I am not sure what causing this issue, here is my configuration: #settings.py INSTALLED_APPS = ( 'django.contrib.admin', ...
[ "You are most probably using a very old version of one of your apps. The newforms module has disappeared from django a long time ago.\n" ]
[ 4 ]
[]
[]
[ "blogs", "comments", "django", "python" ]
stackoverflow_0002819130_blogs_comments_django_python.txt
Q: How do I open the default mail program with a subject in Python in a cross-platform way? I am trying to add the ability to send mails using the default mail client from my python app. It can be done with the webbrowser module by opening a 'mailto:' URI. But, is there a better and direct way to do this like java's...
How do I open the default mail program with a subject in Python in a cross-platform way?
I am trying to add the ability to send mails using the default mail client from my python app. It can be done with the webbrowser module by opening a 'mailto:' URI. But, is there a better and direct way to do this like java's Desktop.mail(URI). Thanks in advance.
[ "As far as my research goes, there is no proper solution. We currently use this solution, which is the recipe by Antonio Valentino with a few modifications.\nYou're interested in the mailto function in that file.\n" ]
[ 0 ]
[]
[]
[ "email", "python" ]
stackoverflow_0002818720_email_python.txt
Q: small python code refactor I am having this piece of code, which in my opinion is fairly ugly and I am wondering how it can be done better: if dic.get(key, None) is None: dic[key] = None Points for elegance ;-) A: d.setdefault(key) # sets d[key] to None if key is not in d A: if key not in dic: dic[key]...
small python code refactor
I am having this piece of code, which in my opinion is fairly ugly and I am wondering how it can be done better: if dic.get(key, None) is None: dic[key] = None Points for elegance ;-)
[ "d.setdefault(key) # sets d[key] to None if key is not in d\n\n", "if key not in dic:\n dic[key] = None\n\nThis might not be as short as Olivier's code, but at least it's explicit and fast.\nPlease, don't use dict as a variable name, it shadows built-in.\n", "import collections\n\nmydict = collections.defaul...
[ 10, 7, 3 ]
[]
[]
[ "dictionary", "python" ]
stackoverflow_0002819627_dictionary_python.txt
Q: matplotlib - zebra-stripe a figure's background color? I'm building a simple line chart with matplotlib, and I'd like to zebra-stripe the background of the chart, so that each alternating row is colored differently. Is there a way to do this? My chart already has gridding, and has major ticks only. Edit: The code ...
matplotlib - zebra-stripe a figure's background color?
I'm building a simple line chart with matplotlib, and I'd like to zebra-stripe the background of the chart, so that each alternating row is colored differently. Is there a way to do this? My chart already has gridding, and has major ticks only. Edit: The code from my comment below, but more legible: yTicks = ax.get_yti...
[ "Here's a quick hack that uses a barchart (axes.barh) to simulate striping.\nimport matplotlib.pyplot as plt\n\n# initial plot\nfig = plt.figure()\nax = fig.add_subplot(111)\nax.plot([1,2,3,4,5])\n\nyTickPos,_ = plt.yticks()\nyTickPos = yTickPos[:-1] #slice off the last as it is the top of the plot\n# create bars a...
[ 5 ]
[]
[]
[ "charts", "matplotlib", "python" ]
stackoverflow_0002815455_charts_matplotlib_python.txt
Q: How to use a callable as the setup with timeit.Timer? I want to time some code that depends on some setup. The setup code looks a little like this: >>> b = range(1, 1001) And the code I want to time looks vaguely like this: >>> sorted(b) Except my code uses a different function than sorted. But that ain't impo...
How to use a callable as the setup with timeit.Timer?
I want to time some code that depends on some setup. The setup code looks a little like this: >>> b = range(1, 1001) And the code I want to time looks vaguely like this: >>> sorted(b) Except my code uses a different function than sorted. But that ain't important right now. Anyhow, I know how to time this code as lo...
[ "In 2.6, you can \"just do it\", per the docs:\n\nChanged in version 2.6: The stmt and\n setup parameters can now also take\n objects that are callable without\n arguments. This will embed calls to\n them in a timer function that will\n then be executed by timeit(). Note\n that the timing overhead is a little...
[ 1, 1 ]
[]
[]
[ "python", "timeit" ]
stackoverflow_0002819625_python_timeit.txt
Q: Handling KeyboardInterrupt when working with PyGame I have written a small Python application where I use PyGame for displaying some simple graphics. I have a somewhat simple PyGame loop going in the base of my application, like so: stopEvent = Event() # Just imagine that this eventually sets the stopEvent # as s...
Handling KeyboardInterrupt when working with PyGame
I have written a small Python application where I use PyGame for displaying some simple graphics. I have a somewhat simple PyGame loop going in the base of my application, like so: stopEvent = Event() # Just imagine that this eventually sets the stopEvent # as soon as the program is finished with its task. disp = Sort...
[ "What about changing your final loop to...:\nwhile not stopEvent.isSet():\n try:\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n stopEvent.set()\n except KeyboardInterrupt:\n stopEvent.set()\n\ni.e., make sure you catch keyboard interrupts and treat...
[ 3, 2 ]
[]
[]
[ "pygame", "python" ]
stackoverflow_0002819931_pygame_python.txt
Q: Appengine Python Bulk Export error This seems to run for ~42,200 records then fails: import datetime import time from google.appengine.ext import db from google.appengine.tools import bulkloader from google.appengine.api import datastore_types class SearchRec(db.Model): WebSite = db.StringProperty() WebPage ...
Appengine Python Bulk Export error
This seems to run for ~42,200 records then fails: import datetime import time from google.appengine.ext import db from google.appengine.tools import bulkloader from google.appengine.api import datastore_types class SearchRec(db.Model): WebSite = db.StringProperty() WebPage = db.StringProperty() DateStamp = db.D...
[ "I'm not sure why exactly that would be happening. I'm not too familiar with the Bulk Exporting facilities of App Engine, but it sounds like the DateStamp field is being given to the bulk exporter as a string (which is what your converter expects) for the first 42200 records and then, for some reason, it is given ...
[ 1 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0002819584_google_app_engine_python.txt
Q: appcfg.py upload_data is failing with expected even though I've got it I am having trouble getting the bulk uploader to work. I have been following the tutorial here:http://code.google.com/appengine/docs/ python/tools/uploadingdata.html. When I enter the following command (from Windows, using PowerShell) appcfg....
appcfg.py upload_data is failing with expected even though I've got it
I am having trouble getting the bulk uploader to work. I have been following the tutorial here:http://code.google.com/appengine/docs/ python/tools/uploadingdata.html. When I enter the following command (from Windows, using PowerShell) appcfg.py upload_data --config_file=src/friend_loader.py --filename=frienddata.csv -...
[ "Do you get any more information when you add \"--noisy\" ? Are you logged in before you run above line ?\n", "the last parameter ./src/ could you explain what are you using it for?\nthe tools is expecting a parameter of: the app_Id of your app running on the google app engine or the root path of your applicacio...
[ 0, 0 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0001753867_google_app_engine_python.txt
Q: How to achieve interaction between GUI class with logic class Im new to GUI programming, and haven't done much OOP. Im working on a basic calculator app to help me learn GUI design and to brush up on OOP. I understand that anything GUI related should be kept seperate from the logic, but Im unsure how to implement ...
How to achieve interaction between GUI class with logic class
Im new to GUI programming, and haven't done much OOP. Im working on a basic calculator app to help me learn GUI design and to brush up on OOP. I understand that anything GUI related should be kept seperate from the logic, but Im unsure how to implement interaction between logic an GUI classes when needed i.e. basically...
[ "Corrected:\nMy first answer was totally mistaken, ignore it. The problem was that you were accidentally overwriting your entry variable text with an a string representation of the entryVariable object. Note the addition of a get() in the call to Calc():\ndef on_equal_btn_click(self):\n print self.entryVariable....
[ 2 ]
[]
[]
[ "oop", "python", "tkinter", "user_interface" ]
stackoverflow_0002820417_oop_python_tkinter_user_interface.txt
Q: Is there a better way of making numpy.argmin() ignore NaN values I want to get the index of the min value of a numpy array that contains NaNs and I want them ignored >>> a = array([ nan, 2.5, 3., nan, 4., 5.]) >>> a array([ NaN, 2.5, 3. , NaN, 4. , 5. ]) if I run argmin, it returns the index o...
Is there a better way of making numpy.argmin() ignore NaN values
I want to get the index of the min value of a numpy array that contains NaNs and I want them ignored >>> a = array([ nan, 2.5, 3., nan, 4., 5.]) >>> a array([ NaN, 2.5, 3. , NaN, 4. , 5. ]) if I run argmin, it returns the index of the first NaN >>> a.argmin() 0 I substitute NaNs with Infs and ...
[ "Sure! Use nanargmin:\nimport numpy as np\na = np.array([ np.nan, 2.5, 3., np.nan, 4., 5.])\nprint(np.nanargmin(a))\n# 1\n\nThere is also nansum, nanmax, nanargmax, and nanmin,\nIn scipy.stats, there is nanmean and nanmedian.\nFor more ways to ignore nans, check out masked arrays.\n" ]
[ 54 ]
[]
[]
[ "arrays", "nan", "numpy", "python" ]
stackoverflow_0002821072_arrays_nan_numpy_python.txt
Q: How we get a session key from an access_token I got an access_token using facebook Graph API. https://graph.facebook.com/me?access_token=... I want session key. is there any method to get session key from access_token?. A: There is no such term infinite session keys. But you can ask user to give you offline acce...
How we get a session key from an access_token
I got an access_token using facebook Graph API. https://graph.facebook.com/me?access_token=... I want session key. is there any method to get session key from access_token?.
[ "There is no such term infinite session keys. But you can ask user to give you offline access extended permission. If user approved the permission, then you can save the session key and later user. \nIf you use new php sdk, then you'll find there is a method $facebook->setSession($session); You've to pass users's s...
[ 0 ]
[]
[]
[ "facebook", "python" ]
stackoverflow_0002816733_facebook_python.txt
Q: change values in a list - python I have this code: a=[['a','b','c'],['a','f','c'],['a','c','d']] for x in a: for y in x: if 'a' in x: x.replace('a','*')` but the result is: a=[['a','b','c'],['a','f','c'],['a','c','d']] and bot a=[['b','c'],['f','c'],['c','d']] What ...
change values in a list - python
I have this code: a=[['a','b','c'],['a','f','c'],['a','c','d']] for x in a: for y in x: if 'a' in x: x.replace('a','*')` but the result is: a=[['a','b','c'],['a','f','c'],['a','c','d']] and bot a=[['b','c'],['f','c'],['c','d']] What should I do so the changes will last?
[ "If you want to remove all occurrences of 'a' from all nested sublists, you could do:\n>>> [[i for i in x if i != 'a'] for x in a]\n[['b', 'c'], ['f', 'c'], ['c', 'd']]\n\nif you want to replace them with asterisk:\n>>> [[i if i != 'a' else '*' for i in x] for x in a]\n[['*', 'b', 'c'], ['*', 'f', 'c'], ['*', 'c', ...
[ 5, 4, 1, 0, 0, 0 ]
[]
[]
[ "list", "python" ]
stackoverflow_0002821329_list_python.txt
Q: Python print statement prints nothing with a carriage return I'm trying to write a simple tool that reads files from disc, does some image processing, and returns the result of the algorithm. Since the program can sometimes take awhile, I like to have a progress bar so I know where it is in the program. And since ...
Python print statement prints nothing with a carriage return
I'm trying to write a simple tool that reads files from disc, does some image processing, and returns the result of the algorithm. Since the program can sometimes take awhile, I like to have a progress bar so I know where it is in the program. And since I don't like to clutter up my command line and I'm on a Unix platf...
[ "Try adding sys.stdout.flush() after the print statement. It's possible that print isn't flushing the output until it writes a newline, which doesn't happen here.\n", "Handling of carriage returns in Linux differs greatly between terminal-emulators.\nNormally, one would use terminal escape codes that would tell t...
[ 10, 2, 2 ]
[]
[]
[ "carriage_return", "command_line", "python" ]
stackoverflow_0002821503_carriage_return_command_line_python.txt
Q: PyGTK: Doubleclick on CellRenderer In my PyGTK application I currently use 'editable' to make cells editable. But since my cell contents sometimes are really really large I want to ask the user for changes in a new window when he doubleclicks on a cell. But I could not find out how to hook on double-clicks on spec...
PyGTK: Doubleclick on CellRenderer
In my PyGTK application I currently use 'editable' to make cells editable. But since my cell contents sometimes are really really large I want to ask the user for changes in a new window when he doubleclicks on a cell. But I could not find out how to hook on double-clicks on specific cellrenderers - I don't want to edi...
[ "I believe this is not possible directly. However, you can connect to button-press-event on the gtk.TreeView. Then, when event.type equals to gtk.gdk._2BUTTON_PRESS, convert x and y to tree location using gtk.TreeView.get_path_at_pos(). This will return both a tree path indicating the row and gtk.TreeViewColumn ...
[ 3 ]
[]
[]
[ "cellrenderer", "double_click", "pygtk", "python" ]
stackoverflow_0002821584_cellrenderer_double_click_pygtk_python.txt
Q: Why does 'url' not work as a variable here? I originally had the variable cpanel named url and the code would not return anything. Any idea why? It doesn't seem to be used by anything else, but there's gotta be something I'm overlooking. import urllib2 cpanel = 'http://www.tas-tech.com/cpanel' req = urllib2.Reque...
Why does 'url' not work as a variable here?
I originally had the variable cpanel named url and the code would not return anything. Any idea why? It doesn't seem to be used by anything else, but there's gotta be something I'm overlooking. import urllib2 cpanel = 'http://www.tas-tech.com/cpanel' req = urllib2.Request(cpanel) try: handle = urllib2.urlopen(req)...
[ "Note that urllib2.Request has a parameter named url, but that really shouldn't be the source of the problem, it works as expected:\n>>> import urllib2\n>>> url = \"http://www.google.com\"\n>>> req = urllib2.Request(url)\n>>> urllib2.urlopen(req).code\n200\n\nNote that your code above functions identically when you...
[ 2, 0 ]
[]
[]
[ "python" ]
stackoverflow_0002822199_python.txt
Q: Python copy a DLL to site-packages on Windows I am writing a python extension module that needs to link with a third-party DLL. How can I copy this DLL to the site-packages directory using distutils (i.e. in my setup.py file)? A: Put your DLL in the package_data argument of your setup() (see the Installing P...
Python copy a DLL to site-packages on Windows
I am writing a python extension module that needs to link with a third-party DLL. How can I copy this DLL to the site-packages directory using distutils (i.e. in my setup.py file)?
[ "Put your DLL in the package_data argument of your setup() (see the Installing Package Data section of the distutils documentation for details).\nIf you need to put the DLL outside of the package directory , you can use the data_files option. For example to put it in the site-packages directory:\nimport distutils.s...
[ 8 ]
[]
[]
[ "dll", "python", "windows" ]
stackoverflow_0002822424_dll_python_windows.txt
Q: Program to find canonical cover or minimum number of functional dependencies I would like to find the canonical cover or minimum number of functional dependencies in a database. For example: If you have: Table = (A,B,C) <-- these are columns: A,B,C And dependencies: A → BC B → C A → B AB → C The canonical cove...
Program to find canonical cover or minimum number of functional dependencies
I would like to find the canonical cover or minimum number of functional dependencies in a database. For example: If you have: Table = (A,B,C) <-- these are columns: A,B,C And dependencies: A → BC B → C A → B AB → C The canonical cover (or minimum number of dependencies) is: A → B B → C Is there a program that ca...
[ "Looking at your dependencies, it looks like you can view them as a partial order on A, B, C. What you want sounds a lot like (but not entirely) a topological sort (a partial order sort on a directed acyclic graph).\n", "Looks to me like you can refactor any rules of the form:\n A -> BC\n\ninto\n A -> B\n\nand...
[ 0, 0 ]
[]
[]
[ "database", "database_design", "java", "python" ]
stackoverflow_0002822809_database_database_design_java_python.txt
Q: call multiple c++ functions in python using threads Suppose I have a C(++) function taking an integer, and it is bound to (C)python with python api, so I can call it from python: import c_module c_module.f(10) now, I want to parallelize it. The problem is: how does the GIL work in this case? Suppose I have a queu...
call multiple c++ functions in python using threads
Suppose I have a C(++) function taking an integer, and it is bound to (C)python with python api, so I can call it from python: import c_module c_module.f(10) now, I want to parallelize it. The problem is: how does the GIL work in this case? Suppose I have a queue of numbers to be processed, and some workers (threading...
[ "Threads currently executing the C extension code for which the GIL was explicitly released will run in parallel. See http://docs.python.org/c-api/init.html#thread-state-and-the-global-interpreter-lock for what you need to do in your extension.\nPython threads are most useful for I/O bound execution or for GUI res...
[ 4 ]
[]
[]
[ "c++", "gil", "multithreading", "python" ]
stackoverflow_0002822636_c++_gil_multithreading_python.txt
Q: integrate / build 'weather radar' widget I'm looking to integrate a 'weather radar' widget into a site I'm building. The only available resource I can find is: http://www.meteoonline.co.uk/gadgets/Europe/Netherlands/135 which basically delivers a flash mov in a iframe ! urrrgh! - and 'permission denied' of course...
integrate / build 'weather radar' widget
I'm looking to integrate a 'weather radar' widget into a site I'm building. The only available resource I can find is: http://www.meteoonline.co.uk/gadgets/Europe/Netherlands/135 which basically delivers a flash mov in a iframe ! urrrgh! - and 'permission denied' of course with any javascript interaction on the iframe...
[ "My suggestion would be to check Programmable Web to see what APIs are available for weather data. A quick scan shows they had a blog post about 5 weather APIs last year\nand filtering by 'weather' category I see 10 available now. I don't know if any of them have a radar but it would be a good place to start.\n", ...
[ 1, 0 ]
[]
[]
[ "django", "jquery", "python", "weather" ]
stackoverflow_0002820953_django_jquery_python_weather.txt
Q: Parsing a string representing a float *with an exponent* in Python I have a large file with numbers in the form of 6,52353753563E-7. So there's an exponent in that string. float() dies on this. While I could write custom code to pre-process the string into something float() can eat, I'm looking for the pythonic wa...
Parsing a string representing a float *with an exponent* in Python
I have a large file with numbers in the form of 6,52353753563E-7. So there's an exponent in that string. float() dies on this. While I could write custom code to pre-process the string into something float() can eat, I'm looking for the pythonic way of converting these into a float (something like a format string passe...
[ "Nothing to do with exponent. Problem is comma instead of decimal point.\n>>> float(\"6,52353753563E-7\")\nTraceback (most recent call last):\n File \"<stdin>\", line 1, in <module>\nValueError: invalid literal for float(): 6,52353753563E-7\n>>> float(\"6.52353753563E-7\")\n6.5235375356299998e-07\n\nFor a general ...
[ 15, 1 ]
[]
[]
[ "python" ]
stackoverflow_0002823269_python.txt
Q: Parsing dbpedia JSON in Python I'm trying to get my head around the dbpedia JSON schema and can't figure out an efficient way of extracting a specific node: This is what dbpedia gives me: http://dbpedia.org/data/Ceramic_art.json I've got the whole thing as a JSON object in Python but don't really understand how to...
Parsing dbpedia JSON in Python
I'm trying to get my head around the dbpedia JSON schema and can't figure out an efficient way of extracting a specific node: This is what dbpedia gives me: http://dbpedia.org/data/Ceramic_art.json I've got the whole thing as a JSON object in Python but don't really understand how to get the english abstract from this ...
[ "It's a list of dicts. Just iterate through the elements of the list until you find the one whose value for u'lang' is u'en'.\n", "\nprint [abstract['value'] for abstract in json_data[\"http://dbpedia.org/resource/Ceramic_art\"][\"http://dbpedia.org/ontology/abstract\"] if abstract['lang'] == 'en'][0]\n\nObviousl...
[ 3, 3 ]
[]
[]
[ "dbpedia", "json", "python" ]
stackoverflow_0002823214_dbpedia_json_python.txt
Q: How do I code this relationship in SQLAlchemy? I am new to SQLAlchemy (and SQL, for that matter). I can't figure out how to code the idea I have in my head. I am creating a database of performance-test results. A test run consists of a test type and a number (this is class TestRun below) A test suite consists the...
How do I code this relationship in SQLAlchemy?
I am new to SQLAlchemy (and SQL, for that matter). I can't figure out how to code the idea I have in my head. I am creating a database of performance-test results. A test run consists of a test type and a number (this is class TestRun below) A test suite consists the version string of the software being tested, and on...
[ "I cannot understand what your question is, in large part because you haven't refined it. Your question is about a schema perhaps, and possibly its corresponding object relational model. So, here is the ORM stripped to its core:\nclass TestVersion(Base):\n __tablename__ = 'versions'\n id = Column(Integer, pri...
[ 1 ]
[]
[]
[ "python", "sql", "sqlalchemy" ]
stackoverflow_0002822789_python_sql_sqlalchemy.txt
Q: Remove padding in wxPython's wxWizard I'm using wxPython to create a wizard using the wxWizard control. I'm trying to a draw a colored rectangle but when I run the app, there seems to be a about a 10px padding on each side of the rectangle. This goes for all other controls too. I have to offset them a bit so that ...
Remove padding in wxPython's wxWizard
I'm using wxPython to create a wizard using the wxWizard control. I'm trying to a draw a colored rectangle but when I run the app, there seems to be a about a 10px padding on each side of the rectangle. This goes for all other controls too. I have to offset them a bit so that they appear exactly where I want them to. I...
[ "I can't verify this ( I would post as comment but i don't have enough reputation). \nOn my system the above code with \nif __name__ == \"__main__\":\n app = wx.App(0)\n frame_1 = wx.wizard.Wizard(None)\n s = SimplePage(frame_1,\"\")\n\n app.SetTopWindow(frame_1)\n s.Show()\n frame_1.Show()\n a...
[ 1 ]
[]
[]
[ "python", "wxpython" ]
stackoverflow_0002816323_python_wxpython.txt
Q: Design question? I am building music app, where user can do several tasks including but not limited to listening song, like song, recommend song to a friend and extra. currently I have this model: class Activity(models.Model): activity = models.TextField() user = models.ForeignKey(User) date = models.D...
Design question?
I am building music app, where user can do several tasks including but not limited to listening song, like song, recommend song to a friend and extra. currently I have this model: class Activity(models.Model): activity = models.TextField() user = models.ForeignKey(User) date = models.DateTimeField(auto_now=...
[ "Looks like all you need is an enumeration to match a table in your database.\nSo in your UserActivity table, you will have\nuserid, activityid, songid, datetime etc etc\n", "What about GenericForeignKey? You could have userid, activityid and content_object on your UserActivity where content_object is a song, an ...
[ 0, 0 ]
[]
[]
[ "django", "json", "pickle", "python" ]
stackoverflow_0002823783_django_json_pickle_python.txt
Q: how do i add variables with logistic distributions? i have X, Y, random logistic variables, how do I add them given the mean and scale for each? Logistic distribution. i ran a simulation in python, but i cannot get it to be exact. i ran a simulation on getting a random number X, Y, and keep score on the value of ...
how do i add variables with logistic distributions?
i have X, Y, random logistic variables, how do I add them given the mean and scale for each? Logistic distribution. i ran a simulation in python, but i cannot get it to be exact. i ran a simulation on getting a random number X, Y, and keep score on the value of X + Y. then i did the same for getting a single random n...
[ "The sum of two logistic random variables does not have a logistic distribution. However, the sum is approximately logistic. You could justify this by arguing that a logistic distribution is approximately normal and the sum of two normal random variables is normal. (This post explains how close the normal and log...
[ 6, 1 ]
[]
[]
[ "math", "python" ]
stackoverflow_0002823468_math_python.txt
Q: Idea for a small project, should I use Python? I have a project idea, but unsure if using Python would be a good idea. Firstly, I'm a C++ and C# developer with some SQL experience. My day job is C++. I have a project idea i'd like to create and was considering developing it in a language I don't know. Python se...
Idea for a small project, should I use Python?
I have a project idea, but unsure if using Python would be a good idea. Firstly, I'm a C++ and C# developer with some SQL experience. My day job is C++. I have a project idea i'd like to create and was considering developing it in a language I don't know. Python seems to be popular and has piqued my interests. I de...
[ "I find that the best way to learn a new language is by doing something like this (small project of your own). Python is no different. \nEverything you wrote can be done in Python, so I can't find any reason not to use it, if you want to learn.\n", "Python seems very suitable to your purposes (e.g., pygame and ot...
[ 6, 5, 3, 1 ]
[]
[]
[ "oop", "python" ]
stackoverflow_0002823983_oop_python.txt
Q: Dynamically add items to Tkinter Canvas I'm attempting to learn Tkinter with the goal of being able to create a 'real-time' scope to plot data. As a test, I'm trying to draw a polygon on the canvas every time the 'draw' button is pressed. The triangle position is randomized. I have two problems: There is a triang...
Dynamically add items to Tkinter Canvas
I'm attempting to learn Tkinter with the goal of being able to create a 'real-time' scope to plot data. As a test, I'm trying to draw a polygon on the canvas every time the 'draw' button is pressed. The triangle position is randomized. I have two problems: There is a triangle on the canvas as soon as the program start...
[ "command=self.pt([50,50]) (that you use in the Button call which builds the Draw button) immediately executes the call you're telling it to execute, and binds the result (None) to command. Use, instead, in that same:\n, command=lambda: self.pt([50, 50]) )\n\nto delay the execution of the call to each time that but...
[ 5 ]
[]
[]
[ "dynamic", "python", "tkinter_canvas" ]
stackoverflow_0002824041_dynamic_python_tkinter_canvas.txt
Q: Word XML to RTF conversion I am in a need of programatically convert an Word-XML file into a RTF file. It has become a requirement, because of some third party libraries. Any API/Library that can do that? Actually the language is not a problem because I just need to work done. But Java, .NET languages or Python a...
Word XML to RTF conversion
I am in a need of programatically convert an Word-XML file into a RTF file. It has become a requirement, because of some third party libraries. Any API/Library that can do that? Actually the language is not a problem because I just need to work done. But Java, .NET languages or Python are preferred.
[ "A Python/linux way:\nYou need the OpenOffice Uno Bride (On server you could run OO in headless mode).\nAs a result you can convert every OO-readable format to every OO-writeable:\nsee http://wiki.services.openoffice.org/wiki/Framework/Article/Filter/FilterList_OOo_3_0\nRun Example Code\n/usr/lib64/openoffice.org/p...
[ 2, 0, 0, 0, 0 ]
[]
[]
[ ".net", "java", "python", "rtf", "xml" ]
stackoverflow_0002612915_.net_java_python_rtf_xml.txt
Q: Python module shared between multiple products I'm working on a python class that is being shared between two products. 90% of the functionality applies to both products. For the 10% that's different the code is littered with this kind of thing: #Start of file project = 'B' #Some line of code if project == 'A': ...
Python module shared between multiple products
I'm working on a python class that is being shared between two products. 90% of the functionality applies to both products. For the 10% that's different the code is littered with this kind of thing: #Start of file project = 'B' #Some line of code if project == 'A': import moduleA elif project == 'B': import m...
[ "No, as this is very poor design. If your module's behavior is influenced by the project in which it is used, then it should accept an object, function, or other callback for the project-specific behavior. My suggestion is to factor out the pieces that are shared and make them into a single module, and for anything...
[ 3, 0, 0 ]
[]
[]
[ "module", "python" ]
stackoverflow_0002823465_module_python.txt
Q: Python features Is there any article/paper on what features the Python language has to offer? Why should one go with Python instead of any other language? What are the strong and the weak points of Python? A: Why Python and Why Python so Choose Python (import this) A: Probably the prime reason I use Python is ...
Python features
Is there any article/paper on what features the Python language has to offer? Why should one go with Python instead of any other language? What are the strong and the weak points of Python?
[ "Why Python\nand\nWhy Python\nso\nChoose Python (import this)\n", "Probably the prime reason I use Python is because it's very good at self-documenting. There are lots of other reasons too, but probably the best way to find out is to do something with it. Find a project and see what it takes to do it in Python. I...
[ 5, 3, 2, 1 ]
[]
[]
[ "language_comparisons", "language_features", "python" ]
stackoverflow_0002820705_language_comparisons_language_features_python.txt
Q: Python program to search for specific strings in hash values (coding help) Trying to write a code that searches hash values for specific string's (input by user) and returns the hash if searchquery is present in that line. Doing this to kind of just learn python a bit more, but it could be a real world applicatio...
Python program to search for specific strings in hash values (coding help)
Trying to write a code that searches hash values for specific string's (input by user) and returns the hash if searchquery is present in that line. Doing this to kind of just learn python a bit more, but it could be a real world application used by an HR department to search a .csv resume database for specific words i...
[ "What @Justin Peel said. Also to be more pythonic I would say change\nif resumetext.find(id2find) != -1: to if id2find in resumetext:\nA few more changes: you might want to lower case the comparison and user input so it matches GPA, gpa, Gpa, etc. You can do this by doing searchquery = raw_input(\"please enter your...
[ 1, 1, 0 ]
[]
[]
[ "full_text_search", "hash", "parsing", "python", "regex" ]
stackoverflow_0002824360_full_text_search_hash_parsing_python_regex.txt
Q: Handle iterable and non-iterable seamlessly Could you let me know how I can optimize the following code? def f(y, list_or_elem): if getattr(list_or_elem, '__iter__'): y = max(y, *list_or_elem) else: y = max(y, list_or_elem) A: The best optimization of all would be to avoid such silliness as taking "e...
Handle iterable and non-iterable seamlessly
Could you let me know how I can optimize the following code? def f(y, list_or_elem): if getattr(list_or_elem, '__iter__'): y = max(y, *list_or_elem) else: y = max(y, list_or_elem)
[ "The best optimization of all would be to avoid such silliness as taking \"either a list or a single element\" as an argument. But, if you insist, it's better to use a try/except to remove the anomaly ASAP and make what's sure to be an iterable:\ntry: iter(list_or_elem)\nexcept TypeError: iterable = [list_or_elem]...
[ 1, 0 ]
[]
[]
[ "iterable", "python" ]
stackoverflow_0002824612_iterable_python.txt
Q: Sqlalchemy: Many to Many relationship error Dear everyone, I am following the Many to many relationship described on http://www.sqlalchemy.org/docs/mappers.html#many-to-many #This is actually a VIEW tb_mapping_uGroups_uProducts = Table( 'mapping_uGroups_uProducts', metadata, Column('upID', Integer, ForeignKey(...
Sqlalchemy: Many to Many relationship error
Dear everyone, I am following the Many to many relationship described on http://www.sqlalchemy.org/docs/mappers.html#many-to-many #This is actually a VIEW tb_mapping_uGroups_uProducts = Table( 'mapping_uGroups_uProducts', metadata, Column('upID', Integer, ForeignKey('uProductsInfo.upID')), Column('ugID', Intege...
[ "Existence of foreign key definitions in SQLAlchemy schema is enough, they are not mandatory in actual table. There is no direct foreign relation between your models, so SQLAlchemy fails to find them. Specify the relation to join on explicitly:\nsess.query(UnifiedProduct).join(UnifiedProduct.unifiedGroups).distinct...
[ 2 ]
[]
[]
[ "python", "sqlalchemy" ]
stackoverflow_0002824322_python_sqlalchemy.txt
Q: catch output from linux telnet to a python script My problem is that i want to do something like this in linux console telnet 192.168.255.28 > process.py i.e i would like to do some transformation with console telnet output using python script. I'm see Popen in python for this case, but i can't understand how can...
catch output from linux telnet to a python script
My problem is that i want to do something like this in linux console telnet 192.168.255.28 > process.py i.e i would like to do some transformation with console telnet output using python script. I'm see Popen in python for this case, but i can't understand how can i get input from telnet if it do not stop all time.. P...
[ "Have you considered telnetlib? It seems like pretty much exactly what you're looking for?\n", "If you can adapt your solution, telnetlib seems like the right way to do it -- +1 to xitrium.\nThat said, though, if you're dead set on piping the output of telnet into your Python script, it'll be coming in on standa...
[ 3, 2, 1 ]
[]
[]
[ "python" ]
stackoverflow_0002825100_python.txt
Q: How can I add dynamic field in the model in django? I'm using django to create a application download site. I try to write a model, that the admin can add the different download content dynamically in the admin page. For example I have a software named foobar, it have 3 different version: 1.1, 1.2, 1.3. I would li...
How can I add dynamic field in the model in django?
I'm using django to create a application download site. I try to write a model, that the admin can add the different download content dynamically in the admin page. For example I have a software named foobar, it have 3 different version: 1.1, 1.2, 1.3. I would like the user can admin the model by using an add button to...
[ "Set up your models to have a main model and ancillary models that have foreign keys to the main model:\nclass DownloadItem(models.Model):\n\n name = models.CharField( etc etc)\n ... other attributes here ...\n\n\nclass DownloadItemFile(models.Model):\n parent = models.ForeignKey('DownloadItem', related_name=...
[ 1 ]
[]
[]
[ "database", "django", "python" ]
stackoverflow_0002825435_database_django_python.txt
Q: Any experience with the Deliverance system? My new boss went to a speech where Deliverance, a kind of proxy allowing to add skin to any html output on the fly, was presented. He decided to use it right after that, no matter how young it is. More here : http://www.openplans.org/projects/deliverance/introduction In ...
Any experience with the Deliverance system?
My new boss went to a speech where Deliverance, a kind of proxy allowing to add skin to any html output on the fly, was presented. He decided to use it right after that, no matter how young it is. More here : http://www.openplans.org/projects/deliverance/introduction In theory, the system sounds great when you want a n...
[ "Having used Plone professionally for the last 4 years or so, and Deliverance on 4 commercial sites, I would advise all new front end developers (and old hands alike) to use Deliverance to theme Plone sites.\nIt is much easier to learn (a couple of weeks Vs couple of months) and potentially much more powerful than ...
[ 5, 2, 1, 0 ]
[]
[]
[ "deliverance", "html", "python" ]
stackoverflow_0000204570_deliverance_html_python.txt
Q: deploying a war to tomcat using python I'm trying to deploy a war to a Apache Tomcat server (Build 6.0.24) using python (2.4.2) as part of a build process. I'm using the following code import urllib2 import base64 war_file_contents = open('war_file.war','rb').read() username='some_user' password='some_pwd' base...
deploying a war to tomcat using python
I'm trying to deploy a war to a Apache Tomcat server (Build 6.0.24) using python (2.4.2) as part of a build process. I'm using the following code import urllib2 import base64 war_file_contents = open('war_file.war','rb').read() username='some_user' password='some_pwd' base64string = base64.encodestring('%s:%s' % (u...
[ "Okay, figured it out.\nThe urllib2.Request line needs to have a slash in front of the path so:-\nrequest = urllib2.Request('http://localhost:8080/manager/deploy?path=/war_file', data=war_file_contents)\n\nAll then works fine.\n" ]
[ 2 ]
[]
[]
[ "deployment", "python", "tomcat", "urllib2" ]
stackoverflow_0002825350_deployment_python_tomcat_urllib2.txt
Q: Spotting similarities and patterns within a string - Python this is the use case I'm trying to figure this out for. I have a list of spam subscriptions to a service and they are killing conversion rate and other usability studies. The emails inserted look like the following: rogerep_dyeepvu@hotmail.com rogeram_in...
Spotting similarities and patterns within a string - Python
this is the use case I'm trying to figure this out for. I have a list of spam subscriptions to a service and they are killing conversion rate and other usability studies. The emails inserted look like the following: rogerep_dyeepvu@hotmail.com rogeram_ingramameb@hotmail.com rogerew_jonesewct@hotmail.com roger[...]_sur...
[ "I don't think you can easily check for this. It's not likely to be a simple string matching problem that you can throw a regular expression at because I would guess that your use of the name 'Roger' was just an example, and that any number of names can appear in that position. You could also run one of the regular...
[ 3, 1, 1 ]
[]
[]
[ "pattern_matching", "python", "spam_prevention", "string" ]
stackoverflow_0002825520_pattern_matching_python_spam_prevention_string.txt
Q: python check value not in unicode list I have a list and a value and want to check if the value is not in the list. list = [u'first record', u'second record'] value = 'first record' if value not in list: do something however this is not working and I think it has something to do with the list values having a...
python check value not in unicode list
I have a list and a value and want to check if the value is not in the list. list = [u'first record', u'second record'] value = 'first record' if value not in list: do something however this is not working and I think it has something to do with the list values having a u at the start, how can I fix this? And be...
[ "unicode(value) transforms your 'first record' into u'first record'. That might fix your issues. However, depending on the contents this might fail and you'll have to use the .encode('charset') function strings have.\nPS: Your example is bad as those strings are equal in unicode and non-unicode and thus your exampl...
[ 4, 3 ]
[]
[]
[ "python" ]
stackoverflow_0002825884_python.txt
Q: Django + Apache wsgi = paths problem I have this view which generates interface language options menu def lang_menu(request,language): lang_choices = [] import os.path for lang in settings.LANGUAGES: if os.path.isfile("gui/%s.py" % lang) or os.path.isfile("gui/%s.pyc" % lang): lan...
Django + Apache wsgi = paths problem
I have this view which generates interface language options menu def lang_menu(request,language): lang_choices = [] import os.path for lang in settings.LANGUAGES: if os.path.isfile("gui/%s.py" % lang) or os.path.isfile("gui/%s.pyc" % lang): langimport = "from gui.%s import menu" % lang...
[ "Does this give you the right path if you call it in lang_menu?\nos.path.abspath(os.path.dirname(__file__))\n\nIf this indeed points to the directory your view module lives in, you can build from there to create an absolute path, e.g.:\nhere = lambda *x: os.path.join(os.path.abspath(os.path.dirname(__file__)), *x)\...
[ 2, 1, 1 ]
[]
[]
[ "django", "path", "python", "wsgi" ]
stackoverflow_0002825678_django_path_python_wsgi.txt
Q: Is there any graphics library in a higher level than OpenGL I am looking for a graphics library for 3D reconstruction research to develop my specific viewer based on some library. OpenGL seems in a low level and I have to remake the wheel everywhere. And I also tried VTK(visualization toolkit). However, it seems t...
Is there any graphics library in a higher level than OpenGL
I am looking for a graphics library for 3D reconstruction research to develop my specific viewer based on some library. OpenGL seems in a low level and I have to remake the wheel everywhere. And I also tried VTK(visualization toolkit). However, it seems too abstract that I need to master many conceptions before I start...
[ "Panda3D seems to be a nice 3D graphics library designed to be used in Python, although it's mostly game oriented. I've browsed the manuals a few times and it's very polished and of a high quality, it has even been used in some big studio's games (like Disney's Pirates of the Caribbean online, if I remember well).\...
[ 2, 1, 0 ]
[ "I have no personal experience with this, but I have heard some decent things about Pyglet\n", "I used openGL with C++ a few years back - found it quite low level. I also have used Java3D which seemed to be a bit higher level. If you are not stuck on using python - try Java3D - very simple to get up and running.\...
[ -1, -1 ]
[ "graphics", "opengl", "python" ]
stackoverflow_0002823907_graphics_opengl_python.txt
Q: Simple XML over http web service I have a simple html service, developed in django. You enter your name - it posts this, and returns a value (male/female). I need to ofer this as a web service. I have no idea where to start. I want to accept a xml request, and provide an xml response - thats it. Can anyone give m...
Simple XML over http web service
I have a simple html service, developed in django. You enter your name - it posts this, and returns a value (male/female). I need to ofer this as a web service. I have no idea where to start. I want to accept a xml request, and provide an xml response - thats it. Can anyone give ma any pointers - Googling it is diffic...
[ "You probably want Piston, which is framework for exposing Django apps as web services.\n", "See the Generating non-HTML content in the django book for instructions.\nBasically, it's as simple as this:\ndef get_data(request, xml_data):\n data = parse_xml_data(xml_data)\n return_data = create_xml_blob(data)\...
[ 2, 1 ]
[]
[]
[ "django", "python", "web_services", "xml" ]
stackoverflow_0002826004_django_python_web_services_xml.txt
Q: Creating a document tree before or after adding the subelements I am using lxml and Python for writing XML files. I was wondering what is the accepted practice: creating a document tree first and then adding the sub elements OR adding the sub elements and creating the tree later? I know this hardly makes any diffe...
Creating a document tree before or after adding the subelements
I am using lxml and Python for writing XML files. I was wondering what is the accepted practice: creating a document tree first and then adding the sub elements OR adding the sub elements and creating the tree later? I know this hardly makes any difference as to the output, but I was interested in knowing what is the a...
[ "Since tree construction is typically a recursive action, I would say that the tree root could get created last, once the subtree is done. However, I don't see any reason why that should be any better than creating the tree first. I honestly don't think there's an accepted norm for this, and rather than trying to f...
[ 1 ]
[]
[]
[ "lxml", "python" ]
stackoverflow_0002825988_lxml_python.txt
Q: Python to Java translation i get quite short code of algorithm in python, but i need to translate it to Java. I didnt find any program to do that, so i will really appreciate to help translating it. I learned python a very little to know the idea how algorithm work. The biggest problem is because in python all is ...
Python to Java translation
i get quite short code of algorithm in python, but i need to translate it to Java. I didnt find any program to do that, so i will really appreciate to help translating it. I learned python a very little to know the idea how algorithm work. The biggest problem is because in python all is object and some things are made ...
[ "Java doesn't have anything like Python's comprehension syntax. You'll have to replace it with code that loops over the list and aggregates the value of sum as it goes.\nAlso, self.flow looks like a dictionary indexed by pairs. The only way to match this, AFAIK, is to create a class with two fields that implements ...
[ 2 ]
[]
[]
[ "java", "python" ]
stackoverflow_0002826196_java_python.txt
Q: Django and JSON request In a template I have the following code. <script> var url="/mypjt/my_timer" $.post(url, paramarr, function callbackHandler(dict) { alert('got response back'); if (dict.flag == 2) { alert('1'); $.jGrowl("Data could not be saved...
Django and JSON request
In a template I have the following code. <script> var url="/mypjt/my_timer" $.post(url, paramarr, function callbackHandler(dict) { alert('got response back'); if (dict.flag == 2) { alert('1'); $.jGrowl("Data could not be saved"); } else if...
[ "If I understand rightly, you're sniffing the return code in the JavaScript, and then redirecting depending on the results.\nYou can do a redirect from Django, so I would do that instead of worrying about return codes. When you've got both a \"flag\" and a \"ret_status\", that is a hint you should re-think your des...
[ 0, 0 ]
[]
[]
[ "django", "django_views", "json", "jsonresult", "python" ]
stackoverflow_0002822599_django_django_views_json_jsonresult_python.txt
Q: Explain Python extensions multithreading Python interpreter has a Global Interpreter Lock, and it is my understanding that extensions must acquire it in a multi-threaded environment. But Boost.Python HOWTO page says the extension function must release the GIL and reacquire it on exit. I want to resist temptation t...
Explain Python extensions multithreading
Python interpreter has a Global Interpreter Lock, and it is my understanding that extensions must acquire it in a multi-threaded environment. But Boost.Python HOWTO page says the extension function must release the GIL and reacquire it on exit. I want to resist temptation to guess here, so I would like to know what sho...
[ "Whenever Python is interpreting bytecode the GIL is being held by the currently running thread. No other Python thread can run until it manages to acquire the GIL.\nWhen the interpreter has called into native code that code has two options regarding the GIL:\n\nIt could do nothing at all.\nIt could release the GIL...
[ 6 ]
[]
[]
[ "boost_python", "c++", "multithreading", "python" ]
stackoverflow_0002825362_boost_python_c++_multithreading_python.txt
Q: Does Google appengine cache external requests? I have a very simple application running on appengine that requests a web page every five minutes and parses for a specific piece of data. Everything works fine except that the response I get back from the external request (using urllib2) doesn't reflect the latest ch...
Does Google appengine cache external requests?
I have a very simple application running on appengine that requests a web page every five minutes and parses for a specific piece of data. Everything works fine except that the response I get back from the external request (using urllib2) doesn't reflect the latest changes to the page. Sometimes it takes a few minutes ...
[ "It appears that this is an issue the App Engine team is aware of. The suggested workaround is to set Cache-Control header with max-age in seconds:\nresult = urlfetch.fetch(url, headers = {'Cache-Control' : 'max-age=240'})\n\nshould hopefully work for you.\n" ]
[ 8 ]
[]
[]
[ "caching", "google_app_engine", "python", "urllib2" ]
stackoverflow_0002826238_caching_google_app_engine_python_urllib2.txt
Q: Django URL matching Can anyone see why this wouldn't be working? I'm fairly new to Django so any help would be much appreciated. Actual URL: http://127.0.0.1:8000/2010/may/12/my-second-blog-post/ urls.py: (r'(?P<year>d{4})/(?P<month>[a-z]{3})/(?P<day>w{1,2})/(?P<slug>[-w]+)/$', 'object_detail', dict(info_dict, slu...
Django URL matching
Can anyone see why this wouldn't be working? I'm fairly new to Django so any help would be much appreciated. Actual URL: http://127.0.0.1:8000/2010/may/12/my-second-blog-post/ urls.py: (r'(?P<year>d{4})/(?P<month>[a-z]{3})/(?P<day>w{1,2})/(?P<slug>[-w]+)/$', 'object_detail', dict(info_dict, slug_field='slug',template_n...
[ "r'(?P<year>\\d{4})/(?P<month>[a-z]{3})/(?P<day>\\w{1,2})/(?P<slug>[\\w-]+)/$', \n'object_detail', \ndict(info_dict, slug_field='slug',template_name='blog/detail.html')),\n\nYou seem to have forgotten the backslashes.\n", "Are you specifying this in an app context or in the project url routing?\nYou may need to s...
[ 12, 0 ]
[]
[]
[ "django", "python", "regex", "url" ]
stackoverflow_0002827158_django_python_regex_url.txt
Q: how execute a Python Script with activeresource? I need to execute this python script: http://superjared.com/static/code/googleMX.py I installed pyactiveresource, but when I executed it: python googleMX.py I had this response. Traceback (most recent call last): File "googleMX.py", line 15, in ? from pyactivereso...
how execute a Python Script with activeresource?
I need to execute this python script: http://superjared.com/static/code/googleMX.py I installed pyactiveresource, but when I executed it: python googleMX.py I had this response. Traceback (most recent call last): File "googleMX.py", line 15, in ? from pyactiveresource import ActiveResource ImportError: cannot import...
[ "by Responding myself...\nIt was using an older version of pyactiveresource. The author (Lucky) creates another one http://gist.github.com/330832\n" ]
[ 0 ]
[]
[]
[ "activeresource", "python" ]
stackoverflow_0002435778_activeresource_python.txt
Q: Python and Excel - check if file is open hey guys, I need help considering win32com in Python: I have a routine that opens a Workbook, creates a sheet and puts some data on it. If everything runs fine the woorkbook is saved and closed - If not the python session is terminated but the woorkbook is left open. So the...
Python and Excel - check if file is open
hey guys, I need help considering win32com in Python: I have a routine that opens a Workbook, creates a sheet and puts some data on it. If everything runs fine the woorkbook is saved and closed - If not the python session is terminated but the woorkbook is left open. So the reference is lost. Now when restarting the co...
[ "I'm not familiar with Python but have done some Excel/Word COM code in other languages.\nExcel's Application.DisplayAlerts property might help. Setting it to False suppresses most messages that Excel might normally show, and auto-chooses a default response, though I think there are some exceptions.\nLooking at you...
[ 3, 1, 1 ]
[]
[]
[ "excel", "python" ]
stackoverflow_0002816530_excel_python.txt
Q: what if i keep my class members are public? In c++ instance variables are private by default,in Python variables are public by default i have two questions regarding the same:- 1: why Python have all the members are public by default? 2: People say you should your member data should be private what if i make ...
what if i keep my class members are public?
In c++ instance variables are private by default,in Python variables are public by default i have two questions regarding the same:- 1: why Python have all the members are public by default? 2: People say you should your member data should be private what if i make my data to be public? what are the disadvantag...
[ "You can use a leading underscore in the name to tell readers of the code that the name in question is an internal detail and they must not rely on it remaining in future versions. Such a convention is really all you need -- why weigh the language down with an enforcement mechanism?\nData, just like methods, shoul...
[ 13, 3, 1, 0 ]
[]
[]
[ "c++", "python" ]
stackoverflow_0002824579_c++_python.txt
Q: delete all records except the id I have in a python list I want to delete all records in a mysql db except the record id's I have in a list. The length of that list can vary and could easily contain 2000+ id's, ... Currently I convert my list to a string so it fits in something like this: cursor.execute("""delete...
delete all records except the id I have in a python list
I want to delete all records in a mysql db except the record id's I have in a list. The length of that list can vary and could easily contain 2000+ id's, ... Currently I convert my list to a string so it fits in something like this: cursor.execute("""delete from table where id not in (%s)""",(list)) Which doesn't feel...
[ "If the db table is not too large, just read in all the ids, and\nmake a list of the ones you want to delete:\nkeep_ids=[...]\ncursor.execute('SELECT id FROM table')\ndelete_ids=[]\nfor (row_id,) in cursor:\n if row_id not in keep_ids:\n delete_ids.append(row_id)\ncursor.executemany('DELETE FROM table WHE...
[ 4, 1, 0 ]
[ "That's what temporary tables are for. You create a temporary table containing your exclusion list and use the DBM to do your selection for you. A simple example:\nCREATE TABLE words (id integer primary key not null, word string);\nCREATE TEMPORARY TABLE exclusion (word string);\nINSERT INTO words VALUES ... # 100,...
[ -2 ]
[ "mysql", "python" ]
stackoverflow_0002826387_mysql_python.txt
Q: Application with both console and gui mode I have a python console app. Like most python console apps it uses the OptionParser module to take arguments. I've now developed a GUI for my app using wxPython and i'd like to integrate the two. I'd like my app to be run both from the console and from the OS's UI. When i...
Application with both console and gui mode
I have a python console app. Like most python console apps it uses the OptionParser module to take arguments. I've now developed a GUI for my app using wxPython and i'd like to integrate the two. I'd like my app to be run both from the console and from the OS's UI. When it is invoked from the console it runs as a conso...
[ "can you pass args to the app then use the arg parser? \nif __name__ == \"__main__\":\n from optparse import OptionParser\n\n parser = OptionParser() \n parser.add_option(\"-g\",\"--gui_mode\",\n dest=\"guimode\",\n help=\"start program in gui mode\",\n ac...
[ 2, 0 ]
[]
[]
[ "console_application", "optionparser", "python", "user_interface", "wxpython" ]
stackoverflow_0002827582_console_application_optionparser_python_user_interface_wxpython.txt
Q: python logparse search specific text I am using this function in my code to return the strings i want from reading the log file, I want to grep the "exim" process and return the results, but running the code gives no error, but the output is limited to three lines, how can i just get the output only related to exi...
python logparse search specific text
I am using this function in my code to return the strings i want from reading the log file, I want to grep the "exim" process and return the results, but running the code gives no error, but the output is limited to three lines, how can i just get the output only related to exim process.. #output: {'date': '13', 'p...
[ "It's because you have a break statement inside the if that checks for \"exim\". As soon as you find a line with \"exim\", you will stop processing entirely, which sounds like the opposite of what you want!\nI think you want to remove the break and put your printout inside the if. If your question is about the retu...
[ 0, 0 ]
[]
[]
[ "logging", "parsing", "python" ]
stackoverflow_0002826742_logging_parsing_python.txt
Q: How do I find difference between times in different timezones in Python? I am trying to calculate difference(in seconds) between two date/times formatted as following: 2010-05-11 17:07:33 UTC 2010-05-11 17:07:33 EDT time1 = '2010-05-11 17:07:33 UTC' time2 = '2010-05-11 17:07:33 EDT' delta = time.mktime(time.strpti...
How do I find difference between times in different timezones in Python?
I am trying to calculate difference(in seconds) between two date/times formatted as following: 2010-05-11 17:07:33 UTC 2010-05-11 17:07:33 EDT time1 = '2010-05-11 17:07:33 UTC' time2 = '2010-05-11 17:07:33 EDT' delta = time.mktime(time.strptime(time1,"%Y-%m-%d %H:%M:%S %Z"))-\ time.mktime(time.strptime(time2, "...
[ "Check out the pytz world timezone definitions library.\n\nThis library allows accurate and cross platform timezone calculations using Python 2.3 or higher. It also solves the issue of ambiguous times at the end of daylight savings, which you can read more about in the Python Library Reference (datetime.tzinfo).\n\...
[ 8, 5, 0 ]
[]
[]
[ "datetime", "python", "timezone" ]
stackoverflow_0002828158_datetime_python_timezone.txt
Q: Sum records values in Django I defined couple models in my app: class Project(models.Model): title = models.CharField(max_length=150) url = models.URLField() manager = models.ForeignKey(User) class Cost(models.Model): project = models.ForeignKey(Project) cost = models.FloatField() ...
Sum records values in Django
I defined couple models in my app: class Project(models.Model): title = models.CharField(max_length=150) url = models.URLField() manager = models.ForeignKey(User) class Cost(models.Model): project = models.ForeignKey(Project) cost = models.FloatField() date = models.DateField() I w...
[ "Alexander's solution will give you the right result, but with one query for each project. Use\nannotate to do the whole thing in a single query.\nfrom django.db.models import Sum\n\nannotated_projects = Project.objects.all().annotate(cost_sum=Sum('cost__cost'))\nfor project in annotated_projects:\n print projec...
[ 5, 3, 2 ]
[]
[]
[ "django", "python" ]
stackoverflow_0002828343_django_python.txt
Q: overriding callbacks avoiding attribute pollution I've a class that has some callbacks and its own interface, something like: class Service: def __init__(self): connect("service_resolved", self.service_resolved) def service_resolved(self, a,b c): ''' This function is called when it's t...
overriding callbacks avoiding attribute pollution
I've a class that has some callbacks and its own interface, something like: class Service: def __init__(self): connect("service_resolved", self.service_resolved) def service_resolved(self, a,b c): ''' This function is called when it's triggered service resolved signal and has ...
[ "Avoiding accidental clashes with derived classes is the reason the \"double-leading-underscore\" naming approach exists: if you name an attribute in class Service __foo, the Python compiler will internally \"mangle\" that name to _Service__foo, making accidental clashes unlikely. Alas, not impossible: a subclass ...
[ 3 ]
[]
[]
[ "asynchronous", "python" ]
stackoverflow_0002828349_asynchronous_python.txt
Q: Python and hebrew encoding/decoding error I have sqlite database which I would like to insert values in Hebrew to I am keep getting the following error : UnicodeDecodeError: 'ascii' codec can't decode byte 0xd7 in position 0: ordinal not in range(128) my code is as following : runsql(u'INSERT into personal val...
Python and hebrew encoding/decoding error
I have sqlite database which I would like to insert values in Hebrew to I am keep getting the following error : UnicodeDecodeError: 'ascii' codec can't decode byte 0xd7 in position 0: ordinal not in range(128) my code is as following : runsql(u'INSERT into personal values(%(ID)d,%(name)s)' % {'ID':1,'name':fabric...
[ "You are passing the fabricated names into the string formatting parameter for a Unicode string. Ideally, the strings passed this way should also be Unicode.\nBut fabricate_hebrew_name isn't returning Unicode - it is returned UTF-8 encoded string, which isn't the same.\nSo, get rid of the call the encode('utf-8') a...
[ 4, 2 ]
[]
[]
[ "encoding", "hebrew", "python", "sqlite", "unicode" ]
stackoverflow_0002828537_encoding_hebrew_python_sqlite_unicode.txt
Q: How can I load a sql "dump" file into sql alchemy I have a large sql dump file ... with multiple CREATE TABLE and INSERT INTO statements. Is there any way to load these all into a SQLAlchemy sqlite database at once. I plan to use the introspected ORM from sqlsoup after I've created the tables. However, when I u...
How can I load a sql "dump" file into sql alchemy
I have a large sql dump file ... with multiple CREATE TABLE and INSERT INTO statements. Is there any way to load these all into a SQLAlchemy sqlite database at once. I plan to use the introspected ORM from sqlsoup after I've created the tables. However, when I use the engine.execute() method it complains: sqlite3.Wa...
[ "\"or some kind of parser\"\nI've found MySQL to be a great parser for MySQL dump files :)\nYou said it yourself: \"so it has quite a few commands/syntax that sqlite3 does not understand correctly.\" Clearly then, SQLite is not the tool for this task.\nAs for your particular error: without context (i.e. a traceback...
[ 2, 0 ]
[]
[]
[ "python", "sql", "sqlalchemy" ]
stackoverflow_0002824244_python_sql_sqlalchemy.txt
Q: Looking to reimplement build toolchain from bash/grep/sed/awk/(auto)make/configure to something more sane (e.g. boost.build, etc) I currently maintain a few boxes that house a loosely related cornucopia of coding projects, databases and repositories (ranging from a homebrew *nix distro to my class notes), maintain...
Looking to reimplement build toolchain from bash/grep/sed/awk/(auto)make/configure to something more sane (e.g. boost.build, etc)
I currently maintain a few boxes that house a loosely related cornucopia of coding projects, databases and repositories (ranging from a homebrew *nix distro to my class notes), maintained by myself and a few equally pasty-skinned nerdy friends (all of said cornucopia is stored in SVN). The vast majority of our code is ...
[ "We've started using CMake here at work recently. I've been pretty happy with it so far.\n", "scons or cmake.\nBoth \"cross platform\" - enable compiling on Windows and Linux.\nCmake now very popular (for example boost uses it). It creates native build files for each platform - Makefiles (for Linux), VC++ projec...
[ 2, 2, 1 ]
[]
[]
[ "bash", "boost", "c++", "makefile", "python" ]
stackoverflow_0002819558_bash_boost_c++_makefile_python.txt
Q: Django syncdb not making tables for my app It used to work, and now it doesn't. python manage.py syncdb no longer makes tables for my app. From settings.py: INSTALLED_APPS = ( 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'mysite.myapp'...
Django syncdb not making tables for my app
It used to work, and now it doesn't. python manage.py syncdb no longer makes tables for my app. From settings.py: INSTALLED_APPS = ( 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'mysite.myapp', 'django.contrib.admin', ) What could I be...
[ "I'd bet that the SomeModel model you mention above (not necessarily MyUser) has got a problem with it which means it can't be imported by loaddata. If not SomeModel, then a model in the same models.py that SomeModel is defined in. \nHave you tried ./manage.py validate ? Even if that says all models are fine, somet...
[ 2 ]
[]
[]
[ "django", "django_models", "python" ]
stackoverflow_0002829149_django_django_models_python.txt
Q: python convert 12 bit image encoded in a string to 8 bit png I have a string that is read from a usb apogee camera that is a 12-bit grayscale image with the 12-bits each occupying the lowest 12 bits of 16-bits words. I want to create a 8-bit png from this string by ignoring the lowest 4 bits. I can convert it to ...
python convert 12 bit image encoded in a string to 8 bit png
I have a string that is read from a usb apogee camera that is a 12-bit grayscale image with the 12-bits each occupying the lowest 12 bits of 16-bits words. I want to create a 8-bit png from this string by ignoring the lowest 4 bits. I can convert it to a 16-bit image where the highest 4 bits are always zero using PIL ...
[ "Wump's comment about converting an image gave me an idea, and I did it by\n#shifts by 4 bits and converts to 8-bit image\nimg = img.point(lambda i: i * 16, \"L\") \n\nThanks Wump\n", "The only way I know how to do it would be:\ndata = numpy.fromstring(imageStr, numpy.uint16)\ndata >>= 4 # shift out four bits\nda...
[ 2, 1 ]
[]
[]
[ "bit", "image", "python" ]
stackoverflow_0002816144_bit_image_python.txt
Q: SOCKS in C/C++ or another language? How do i add SOCKS support to my application? and where can i get the libs? any help appreciated thanks A: You could try Boost.Asio library. It contains an example with SOCKS4 protocol implementation.
SOCKS in C/C++ or another language?
How do i add SOCKS support to my application? and where can i get the libs? any help appreciated thanks
[ "You could try Boost.Asio library. It contains an example with SOCKS4 protocol implementation.\n" ]
[ 6 ]
[ "VC++ has extensive support if you want to try on Windows. \nGoogle \"Windows sockets for beginners msdn\", great info for windows sockets...\nIf linux, try C sockets by beej... Just google beej's guide for sockets... \n" ]
[ -3 ]
[ "c", "c++", "perl", "python", "socks" ]
stackoverflow_0002829637_c_c++_perl_python_socks.txt
Q: What's the scope of a variable initialized in an if statement? I'm new to Python, so this is probably a simple scoping question. The following code in a Python file (module) is confusing me slightly: if __name__ == '__main__': x = 1 print x In other languages I've worked in, this code would throw an exceptio...
What's the scope of a variable initialized in an if statement?
I'm new to Python, so this is probably a simple scoping question. The following code in a Python file (module) is confusing me slightly: if __name__ == '__main__': x = 1 print x In other languages I've worked in, this code would throw an exception, as the x variable is local to the if statement and should not exi...
[ "Python variables are scoped to the innermost function, class, or module in which they're assigned. Control blocks like if and while blocks don't count, so a variable assigned inside an if is still scoped to a function, class, or module.\n(Implicit functions defined by a generator expression or list/set/dict compre...
[ 465, 155, 48, 15, 15, 6, 3 ]
[]
[]
[ "if_statement", "local_variables", "python", "scope", "variables" ]
stackoverflow_0002829528_if_statement_local_variables_python_scope_variables.txt
Q: Organizing a random list of objects in Python So I have a list that I want to convert to a list that contains a list for each group of objects. ie ['objA.attr1', 'objC', 'objA.attr55', 'objB.attr4'] would return [['objA.attr1', 'objA.attr55'], ['objC'], ['objB.attr4']] currently this is what I use: givenList = ...
Organizing a random list of objects in Python
So I have a list that I want to convert to a list that contains a list for each group of objects. ie ['objA.attr1', 'objC', 'objA.attr55', 'objB.attr4'] would return [['objA.attr1', 'objA.attr55'], ['objC'], ['objB.attr4']] currently this is what I use: givenList = ['a.attr1', 'b', 'a.attr55', 'c.attr4'] trgList = [...
[ "This needs to be better defined: what do you do when there is no property? What order do you want the final list as? What about duplicates?\nA general algorithm would be to use a multi-map: a map that has multiple values per key.\nYou will then scan through the original list, separate each element into an \"object...
[ 0 ]
[]
[]
[ "grouping", "python", "sorting" ]
stackoverflow_0002829758_grouping_python_sorting.txt
Q: Django: Determining if a user has voted or not I have a long list of links that I spit out using the below code, total votes, submitted by, the usual stuff but I am not 100% on how to determine if the currently logged in user has voted on a link or not. I know how to do this from within my view but do I need to a...
Django: Determining if a user has voted or not
I have a long list of links that I spit out using the below code, total votes, submitted by, the usual stuff but I am not 100% on how to determine if the currently logged in user has voted on a link or not. I know how to do this from within my view but do I need to alter my below view code or can I make use of the way...
[ "I've dealt with this before and solved it with extra more or less like so:\n# annotate whether you've already voted on this item\ntable = Vote._meta.db_table\nselect = 'SELECT COUNT(id) FROM %s' %table\nwhere1 = 'WHERE ' + table + '.user_id = %s'\nwhere2 = 'AND ' + table + '.item_id = appname_item.id'\nitems = ite...
[ 2 ]
[]
[]
[ "django", "orm", "python", "sql" ]
stackoverflow_0002829896_django_orm_python_sql.txt
Q: name 'OptionGroup' is not defined This error is done strictly by following examples found on the docs. And you can't find any clarification about it anywhere, be it that long long docs page, google or stackoverflow. Plus, reading optparse.py shows OptionGroup is there, so that adds to the confusion. Python 2.6.1 (...
name 'OptionGroup' is not defined
This error is done strictly by following examples found on the docs. And you can't find any clarification about it anywhere, be it that long long docs page, google or stackoverflow. Plus, reading optparse.py shows OptionGroup is there, so that adds to the confusion. Python 2.6.1 (r261:67515, Feb 11 2010, 00:51:29) >>>...
[ "Perhaps this is another example of why it is better to import modules than functions from modules.\nOptionGroup is defined in the module optparse.\nThe command\nfrom optparse import OptionParser\nputs OptionParser in the global namespace, but neglects OptionGroup entirely.\nTo fix the code, import the optparse mod...
[ 6 ]
[]
[]
[ "nameerror", "optparse", "python" ]
stackoverflow_0002830069_nameerror_optparse_python.txt
Q: Distinguishing between broadcasted messages and direct messages How can I distinguish between a broadcasted message and a direct message for my ip? I'm doing this in python. A: Basically what you need to do is create a raw socket, receive a datagram, and examine the destination address in the header. If that add...
Distinguishing between broadcasted messages and direct messages
How can I distinguish between a broadcasted message and a direct message for my ip? I'm doing this in python.
[ "Basically what you need to do is create a raw socket, receive a datagram, and examine the destination address in the header. If that address is a broadcast address for the network adapter the socket is bound to, then you're golden.\nI don't know how to do this in Python, so I suggest looking for examples of raw so...
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0002830326_python.txt
Q: How should I grab pairs from a list in python? Say I have a list that looks like this: ['item1', 'item2', 'item3', 'item4', 'item5', 'item6', 'item7', 'item8', 'item9', 'item10'] Using Python, how would I grab pairs from it, where each item is included in a pair with both the item before and after it? ['item1', '...
How should I grab pairs from a list in python?
Say I have a list that looks like this: ['item1', 'item2', 'item3', 'item4', 'item5', 'item6', 'item7', 'item8', 'item9', 'item10'] Using Python, how would I grab pairs from it, where each item is included in a pair with both the item before and after it? ['item1', 'item2'] ['item2', 'item3'] ['item3', 'item4'] ['item...
[ "A quick and simple way of doing it would be something like:\na = ['item1', 'item2', 'item3', 'item4', 'item5', 'item6', 'item7', 'item8', 'item9', 'item10']\n\nprint zip(a, a[1:])\n\nWhich will produce the following:\n[('item1', 'item2'), ('item2', 'item3'), ('item3', 'item4'), ('item4', 'item5'), ('item5', 'item6...
[ 11, 3, 1 ]
[]
[]
[ "list", "python" ]
stackoverflow_0002829887_list_python.txt
Q: Identifying a function call in a python script line in runtime I have a python script that I run with 'exec'. When a function is called by the script, I would like it to know the line number and offset in line for that call. Here is an example. If my script is: foo1(); foo2(); foo1() foo3() And if I have code tha...
Identifying a function call in a python script line in runtime
I have a python script that I run with 'exec'. When a function is called by the script, I would like it to know the line number and offset in line for that call. Here is an example. If my script is: foo1(); foo2(); foo1() foo3() And if I have code that prints (line,offset) in every function, I should get (0,0), (0,8),...
[ "Python doesn't provide a lot of information about character offsets in a line.\nIf you are using exec to execute the Python, then you could re-write the code mechanically before executing it to tell you what you want to know. For example, you could change the original code:\nfoo1(); foo2(); foo1()\nfoo3()\n\ninto...
[ 1, 0 ]
[]
[]
[ "python", "stack_frame", "stack_trace" ]
stackoverflow_0002829818_python_stack_frame_stack_trace.txt
Q: Infinite loop when adding a row to a list in a class in python3 I have a script which contains two classes. (I'm obviously deleting a lot of stuff that I don't believe is relevant to the error I'm dealing with.) The eventual task is to create a decision tree, as I mentioned in this question. Unfortunately, I'm...
Infinite loop when adding a row to a list in a class in python3
I have a script which contains two classes. (I'm obviously deleting a lot of stuff that I don't believe is relevant to the error I'm dealing with.) The eventual task is to create a decision tree, as I mentioned in this question. Unfortunately, I'm getting an infinite loop, and I'm having difficulty identifying why....
[ "I suspect that you are appending to the same list that you are iterating over causing it to increase in size before the iterator can reach the end of it. Try iterating over a copy of the list instead:\nfor i in list(self.ds.individuals):\n datasets[i[split_value]].individuals.append(i) \n\n", "class Dataset:\...
[ 4, 4 ]
[]
[]
[ "infinite_loop", "python", "python_3.x" ]
stackoverflow_0002830953_infinite_loop_python_python_3.x.txt
Q: Tool (or combination of tools) for reproducible environments in Python I used to be a java developer and we used tools like ant or maven to manage our development/testing/UAT environments in a standardized way. This allowed us to handle library dependencies, setting OS variables, compiling, deploying, running unit...
Tool (or combination of tools) for reproducible environments in Python
I used to be a java developer and we used tools like ant or maven to manage our development/testing/UAT environments in a standardized way. This allowed us to handle library dependencies, setting OS variables, compiling, deploying, running unit tests, and all the required tasks. Also, the scripts generated guaranteed t...
[ "\nvirtualenv to create a contained virtual environment (prevent different versions of Python or Python packages from stomping on each other). There is increasing buzz from people moving to this tool. The author is the same as the older working-env.py mentioned by Aaron.\npip to install packages inside a virtualen...
[ 18, 3, 2, 2, 2, 0, 0 ]
[]
[]
[ "automated_deploy", "continuous_integration", "development_environment", "installation", "python" ]
stackoverflow_0000545730_automated_deploy_continuous_integration_development_environment_installation_python.txt
Q: Excel CSV into Nested Dictionary; List Comprehensions I have a Excel CSV files with employee records in them. Something like this: mail,first_name,surname,employee_id,manager_id,telephone_number blah@blah.com,john,smith,503422,503423,+65(2)3423-2433 foo@blah.com,george,brown,503097,503098,+65(2)3423-9782 .... I'm...
Excel CSV into Nested Dictionary; List Comprehensions
I have a Excel CSV files with employee records in them. Something like this: mail,first_name,surname,employee_id,manager_id,telephone_number blah@blah.com,john,smith,503422,503423,+65(2)3423-2433 foo@blah.com,george,brown,503097,503098,+65(2)3423-9782 .... I'm using DictReader to put this into a nested dictionary: imp...
[ "Your first part has one simple issue (which might not even be an issue). You don't handle key collisions at all (unless you intend to simply overwrite).\n>>> dict([('a', 'b'), ('a', 'c')])\n{'a': 'c'}\n\nIf you're guaranteed that employee_id is unique, there isn't an issue though.\n2) Sure you can exclude it, but...
[ 4 ]
[]
[]
[ "csv", "list_comprehension", "python" ]
stackoverflow_0002831315_csv_list_comprehension_python.txt
Q: Sending and receiving async over multiprocessing.Pipe() in Python I'm having some issues getting the Pipe.send to work in this code. What I would ultimately like to do is send and receive messages to and from the foreign process while its running in a fork. This is eventually going to be integrated into a pexpect ...
Sending and receiving async over multiprocessing.Pipe() in Python
I'm having some issues getting the Pipe.send to work in this code. What I would ultimately like to do is send and receive messages to and from the foreign process while its running in a fork. This is eventually going to be integrated into a pexpect loop for talking to interpreter processes. from multiprocessing import...
[ "This works, but might need some more work. Not sure how many of these i can create and loop over.\nfrom multiprocessing import Process, Pipe\nfrom pexpect import spawn\n\n\nclass CockProc(Process):\n\n def start(self):\n self.process = spawn('coqtop', ['-emacs-U'])\n\n def run(self, conn):\n if...
[ 1 ]
[]
[]
[ "asynchronous", "multiprocessing", "python" ]
stackoverflow_0002831299_asynchronous_multiprocessing_python.txt
Q: How to generate a tree without recursive using python or other language? class tree: def __init__(self, name='a', childs=[]): self.name = name self.childs = childs output: <ul> <li> Introduction <ul> <li>Sub Intro</li> </ul> </li> <li>Module 1</li> </ul> A: ...
How to generate a tree without recursive using python or other language?
class tree: def __init__(self, name='a', childs=[]): self.name = name self.childs = childs output: <ul> <li> Introduction <ul> <li>Sub Intro</li> </ul> </li> <li>Module 1</li> </ul>
[ "To generate nested lists without recursion you'd simply keep track of your nesting level, incrementing it as you traverse into deeper levels of nesting and decrementing it as you traverse back upwards.\nThe natural approach, for handling things like closing tags, would be to maintain a simple stack (Python list) a...
[ 2 ]
[ "Maybe something like this:\nNEW=object()\nEND=object()\n\nclass tree:\n def __init__(self, name='a', childs=[]):\n self.name = name\n self.childs = childs\n\n def __str__(self):\n indent=0\n result=[]\n for i in self.childs:\n if i is NEW:\n result...
[ -1 ]
[ "python", "tree" ]
stackoverflow_0002831478_python_tree.txt
Q: Wav analysis in python I'm looking for a python library that will help me analyze the audio in wav files. At the very least I'm hoping to find some kind of interface that understands .wav format so that I don't have to :P at best I need a module with methods for reading wave form parameters like pitch, volume leve...
Wav analysis in python
I'm looking for a python library that will help me analyze the audio in wav files. At the very least I'm hoping to find some kind of interface that understands .wav format so that I don't have to :P at best I need a module with methods for reading wave form parameters like pitch, volume levels, etc
[ "How about the wave module?\n" ]
[ 2 ]
[]
[]
[ "python", "wav" ]
stackoverflow_0002831699_python_wav.txt
Q: Pyparsing CSV string with random quotes I have a string like the following: <118>date=2010-05-09,time=16:41:27,device_id=FE-2KA3F09000049,log_id=0400147717,log_part=00,type=statistics,subtype=n/a,pri=information,session_id=o49CedRc021772,from="prvs=4745cd07e1=example@example.org",mailer="mta",client_name="example....
Pyparsing CSV string with random quotes
I have a string like the following: <118>date=2010-05-09,time=16:41:27,device_id=FE-2KA3F09000049,log_id=0400147717,log_part=00,type=statistics,subtype=n/a,pri=information,session_id=o49CedRc021772,from="prvs=4745cd07e1=example@example.org",mailer="mta",client_name="example.org,[194.177.17.24]",resolved=OK,to="example@...
[ "It might be better to leverage an existing parser than to use ad-hoc regexs.\nparse_http_list(s)\n Parse lists as described by RFC 2068 Section 2.\n\n In particular, parse comma-separated lists where the elements of\n the list may include quoted-strings. A quoted-string could\n contain a comma. A non...
[ 6, 5 ]
[]
[]
[ "csv", "logging", "pyparsing", "python" ]
stackoverflow_0002797644_csv_logging_pyparsing_python.txt
Q: pythonic way to associate list elements with their indices I have a list of values and I want to put them in a dictionary that would map each value to it's index. I can do it this way: >>> t = (5,6,7) >>> d = dict(zip(t, range(len(t)))) >>> d {5: 0, 6: 1, 7: 2} this is not bad, but I'm looking for something more...
pythonic way to associate list elements with their indices
I have a list of values and I want to put them in a dictionary that would map each value to it's index. I can do it this way: >>> t = (5,6,7) >>> d = dict(zip(t, range(len(t)))) >>> d {5: 0, 6: 1, 7: 2} this is not bad, but I'm looking for something more elegant. I've come across the following, but it does the opposi...
[ "You can use a list comprehension (or a generator, depending on your python version) to perform a simple in-place swap for your second example.\n\nUsing a list comprehension:\nd = dict([(y,x) for x,y in enumerate(t)])\n\n\nUsing a generator expression (Python 2.4 and up):\nd = dict((y,x) for x,y in enumerate(t))\n\...
[ 14, 14, 4, 2, 2, 0 ]
[]
[]
[ "dictionary", "enumerate", "list", "python" ]
stackoverflow_0002831672_dictionary_enumerate_list_python.txt
Q: Creating a new workbook in Excel from Python breaks I am trying to use the stock standard win32com approach to drive Excel 2007 from Python. However, when I try to create a new workbook, things go pear-shaped: Python 2.6.4 (r264:75706, Nov 3 2009, 13:23:17) [MSC v.1500 32 bit (Intel)] on win32 ... >>> import win3...
Creating a new workbook in Excel from Python breaks
I am trying to use the stock standard win32com approach to drive Excel 2007 from Python. However, when I try to create a new workbook, things go pear-shaped: Python 2.6.4 (r264:75706, Nov 3 2009, 13:23:17) [MSC v.1500 32 bit (Intel)] on win32 ... >>> import win32com.client >>> excel = win32com.client.Dispatch("Excel.A...
[ "you might want to look at the excellent xl*t packages at http://www.python-excel.org/\nCreating workbooks/sheets is as easy as:\nimport xlwt\nfrom datetime import datetime\n\nwb = xlwt.Workbook()\nws = wb.add_sheet('A Test Sheet')\n\nws.write(0, 0, 'Test', style0)\nws.write(1, 0, datetime.now(), style1)\nws.write(...
[ 3, 1 ]
[]
[]
[ "python" ]
stackoverflow_0002831491_python.txt
Q: how to increase Speed of a component made from Javascript or JQuery? I want to make my component faster, I am using Javascript and JQuery to build that. I am using JSON object to communicate with component and back-end is python. Is there any suggestion to make component faster? A: Setup some analysis to see wha...
how to increase Speed of a component made from Javascript or JQuery?
I want to make my component faster, I am using Javascript and JQuery to build that. I am using JSON object to communicate with component and back-end is python. Is there any suggestion to make component faster?
[ "Setup some analysis to see what takes time to process. Then decide if you want to try to optimize the javascript and client code, the communication up/down with the server or the actual speed of the python execution. When you have decided what you want to make faster, you can post samples of that to this site and ...
[ 1, 0, 0 ]
[]
[]
[ "google_apps", "javascript", "jquery", "python" ]
stackoverflow_0002832064_google_apps_javascript_jquery_python.txt
Q: Google App Engine Python: get image upload size server-side I am building a Google App Engine App that lets users upload images; I have everything working fine, but I am struggling to find a way to ensure that the user does not upload an image too large (because I am resizing the images, so this crashes my python ...
Google App Engine Python: get image upload size server-side
I am building a Google App Engine App that lets users upload images; I have everything working fine, but I am struggling to find a way to ensure that the user does not upload an image too large (because I am resizing the images, so this crashes my python script). When a user uploads a large image, I get this error Requ...
[ "from google.appengine.runtime import apiproxy_errors\n\n...\n\ntry:\n #the code you are getting the error at\nexcept apiproxy_errors.RequestTooLargeError, message:\n print message # or something else\n\n", "I am not sure I understand your problem completely but maybe a try would work?\ntry: \n images...
[ 5, 1 ]
[]
[]
[ "google_app_engine", "image", "python" ]
stackoverflow_0002831713_google_app_engine_image_python.txt
Q: python: send a list/dict over network I'm looking for an easy way of packing/unpacking data structures for sending over the network: on client just before sending: a = ((1,2),(11,22,),(111,222)) message = pack(a) and then on server: a = unpack(message) Is there a library that could do pack/unpack magic? Thanks i...
python: send a list/dict over network
I'm looking for an easy way of packing/unpacking data structures for sending over the network: on client just before sending: a = ((1,2),(11,22,),(111,222)) message = pack(a) and then on server: a = unpack(message) Is there a library that could do pack/unpack magic? Thanks in advance
[ "Looks like JSON might fit the bill. It's simple, and it's in the Python standard library.\nIt might not be too happy about the tuples, though:\n>>> import json\n>>> a = ((1,2),(11,22,),(111,222))\n>>> print a\n((1, 2), (11, 22), (111, 222))\n>>> message = json.dumps(a)\n>>> message\n'[[1, 2], [11, 22], [111, 222]]...
[ 12, 2, 1 ]
[]
[]
[ "python", "serialization" ]
stackoverflow_0002562359_python_serialization.txt
Q: how to import the blog.py(i import the 'blog' folder) my dir location,i am in a.py: my_Project |----blog |-----__init__.py |-----a.py |-----blog.py when i 'from blog import something' in a.py , it show error: from blog import BaseRequestHandler ImportError: cannot import n...
how to import the blog.py(i import the 'blog' folder)
my dir location,i am in a.py: my_Project |----blog |-----__init__.py |-----a.py |-----blog.py when i 'from blog import something' in a.py , it show error: from blog import BaseRequestHandler ImportError: cannot import name BaseRequestHandler i think it import the blog folder,n...
[ "When you are in a.py, import blog should import the local blog.py and nothing else. Quoting the docs:\n\nmodules are searched in the list of directories given by the variable sys.path which is initialized from the directory containing the input script\n\nSo my guess is that somehow, the name BaseRequestHandler is ...
[ 1, 0 ]
[]
[]
[ "import", "python" ]
stackoverflow_0002832646_import_python.txt
Q: how to import a.py not a folder zjm_code |-----a.py |-----a |----- __init__.py |-----b.py in a.py is : c='ccc' in b.py is : import a print dir(a) when i execute b.py ,it show (it import 'a' folder): ['__builtins__', '__doc__', '__file__', '__name__', '__path__'] and when i delete a folde...
how to import a.py not a folder
zjm_code |-----a.py |-----a |----- __init__.py |-----b.py in a.py is : c='ccc' in b.py is : import a print dir(a) when i execute b.py ,it show (it import 'a' folder): ['__builtins__', '__doc__', '__file__', '__name__', '__path__'] and when i delete a folder, it show ,(it import a.py): ['__bui...
[ "Use imp.load_module - there you can specify the file directory, overriding the behaviour of import.\n", "Rename the folder to a different name. A folder with the same name takes precedence.\n" ]
[ 2, 1 ]
[]
[]
[ "import", "python" ]
stackoverflow_0002832865_import_python.txt
Q: Possible to access gdata api when using Java App Engine? I have a dilemma where I want to create an application that manipulates google contacts information. The problem comes down to the fact that Python only supports version 1.0 of the api whilst Java supports 3.0. I also want it to be web-based so I'm having a ...
Possible to access gdata api when using Java App Engine?
I have a dilemma where I want to create an application that manipulates google contacts information. The problem comes down to the fact that Python only supports version 1.0 of the api whilst Java supports 3.0. I also want it to be web-based so I'm having a look at google app engine, but it seems that only the python v...
[ "I'm having a look into the google data api protocol which seems to solve the problem.\n", "Google Data API Java Client : link1\nGetting Started with the Google Data Java Client Library link2 \nI guess this is what you were looking for.\n", "I use GDATA apis for my JAVA appengine webapp. So GDATA can be used wi...
[ 0, 0, 0 ]
[]
[]
[ "gdata_api", "google_app_engine", "java", "python" ]
stackoverflow_0001148165_gdata_api_google_app_engine_java_python.txt