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: Python: Identifying string list with length of 1 vs. string In my code I have the following: if all(requiredField in submittedFields for requiredField in requiredFields): # all required fields in submittedFields exist else: # error handling The goal is to check if a list of strings in requiredFields are a...
Python: Identifying string list with length of 1 vs. string
In my code I have the following: if all(requiredField in submittedFields for requiredField in requiredFields): # all required fields in submittedFields exist else: # error handling The goal is to check if a list of strings in requiredFields are all present in submittedFields This works fine when requiredFields...
[ "Using python sets would be much more efficient:\nsubmitted_fields = set(['length', 'width', 'color', 'single element'])\nrequired_fields = set(['width', 'length'])\nif submitted_fields >= required_fields:\n # all required fields in submittedFields exist\nelse:\n # error handling\n\nSeveral optimizations make...
[ 6, 5, 0, 0, 0 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0008248163_python_python_3.x.txt
Q: How to signal alarm in python 2.4 after 0.5 seconds I want to timeout a particular piece of python code after in runs for 0.5 seconds. So I intend to raise an exception/signal after 0.5 seconds, and handle it gracefully and continue with rest of code. In python i know that signal.alarm() can set alarm for integer...
How to signal alarm in python 2.4 after 0.5 seconds
I want to timeout a particular piece of python code after in runs for 0.5 seconds. So I intend to raise an exception/signal after 0.5 seconds, and handle it gracefully and continue with rest of code. In python i know that signal.alarm() can set alarm for integer seconds. Is there any alternative where we can generate ...
[ "Raise the alarm from a patiently waiting \"daemon\" thread. In the code below, snoozealarm does what you want via a SnoozeAlarm thread:\n#! /usr/bin/env python\n\nimport os\nimport signal\nimport threading\nimport time\n\nclass SnoozeAlarm(threading.Thread):\n def __init__(self, zzz):\n threading.Thread.__ini...
[ 5, 2 ]
[]
[]
[ "alarm", "python", "python_2.4", "signals", "timeout" ]
stackoverflow_0008242503_alarm_python_python_2.4_signals_timeout.txt
Q: Creating Python extension with Delphi I'm trying to convert Python function to Delphi using Python4Delphi (to educate myself and to gain speed, I hope). However I've no idea how this works with Delphi and Python. Here's my original function: def MyFunc(img, curve): C = 160 for i in xrange(img.dim()[0]): p ...
Creating Python extension with Delphi
I'm trying to convert Python function to Delphi using Python4Delphi (to educate myself and to gain speed, I hope). However I've no idea how this works with Delphi and Python. Here's my original function: def MyFunc(img, curve): C = 160 for i in xrange(img.dim()[0]): p = img[i] img[i] = (p[0], p[1], p[2] - c...
[ "Python4Delphi handles the problem of loading Python's main DLL into a Delphi program, embedding the Python interpreter into your delphi application, but also has some demos for the reverse; to write an extension using Delphi. Below is some working example code.\nI found a book book reference here to writing pytho...
[ 8 ]
[]
[]
[ "delphi", "python", "python4delphi" ]
stackoverflow_0008244121_delphi_python_python4delphi.txt
Q: Checking to see if any parameters exist within function call in Pylons How can I find out the number of parameters (if any at all) that were passed in. I'm using Mako and I'm calling the template function with: ${article_util.small_article_popular(c.footer_popular_articles[0])} Within the template: <%def name="sm...
Checking to see if any parameters exist within function call in Pylons
How can I find out the number of parameters (if any at all) that were passed in. I'm using Mako and I'm calling the template function with: ${article_util.small_article_popular(c.footer_popular_articles[0])} Within the template: <%def name="small_article_popular(article)"> // check to see if any parameters were passe...
[ "Well small_article_popular(article) is effectively a Python function, so it cannot be called with no parameters, as per the signature. If you want to check if article is None, then just do that.. if article:.\n" ]
[ 1 ]
[]
[]
[ "mako", "pylons", "pyramid", "python" ]
stackoverflow_0008248081_mako_pylons_pyramid_python.txt
Q: PHP based thrift API client like thirft.apache.org example client in python I want to write PHP based thrift API client like thirft.apache.org example client in python at: http://thrift.apache.org/ I write this code: //A struture $up = UserProfile($uid=1, $name="Mark Slee", ...
PHP based thrift API client like thirft.apache.org example client in python
I want to write PHP based thrift API client like thirft.apache.org example client in python at: http://thrift.apache.org/ I write this code: //A struture $up = UserProfile($uid=1, $name="Mark Slee", $blurb="I'll find something to put here."); # Talk to a server...
[ "Look in the Thrift Wiki at the Thrift Usage page. That has examples in many supported languages, in particular, there's an example client in PHP.\n" ]
[ 2 ]
[]
[]
[ "php", "python", "thrift", "thrift_protocol" ]
stackoverflow_0008247874_php_python_thrift_thrift_protocol.txt
Q: Socket : 2 way communication in python I want a two way communication in Python : I want to bind to a socket where one client can connect to, and then server and client can "chat" with eachother. I already have the basic listener : import socket HOST='' #localhost PORT=50008 s=socket.socket(socket.AF_INET, so...
Socket : 2 way communication in python
I want a two way communication in Python : I want to bind to a socket where one client can connect to, and then server and client can "chat" with eachother. I already have the basic listener : import socket HOST='' #localhost PORT=50008 s=socket.socket(socket.AF_INET, socket.SOCK_STREAM ) #create an INET, STREAMin...
[ "Python's sockets have a makefile tool to make this sort of interaction much easier. After creating a socket s, then run f = s.makefile(). That will return an object with a file-like interface (so you can use readline, write, writelines and other convenient method calls). The Python standard library itself makes...
[ 5, 2, 2 ]
[]
[]
[ "python", "sockets" ]
stackoverflow_0008248577_python_sockets.txt
Q: Reverting local changes to a file using GItPython Is there a way under the GitPython library to revert local changes to a single file? Under the Git command line I would just use git checkout filename but attempting to do this under the GitPython API, like so repo.index.checkout([filename]) leads to the following...
Reverting local changes to a file using GItPython
Is there a way under the GitPython library to revert local changes to a single file? Under the Git command line I would just use git checkout filename but attempting to do this under the GitPython API, like so repo.index.checkout([filename]) leads to the following error, git.exc.CheckoutError: Some files could not be...
[ "Ah, figured it out a few minutes after posting by looking at the source.\nIf I turn on force by using repo.index.checkout([filename]. force=True) it works fine.\nThere may be a better way, but according to the source the force parameter is just there to overwrite local changes.\n\n:param force:\n If True,...
[ 1 ]
[]
[]
[ "git", "gitpython", "python" ]
stackoverflow_0008248969_git_gitpython_python.txt
Q: Python trying to write and read class from file but something went horribly wrong Considering this is only for my homework I don't expect much help but I just can't figure this out and honestly I can't get my head around what's going wrong. Usually I have an idea where the problem is but now I just don't get it. L...
Python trying to write and read class from file but something went horribly wrong
Considering this is only for my homework I don't expect much help but I just can't figure this out and honestly I can't get my head around what's going wrong. Usually I have an idea where the problem is but now I just don't get it. Long story short: I'm trying to create a valid looking telephone number within a class a...
[ "You said I just can't figure this out and honestly I can't get my head around what's going wrong. I think this is a great quote which sums up a large part of programming and software development in general -- dealing with crazy, weird problems and spending a lot of time trying to wrap your head around them.\nFigu...
[ 3, 1, 1, 1 ]
[]
[]
[ "python" ]
stackoverflow_0008248700_python.txt
Q: How to use action attribute of form tag in html? I am having trouble to put the right attribute in a action on <form> in HTML I plan to create a DELETE button which on clicking would prompt a alert box for confirmation. Upon receiving the right input would delete that entry. URL for deleting the file is given by ...
How to use action attribute of form tag in html?
I am having trouble to put the right attribute in a action on <form> in HTML I plan to create a DELETE button which on clicking would prompt a alert box for confirmation. Upon receiving the right input would delete that entry. URL for deleting the file is given by "deleteFile?ID=$file_name" Here is what I have develop...
[ "Sample\nhttp://jsfiddle.net/Xv2V4/2/\nIt is better not to have script in html script tags, but JSfiddle won't recognize my functions defined below.\nJS \nfunction ConfirmDelete() {\n\n /* if you need to check this ID or sth. else. */\n var fileId = document.getElementById(\"fileId\"); \n\n var user_confir...
[ 1 ]
[]
[]
[ "forms", "html", "python" ]
stackoverflow_0008249037_forms_html_python.txt
Q: setting a condition for a mixed list Maybe there was a better way to do this, but I have a list of mixed elements: outlist = [10, [ETSc, Juniper Hairstreak], [ETSc, Spotted Turtle], [ETSc, Blanding's Turtle], IWWH] What I would like to do is iterate over this list and if the list element contains ETSc,...
setting a condition for a mixed list
Maybe there was a better way to do this, but I have a list of mixed elements: outlist = [10, [ETSc, Juniper Hairstreak], [ETSc, Spotted Turtle], [ETSc, Blanding's Turtle], IWWH] What I would like to do is iterate over this list and if the list element contains ETSc, then I want to convert it to a string lik...
[ "Something like this, using a list comprehension:\n>>> input = [10, [\"ETSc\", \"Juniper Hairstreak\"], [\"ETSc\", \"Spotted Turtle\"], [\"ETSc\", \"Blanding's Turtle\"], \"IWWH\"]\n>>> output = [elt[0] + \" (\" + elt[1] + \")\" if type(elt) == list and elt[0] == \"ETSc\" else str(elt) for elt in input]\n>>> output...
[ 1, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0008249165_python.txt
Q: Inner dict ordering by key First of all, my structure is following: Collection=[ { 'somekey':'', "anotherkey":'', 'embedded':[ { 'value':'', 'ordering':1 }, { 'value':'', 'ordering':3 }, { 'value':'', ...
Inner dict ordering by key
First of all, my structure is following: Collection=[ { 'somekey':'', "anotherkey":'', 'embedded':[ { 'value':'', 'ordering':1 }, { 'value':'', 'ordering':3 }, { 'value':'', 'ordering':2 }...
[ "Items in an embedded array are stored in the order you added them. As you are sorting to the order you want before inserting then it is okay, and you can rely on this to remain constant. If you want a different order you'd need to bring the whole array back to the client and sort it there.\n" ]
[ 1 ]
[]
[]
[ "mongodb", "python" ]
stackoverflow_0008249041_mongodb_python.txt
Q: Python - How to concatenate to a string in a for loop? I need to "concatenate to a string in a for loop". To explain, I have this list: list = ['first', 'second', 'other'] And inside a for loop I need to end with this: endstring = 'firstsecondother' Can you give me a clue on how to achieve this in python? A: T...
Python - How to concatenate to a string in a for loop?
I need to "concatenate to a string in a for loop". To explain, I have this list: list = ['first', 'second', 'other'] And inside a for loop I need to end with this: endstring = 'firstsecondother' Can you give me a clue on how to achieve this in python?
[ "That's not how you do it.\n>>> ''.join(['first', 'second', 'other'])\n'firstsecondother'\n\nis what you want.\nIf you do it in a for loop, it's going to be inefficient as string \"addition\"/concatenation doesn't scale well (but of course it's possible):\n>>> mylist = ['first', 'second', 'other']\n>>> s = \"\"\n>>...
[ 74, 8, 6, 2, 1 ]
[]
[]
[ "concatenation", "for_loop", "python" ]
stackoverflow_0008249539_concatenation_for_loop_python.txt
Q: How to calculate statistical significance of conversion rate of several goals? I am making a python/django split testing or a/b testing library for my own use. However I don't know how to calculate if my test is statisically significant. I have no knowledge of statistics, so I cannot understand most wikipedia arti...
How to calculate statistical significance of conversion rate of several goals?
I am making a python/django split testing or a/b testing library for my own use. However I don't know how to calculate if my test is statisically significant. I have no knowledge of statistics, so I cannot understand most wikipedia articles, or web pages on this topic, so I'm looking for help from my fellow programmers...
[ "I believe what you need is a chi-squared test of independence. For each treatment, you have a yes count and a no count (total - yes). The method is described here, among other places.\nScipy has a function to do the hard work: http://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.chi2_contingency.html#sc...
[ 4 ]
[]
[]
[ "ab_testing", "python", "statistics" ]
stackoverflow_0008249294_ab_testing_python_statistics.txt
Q: Saving Django model from Scrapy project I have a Scrapy project and I am trying to save the output items as an object from a Django model definition (I am not using DjangoItem). I am importing Django settings as specified here. def setup_django_env(path): import imp, os from django.core.management import s...
Saving Django model from Scrapy project
I have a Scrapy project and I am trying to save the output items as an object from a Django model definition (I am not using DjangoItem). I am importing Django settings as specified here. def setup_django_env(path): import imp, os from django.core.management import setup_environ f, filename, desc = imp.fin...
[ "I had the same problem and I found a solution. At least, it worked for me.\nIn my case the problem was in Django project's setting.py file - I added not the FQN (fully qualified name) of the my app to the INSTALLED_APPS tuple, but it's short name.\nTalking about your example, it may be that you added to the INSTAL...
[ 4, 0 ]
[]
[]
[ "django", "python", "scrapy" ]
stackoverflow_0007883196_django_python_scrapy.txt
Q: Is there a library that implements a fast maximum rank correlation estimator? I'm looking for an implementation of a fast maximum rank correlation (MRC) estimator. This will be applied to large-ish sparse matrices (~100,000 by 10,000) in a text-mining application. I'm working in python and R, so it would be nice t...
Is there a library that implements a fast maximum rank correlation estimator?
I'm looking for an implementation of a fast maximum rank correlation (MRC) estimator. This will be applied to large-ish sparse matrices (~100,000 by 10,000) in a text-mining application. I'm working in python and R, so it would be nice to find something in those languages. Failing that, I could probably convert code f...
[ "The answer is no. Having read up on the subject, MRC estimators are famously hard to compute, although there is hope that maybe better algorithms could be designed.\nI'll post this answer to CV as well.\n" ]
[ 0 ]
[]
[]
[ "correlation", "max", "python", "r", "rank" ]
stackoverflow_0005636093_correlation_max_python_r_rank.txt
Q: Importing module from python makes submodules disappear I have ipython (0.12.dev) installed and I have noticed that I cannot use it in a project that has a path module because of a name collision. This is understandable, but the problem is that when I import the module full path the submodules I care about are not...
Importing module from python makes submodules disappear
I have ipython (0.12.dev) installed and I have noticed that I cannot use it in a project that has a path module because of a name collision. This is understandable, but the problem is that when I import the module full path the submodules I care about are not there. For instance, if I run this in a normal (without path...
[ "path is a third party library that IPython will try to use if it's present. Unfortunately, that means it tries to use your path module or package when that's in the working directory.\nOne simple workaround is to start IPython in another directory, and cd myproject inside IPython (but then you won't be able to use...
[ 1 ]
[]
[]
[ "ipython", "python" ]
stackoverflow_0008249793_ipython_python.txt
Q: plotting angularly-wrapped data in cartesian space with matplotlib Perhaps I've made the title more complicated than the question, but here goes...! I have some angular data, contiguous in the x-y plane, that straddle the 360 => 0 degree line - ie, 358,359,0,1,2.... If I were plotting these and setting: plt.xlim(...
plotting angularly-wrapped data in cartesian space with matplotlib
Perhaps I've made the title more complicated than the question, but here goes...! I have some angular data, contiguous in the x-y plane, that straddle the 360 => 0 degree line - ie, 358,359,0,1,2.... If I were plotting these and setting: plt.xlim(0,360) I would of course have three dots at the far left of the plot, a...
[ "I honestly think just transforming your data will be much faster. x[x>180] -= 360 is quite fast. Unless your dataset is several GB in size, the time it takes to transform your data will only be a few milliseconds. \nSo, here's the easy way (transforming your data):\nimport matplotlib.pyplot as plt\nimport numpy a...
[ 4 ]
[]
[]
[ "axes", "matplotlib", "plot", "python" ]
stackoverflow_0008248841_axes_matplotlib_plot_python.txt
Q: python (enthoughts distribution) - run example results in runtime error I recently installed the enthoughts distribution of python and started to go through the examples as outlined here http://www.enthought.com/products/epdgetstart.php?platform=mac i.e. EPD comes with a number of examples to get you started. To ...
python (enthoughts distribution) - run example results in runtime error
I recently installed the enthoughts distribution of python and started to go through the examples as outlined here http://www.enthought.com/products/epdgetstart.php?platform=mac i.e. EPD comes with a number of examples to get you started. To run the scripts in the Examples subdirectories, simply launch IPython and typ...
[ "User 'minrk' answered this question:\nAs described on the 64bit EPD download page, several GUI toolkits (definitely Wx, and I think Pyglet as well) are not functional when run in 64bit mode on EPD on OS X. It is recommended that if you want to use the GUI tools on OSX, you use 32bit EPD. – minrk\n" ]
[ 0 ]
[]
[]
[ "ipython", "python", "runtime_error" ]
stackoverflow_0008205527_ipython_python_runtime_error.txt
Q: LaunchDaemon handling system shutdown - no SIGTERM? I've written a small python script that I'm running as a LaunchDaemon to record startup/shutdown times to a remote database. When the script launches it records the startup time, then pauses and waits to catch SIGTERM to record the shutdown time. An almost identi...
LaunchDaemon handling system shutdown - no SIGTERM?
I've written a small python script that I'm running as a LaunchDaemon to record startup/shutdown times to a remote database. When the script launches it records the startup time, then pauses and waits to catch SIGTERM to record the shutdown time. An almost identical workflow is being used as a LaunchAgent for login/log...
[ "If I'm reading this right, it shouldn't use sudden termination on daemons unless you have <key>EnableTransactions</key><true/> in the launchd plist. But the docs are a little vague, so I'd also try adding <key>EnableTransactions</key><false/> to the plist, or if that doesn't work call vproc_transaction_begin fro...
[ 5 ]
[]
[]
[ "launchd", "macos", "python" ]
stackoverflow_0008248907_launchd_macos_python.txt
Q: Python: Finding a minimum value according to a dictionary So this is what I'd "like" to be able to write: cur_loc = min(open_set,key=lambda x:costs[x]) cur_loc is a tuple, and the goal is to set it equal to the tuple in open_set with the lowest cost. (and you find the cost of x with costs[x]) How could I d...
Python: Finding a minimum value according to a dictionary
So this is what I'd "like" to be able to write: cur_loc = min(open_set,key=lambda x:costs[x]) cur_loc is a tuple, and the goal is to set it equal to the tuple in open_set with the lowest cost. (and you find the cost of x with costs[x]) How could I do this? I tried Python.org's documentation on min(), but I didn...
[ "Worked for me. What's your question?\n>>> costs = { '1': 1, '2': 2, '3': 3 }\n>>> open_set = set( ['1','2'] )\n>>> min(open_set,key=lambda x:costs[x])\n'1'\n\n", "The you supplied would be correct if cost[x] was a dictionary lookup with tuples as keys. I think you may have meant to extract a field for the tupl...
[ 5, 3 ]
[]
[]
[ "a_star", "dictionary", "python" ]
stackoverflow_0008250350_a_star_dictionary_python.txt
Q: File-like wrapper for Python logging I would like to build an adaptor object which behaves like a (text) file (opened for output) and forwards each complete line given to it to standard Python logging. Which logger to use and which level to be assigned to lines logged should be specified in the ctor. Suggestions? ...
File-like wrapper for Python logging
I would like to build an adaptor object which behaves like a (text) file (opened for output) and forwards each complete line given to it to standard Python logging. Which logger to use and which level to be assigned to lines logged should be specified in the ctor. Suggestions? Code? Caveats?
[ "I've already done this, see my post about it.\nUpdate: It could be a subclass of file, but it doesn't especially support other file operations, so there's no particular need for it to be a file subclass.\nFurther update: It's up to the OP to adapt the approach in my post - you can subclass file if you like, handle...
[ 1 ]
[]
[]
[ "logging", "python" ]
stackoverflow_0008249755_logging_python.txt
Q: How can I process a tarfile with a Python multiprocessing pool? I'm trying to process the contents of a tarfile using multiprocessing.Pool. I'm able to successfully use the ThreadPool implementation within the multiprocessing module, but would like to be able to use processes instead of threads as it would possib...
How can I process a tarfile with a Python multiprocessing pool?
I'm trying to process the contents of a tarfile using multiprocessing.Pool. I'm able to successfully use the ThreadPool implementation within the multiprocessing module, but would like to be able to use processes instead of threads as it would possibly be faster and eliminate some changes made for Matplotlib to handle...
[ "You're not passing a TarInfo object into the other process, you're passing the result of tar.extractfile(member) into the other process where member is a TarInfo object. The extractfile(...) method returns a file-like object which has, among other things, a read() method which operates upon the original tar file y...
[ 7 ]
[]
[]
[ "multiprocessing", "python", "tarfile" ]
stackoverflow_0008250264_multiprocessing_python_tarfile.txt
Q: how to run python in iphone? Possible Duplicate: Can I write native iPhone apps using Python this post Can I write native iPhone apps using Python is 3 years old, i think there should be a new one, since the old one comes very frequently in Google searches. this post http://www.saurik.com/id/5 is looking good an...
how to run python in iphone?
Possible Duplicate: Can I write native iPhone apps using Python this post Can I write native iPhone apps using Python is 3 years old, i think there should be a new one, since the old one comes very frequently in Google searches. this post http://www.saurik.com/id/5 is looking good and is seems to be up to date. i th...
[ "You cannot run python on the iphone. There maybe a way if the iphone is jailbroken but that's not something I would bet on when writing a program.\nYou may need to write your iphone app using objective C and, if you really want to use python, can connect it to a python web service(i.e. you run python on your serv...
[ 1 ]
[]
[]
[ "iphone", "python" ]
stackoverflow_0008249900_iphone_python.txt
Q: What exactly is happening when I copy and then edit this list? I cannot figure out at all why this is happening: A = [[1,0], [2,2]] B = list(A) print('start A:', A, 'start B:', B) A[0][0] = 999 print('end A:', A, 'end B:', B) This returns: start A: [[1, 0], [2, 2]] start B: [[1, 0], [2, 2]] end A: [[999, 0], [2,...
What exactly is happening when I copy and then edit this list?
I cannot figure out at all why this is happening: A = [[1,0], [2,2]] B = list(A) print('start A:', A, 'start B:', B) A[0][0] = 999 print('end A:', A, 'end B:', B) This returns: start A: [[1, 0], [2, 2]] start B: [[1, 0], [2, 2]] end A: [[999, 0], [2, 2]] end B: [[999, 0], [2, 2]] The lists A and B end up being the s...
[ "You are creating a shallow copy of the original list, that is a new list containing new references to the same objects as the original list.\nModifying the new list object does not alter the original list. Modifying the objects in the new list does modify the objects in the old list because they are the same.\nTo...
[ 3, 2, 1, 1, 1 ]
[]
[]
[ "list", "python", "python_3.x" ]
stackoverflow_0008249778_list_python_python_3.x.txt
Q: How to write to a spreadsheet in python3.2? I am currently writing a script where I want to take the data and write it to a spreadsheet. I've found a few modules for writing xls files, however those only seem to work up to python 2.x, and I'm using 3.2 (also on a mac if that's helpful). Anyone have any ideas on ho...
How to write to a spreadsheet in python3.2?
I am currently writing a script where I want to take the data and write it to a spreadsheet. I've found a few modules for writing xls files, however those only seem to work up to python 2.x, and I'm using 3.2 (also on a mac if that's helpful). Anyone have any ideas on how to get a python3.2 script to output to a spread...
[ "Use the csv module. The intro from the docs:\n\nThe csv module implements classes to read and write tabular data in\n CSV format. It allows programmers to say, “write this data in the\n format preferred by Excel,” or “read data from this file which was\n generated by Excel,” without knowing the precise details...
[ 2, 0 ]
[]
[]
[ "csv", "excel", "module", "python", "python_3.2" ]
stackoverflow_0008251039_csv_excel_module_python_python_3.2.txt
Q: Catching a Python exception in C++ I am developing a server-client application in which the client calls a server's API which gives a Python interface for user input. It means the client interface and server interface is written in Python whereas the socket code is in C++. On the server side:- I have a class, Test...
Catching a Python exception in C++
I am developing a server-client application in which the client calls a server's API which gives a Python interface for user input. It means the client interface and server interface is written in Python whereas the socket code is in C++. On the server side:- I have a class, Test, in C++ and this class is inherited in ...
[ "To do this you basically need to write a %feature(\"director:except\") that can handle a Python exception and re-throw it as a C++ one. Here's a small but complete example:\nSuppose we have the following header file we wish to wrap:\n#include <iostream>\n#include <exception>\n\nclass MyException : public std::exce...
[ 3 ]
[]
[]
[ "c++", "exception", "python", "swig" ]
stackoverflow_0008084353_c++_exception_python_swig.txt
Q: python oauth 2.0 new fbsr facebook cookie, error validating verification code I'm trying to use the new fbsr_{{appID}} cookie. I'm using the following functions to parse it, but when I try to get the access_token afterwards, I get 'error validating verification code' message. Is something wrong with these parsing ...
python oauth 2.0 new fbsr facebook cookie, error validating verification code
I'm trying to use the new fbsr_{{appID}} cookie. I'm using the following functions to parse it, but when I try to get the access_token afterwards, I get 'error validating verification code' message. Is something wrong with these parsing functions? If not, what could be the problem? more info: I managed to log users in ...
[ "There is a modified version of the facebook python SDK which supports OAuth 2.0 and parsing of the fbsr_ cookie on github here:\nhttps://gist.github.com/1190267\nYou can look into the code to see how to parse the cookie or just let that file do the work for you.\n", "I had to programetically expire the cookie fo...
[ 10, 0 ]
[]
[]
[ "facebook_oauth", "google_app_engine", "python" ]
stackoverflow_0007585488_facebook_oauth_google_app_engine_python.txt
Q: How to Get The field value dynamically in python? I have a form view. I entered a value in a field. How can i retrieve that value and have it assigned to some variable in .py for making operations For Example: I have ActiveFrom field.I entered value 23-11-2011 to field in form view. I want to get that value dynami...
How to Get The field value dynamically in python?
I have a form view. I entered a value in a field. How can i retrieve that value and have it assigned to some variable in .py for making operations For Example: I have ActiveFrom field.I entered value 23-11-2011 to field in form view. I want to get that value dynamically in openerp. How can I do that?
[ "I suspect you want the on_change event. It lets you trigger server-side code when the user changes a field's value. You can then change the value of other fields, or pop up a warning message.\nHere's an example of how to pop up a warning from the warning module (slightly edited):\ndef onchange_partner_id(self, cr,...
[ 1 ]
[]
[]
[ "openerp", "postgresql_9.1", "python" ]
stackoverflow_0008239432_openerp_postgresql_9.1_python.txt
Q: how to get all possible combination of items from 2-dimensional list in python? I didn't find a better way to phrase this question in the title. If you can, please edit. I have a list of lists like this: a = [['a','b'],[1,2]] now, I'd like a function that spits out all possible combination like this: [['a',1],['a...
how to get all possible combination of items from 2-dimensional list in python?
I didn't find a better way to phrase this question in the title. If you can, please edit. I have a list of lists like this: a = [['a','b'],[1,2]] now, I'd like a function that spits out all possible combination like this: [['a',1],['a',2],['b',1],['b',2]] where nor the number of lists in a is known in advance, nor is...
[ "You need itertools.product():\n>>> list(itertools.product(*a))\n[('a', 1), ('a', 2), ('b', 1), ('b', 2)]\n\n", "This may be what itertools.product() (which Sven mentions) does:\ndef combs(list1, list2):\n results = []\n for x in list1:\n for y in list2:\n l.append([x,y])\n return resul...
[ 13, 0, 0 ]
[]
[]
[ "combinatorics", "list", "python" ]
stackoverflow_0008249836_combinatorics_list_python.txt
Q: Read a zip an write it to an other file python I want to read a file and write it back out. Here's my code: file = open( zipname , 'r' ) content = file.read() file.close() alt = open('x.zip', 'w') alt.write(content ) alt.close() This doesn't work, why????? Edit: The rewritten file is corrupt...
Read a zip an write it to an other file python
I want to read a file and write it back out. Here's my code: file = open( zipname , 'r' ) content = file.read() file.close() alt = open('x.zip', 'w') alt.write(content ) alt.close() This doesn't work, why????? Edit: The rewritten file is corrupt (python 2.7.1 on windows)
[ "Read and write in the binary mode, 'rb' and 'wb':\nf = open(zipname , 'rb')\ncontent = f.read() \nf.close()\n\nalt = open('x.zip', 'wb')\nalt.write(content )\nalt.close()\n\nThe reason the text mode didn't work on Windows is that the newline translation from '\\r\\n' to '\\r' mangled the binary data in the zip fi...
[ 9, 6, 1 ]
[]
[]
[ "python", "zip" ]
stackoverflow_0008251387_python_zip.txt
Q: Making "durable" objects I'm programming a complex tree structure in Python and I'm tired of creating tree objects and filling them with data everytime I run the code. So, is there a way to make your objects "durable" in Python. With "durable" I mean if there is a way to save all my objects as bytes in a file, so ...
Making "durable" objects
I'm programming a complex tree structure in Python and I'm tired of creating tree objects and filling them with data everytime I run the code. So, is there a way to make your objects "durable" in Python. With "durable" I mean if there is a way to save all my objects as bytes in a file, so when I run the code again, I c...
[ "You can use the pickle module to serialize your data (which is the general phrase for turning your in-memory representation into something that can be written to disk). You read more in the Python documentation.\nThe simplest code looks like this to store your object in a file:\npickle.dump(myobject, open('myfile...
[ 5, 1 ]
[]
[]
[ "python", "store" ]
stackoverflow_0008251549_python_store.txt
Q: HTTPForbidden context route not firing I'm having a bit of trouble getting security in Pyramid to work properly. My security itself seems to be working: if a user attempts to access a resource they are not authorized to view, Pyramid throws an HTTPForbidden exception. The problem is that in this instance, it's sup...
HTTPForbidden context route not firing
I'm having a bit of trouble getting security in Pyramid to work properly. My security itself seems to be working: if a user attempts to access a resource they are not authorized to view, Pyramid throws an HTTPForbidden exception. The problem is that in this instance, it's supposed to fall back to the login view, which ...
[ "This is probably unrelated to your problem, but the way a class-based view works in Pyramid is that it's a 2-step process. 1) Pyramid instantiates your class with the request object 2) Pyramid calls either the __call__ method or a method specified by attr in view_config. Thus, the call to self.__call__() in your _...
[ 1, 0, 0 ]
[]
[]
[ "authentication", "pyramid", "python" ]
stackoverflow_0007773851_authentication_pyramid_python.txt
Q: Is there a way to move a window to another monitor using Python? I need to get a handle to a Window and then move it to my secondary monitor. Is this doable with python 2.6, preferably using the standard libraries. A: Use the pywin32 module to access the native Win32 API. The functions you'll need to use are: ...
Is there a way to move a window to another monitor using Python?
I need to get a handle to a Window and then move it to my secondary monitor. Is this doable with python 2.6, preferably using the standard libraries.
[ "Use the pywin32 module to access the native Win32 API. The functions you'll need to use are:\n\nEnumWindows to enumerate all of the top-level windows in the system; search for the one you want and save off the window handle\nEnumDisplayMonitors to enumerate all of the monitors in the system\nGetMonitorInfo to get...
[ 15 ]
[]
[]
[ "python", "windows" ]
stackoverflow_0008251712_python_windows.txt
Q: Using Django templates for Google App Engine to access an entity with specific ReferenceProperty value from a list of entities I have been struggling with a problem in Google App Engine and Django and have not been able to locate the solution (despite finding similar problems). Let me set the scene a bit. I have ...
Using Django templates for Google App Engine to access an entity with specific ReferenceProperty value from a list of entities
I have been struggling with a problem in Google App Engine and Django and have not been able to locate the solution (despite finding similar problems). Let me set the scene a bit. I have the following three entities: Contributor: user = db.UserProperty() Question: contributor = db.ReferenceProperty(Contributo...
[ "The best way to do this is to do the processing in your Python code, and pass in a list of dicts that contain just the relevant information to your Django template. This also means you can take advantage of hacks like reference property prefetching to minimize the number of RPCs you have to do.\n" ]
[ 0 ]
[]
[]
[ "django", "django_models", "django_templates", "google_app_engine", "python" ]
stackoverflow_0008251807_django_django_models_django_templates_google_app_engine_python.txt
Q: Accessing Django Runserver on Shared Hosting I'm developing a Django application on a shared hosting service (hostmonster) and am, of course, unable to access the runserver on the default localhost ip of 127.0.0.1:8000 over Firefox. The Django Project site's documentation details how to set up remote access to the...
Accessing Django Runserver on Shared Hosting
I'm developing a Django application on a shared hosting service (hostmonster) and am, of course, unable to access the runserver on the default localhost ip of 127.0.0.1:8000 over Firefox. The Django Project site's documentation details how to set up remote access to the run-server, but I'm not having any success with t...
[ "Other comments about (not) using runserver on production environments apply.\nIf you really must run it this way I would recommend using SSH tunnelling, via the -L switch.\ne.g. ssh -L 8888:127.0.0.1:8000 <user>@<remotehost>\nThen you should be able to view the site on your local machine via http://localhost:8888\...
[ 6, 3, 0, 0 ]
[]
[]
[ "django", "django_admin", "python", "shared_hosting", "timeout" ]
stackoverflow_0008250936_django_django_admin_python_shared_hosting_timeout.txt
Q: What is the DRAG mouse stock cursor ID, wxpython? ive looked through the wxpython website however I do not believe it has the stock cursor ID for drag. Here is an image of the cursor: http://helpcentral.componentone.com/nethelp/truedbgrid8/ImagesExt/image19_31.gif Thanks A: Cursor availability depends on OS. In...
What is the DRAG mouse stock cursor ID, wxpython?
ive looked through the wxpython website however I do not believe it has the stock cursor ID for drag. Here is an image of the cursor: http://helpcentral.componentone.com/nethelp/truedbgrid8/ImagesExt/image19_31.gif Thanks
[ "Cursor availability depends on OS. In Windows, None of the available cursor images correspond to the one you want. You can use the wxPython demo to check it for your OS (Demos -> Using images -> Cursor) although apparently there is no cursor with a promising name such as wx.DRAG_CURSOR.\nHowever it is very easy to...
[ 1 ]
[]
[]
[ "python", "wxpython" ]
stackoverflow_0008250156_python_wxpython.txt
Q: Pygame move object position from one point to another at constant speed I have a bunch of objects at different coordinates, and I need to animate them moving to another coordinate ie. one object is at coodinate (234,30) and I need it to go to (310,540). How do I do this in pygame? I tried messing around with slop...
Pygame move object position from one point to another at constant speed
I have a bunch of objects at different coordinates, and I need to animate them moving to another coordinate ie. one object is at coodinate (234,30) and I need it to go to (310,540). How do I do this in pygame? I tried messing around with slope and stuff like that but I couldn't get my object,s position to smoothly go ...
[ "Well, you should just change it's coordinates in your game loop.\nThere's two ways you can do this. \nFirst, for example, if you want your object to move 50px per second, you should send your update function ticks in every frame, and then change your object's x and y coordinates by x + x_speed * ticks / 1000 (here...
[ 4 ]
[]
[]
[ "animation", "pygame", "python" ]
stackoverflow_0008252860_animation_pygame_python.txt
Q: Chameleon Templating: Default value in 'tal:switch' I am trying to build a switch/case structure around a range of integer values. As stated in the language reference, if the case expression is the symbol default, it always matches the switch. However, I am looking for a symbol that matches in all cases except for...
Chameleon Templating: Default value in 'tal:switch'
I am trying to build a switch/case structure around a range of integer values. As stated in the language reference, if the case expression is the symbol default, it always matches the switch. However, I am looking for a symbol that matches in all cases except for the ones listed above the symbol... <ul tal:switch="i"> ...
[ "True. There's no sense in the docs, because \"default\" will always match. It's a bug!\nPlease someone report it on the Github tracker.\n", "I'm fairly certain the symbol needs to be in the namespaced case statement or the parser will just ignore the symbol you put in there.\n<ul tal:switch=\"i\">\n <li tal:cas...
[ 3, 0 ]
[]
[]
[ "chameleon", "python", "switch_statement", "template_engine" ]
stackoverflow_0008230502_chameleon_python_switch_statement_template_engine.txt
Q: escaping sqlite results Given the following input string: (?i:\bsys\.user_catalog\b) Stored into sqlite TEXT field. When retrieved with select, I get the following: When doing simple command line, e.g. $ sqlite3 databse.name "select a from b" > file.results It appear in the editor like this: When I use, python...
escaping sqlite results
Given the following input string: (?i:\bsys\.user_catalog\b) Stored into sqlite TEXT field. When retrieved with select, I get the following: When doing simple command line, e.g. $ sqlite3 databse.name "select a from b" > file.results It appear in the editor like this: When I use, python's sqlite3 lib, it prints out...
[ "A couple of ideas:\n\nMake sure the string was originally input as raw so that the escaping doesn't take place before you store it.\nI think TEXT will work as well as BLOB but you may have to confirm by experiment.\nStore as a buffer object: c.execute('INSERT INTO documents VALUES (?, ?)', (somekey, buffer(yourst...
[ 1 ]
[]
[]
[ "escaping", "python", "sqlite" ]
stackoverflow_0008253159_escaping_python_sqlite.txt
Q: What are the >> and << operators in Python? What are >> and << for? I read this in code: https://github.com/mlaiosa/emlx2maildir/blob/master/emlx2maildir.py FL_READ = (1<<0) FL_DELETED = (1<<1) FL_ANSWERED = (1<<2) FL_ENCRYPTED = (1<<3) FL_FLAGGED = (1<<4) FL_RECENT = (1<<5) FL_DRAFT = (1<<6) FL_INITIAL = (1<<7) F...
What are the >> and << operators in Python?
What are >> and << for? I read this in code: https://github.com/mlaiosa/emlx2maildir/blob/master/emlx2maildir.py FL_READ = (1<<0) FL_DELETED = (1<<1) FL_ANSWERED = (1<<2) FL_ENCRYPTED = (1<<3) FL_FLAGGED = (1<<4) FL_RECENT = (1<<5) FL_DRAFT = (1<<6) FL_INITIAL = (1<<7) FL_FORWARDED = (1<<8) FL_REDIRECTED = (1<<9) FL_SI...
[ "It's bitshift operator. If you have a 1(0b1), and shift it left 4 bits(1 << 4), what you get is 0b10000, which means 16.\nAnd here's the documentation: http://docs.python.org/reference/expressions.html#shifting-operations\n", "The operators are defined in section 5.7, \"Shifting Operations\", of the Python Langu...
[ 4, 2, 1 ]
[]
[]
[ "bitwise_operators", "operators", "python" ]
stackoverflow_0008253211_bitwise_operators_operators_python.txt
Q: Problems with logging setup in bootstrapped Pyramid I am trying to do simple file logging config in pyramid, with python 2.7.2 and pyramid 1.2.3 It isn't working at all how I expected. It looks like even though i'm bootstrapping into pyramid, it isn't loading the right logs. Specific problems below within test.p...
Problems with logging setup in bootstrapped Pyramid
I am trying to do simple file logging config in pyramid, with python 2.7.2 and pyramid 1.2.3 It isn't working at all how I expected. It looks like even though i'm bootstrapping into pyramid, it isn't loading the right logs. Specific problems below within test.py: test.py from pyramid.paster import bootstrap env = boo...
[ "Pyramid doesn't load the logging configuration when bootstrapping. If you want to make an argument that it should, please open a ticket at https://github.com/Pylons/pyramid/issues\nRegardless, it's pretty simple to load the logging information yourself:\nimport logging\nimport logging.config\nfrom pyramid.paster i...
[ 9 ]
[]
[]
[ "pyramid", "python" ]
stackoverflow_0008253334_pyramid_python.txt
Q: View Variables in Python Is there a way to view a list of all of my variables in python while the program is running without setting breakpoints? Printing is too messy because I have a lot of variables that are constantly changing. Thanks A: Maybe inspect helps you, but you have to filter the information then. ...
View Variables in Python
Is there a way to view a list of all of my variables in python while the program is running without setting breakpoints? Printing is too messy because I have a lot of variables that are constantly changing. Thanks
[ "Maybe inspect helps you, but you have to filter the information then. \nUsage like:\n> import inspect\n> a = 5\n> f = inspect.currentframe()\n> print f.f_locals\n...\n...\n'a': 5\n...\n\nMaybe it's worth to mention that you cannot iterate over the resulting dictionary in a for loop because asignment to a variable ...
[ 5, 2, 1, 1 ]
[]
[]
[ "debugging", "python" ]
stackoverflow_0008253475_debugging_python.txt
Q: Python itertools.combinations() memory problems I'm processing a huge number of combinations of items (from League of Legends), about 72 million, all of which are fed into a function that calculates how beneficial they are. We're trying to find the best possible combination. Ignoring the fact that there might be b...
Python itertools.combinations() memory problems
I'm processing a huge number of combinations of items (from League of Legends), about 72 million, all of which are fed into a function that calculates how beneficial they are. We're trying to find the best possible combination. Ignoring the fact that there might be better ways, algorithmically speaking, to do this, can...
[ "Combinations creates a pool by consuming the whole iterator provided. There is no way around that. See the pseudocode in the docs for the function: http://docs.python.org/library/itertools.html#itertools.combinations\n" ]
[ 0 ]
[]
[]
[ "combinatorics", "python", "python_itertools" ]
stackoverflow_0008253227_combinatorics_python_python_itertools.txt
Q: Python Static Variable I'm creating an application that uses a base class to hold all of the configuration values, import methods, etc. / - application.py + class foo + config = None + def loadconfig - otherfile.py + class bar + def getconfigvalue So, if I start...
Python Static Variable
I'm creating an application that uses a base class to hold all of the configuration values, import methods, etc. / - application.py + class foo + config = None + def loadconfig - otherfile.py + class bar + def getconfigvalue So, if I start application.py and it runs ...
[ "I'll work from what I believe your issue is with asgard, because your simplified example is broken:\n\nYou can't run main.py because of a circular import, yet I believe it was main.py you intended to be running (running otherfile.py won't exhibit the problem I believe you're running into).\nYou're never actually a...
[ 4 ]
[]
[]
[ "python", "python_3.x", "static_variables" ]
stackoverflow_0008253095_python_python_3.x_static_variables.txt
Q: pretty print assertEqual() for HTML strings I want to compare two strings in a python unittest which contain html. Is there a method which outputs the result in a human friendly (diff like) version? A: A simple method is to strip whitespace from the HTML and split it into a list. Python 2.7's unittest (or the ba...
pretty print assertEqual() for HTML strings
I want to compare two strings in a python unittest which contain html. Is there a method which outputs the result in a human friendly (diff like) version?
[ "A simple method is to strip whitespace from the HTML and split it into a list. Python 2.7's unittest (or the backported unittest2) then gives a human-readable diff between the lists.\nimport re\n\ndef split_html(html):\n return re.split(r'\\s*\\n\\s*', html.strip())\n\ndef test_render_html():\n expected = ['...
[ 3, 2, 1, 1 ]
[]
[]
[ "html", "python", "testing", "unit_testing" ]
stackoverflow_0008006909_html_python_testing_unit_testing.txt
Q: Unable to install pymongo I am unable to install pymongo using easy_install on python 3.2. c:\Python32\Scripts>easy_install pymongo ... Processing pymongo-2.0.1.tar.gz Running pymongo-2.0.1\setup.py -q bdist_egg --dist-dir c:\users\rajesh\appdata\l ocal\temp\easy_install-dflvnv\pymongo-2.0.1\egg-d...
Unable to install pymongo
I am unable to install pymongo using easy_install on python 3.2. c:\Python32\Scripts>easy_install pymongo ... Processing pymongo-2.0.1.tar.gz Running pymongo-2.0.1\setup.py -q bdist_egg --dist-dir c:\users\rajesh\appdata\l ocal\temp\easy_install-dflvnv\pymongo-2.0.1\egg-dist-tmp-m35zko Traceback (m...
[ "There is no official PyMongo for Python 3.\nIs there an equivalent of PyMongo for Python 3.2?\nAs noted there though, there is a semi official port, available on PyPI as pymongo3: http://pypi.python.org/pypi/pymongo3\n", "Try this\neasy_install pymongo3\n\n" ]
[ 0, 0 ]
[]
[]
[ "mongodb", "python", "python_3.x" ]
stackoverflow_0008252294_mongodb_python_python_3.x.txt
Q: Developing and Publishing Custom Django Modules How should I create a Django app for 3rd party use? I've been hacking on something lately and I'd like to put it up on GitHub and let it loose. How should I structure it? Is there a way I can use it without having to store an entire Django project around it in the re...
Developing and Publishing Custom Django Modules
How should I create a Django app for 3rd party use? I've been hacking on something lately and I'd like to put it up on GitHub and let it loose. How should I structure it? Is there a way I can use it without having to store an entire Django project around it in the repository? How can I test it locally inside of another...
[ "James Bennett in DjangoCon 2008 talked about how to develop reusable django applications which are well de-coupled and can be dropped into different projects. You can watch the talk here. He explains some good practices to follow for doing so. You can also look into some popular existing external apps (some by Jam...
[ 6 ]
[]
[]
[ "django", "python" ]
stackoverflow_0008254206_django_python.txt
Q: python raw string assignment Given a file contains lines such as: (?i:\bsys\.user_catalog\b) While reading those line, I want the value to be a raw string (unescaped), meaning, in memory, line should be r'(?i:\bsys\.user_catalog\b)' instead of (?i:\bsys\.user_catalog\b) Which is escaped when passed over to li...
python raw string assignment
Given a file contains lines such as: (?i:\bsys\.user_catalog\b) While reading those line, I want the value to be a raw string (unescaped), meaning, in memory, line should be r'(?i:\bsys\.user_catalog\b)' instead of (?i:\bsys\.user_catalog\b) Which is escaped when passed over to libs such as sqlobject. For instance...
[ "The raw string notation is only used in Python source code; all strings declared as raw strings are \"converted\" to normal strings with the necessary escape sequences added during \"compile time\" (unlike (in Python 2) the two different string types string/Unicode string):\n>>> r\"\\b\"\n'\\\\b'\n>>> \"Hello\"\n'...
[ 8, 2, 1 ]
[]
[]
[ "python", "sqlobject", "string" ]
stackoverflow_0008254218_python_sqlobject_string.txt
Q: Configuring SCons to use separate tools for code generation and assembly I am trying to prepare a build system using SCons. I want to use clang for the code generation phase and a custom compiler toolchain for everything else. By default, the SCons configuration does not have an explicit step in which the assembly...
Configuring SCons to use separate tools for code generation and assembly
I am trying to prepare a build system using SCons. I want to use clang for the code generation phase and a custom compiler toolchain for everything else. By default, the SCons configuration does not have an explicit step in which the assembly (.s) files are generated. In order to get around this, I created my own Build...
[ "There are a large number of keyword arguments for the Builder class that are documented on the SCons man page, that aren't mentioned in the user manual. This is one of the weak points in the documentation for SCons, and has been for some time.\nIn this case, I believe you are looking for the single_source keyword ...
[ 3 ]
[]
[]
[ "build", "clang", "code_generation", "python", "scons" ]
stackoverflow_0008253443_build_clang_code_generation_python_scons.txt
Q: The best tools for working with Google App Engine Python I'm an existing C# (ASP.NET MVC 3 years +), C++, Javascript developer, and have done a bit of Python development in my time. I'm looking to take on a Google App Engine Python project and essentially I feel a bit lost without a decent integrated IDE experienc...
The best tools for working with Google App Engine Python
I'm an existing C# (ASP.NET MVC 3 years +), C++, Javascript developer, and have done a bit of Python development in my time. I'm looking to take on a Google App Engine Python project and essentially I feel a bit lost without a decent integrated IDE experience + Data Management tool with GUI. Is GAE just for hardcore de...
[ "I have used both Wing IDE Pro and PyCharm. Both are great lightweight IDEs but for me Pycharm is the winner for Google App Engine development. It has built in support for GAE.\n", "Get the python plugin for google app engine from http://pydev.org/. It supportS direct deployment to appengine from eclipse. It's ...
[ 3, 1, 0 ]
[]
[]
[ "debugging", "google_app_engine", "ide", "python" ]
stackoverflow_0008250330_debugging_google_app_engine_ide_python.txt
Q: Memory problems while code is running (Python, Networkx) I made a code for generate a graph with 379613734 edges. But the code couldn't be finished because of memory. It takes about 97% of server memory when it go through 62 million lines. So I killed it. Do you have any idea to solve this problem? My code is like...
Memory problems while code is running (Python, Networkx)
I made a code for generate a graph with 379613734 edges. But the code couldn't be finished because of memory. It takes about 97% of server memory when it go through 62 million lines. So I killed it. Do you have any idea to solve this problem? My code is like this: import os, sys import time import networkx as nx G = ...
[ "First, you should consider whether you could just add more RAM. Make some estimates of memory usage, either by calculating based on the data you have or by reading in subsamples of the data of various sizes to measure how things scale. The modest cost of a few GB of RAM might spare you lots of time and trouble.\nS...
[ 7, 6 ]
[]
[]
[ "networkx", "python" ]
stackoverflow_0008252954_networkx_python.txt
Q: Does using funcName when logging in Python have any performance impact? Was just looking at the logging docs in Python and came across funcName as a parameter in the log formatter. While it looks handy, great way to see exactly where the log is coming from obviously, someone's raised a concern about it, possibly t...
Does using funcName when logging in Python have any performance impact?
Was just looking at the logging docs in Python and came across funcName as a parameter in the log formatter. While it looks handy, great way to see exactly where the log is coming from obviously, someone's raised a concern about it, possibly that it would need to generate a stack trace that would be a performance hit. ...
[ "Resist the temptation to guess, the source for logging is available to you as part of your Python distribution.\nHow it finds the function name (logging/__init__.py):\n#\n# _srcfile is used when walking the stack to check when we've got the first\n# caller stack frame.\n#\nif hasattr(sys, 'frozen'): #support for p...
[ 4, 1 ]
[]
[]
[ "logging", "performance", "python" ]
stackoverflow_0008254353_logging_performance_python.txt
Q: Can I serve generated images without storing them on the server side? I have a form where the user uploads two images, and based on them I generate about 10 other images ( using PIL ). The thing is, I want to show an HTML page that contains all the generated images, but I would like not to have to store them on se...
Can I serve generated images without storing them on the server side?
I have a form where the user uploads two images, and based on them I generate about 10 other images ( using PIL ). The thing is, I want to show an HTML page that contains all the generated images, but I would like not to have to store them on server side. Is this possible?
[ "You could use the Data URI scheme. The examples section on that Wikipedia article has some nice things to start with. What you need then, is to convert the binary image data to base64 so you can include it on your page. Fortunately, there are scripts available for this already.\nBrowser support seems okay, all maj...
[ 2, 1 ]
[]
[]
[ "django", "python" ]
stackoverflow_0008254677_django_python.txt
Q: retrieve data from a column in mysql As I know, the SELECT syntax is used for getting data from a row instead of column, here I have a column called time in a table, and I just want to select all the data in this time column, put them in an array, and use this array later. So how can I select a column of data and ...
retrieve data from a column in mysql
As I know, the SELECT syntax is used for getting data from a row instead of column, here I have a column called time in a table, and I just want to select all the data in this time column, put them in an array, and use this array later. So how can I select a column of data and put them into an array?
[ "The query: SELECT time FROM Table\nUse this query to populate an array in python!\ndb = MySQLdb.connect(user=\"yourUser\",passwd=\"1337\",db=\"awesomeDB\")\ncursor = db.cursor()\nresultSet = \"SELECT time FROM tableX\"\ncursor.execute(resultSet)\nfor row in cursor\n#do something here, maybe add to an array if you ...
[ 2 ]
[]
[]
[ "mysql", "python" ]
stackoverflow_0008255190_mysql_python.txt
Q: Find specific variables inside a function and return them sorted first of all, thank you for your help in forward. I'm using Python and I'm trying to search a .py file for all of its functions starting with the name "test_" and all of the variables included. The variables I search for are formatted like this: "va...
Find specific variables inside a function and return them sorted
first of all, thank you for your help in forward. I'm using Python and I'm trying to search a .py file for all of its functions starting with the name "test_" and all of the variables included. The variables I search for are formatted like this: "var["blabla"]". So here I have an example: def test_123: init = var[...
[ "This program will help you with the first part of your question, namely finding all functions that start with test_. You might expand it to find variable definitions of your choice as well, but this is a little more complicated.\nThe basic idea is to use the ast package to parse your Python source, and scan the re...
[ 1, 0, 0 ]
[]
[]
[ "function", "python", "sorting", "variables" ]
stackoverflow_0008254266_function_python_sorting_variables.txt
Q: print and format output I have a simple script: now = datetime.datetime.now() print "%d%d%d%d%d" % ( now.year, now.month, now.day, now.hour, now.minute ) result: 20111124149 How to get result: 201111241409 ? A: Method one: use %02d instead of %d. This pads up to width two with leading zeros. print "%02d%02d%0...
print and format output
I have a simple script: now = datetime.datetime.now() print "%d%d%d%d%d" % ( now.year, now.month, now.day, now.hour, now.minute ) result: 20111124149 How to get result: 201111241409 ?
[ "Method one: use %02d instead of %d. This pads up to width two with leading zeros.\nprint \"%02d%02d%02d%02d%02d\" % (now.year, now.month, now.day, now.hour, now.minute)\n\nMethod two, the correct way: use datetime.strftime.\nprint now.strftime('%Y%m%d%H%M')\n\nFor explanation of the format string, see strftime() a...
[ 7, 4, 1, 1 ]
[]
[]
[ "python" ]
stackoverflow_0008255309_python.txt
Q: web ERP in django where do i start? I'm a computer science student doing my bachelor's degree. i'm interested in doing an simple application like an ERP in django. I've got about a month of time don't know where do i start. please do give in your opinion. A: There's a Django Book It's an awsome introductory mat...
web ERP in django where do i start?
I'm a computer science student doing my bachelor's degree. i'm interested in doing an simple application like an ERP in django. I've got about a month of time don't know where do i start. please do give in your opinion.
[ "There's a Django Book It's an awsome introductory material.\nLike @pace says (vote up!) the django tutorial is fine too (although the rest of the documentation assumes you have all the time of the world to comprehend it)\nBut my recommendation is take a look at python first. Not too deep, but enough to know what a...
[ 6, 5, 2, 1 ]
[]
[]
[ "django", "python", "web_applications" ]
stackoverflow_0002209125_django_python_web_applications.txt
Q: How to link python program with twisted python? I have to do a program of multiclient chat server in python using twisted python. I don't know, how to link it with that library. Can anybody tell the answer, please? Is there a need to implement separate client and server programs for multiclient chat server as in ...
How to link python program with twisted python?
I have to do a program of multiclient chat server in python using twisted python. I don't know, how to link it with that library. Can anybody tell the answer, please? Is there a need to implement separate client and server programs for multiclient chat server as in socket programming in C?
[ "As suggested by Chris Morgan, I add this as an answer.\nYou don't \"link\" python packages, you \"import\" them. May I suggest the Python module tutorial?\n" ]
[ 3 ]
[]
[]
[ "python" ]
stackoverflow_0008253212_python.txt
Q: automatically import module when run python script? I think other may ask this before but I cannot find it. My question is, I have these statements in my .ipython/ipy_user_conf.py: ip.ex('import matplotlib as mat') ip.ex('import matplotlib.pyplot as plt') ip.ex('import numpy as np') ip.ex('import pupynere as pu') ...
automatically import module when run python script?
I think other may ask this before but I cannot find it. My question is, I have these statements in my .ipython/ipy_user_conf.py: ip.ex('import matplotlib as mat') ip.ex('import matplotlib.pyplot as plt') ip.ex('import numpy as np') ip.ex('import pupynere as pu') ip.ex('import g') ip.ex('import bsite') ip.ex('import csv...
[ "It's bad practice to have a script which depends on an external startup script to make it work. Doing these imports is how you should do it.\nYou could simplify it if you regularly import a fairly large set of things by centralising your imports in a file (call it common_imports.py, for example), and then importin...
[ 3, 1 ]
[]
[]
[ "import", "module", "python" ]
stackoverflow_0008255593_import_module_python.txt
Q: does choosing these: django + smartGWT seems like the good way to go? I want to develop web sites rapidly with good looking easy to use components when needed. I like python and java both (each with its own strengths). from my small research it looks to me like i would like to use django for the general web sites ...
does choosing these: django + smartGWT seems like the good way to go?
I want to develop web sites rapidly with good looking easy to use components when needed. I like python and java both (each with its own strengths). from my small research it looks to me like i would like to use django for the general web sites framework (models, views, some generic apps like login, registration, comme...
[ "I have been developing a Django + GWT site for the last 6 months. The last 6 weeks have been with a designer.\nDjango and GWT are both excellent ways of working. I'm really impressed with both... but if your key objective is \"VERY easy integration\", they might not be a good match.\nDjango's default templating is...
[ 0 ]
[]
[]
[ "java", "python", "web_applications" ]
stackoverflow_0008253530_java_python_web_applications.txt
Q: How can I "map" a dict to change only the values in Python I have a dict like this: food_to_food_type = {"apple": "fruit", "green bean": "vegetable", "tomato": "controversial"} I have a function that wants a dict where keys are food types and values are the number of foods belonging to that type that I want, e.g....
How can I "map" a dict to change only the values in Python
I have a dict like this: food_to_food_type = {"apple": "fruit", "green bean": "vegetable", "tomato": "controversial"} I have a function that wants a dict where keys are food types and values are the number of foods belonging to that type that I want, e.g.: num_foods_of_type = {"fruit": 1, "vegetable": 1, "controversia...
[ "A wonderful solution was proposed here to count the number of occurence in a python list.\nThis can be applied to your case:\nvalues = food_to_food_type.values()\ndict( zip( values, map( values.count, values ) ) )\n\nApparantly, I haven't read your question sufficiently careful. You meant something like this: (?)\...
[ 4, 2, 1 ]
[]
[]
[ "functional_programming", "python" ]
stackoverflow_0008254184_functional_programming_python.txt
Q: Passing from one socket to another I am trying to write a program that works as an intermedium. (M) I can only use telnet to connect : A needs to connect to M, B connects to M. A sends data to M on a socket, M needs to pass it to B B sends data to M on another socket I tried this by starting four threads with a sh...
Passing from one socket to another
I am trying to write a program that works as an intermedium. (M) I can only use telnet to connect : A needs to connect to M, B connects to M. A sends data to M on a socket, M needs to pass it to B B sends data to M on another socket I tried this by starting four threads with a shared list The problem is it seems it is ...
[ "You don't really need threads for this...\nWhen a new connection is accepted, add it to a list. When receiving anything from one of the connection in the list, send to all connections except the one you got the message from.\nUse select to see which connections have send data to you.\nEdit\nExample using select:\n...
[ 4 ]
[]
[]
[ "multithreading", "python" ]
stackoverflow_0008256085_multithreading_python.txt
Q: Can't run one python module from another (when run from Eclipse) I'm using Fedora 15 64bit and python 2.7 When I run python test.py from command line it works well but when I run subprocess.call(["python","test.py"]) from another python module I get File "/usr/lib64/python2.7/site.py", line 557, in <module> ...
Can't run one python module from another (when run from Eclipse)
I'm using Fedora 15 64bit and python 2.7 When I run python test.py from command line it works well but when I run subprocess.call(["python","test.py"]) from another python module I get File "/usr/lib64/python2.7/site.py", line 557, in <module> main() File "/usr/lib64/python2.7/site.py", line 539, in main k...
[ "I assume you're using something like pydev for development.\nIf you have a look at the \"Interpreter\" tab in the \"Run Configurations\", you should see the python path (with the \"See resulting command-line...\") and the binary used for the command. Pydev alters the PYTHONPATH (it's not the same as you have in th...
[ 0 ]
[]
[]
[ "eclipse", "fedora", "python" ]
stackoverflow_0008254243_eclipse_fedora_python.txt
Q: access to sms inbox How can I access the SMS inbox from an application (on Symbian s60)? Us it possible with j2me? How about C++ or Python? A: In j2me, you can't access the native message box related stuff like Inbox, Sent Message or etc. But it is possible in c++. I don't know about python. A: Reading message...
access to sms inbox
How can I access the SMS inbox from an application (on Symbian s60)? Us it possible with j2me? How about C++ or Python?
[ "In j2me, you can't access the native message box related stuff like Inbox, Sent Message or etc. But it is possible in c++. I don't know about python.\n", "Reading message from inbox in j2me is not possible\nif you want to read sms then you can send message using particular port and\nyour j2me application should ...
[ 2, 2, 0 ]
[]
[]
[ "c++", "inbox", "java_me", "python", "symbian" ]
stackoverflow_0004609956_c++_inbox_java_me_python_symbian.txt
Q: How can i write this Java code in Python? How to write this (Java) in Python? class Test { private String test1 = "test"; private static void main(String args[]) { System.out.println("test" + test1); } } A: Since Python supports code outside of classes, the equivalent is as simple as: test1 = "test" ...
How can i write this Java code in Python?
How to write this (Java) in Python? class Test { private String test1 = "test"; private static void main(String args[]) { System.out.println("test" + test1); } }
[ "Since Python supports code outside of classes, the equivalent is as simple as:\ntest1 = \"test\"\nprint(\"test\" + test1)\n\n\nUPDATE: To get the args:\nimport sys\nprint sys.argv\n\nYou really should start with the tutorial!\n", "Hmmm, like this:\ntest1 = \"test\"\nprint \"test\" + test1\n\nBut if you are using...
[ 5, 3 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0008256612_python_python_3.x.txt
Q: extract only one contour after FindContours operation I am currently using FindContours and DrawContours function in order to segment an image. I only extract external contours, and want to save only the contour which contains a given point. I use h_next to move through the cv_seq structure and test if the point ...
extract only one contour after FindContours operation
I am currently using FindContours and DrawContours function in order to segment an image. I only extract external contours, and want to save only the contour which contains a given point. I use h_next to move through the cv_seq structure and test if the point is contained using PointPolygonTest I actually can find the...
[ "There is finally a way to get only one contour. Juste use another function that needs a cvseq in input, as ConvexHull for example. The output will be only the first contour of the sequence.\n" ]
[ 0 ]
[]
[]
[ "image_segmentation", "opencv", "python" ]
stackoverflow_0008185383_image_segmentation_opencv_python.txt
Q: Collecting results from a loop that returns NumPy Arrays I'm an admittedly pretty basic Python programmer, trying to learn as I encounter problems implementing various research problems. And I've hit one of those problems - particularly, how to handle loops where I'm returning a bunch of data, rather than the usua...
Collecting results from a loop that returns NumPy Arrays
I'm an admittedly pretty basic Python programmer, trying to learn as I encounter problems implementing various research problems. And I've hit one of those problems - particularly, how to handle loops where I'm returning a bunch of data, rather than the usual "out comes a single number" examples where you just add the ...
[ "use a list to save all the results:\nresults = []\nfor i in range(runs):\n results.append(model_solve(100))\n\nthen get the output array by:\nnp.hstack(results)\n\n", "Actually, if your code is having a much larger loop you should always try to vectorize your problem.\nIf speed is important you should know th...
[ 14, 11 ]
[]
[]
[ "numpy", "python" ]
stackoverflow_0008251111_numpy_python.txt
Q: Simple validation with SQLAlchemy I'm new to sqlalchemy, and I'm trying to achieve simple validation of model's fields, as provided by Django ORM (min & max for Integer, email, ...). Can SQLAlchemy do this sort of field validations out of the box ? By the way, I'm using SQLAlchemy with Flask. A: See Simple Valid...
Simple validation with SQLAlchemy
I'm new to sqlalchemy, and I'm trying to achieve simple validation of model's fields, as provided by Django ORM (min & max for Integer, email, ...). Can SQLAlchemy do this sort of field validations out of the box ? By the way, I'm using SQLAlchemy with Flask.
[ "See Simple Validators in the documentation. Sample code extract below:\nclass EmailAddress(Base):\n __tablename__ = 'address'\n\n id = Column(Integer, primary_key=True)\n email = Column(String)\n\n @validates('email')\n def validate_email(self, key, address):\n assert '@' in address\n ...
[ 11 ]
[]
[]
[ "flask_sqlalchemy", "python", "sqlalchemy" ]
stackoverflow_0008256715_flask_sqlalchemy_python_sqlalchemy.txt
Q: Writing huge Mongo result set to disk w/ Python in a resource friendly way There is a Mongo collection with >5 Million items. I need to get a "representation" (held in a variable, or put into a file on disk, anything at this point) of a single attribute of all of the 'documents'. My query is something like this: ...
Writing huge Mongo result set to disk w/ Python in a resource friendly way
There is a Mongo collection with >5 Million items. I need to get a "representation" (held in a variable, or put into a file on disk, anything at this point) of a single attribute of all of the 'documents'. My query is something like this: cursor = db.collection.find({"conditional_field": {"subfield": True}}, {"field_...
[ "I think that streaming the results is likely to help here:\nwith open(\"/path/to/storage/file\", \"w\") as f:\n for row in cursor:\n f.write(row['your_field'])\n\nDon't hold everything in memory if you don't have to.\n", "Though accepted already, I'd add that you might consider adding an index too. It...
[ 3, 0 ]
[]
[]
[ "mongodb", "python" ]
stackoverflow_0007547927_mongodb_python.txt
Q: Installing Python-2.7 on Ubuntu 10.4 I can't seem to install zlib properly, I installed Python from source on Ubuntu10.4 '######## edit ##################### bobince and Luper helped. Make sure you install these packages and then recompile Python: sudo aptitude install zlib1g-dev libreadline6-dev libdb4.8-dev li...
Installing Python-2.7 on Ubuntu 10.4
I can't seem to install zlib properly, I installed Python from source on Ubuntu10.4 '######## edit ##################### bobince and Luper helped. Make sure you install these packages and then recompile Python: sudo aptitude install zlib1g-dev libreadline6-dev libdb4.8-dev libncurses5-dev '###########################...
[ "You don't want zlibc, it's something else completely. You want zlib1g (which will certainly be installed already) and, as Luper mentioned, the ‘development’ package which is zlib1g-dev.\nDebian-based Linux distros split each C library into a separate runtime binary package and a development package which delivers ...
[ 20, 9, 2, 1 ]
[]
[]
[ "python", "setuptools", "zlib" ]
stackoverflow_0004047212_python_setuptools_zlib.txt
Q: Mutable default arguments in Python Possible Duplicate: “Least Astonishment” in Python: The Mutable Default Argument I have written the following python program: #!/usr/bin/env python def bug( numbers = [] ): numbers.append( 1 ) return numbers print bug() print bug() The result i would expect is [1] [...
Mutable default arguments in Python
Possible Duplicate: “Least Astonishment” in Python: The Mutable Default Argument I have written the following python program: #!/usr/bin/env python def bug( numbers = [] ): numbers.append( 1 ) return numbers print bug() print bug() The result i would expect is [1] [1] But i got [1] [1, 1] Is this a bug?...
[ "No, this is not a bug and this behaviour has been around in Python for a very long time.\nThe problem is that the list object is mutable, i.e. you can change it, and when you call a function you don't get a new default value. What's happening is this:\ndef bug( numbers = [] ):\n numbers.append( 1 )\n return nu...
[ 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0008257372_python.txt
Q: Referencing related field values in Django Consider a simple ForeignKey relationship: class ModelA(models.Model): other_field = CharField() class ModelB(models.Model): my_field = CharField() parent = ForeignKey(ModelA) So I can do this: my_fields = ModelB.objects.all().values('my_field') Is there an...
Referencing related field values in Django
Consider a simple ForeignKey relationship: class ModelA(models.Model): other_field = CharField() class ModelB(models.Model): my_field = CharField() parent = ForeignKey(ModelA) So I can do this: my_fields = ModelB.objects.all().values('my_field') Is there any way to reference other_field in the same call?...
[ "as per the docs you can use\n...values('parent__other_field')\n\n" ]
[ 5 ]
[]
[]
[ "django", "django_models", "python" ]
stackoverflow_0008257519_django_django_models_python.txt
Q: Web Frameworks & Available Libraries: Is it a brave move to opt for Node.js instead of Python? I have quite sometime now (a month or two) before I can actually start learning a web programming language; so I am still worrying about what language to learn. Whatever programming language I choose, I'd also have to le...
Web Frameworks & Available Libraries: Is it a brave move to opt for Node.js instead of Python?
I have quite sometime now (a month or two) before I can actually start learning a web programming language; so I am still worrying about what language to learn. Whatever programming language I choose, I'd also have to learn JavaScript alongside that language as it's the go to for client-side scripting. I am looking at:...
[ "1) I personally love (!) Ruby, I think it's the most beautiful language one can possibly code in, but I also love the speed of Node.js and JavaScript. Fortunately I can combine what I love about the two, the answer is CoffeeScript (it has a Ruby / Python style of programming, but it compiles to plain JavaScript). ...
[ 0 ]
[]
[]
[ "node.js", "python", "server_side", "serverside_javascript" ]
stackoverflow_0008257362_node.js_python_server_side_serverside_javascript.txt
Q: Escape html with exception I have some text that needs to be HTML-escaped, except for some a elements! How best to implement it? Python version 2.5/2.6/2.7 A: Your question is too vague, so I'm just guessing here. You have some text that needs to be HTML-escaped, except for some a elements. Step 1: Do the escap...
Escape html with exception
I have some text that needs to be HTML-escaped, except for some a elements! How best to implement it? Python version 2.5/2.6/2.7
[ "Your question is too vague, so I'm just guessing here.\nYou have some text that needs to be HTML-escaped, except for some a elements.\nStep 1:\nDo the escape. If on Python ≥ 3.2, there is the html module and its escape function; otherwise, use the cgi module and its escape function.\nStep 2:\nSomewhere inside your...
[ 2, 0, 0 ]
[]
[]
[ "escaping", "html", "python" ]
stackoverflow_0008257536_escaping_html_python.txt
Q: Enable / Disable video cards from Window 7 64-bit via Python I have a 64-bit Windows 7 machine with 2 PCIe video cards, one of which I would like to be able to programmatically enable and disable ideally from a Python script. Any suggestions? A: I have found a MS tool called DevCon, part of the WDK tool kit that...
Enable / Disable video cards from Window 7 64-bit via Python
I have a 64-bit Windows 7 machine with 2 PCIe video cards, one of which I would like to be able to programmatically enable and disable ideally from a Python script. Any suggestions?
[ "I have found a MS tool called DevCon, part of the WDK tool kit that can be downloaded as part of a 640 MB ISO from here...\nhttp://www.microsoft.com/download/en/details.aspx?displaylang=en&id=11800\nDocumentation can be found at...\nhttp://msdn.microsoft.com/en-us/windows/hardware/gg487458\nThis installs 3 copies ...
[ 1 ]
[]
[]
[ "pci", "python", "windows_7", "wmi" ]
stackoverflow_0008247538_pci_python_windows_7_wmi.txt
Q: How can I package python source code? For example, I have a lots of .py file, which can say it is my own library, install of zip all to share my friends, can I have something like .jar in java to package all the classes in a one single file for sharing? Thanks. A: Try reading http://guide.python-distribute.org/...
How can I package python source code?
For example, I have a lots of .py file, which can say it is my own library, install of zip all to share my friends, can I have something like .jar in java to package all the classes in a one single file for sharing? Thanks.
[ "Try reading http://guide.python-distribute.org/creation.html , it will walk you through the process. You don't need the uploading part, unless you want to share it on PyPi, but remaining guide should be helpful.\n" ]
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0008258413_python.txt
Q: Access violation with Ctypes Python <> Fortran DLL I'm trying to make Python use a Fortran DLL (call by referance). When running Fortran 90 code, it works fine, but will not work in Python; it only gives "access violation" errors or "called with not enough arguments". The python code: from ctypes import * mydll =...
Access violation with Ctypes Python <> Fortran DLL
I'm trying to make Python use a Fortran DLL (call by referance). When running Fortran 90 code, it works fine, but will not work in Python; it only gives "access violation" errors or "called with not enough arguments". The python code: from ctypes import * mydll = cdll.LoadLibrary("test.dll") # This function works. pr...
[ "I'm not sure on what the conventions of your Fortran compiler are so I'll answer with some general points rather than specifics:\n\nYour calling conventions don't match. The Fortran code specifies stdcall and the ctypes code specifies cdecl. You need to make them match up. For example, change the ctypes to use win...
[ 4 ]
[]
[]
[ "ctypes", "dll", "fortran", "python" ]
stackoverflow_0008258861_ctypes_dll_fortran_python.txt
Q: Recalling sheet names for a while loop I have imported xlrd etc. The main part of my code is then as follows: for serie_diam in range(0,9): namesheet = "Diamètre " + str(serie_diam) #select(namesheet) numLine = sh.row_values(3) OK = 1 while OK == 1: d = sh1(numLine, 1) D = sh1(numLine, 2) rs = sh1(numL...
Recalling sheet names for a while loop
I have imported xlrd etc. The main part of my code is then as follows: for serie_diam in range(0,9): namesheet = "Diamètre " + str(serie_diam) #select(namesheet) numLine = sh.row_values(3) OK = 1 while OK == 1: d = sh1(numLine, 1) D = sh1(numLine, 2) rs = sh1(numLine, 7) for i in range(4): BB = ...
[ "import xlrd\n\nbook = xlrd.open_workbook('xlrd_test.xls')\n\nfor sheet in book.sheets():\n print sheet.row(0) # do stuff here - I'm printing the first line as example\n\n# or if you need the sheet index for some purpose:\nfor shidx in xrange(0, book.nsheets):\n sheet = book.sheet_by_index(shidx)\n # would...
[ 8 ]
[]
[]
[ "export_to_excel", "python", "worksheet", "xlrd" ]
stackoverflow_0008258734_export_to_excel_python_worksheet_xlrd.txt
Q: Looping for every character in a string in Python decoder ring I'm trying to make a simple decoder ring in Python. Example: a=b, `b=c, c=d, etc. I want the script to take an encoded message and output the decoded message. For instance, I would input "ifmmp" and it would output "hello". I've been thinking I ne...
Looping for every character in a string in Python decoder ring
I'm trying to make a simple decoder ring in Python. Example: a=b, `b=c, c=d, etc. I want the script to take an encoded message and output the decoded message. For instance, I would input "ifmmp" and it would output "hello". I've been thinking I need to split all the characters up and loop through them and change t...
[ "How about:\ns = 'ifmmp'\nnew_s = ''\nfor c in s:\n n = ord(c)\n n = n - 1\n if n < ord('a'):\n # 'a' -> 'z'\n n = ord('z')\n new_s += chr(n)\n# print('new_s = %r' % new_s) -> new_s = 'hello'\n\nOf course, this is only handling small letters, not capital.\n", "Forget loops, whenever pos...
[ 14, 4, 3, 1 ]
[]
[]
[ "caesar_cipher", "decoder", "python", "string" ]
stackoverflow_0008254477_caesar_cipher_decoder_python_string.txt
Q: Parse HTML/XML and find locations of elements in original document Is there a way to get the original location of an element in a document, ie. the start and end character index, when parsing html/xml in Python? I've looked through the lxml documentation and couldn't find anything. eg. <a>1</a><b>2</b> ... print ...
Parse HTML/XML and find locations of elements in original document
Is there a way to get the original location of an element in a document, ie. the start and end character index, when parsing html/xml in Python? I've looked through the lxml documentation and couldn't find anything. eg. <a>1</a><b>2</b> ... print tree.find('b').original_position # result: (9, 16)
[ "Google found this, the gist of which is: it's hard for malformed documents because parsing requires synthesizing valid tokens that don't have any corresponding input. It's possible for valid documents, but most parsing libraries don't support it.\n" ]
[ 1 ]
[]
[]
[ "html_parsing", "lxml", "python", "xml_parsing" ]
stackoverflow_0008258529_html_parsing_lxml_python_xml_parsing.txt
Q: position of logo and page border for printing by pyqt4 I wrote this code. I need a function that put my logo in middle of first line. And how do I add a border to my page? QtCore.QObject.connect(self.pushButton_5,QtCore.SIGNAL(_fromUtf8("clicked()")),self.Delete) def Delete(self): self.printer = QtGui.QPrinter...
position of logo and page border for printing by pyqt4
I wrote this code. I need a function that put my logo in middle of first line. And how do I add a border to my page? QtCore.QObject.connect(self.pushButton_5,QtCore.SIGNAL(_fromUtf8("clicked()")),self.Delete) def Delete(self): self.printer = QtGui.QPrinter() self.printer.setPageSize(self.printer.A4) self.te...
[ "just add this code before self.image\nself.text.setAlignment(QtCore.Qt.AlignCenter)\n\n" ]
[ 0 ]
[]
[]
[ "pyqt4", "python" ]
stackoverflow_0008248813_pyqt4_python.txt
Q: Python Threads: only one thread gets launched thread.start_new_thread(target=self.socketFunctionRead1()) print "Thread 1" thread.start_new_thread(target=self.socketFunctionWrite1()) print "Thread 2" thread.start_new_thread(target=self.socketFunctionRead2()) print "Thread 3" thread.start_new_thread(target=self.sock...
Python Threads: only one thread gets launched
thread.start_new_thread(target=self.socketFunctionRead1()) print "Thread 1" thread.start_new_thread(target=self.socketFunctionWrite1()) print "Thread 2" thread.start_new_thread(target=self.socketFunctionRead2()) print "Thread 3" thread.start_new_thread(target=self.socketFunctionWrite2()) print "Thread 4" I am trying t...
[ "Instead of thread.start_new_thread(target=self.socketFunctionRead1()),\ntry thread.start_new_thread(target=self.socketFunctionRead1)\nBecause of the parenthese, the function is called and the return value of the function is assigned to target. Since thread.start_new_thread(target=self.socketFunctionRead1()) is pro...
[ 2, 1, 0 ]
[]
[]
[ "multithreading", "python" ]
stackoverflow_0008259583_multithreading_python.txt
Q: Compressing short English strings in Python? I would like to fit 80M strings of length < 20 characters in memory and use as little memory as possible. I would like a compression library that I can drive from Python, that will allow me to compress short (<20 char) English strings. I have about 80M of them, and I wo...
Compressing short English strings in Python?
I would like to fit 80M strings of length < 20 characters in memory and use as little memory as possible. I would like a compression library that I can drive from Python, that will allow me to compress short (<20 char) English strings. I have about 80M of them, and I would like them to fit in as little memory as possib...
[ "\nI don't want the dictionary stored with each string, because that would be high overhead.\n\nSo build a single string with all of the desired contents, and compress it all at once with whichever solution. This solves the \"header is too large\" problem as well.\nYou can do this in a variety of ways. Probably the...
[ 2, 1, 1, 1, 1 ]
[]
[]
[ "compression", "python" ]
stackoverflow_0008047384_compression_python.txt
Q: Secure Copy File from remote server via scp and os module in Python I'm pretty new to Python and programming. I'm trying to copy a file between two computers via a python script. However the code os.system("ssh " + hostname + " scp " + filepath + " " + user + "@" + localhost + ":" cwd) won't work. I think it need...
Secure Copy File from remote server via scp and os module in Python
I'm pretty new to Python and programming. I'm trying to copy a file between two computers via a python script. However the code os.system("ssh " + hostname + " scp " + filepath + " " + user + "@" + localhost + ":" cwd) won't work. I think it needs a password, as descriped in How to copy a file to a remote server in Py...
[ "I think the easiest (to avoid having to enter a password) and most secure way to go about this is to first set public/private key authentication. Once that is done, and you can log in to the remote system by doing ssh user@hostname, the following bash command would do the trick:\nscp some/complete/path/to/file use...
[ 4 ]
[]
[]
[ "python", "scp", "ssh" ]
stackoverflow_0008254860_python_scp_ssh.txt
Q: How can I define any number of variables without first setting the number? I want to be able to do something along the lines of this: _______ [button] text [] text2 [] text3 [] and so on. The __ is a space for the user to type in text. When they click the button, that text is added above where it says text [], and...
How can I define any number of variables without first setting the number?
I want to be able to do something along the lines of this: _______ [button] text [] text2 [] text3 [] and so on. The __ is a space for the user to type in text. When they click the button, that text is added above where it says text [], and everything else is moved down. I thought to have a class for a line of text, an...
[ "\nI believe that once the array length is set it can't be changed.\n\nUse a list and its the append member:\narray.append(Text(5))\n\nI'm not sure if you actually used Python arrays from the array package or lists, but you should be using the latter. Python lists are implemented as dynamic arrays, not linked lists...
[ 3, 2, 0 ]
[]
[]
[ "arrays", "infinite", "python", "range", "variables" ]
stackoverflow_0008259731_arrays_infinite_python_range_variables.txt
Q: Accessing inherited methods that have been overridden class A: def start(self): pass class B(A): def start(self): super(A,self).start() b = B() b.start() Gives this error: Traceback (most recent call last): File "C:/Python32/a.py", line 10, in <module> b.start() File "C:/Python32...
Accessing inherited methods that have been overridden
class A: def start(self): pass class B(A): def start(self): super(A,self).start() b = B() b.start() Gives this error: Traceback (most recent call last): File "C:/Python32/a.py", line 10, in <module> b.start() File "C:/Python32/a.py", line 7, in start super(A,self).start() Attribut...
[ "As explained in python doc, super works only for new style class, ie : \n\nNote super() only works for new-style classes.\n\nSo you should do something like this :\nclass A(object): # inherit from object to be a new style class\n def start(self):\n pass\n\nclass B(A):\n def start(self):\n su...
[ 7 ]
[]
[]
[ "python" ]
stackoverflow_0008259807_python.txt
Q: Did you face textbox not responding? I need to know if you ever faced slowing or even hang while using text box to display large amount of data. In my case I am running a simulation script using subprocess and its stdout is displayed in text box. The text can be in MBs. I tried two implementations: 1) The textbox ...
Did you face textbox not responding?
I need to know if you ever faced slowing or even hang while using text box to display large amount of data. In my case I am running a simulation script using subprocess and its stdout is displayed in text box. The text can be in MBs. I tried two implementations: 1) The textbox waited for the simulation(subprocess) to f...
[ "I've used tk for close to 20 years and haven't noticed any problems with large amounts of text, though I don't guess I've ever tried to load up more than a few 10's of thousands of lines. Just how much data are you trying to show? Are you using a large number of tags and different fonts, or is this just plain tex...
[ 2, 0 ]
[]
[]
[ "canvas", "freeze", "python", "textbox", "tkinter" ]
stackoverflow_0008253032_canvas_freeze_python_textbox_tkinter.txt
Q: Python multiple threads/ multiple processes for reading serial ports I'm trying to write a python class utilizing parallel processing/threading for reading two serial ports(/dev/ttyS1 and /dev/ttyS2). Both of these ports are running at a 19200 baud rate and are constantly active. I used pySerial for this purpose. ...
Python multiple threads/ multiple processes for reading serial ports
I'm trying to write a python class utilizing parallel processing/threading for reading two serial ports(/dev/ttyS1 and /dev/ttyS2). Both of these ports are running at a 19200 baud rate and are constantly active. I used pySerial for this purpose. Both of the read operations need to be run continuously and concurrently. ...
[ "I'm not an expert on the subject in any way, but I keep on finding that the amount of additional subtleties that using threading requires is not worth the effort if I can parallelise via processes instead.\nA third module that you did not mention among the alternatives is subprocess.\nEDIT on request of OP: You ca...
[ 2, 1 ]
[]
[]
[ "concurrency", "multiprocessing", "multithreading", "python" ]
stackoverflow_0008260502_concurrency_multiprocessing_multithreading_python.txt
Q: Python: Best particles self-collision / triangle collision algorithm I'm starting to work on this particle engine for Blender in Python: http://www.youtube.com/watch?v=uoK4QV3jg58&feature=channel_video_title All data is processed by my script, Blender is just there for the visual. My problem is for now, in the vid...
Python: Best particles self-collision / triangle collision algorithm
I'm starting to work on this particle engine for Blender in Python: http://www.youtube.com/watch?v=uoK4QV3jg58&feature=channel_video_title All data is processed by my script, Blender is just there for the visual. My problem is for now, in the video above, I calculate distance between each particle for all particles to ...
[ "If \"everything is dynamic\", then you lose the benefits of data structures with fast-lookups and slow-insertions. \nIdeally, you can find some structure in your data to simplify the running time. Perhaps the moving polygons all move in the same direction, so you can you use them as a frame of reference, effecti...
[ 0 ]
[]
[]
[ "aabb", "collision_detection", "kdtree", "octree", "python" ]
stackoverflow_0008260723_aabb_collision_detection_kdtree_octree_python.txt
Q: Open source examples of well designed Python applications Do you know of well designed open source applications that are instructive to analyse? Of course this question is strictly related to this other post, but I am specifically interested in applications written in Python. A: Django is a python package that i...
Open source examples of well designed Python applications
Do you know of well designed open source applications that are instructive to analyse? Of course this question is strictly related to this other post, but I am specifically interested in applications written in Python.
[ "Django is a python package that is very nicely coded and designed.\n", "Look in the Python Standard Library. It is a great wealth of python code. I particularly like this.py :)\nSeriously though there is good code in the std library.\n", "Zope .\n", "Pyramid is Great !\nPyramid - Web Framework\n" ]
[ 3, 1, 1, 0 ]
[]
[]
[ "architecture", "design_patterns", "open_source", "python" ]
stackoverflow_0000234328_architecture_design_patterns_open_source_python.txt
Q: Python: Efficiently iterating over a multidimensional list I'm using for-loops to iterate over two-dimensional list: def itr(lpic, lH, lW, x, y): '''lpic=2D-Array; lH=Row_count; lW=Column_count;''' stack = [] range_x = range(x-1, x+2) range_y = range(y-1, y+2) append = stack.append for i in...
Python: Efficiently iterating over a multidimensional list
I'm using for-loops to iterate over two-dimensional list: def itr(lpic, lH, lW, x, y): '''lpic=2D-Array; lH=Row_count; lW=Column_count;''' stack = [] range_x = range(x-1, x+2) range_y = range(y-1, y+2) append = stack.append for i in range_x: if 0<=i<lH:#i is a valid index *Update...
[ "Not really. In Python 2.6 if you wanted to compact your code a little, you could use itertools.product() to turn it into a single for loop, but the general efficiency wouldn't change at all - you'd still have N*M iterations of the loop.\nimport itertools\n\ndef itr(lpic, lH, lW, x, y):\n '''lpic=2D-Array; lH=Ro...
[ 5, 5 ]
[]
[]
[ "loops", "multidimensional_array", "python" ]
stackoverflow_0008260939_loops_multidimensional_array_python.txt
Q: Pythonic way to name derived classes I can't figure out what is the more acceptable naming convention for derived classes. Let's say we have a base class Fruit, from which we derive, classes for apple, orange and passion fruit. It is a concensus that the name of the base class should appear in the derived ones,...
Pythonic way to name derived classes
I can't figure out what is the more acceptable naming convention for derived classes. Let's say we have a base class Fruit, from which we derive, classes for apple, orange and passion fruit. It is a concensus that the name of the base class should appear in the derived ones, but should it appear in the beginning of ...
[ "Use common sense.\nIn your example, as others have discussed, the Fruit part is obviously redundant. Use just Apple, Orange, etc. Let's consider use another example instead.\nIf I had a base class called Plugin, I would name the derived class FormattingPlugin, which I read as “plugin that does formatting”. The al...
[ 5, 4, 1 ]
[]
[]
[ "naming_conventions", "python" ]
stackoverflow_0008260863_naming_conventions_python.txt
Q: python xml.sax parsing issue with accentuated characters The following code causes the well-known "UnicodeDecodeError: 'ascii' codec can't decode" error: import xml.sax import io parser = xml.sax.make_parser() parser.parse(io.StringIO(u'<a>é</a>')) While import xml.sax parser = xml.sax.make_parser() parser.parse(...
python xml.sax parsing issue with accentuated characters
The following code causes the well-known "UnicodeDecodeError: 'ascii' codec can't decode" error: import xml.sax import io parser = xml.sax.make_parser() parser.parse(io.StringIO(u'<a>é</a>')) While import xml.sax parser = xml.sax.make_parser() parser.parse(open('foo')) works (the content of file "foo" is <a>é</a>). I...
[ "A file contains bytes, and must have some encoding to store Unicode characters, so use a BytesIO object instead:\n#coding: utf8\nimport xml.sax \nimport io \nparser = xml.sax.make_parser() \nparser.parse(io.BytesIO(u'<a>é</a>'.encode('utf8')))\n\nNote: #coding: utf8 specifies the encoding of the source file; .enco...
[ 2 ]
[]
[]
[ "encoding", "python", "sax", "xml" ]
stackoverflow_0008260856_encoding_python_sax_xml.txt
Q: tornado websockets ioloop exception I'm trying to get the hello-world example from the tornado websockets docs working. I'm pretty new to tornado, and totally new to websockets. I have specified the following handler, straight from the docs: class EchoWebSocket(tornado.websocket.WebSocketHandler): def open(sel...
tornado websockets ioloop exception
I'm trying to get the hello-world example from the tornado websockets docs working. I'm pretty new to tornado, and totally new to websockets. I have specified the following handler, straight from the docs: class EchoWebSocket(tornado.websocket.WebSocketHandler): def open(self): print "WebSocket opened" ...
[ "It might have to do with the old version of Python you are using (2.5 from the logs).\nThe behavior of object.__init__ and object.__new__ changed few years ago: http://svn.python.org/view?revision=54539&view=revision\nMoreover, I believe there is a typo in your question: you meant \"tornado 2.1.1\" not \"tornado 1...
[ 0 ]
[]
[]
[ "python", "tornado", "websocket" ]
stackoverflow_0008248142_python_tornado_websocket.txt
Q: Satchmo Store KNET Integration Thanks in Advance I am doing a project in Django Satchmo Store. For that I have to Integrate KNET Payment Gateway. I didn't get any usefull codes in python for KNET Integration. Which is the best solution for KNET Integration?? i am getting the error url every time even though we are...
Satchmo Store KNET Integration
Thanks in Advance I am doing a project in Django Satchmo Store. For that I have to Integrate KNET Payment Gateway. I didn't get any usefull codes in python for KNET Integration. Which is the best solution for KNET Integration?? i am getting the error url every time even though we are in the test mode
[ "I have open sourced my knet library for python. You can grab it from my github. The actual library used is called e24PaymentPipe, you should google that for more information.\nIt is missing one key component (the encryption key); which for obvious reasons I cannot post to a public repository. Let me know if you n...
[ 0 ]
[]
[]
[ "django", "payment_gateway", "python" ]
stackoverflow_0008258623_django_payment_gateway_python.txt
Q: How to fix pylint warning "Abstract class not referenced"? I have a Python class that raises "NotImplementedError" for a couple of methods and the class is inherited by a few other classes which are defined in their own files. When I run Pylint on the file that has the abstract class, it always complains "Abstract...
How to fix pylint warning "Abstract class not referenced"?
I have a Python class that raises "NotImplementedError" for a couple of methods and the class is inherited by a few other classes which are defined in their own files. When I run Pylint on the file that has the abstract class, it always complains "Abstract class not referenced". I was wondering is it just Pylint being ...
[ "If you have in your class a method raising a NotImplementedError it is enough to make pylint think this is an abstract class. \nAs pylint check each file isolated from the rest of the project, if no one inherit from this class in the file it will raise this message. \nIf you want to desactivate it you'll have to p...
[ 25, 6 ]
[]
[]
[ "abstract_class", "pylint", "python", "warnings" ]
stackoverflow_0008261526_abstract_class_pylint_python_warnings.txt
Q: What Frameworks represent a paradigm different than the MVC? We hear a lot about frameworks like Django, ROR and CodeIgniter in Python, ruby and PHP respectively, all of them represents the MVC paradigm, is there other paradigm different than MVC represented with a framework?, what's the framework name, the paradi...
What Frameworks represent a paradigm different than the MVC?
We hear a lot about frameworks like Django, ROR and CodeIgniter in Python, ruby and PHP respectively, all of them represents the MVC paradigm, is there other paradigm different than MVC represented with a framework?, what's the framework name, the paradigm and the differences?
[ "Lift\nfrom http://liftweb.net/lift_overview\n\nSo, Lift is not just another me-too MVC framework. It's a framework\n that's got some core design principals behind it that have matured\n very well. It's a framework that gives the dual advantages of security\n and developer productivity. Lift is a framework that'...
[ 1, 1 ]
[]
[]
[ "frameworks", "paradigms", "php", "python", "ruby" ]
stackoverflow_0008261640_frameworks_paradigms_php_python_ruby.txt
Q: Python : threads; SyntaxError: non-keyword arg after keyword arg I wanted to run a certain function as a thread, but I get SyntaxError: non-keyword arg after keyword arg And I do not understand why : #!/usr/bin/env python import sys import arduinoReadThread import arduinoWriteThread import socket import thread ...
Python : threads; SyntaxError: non-keyword arg after keyword arg
I wanted to run a certain function as a thread, but I get SyntaxError: non-keyword arg after keyword arg And I do not understand why : #!/usr/bin/env python import sys import arduinoReadThread import arduinoWriteThread import socket import thread bolt = 0 socketArray=list() HOST ="localhost" PORT1 =50000 PORT2 =500...
[ "The docs say the the signature for the thread.start_new_thread call is:\nthread.start_new_thread(function, args[, kwargs])\n\nThe way you are calling it is:\nthread.start_new_thread(target=socketFunctionRead1,())\n\nAs you can see you are passing a named (keyword) argument before the non-named one: you are saying ...
[ 1, 1, 0 ]
[]
[]
[ "multithreading", "python" ]
stackoverflow_0008261785_multithreading_python.txt
Q: Decrypt a a middle chunk of data using pycrypto AES or other algorithm I was looking for a way to use an encryption algorithm from pycrypto package that allows me to encrypt an original LARGE piece of data, and then decrypt only a MIDDLE chunk of this data. In other words, start decrypting the data at a certain of...
Decrypt a a middle chunk of data using pycrypto AES or other algorithm
I was looking for a way to use an encryption algorithm from pycrypto package that allows me to encrypt an original LARGE piece of data, and then decrypt only a MIDDLE chunk of this data. In other words, start decrypting the data at a certain offset, instead of starting to decrypt it at offset 0. I've tried AES, as you ...
[ "You are using CBC (ciphertext block chaining) mode, in which the message is split up into blocks and the output of one block used to encrypt the next. This is fundamentally a sequential operation; to decrypt, you must also work through the ciphertext sequentially.\nIf you use CTR (counter) mode, you can have rando...
[ 2 ]
[]
[]
[ "pycrypto", "python" ]
stackoverflow_0008261535_pycrypto_python.txt
Q: how makemessages command address templates outside of project folder for *.po files this is my directory structure: Implementaion\template Implementaion\Agency_project\locale Implementaion\Agency_project\airAgency_app when running django-admin.py makemessages -l fa it just collect translation tags from Agency_pr...
how makemessages command address templates outside of project folder for *.po files
this is my directory structure: Implementaion\template Implementaion\Agency_project\locale Implementaion\Agency_project\airAgency_app when running django-admin.py makemessages -l fa it just collect translation tags from Agency_project folder,I don't know how to associate it with my template folder that contains my ht...
[ "No, my experience is also that somehow makemessages does not use symlinks. And it does not want to mix project-wide translations with app translations which I think is quite sane.\nThe solution is to do \"cd airAgency_app\" and then \"../manage.py makemessages -l fa\". Just remember to create a locale folder in yo...
[ 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0008258833_django_python.txt