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:
Getting pid of the program just started in Python
I need to create startup and stop scripts for a python program. My temporary solution was to have the startup.sh:
python -m root.scripts.run
python server.py 'localhost' 42345
This starts my program and a server that is needed to do some computations. Now for st... | Getting pid of the program just started in Python | I need to create startup and stop scripts for a python program. My temporary solution was to have the startup.sh:
python -m root.scripts.run
python server.py 'localhost' 42345
This starts my program and a server that is needed to do some computations. Now for stop.sh I just do:
killall -m Python
killall python
killa... | [
"Use the subprocess module to start the program from Python (this is the recommended way anyway). The object returned from subprocess.Popen has terminate() and kill() methods as well as a pid attribute that you can save and use for stopping the process again.\nOn Unix systems, you might consider saving the PID in ... | [
4,
1
] | [] | [] | [
"python",
"scripting"
] | stackoverflow_0006937245_python_scripting.txt |
Q:
Can't open Python encoded URL containing Cyrillic symbols
I have the following URL "mysite.com/\u0422\u0435\u043A\u0441\u0442 \u043D\u0430 \u043A\u0438\u0440\u0438\u043B\u0438\u0446\u0430" ("mysite.com/Текст на кирилица"). I want to open this URL using browser.open(link) where browser is
$CHandler = urllib2.HTTPC... | Can't open Python encoded URL containing Cyrillic symbols | I have the following URL "mysite.com/\u0422\u0435\u043A\u0441\u0442 \u043D\u0430 \u043A\u0438\u0440\u0438\u043B\u0438\u0446\u0430" ("mysite.com/Текст на кирилица"). I want to open this URL using browser.open(link) where browser is
$CHandler = urllib2.HTTPCookieProcessor(cookielib.CookieJar())
browser = urllib2.build_o... | [
"mysite.com/Текст на кирилица is not a URL:\n\nbecause it has omitted the http:// (or other) schema;\nit has spaces in, which aren't valid;\nbecause URIs can't contain non-ASCII characters. Only IRIs can, and urllib2 doesn't support them.\n\nSo you will need to fix the brokennesses, %-encoding out of band character... | [
4
] | [] | [] | [
"encoding",
"python",
"url"
] | stackoverflow_0006938678_encoding_python_url.txt |
Q:
Combine python flask and express.js
I have a web application where the site is built with Python Flask. Now we want to introduce a real time chat system in a page. Is it advisable to mix both flask and express.js, or develop only the chat page using express.js and the rest with Flask, or do we have any Framework l... | Combine python flask and express.js | I have a web application where the site is built with Python Flask. Now we want to introduce a real time chat system in a page. Is it advisable to mix both flask and express.js, or develop only the chat page using express.js and the rest with Flask, or do we have any Framework like express.js in python that can work al... | [
"In python you can use\nhttp://twistedmatrix.com/trac/\nhttp://www.gevent.org/\nhttp://eventlet.net/\nLook into this\nhttp://librelist.com/browser//flask/2010/9/1/flask-and websockets/\nTwisted has huge support and lot of success projects are built based upon it.\ngevent is light when compared to twisted. \nLook in... | [
5,
4
] | [] | [] | [
"express",
"flask",
"node.js",
"python"
] | stackoverflow_0006938674_express_flask_node.js_python.txt |
Q:
Why the hashlib and hmac are generating different hash values?
In Python 2.7,
my = "my"
key = "key"
print(hashlib.sha256(my + key).hexdigest())
print(hmac.new(my, key, hashlib.sha256).hexdigest())
output,
5e50f405ace6cbdf17379f4b9f2b0c9f4144c5e380ea0b9298cb02ebd8ffe511
15a55993a27e0de7a4c4daa67a7c219199a464ca2837... | Why the hashlib and hmac are generating different hash values? | In Python 2.7,
my = "my"
key = "key"
print(hashlib.sha256(my + key).hexdigest())
print(hmac.new(my, key, hashlib.sha256).hexdigest())
output,
5e50f405ace6cbdf17379f4b9f2b0c9f4144c5e380ea0b9298cb02ebd8ffe511
15a55993a27e0de7a4c4daa67a7c219199a464ca283797f545b783cce07b38a5
or have I misunderstood?
| [
"This is because hmac uses the provided key to generate a salt and make the hash more strong, while hashlib only hashes the provided message.\nBy looking at the hmac module source code, you will find how to achieve the same behaviour as hmac using the hashlib module, here the used algorithm (it's not the original o... | [
28
] | [] | [] | [
"hashlib",
"hmac",
"python"
] | stackoverflow_0006938675_hashlib_hmac_python.txt |
Q:
I want to embed Python to MVC application, by linking dynamically to python
I want to embed Python to m vc application, by linking dynamically to Python.
hModPython = AfxLoadLibrary("Python23.dll");
pFnPyRun_SimpleString *pFunction = NULL;
pFnPy_Initialize *pPy_Initialize = NULL;
pFunction = (pFnPyRun_Simpl... | I want to embed Python to MVC application, by linking dynamically to python | I want to embed Python to m vc application, by linking dynamically to Python.
hModPython = AfxLoadLibrary("Python23.dll");
pFnPyRun_SimpleString *pFunction = NULL;
pFnPy_Initialize *pPy_Initialize = NULL;
pFunction = (pFnPyRun_SimpleString *)::GetProcAddress(hModPython, "PyRun_SimpleString");
pPy_Initialize = (p... | [
"What you are doing is quite triky... I don't understand the problem with Python.h. It is needed only for compiling your program, not for running it. Surely you do not need it to be compile-time-path-independent, do you?\nAnyway, you may get rid of the PyObject* definition simply by replacing it with void*, because... | [
0
] | [] | [] | [
"dynamic",
"linker",
"python"
] | stackoverflow_0006937732_dynamic_linker_python.txt |
Q:
Downloading files from the other side of a login
I need to use Python to download a large number of URLS, but they require a password to access them (similar to systems like cpanel, for example).
Is there a way I can do this, storing the cookie?
I'd like to use urllib2 if possible.
EDIT: To clarify, it's my websit... | Downloading files from the other side of a login | I need to use Python to download a large number of URLS, but they require a password to access them (similar to systems like cpanel, for example).
Is there a way I can do this, storing the cookie?
I'd like to use urllib2 if possible.
EDIT: To clarify, it's my website and I have the login details.
UPDATE:
OK I'm using t... | [
"You have to use the urllib2.HTTPCookieProcessor, like this:\nimport urllib2\nfrom cookielib import CookieJar\n\ncookiejar = CookieJar()\nopener = urllib2.build_opener()\ncookieproc = urllib2.HTTPCookieProcessor(cookiejar)\nopener.add_handler(cookieproc)\n\nThen you just use opener.open() to access URLs, and cookie... | [
1
] | [] | [] | [
"cookies",
"python",
"urllib2"
] | stackoverflow_0006938895_cookies_python_urllib2.txt |
Q:
Create Python .egg that installs from git repository
I'm currently researching deployment techniques for our Python products. We manage our code with multiple git repositories already but want to improve the process of setting up and updating our servers. It seems that easy_install, .egg files and virtualenv are t... | Create Python .egg that installs from git repository | I'm currently researching deployment techniques for our Python products. We manage our code with multiple git repositories already but want to improve the process of setting up and updating our servers. It seems that easy_install, .egg files and virtualenv are the best tools for doing this nowadays.
Here's the catch: W... | [
"You can use pip instead of easy_install, it supports a number of possible ways to specify where to get the package from, one being git, you could then install your package like this:\n\npip install git://my.git-repo.com/my_project.git\n\n"
] | [
5
] | [] | [] | [
"python",
"setuptools",
"virtualenv"
] | stackoverflow_0006939351_python_setuptools_virtualenv.txt |
Q:
UnicodeEncodeError when writing to a file
I am trying to write some strings to a file (the strings have been given to me by the HTML parser BeautifulSoup).
I can use "print" to display them, but when I use file.write() I get the following error:
UnicodeEncodeError: 'ascii' codec can't encode character u'\xa3' in p... | UnicodeEncodeError when writing to a file | I am trying to write some strings to a file (the strings have been given to me by the HTML parser BeautifulSoup).
I can use "print" to display them, but when I use file.write() I get the following error:
UnicodeEncodeError: 'ascii' codec can't encode character u'\xa3' in position 6: ordinal not in range(128)
How can I... | [
"If I type 'python unicode' into Google, I get about 14 million results; the first is the official doc which describes the whole situation in excruciating detail; and the fourth is a more practical overview that will pretty much spoon-feed you an answer, and also make sure you understand what's going on. \nYou rea... | [
20,
15,
3
] | [] | [] | [
"beautifulsoup",
"python",
"unicode"
] | stackoverflow_0006939692_beautifulsoup_python_unicode.txt |
Q:
Is there a way to determine if a Linux PID is paused or not?
I have a python script that is using the SIGSTOP and .SIGCONT commands with os.kill to pause or resume a process. Is there a way to determine whether the related PID is in the paused or resumed state?
A:
call ps and check the STAT value.
D Uninterr... | Is there a way to determine if a Linux PID is paused or not? | I have a python script that is using the SIGSTOP and .SIGCONT commands with os.kill to pause or resume a process. Is there a way to determine whether the related PID is in the paused or resumed state?
| [
"call ps and check the STAT value.\nD Uninterruptible sleep (usually IO)\nR Running or runnable (on run queue)\nS Interruptible sleep (waiting for an event to complete)\nT Stopped, either by a job control signal or because it is being traced.\nW paging (not valid since the 2.6.xx kernel)\nX dead (... | [
4,
4,
2
] | [] | [] | [
"controls",
"linux",
"pid",
"process",
"python"
] | stackoverflow_0006021771_controls_linux_pid_process_python.txt |
Q:
Virtualenvwrapper errors on Mac OS X Lion
I have just update my Mac from Snow Leopard to Lion. I then needed to install virtualenv and virtualenvwrapper. I used for both easy_install.
I also added virtualenvwrapper settings to my .bash_profile file as following:
# virtualenvwrapper settings
export WORKON_HOME="~/v... | Virtualenvwrapper errors on Mac OS X Lion | I have just update my Mac from Snow Leopard to Lion. I then needed to install virtualenv and virtualenvwrapper. I used for both easy_install.
I also added virtualenvwrapper settings to my .bash_profile file as following:
# virtualenvwrapper settings
export WORKON_HOME="~/virtualenvs"
source "/usr/local/bin/virtualenvwr... | [
"Since /Library/Frameworks/Python.framework/Versions/2.7/bin/python is the path to a separately-installed Python 2.7 (possibly from a python.org installer) rather than the Apple-supplied Python 2.7 (/usr/bin/python2.7), you need to make sure you are using an easy_install for that separate Python or change to using ... | [
13,
0
] | [] | [] | [
"macos",
"osx_lion",
"python",
"virtualenv",
"virtualenvwrapper"
] | stackoverflow_0006933535_macos_osx_lion_python_virtualenv_virtualenvwrapper.txt |
Q:
Generating class dynamically from a list of values
Say I got a list of dictionaries like so:
[
dict(name='Person', title='Person class'),
dict(name='Employee', title='Employee class')
]
And I want to create to classes; one named Person with an attribute title set to 'Person class' and another class call... | Generating class dynamically from a list of values | Say I got a list of dictionaries like so:
[
dict(name='Person', title='Person class'),
dict(name='Employee', title='Employee class')
]
And I want to create to classes; one named Person with an attribute title set to 'Person class' and another class called Employee with title set to 'Employee class'. The name... | [
"You can use type function:\n>>> d = [\n... dict(name='Person', title='Person class'), \n... dict(name='Employee', title='Employee class') \n... ]\n>>> t = [type(i[\"name\"], (object,), i) for i in d]\n>>> t\n[<class '__main__.Person'>, <class '__main__.Employee'>]\n>>> t[0].title\n'Person class'\n>>> t[1].... | [
1,
1,
0
] | [] | [] | [
"class",
"dynamic",
"python"
] | stackoverflow_0006940381_class_dynamic_python.txt |
Q:
Embedding Python: How to help the scripter?
I'm using Boost to embed Python in my application. For example, I want to check that the following function receives an integer and a string as the first and second parameters (the function is defined in C++).
someFunction(123, 'words')
If I find that the parameters are... | Embedding Python: How to help the scripter? | I'm using Boost to embed Python in my application. For example, I want to check that the following function receives an integer and a string as the first and second parameters (the function is defined in C++).
someFunction(123, 'words')
If I find that the parameters are incorrect, how can I notify the scripter about w... | [
"If you wrap the function using usual def(\"someFunction\",someFunction,...), caller will get automatically notified about c++ signature which could not be matched with objects passed from python, like this (the method takes one dictionary argument, is called with 3 numbers instead):\n>>> scene.updateAttrs(1,2,3)\n... | [
3,
1
] | [] | [] | [
"boost",
"boost_python",
"c++",
"python"
] | stackoverflow_0006939711_boost_boost_python_c++_python.txt |
Q:
Are there any usable path-finding libraries for python?
I'm working on a real-time isometric RPG in python, and wish to target mobile devices as a platform. The main area where I'm having difficulties is with my pathfinding. I have tried a few algorithms including A* and a few tweaks to better fit the maps I'm usi... | Are there any usable path-finding libraries for python? | I'm working on a real-time isometric RPG in python, and wish to target mobile devices as a platform. The main area where I'm having difficulties is with my pathfinding. I have tried a few algorithms including A* and a few tweaks to better fit the maps I'm using.
I am satisfied with the results of my algorithm - they g... | [
"First of all, I know a quite efficient and generic library to handle A* search algorithm. It is lib2dp. You may easily plug your python-generated graph into this library and get a quick answer.\nSecond, A* is essentially good to find an optimal path according that:\n\nYou have perfect and total information about y... | [
5,
4,
2,
1
] | [] | [] | [
"c",
"path_finding",
"performance",
"python"
] | stackoverflow_0006897924_c_path_finding_performance_python.txt |
Q:
Using Django with app engine and eclipse
We are new to the python world and would like to get started a s soon a possible and develop a little web app for app engine. We are using Eclipse + Google plugin + Pydev.
We also would like to start using Django framework and we have two questions:
1. We are looking for a ... | Using Django with app engine and eclipse | We are new to the python world and would like to get started a s soon a possible and develop a little web app for app engine. We are using Eclipse + Google plugin + Pydev.
We also would like to start using Django framework and we have two questions:
1. We are looking for a good tutorial which will put us on the right t... | [
"The AppEngine documentation has a section about django integration, it could be useful as a start point. There are also several other articles around the web about this topic, just google django appengine.\nRegarding the IDE, i'd suggest using PyCharm, it's not free, but it has great integration for appengine and ... | [
3,
0
] | [] | [] | [
"django",
"eclipse",
"google_app_engine",
"pydev",
"python"
] | stackoverflow_0006940257_django_eclipse_google_app_engine_pydev_python.txt |
Q:
How to rotate a numpy array?
I have some numpy/scipy issue. I have a 3D array that represent an ellipsoid in a binary way [ 0 out of the ellipsoid].
The thing is I would like to rotate my shape of a certain degree. Do you think it's possible ?
Or is there an efficient way to write directly the ellipsoid equation w... | How to rotate a numpy array? | I have some numpy/scipy issue. I have a 3D array that represent an ellipsoid in a binary way [ 0 out of the ellipsoid].
The thing is I would like to rotate my shape of a certain degree. Do you think it's possible ?
Or is there an efficient way to write directly the ellipsoid equation with the rotation ?
| [
"Just a short answer. If you need more informations or you don't know how to do it, then I will edit this post and add a small example. \nThe right way to rotate your matrix of data points is to do a matrix multiplication. Your rotation matrix would be probably an n*n-matrix and you have to multiply it with every p... | [
2,
1
] | [] | [] | [
"arrays",
"numpy",
"python",
"rotation",
"scipy"
] | stackoverflow_0006938377_arrays_numpy_python_rotation_scipy.txt |
Q:
Django unit testing with date/time-based objects
Suppose I have the following Event model:
from django.db import models
import datetime
class Event(models.Model):
date_start = models.DateField()
date_end = models.DateField()
def is_over(self):
return datetime.date.today() > self.date_end
I w... | Django unit testing with date/time-based objects | Suppose I have the following Event model:
from django.db import models
import datetime
class Event(models.Model):
date_start = models.DateField()
date_end = models.DateField()
def is_over(self):
return datetime.date.today() > self.date_end
I want to test Event.is_over() by creating an Event that ... | [
"EDIT: Since my answer is the accepted answer here I'm updating it to let everyone know a better way has been created in the meantime, the freezegun library: https://pypi.python.org/pypi/freezegun. I use this in all my projects when I want to influence time in tests. Have a look at it.\nOriginal answer:\nReplacing ... | [
41,
7,
7,
4,
3,
1
] | [
"Two choices.\n\nMock out datetime by providing your own. Since the local directory is searched before the standard library directories, you can put your tests in a directory with your own mock version of datetime. This is harder than it appears, because you don't know all the places datetime is secretly used.\nU... | [
-6
] | [
"datetime",
"django",
"python",
"stub",
"unit_testing"
] | stackoverflow_0001042900_datetime_django_python_stub_unit_testing.txt |
Q:
how to split pdf file into multiple pdf files by specific word?
I have one pdf file. I want to split that file into multiple pdf files
by some specific word from that file. how can i do that in python ?
A:
Have a look at pdftk. It is a toolbox for working with pdf files. You can integrate it into python with t... | how to split pdf file into multiple pdf files by specific word? |
I have one pdf file. I want to split that file into multiple pdf files
by some specific word from that file. how can i do that in python ?
| [
"Have a look at pdftk. It is a toolbox for working with pdf files. You can integrate it into python with the subprocess module.\n"
] | [
1
] | [] | [] | [
"pdf",
"pypdf",
"python"
] | stackoverflow_0006941231_pdf_pypdf_python.txt |
Q:
Average trend curve for data points in Python
I'd love to reproduce a plot similar to this:
(source: brleader.com)
I mean I have a set of data points and I'd love to have a curve which shows the average trend.
I tried adding random noise to the function y=2x
from scipy import interpolate
x=arange(0,1,1e-3)
... | Average trend curve for data points in Python | I'd love to reproduce a plot similar to this:
(source: brleader.com)
I mean I have a set of data points and I'd love to have a curve which shows the average trend.
I tried adding random noise to the function y=2x
from scipy import interpolate
x=arange(0,1,1e-3)
noise=np.random.random(len(x))
y=2*x+noise
And... | [
"One of the reasons why the curve doesn't look like y=2*x (I think it does, but that's subject to opinion) is that your noise is large compared to the average change in y. If you try something like:\nnoise=0.1*np.random.random(len(x))\n\n(i.e make the noise smaller) or \ny=5*x**2+noise\n\n(i.e make the change in y ... | [
4,
2,
0
] | [] | [] | [
"numpy",
"python",
"scipy"
] | stackoverflow_0006939901_numpy_python_scipy.txt |
Q:
How to setup python 2.7 features into Python 2.6?
I am using Python 2.6 in Windows environment for my current work. But i am interested in some features which were added in Python 2.7.
Is it possible to move some features(particularly "Collections.OrderedDict") from 2.7 to 2.6? If so how can we do that?
A:
Tak... | How to setup python 2.7 features into Python 2.6? | I am using Python 2.6 in Windows environment for my current work. But i am interested in some features which were added in Python 2.7.
Is it possible to move some features(particularly "Collections.OrderedDict") from 2.7 to 2.6? If so how can we do that?
| [
"Take a look at http://pypi.python.org/pypi/ordereddict\nIt's advertised as\n\nA drop-in substitute for Py2.7's new collections.OrderedDict that\n works in Python 2.4-2.6.\n\n"
] | [
5
] | [] | [] | [
"python",
"python_2.7",
"windows"
] | stackoverflow_0006941402_python_python_2.7_windows.txt |
Q:
Python list of list from CSV files to create grouped bar chart
I have several CSV files in this format, named n-data.csv where n is the number of threads:
elapsed,label
120,Step 01
260,Step 02
113,Step 03
100,Step 01
200,Step 02
103,Step 03
and I would like to get the average of each step per thread (or n), and p... | Python list of list from CSV files to create grouped bar chart | I have several CSV files in this format, named n-data.csv where n is the number of threads:
elapsed,label
120,Step 01
260,Step 02
113,Step 03
100,Step 01
200,Step 02
103,Step 03
and I would like to get the average of each step per thread (or n), and plot them as grouped bar charts much like this: http://matplotlib.sou... | [
"Perhaps have a list of lists ...\nav = []\nidx = []\n\nfor file in sys.argv[1:]:\n next_av = []\n next_idx = []\n\n ...\n\n for i in sorted (result.iterkeys()):\n s = sum(int(v) for v in result[i])\n a = s/float(len(result[i]))\n next_av.append(a)\n next_idx.append(i)\n a... | [
1
] | [] | [] | [
"charts",
"csv",
"list",
"matplotlib",
"python"
] | stackoverflow_0006932487_charts_csv_list_matplotlib_python.txt |
Q:
Use Python standard logging in Celery
I have to implement Celery in a pre-existing system. The previous version of the system already used Python standard logging.
My code is similar to the code below. Process one and process two are non-Celery functions, which are logging everywhere. We are using the logging to t... | Use Python standard logging in Celery | I have to implement Celery in a pre-existing system. The previous version of the system already used Python standard logging.
My code is similar to the code below. Process one and process two are non-Celery functions, which are logging everywhere. We are using the logging to track data loss if something bad happens.
@t... | [
"You probably want this setting:\nCELERYD_HIJACK_ROOT_LOGGER = False\n\nTell me how that works out.\nBtw, the reason it hijacks the root logger is because some badly written\nlibraries sets up logging, something a library should never do, resulting in users experiencing no output from the celeryd\nworker :(\n"
] | [
17
] | [] | [] | [
"celery",
"django",
"logging",
"python",
"standards"
] | stackoverflow_0006940987_celery_django_logging_python_standards.txt |
Q:
How to limit the number of revisions returned by Google Docs API?
I have the following code in python, using the gdata lib:
feed = self.client.GetDocList(uri='/feeds/default/private/full')
for entry in feed.entry:
# get the revisions for this entry
revisions_feed = self.client.GetRevisions(entry.resource_id.... | How to limit the number of revisions returned by Google Docs API? | I have the following code in python, using the gdata lib:
feed = self.client.GetDocList(uri='/feeds/default/private/full')
for entry in feed.entry:
# get the revisions for this entry
revisions_feed = self.client.GetRevisions(entry.resource_id.text)
The problem is that I only need the last n revisions, not all of... | [
"Since I asked the question, Google released a new API endpoint that allows this behavior: http://code.google.com/apis/documents/docs/3.0/developers_guide_protocol.html#Changes\n\nThe changes feed is a read-only feed that provides information about all changes to all resources, including resources that have been sh... | [
1
] | [] | [] | [
"gdata",
"gdata_api",
"google_docs_api",
"python"
] | stackoverflow_0006734260_gdata_gdata_api_google_docs_api_python.txt |
Q:
Compressing measurements data files
from measurements I get text files that basically contain a table of float numbers, with the dimensions 1000x1000. Those take up about 15MB of space which, considering that I get about 1000 result files in a series, is unacceptable to save. So I am trying to compress those by as... | Compressing measurements data files | from measurements I get text files that basically contain a table of float numbers, with the dimensions 1000x1000. Those take up about 15MB of space which, considering that I get about 1000 result files in a series, is unacceptable to save. So I am trying to compress those by as much as possible without loss of data. M... | [
"I see you store the numpy arrays as text files. There is a faster and more space-efficient way: just dump it.\nIf your floats can be stored as 32-bit floats, then use this:\ndata = numpy.genfromtxt('sample.txt',autostrip=True, case_sensitive=True)\n\ndata.astype(numpy.float32).dump(open('converted.numpy', 'wb'))\n... | [
4,
2,
1
] | [] | [] | [
"compression",
"numpy",
"python"
] | stackoverflow_0006942172_compression_numpy_python.txt |
Q:
Session differences in Pylons and Pyramid
As a Pylons user I'm trying to switch to Pyramid now trying to understand differences.
In Pylons I was used to define Session in myproj.model.meta as:
Session = scoped_session(sessionmaker())
then import it in myproj.model to define model and so on then in app refer to:
r... | Session differences in Pylons and Pyramid | As a Pylons user I'm trying to switch to Pyramid now trying to understand differences.
In Pylons I was used to define Session in myproj.model.meta as:
Session = scoped_session(sessionmaker())
then import it in myproj.model to define model and so on then in app refer to:
root = Session.query(MyModel).filter(...)...
no... | [
"Actually the way you are looking up your sqlalchemy session instance for querying doesn't really have anything to do with pylons and/or pyramid. Pylons may have suggested one of the ways as being the \"standard\" pylons way but that's it. The only real difference between the ways you're getting your session is i... | [
10,
0
] | [] | [] | [
"pylons",
"pyramid",
"python",
"session",
"sqlalchemy"
] | stackoverflow_0006042681_pylons_pyramid_python_session_sqlalchemy.txt |
Q:
Is it possible to know which SciPy / NumPy functions run on multiple cores?
I am trying to figure out explicitly which of the functions in SciPy/NumPy run on multiple processors. I can e.g. read in the SciPy reference manual that SciPy uses this, but I am more interested in exactly which functions do run parallel ... | Is it possible to know which SciPy / NumPy functions run on multiple cores? | I am trying to figure out explicitly which of the functions in SciPy/NumPy run on multiple processors. I can e.g. read in the SciPy reference manual that SciPy uses this, but I am more interested in exactly which functions do run parallel computations, because not all of them do. The dream scenario would of course be i... | [
"I think the question is better addressed to the BLAS/LAPACK libraries you use rather than to SciPy/NumPy.\nSome BLAS/LAPACK libraries, such as MKL, use multiple cores natively where other implementations might not.\nTo take scipy.linalg.solve as an example, here's its source code (with some error handling code omi... | [
5
] | [] | [] | [
"multiprocess",
"python"
] | stackoverflow_0006941459_multiprocess_python.txt |
Q:
Can't get Excel drop-down list (combobox) value with python
I have an excel file with a drop-down list and I would like to access its current value from python.
In vba the code is really simple :
Sheets("name_of_my_sheet").name_of_my_list.value
I looked for an equivalent in xlrd but couldn't find one.
A:
I got ... | Can't get Excel drop-down list (combobox) value with python | I have an excel file with a drop-down list and I would like to access its current value from python.
In vba the code is really simple :
Sheets("name_of_my_sheet").name_of_my_list.value
I looked for an equivalent in xlrd but couldn't find one.
| [
"I got my answer. The list the drop-down box is created at run time in vba so you can't \"read\" its value from the xls.\nThe solution is to write in VBA an on change method that will actually write the value to the cell under the box.\nSub My_List_Change()\n Sheets(\"Containing your box\").Cells(x,y) = My_List.v... | [
1
] | [] | [] | [
"combobox",
"drop_down_menu",
"excel",
"python",
"xlrd"
] | stackoverflow_0006935529_combobox_drop_down_menu_excel_python_xlrd.txt |
Q:
Python Array Question(Programming)
What does the [] mean?
Also how can I identify variables as empty arrays in python?
Thanks!
perl: xcoords = ()
How do I translate that?
A:
[] - is an empty list in Python and is the same as calling list() e.g. [] == list()
To check that list is empty you can use len(l) or:
lis... | Python Array Question(Programming) | What does the [] mean?
Also how can I identify variables as empty arrays in python?
Thanks!
perl: xcoords = ()
How do I translate that?
| [
"[] - is an empty list in Python and is the same as calling list() e.g. [] == list()\nTo check that list is empty you can use len(l) or:\nlistV = [] # an empty list\nif listV:\n # do something if list is not empty\nelse:\n # do something if list is really empty\n\nTo read more about list you can use the follo... | [
3,
0
] | [] | [] | [
"arrays",
"perl",
"python",
"syntax"
] | stackoverflow_0006943172_arrays_perl_python_syntax.txt |
Q:
if typeA in [typeB.typeA for typeB in typeBlist]: ... accessing typeB within the if clause?
The full example code:
for typeA in typeAlist:
if typeA in [typeB.typeA for typeB in typeBlist]:
return typeB
Obviously that doesn't work, but it feels like there would be a neat way to retrieve the typeB object that... | if typeA in [typeB.typeA for typeB in typeBlist]: ... accessing typeB within the if clause? | The full example code:
for typeA in typeAlist:
if typeA in [typeB.typeA for typeB in typeBlist]:
return typeB
Obviously that doesn't work, but it feels like there would be a neat way to retrieve the typeB object that matched the typeA object.
The only way I can think of making it work is to have a nested for loo... | [
"You can use a if within your list comprehension:\n[typeB for typeB in typeBlist if typeB.typeA == typeA]\n\nThis would return all the members of typeBlist for which typeB.typeA == typeA.\nIf you're sure there's only a single match you can use a generator expression to stop working through the whole list:\ntry:\n ... | [
3,
1,
0
] | [] | [] | [
"attributes",
"list",
"python"
] | stackoverflow_0006943282_attributes_list_python.txt |
Q:
using pyodbc on ubuntu to insert a image field on SQL Server
I am using Ubuntu 9.04
I have installed the following package versions:
unixodbc and unixodbc-dev: 2.2.11-16build3
tdsodbc: 0.82-4
libsybdb5: 0.82-4
freetds-common and freetds-dev: 0.82-4
python2.6-dev
I have configured /etc/unixodbc.ini like this:
[Fre... | using pyodbc on ubuntu to insert a image field on SQL Server | I am using Ubuntu 9.04
I have installed the following package versions:
unixodbc and unixodbc-dev: 2.2.11-16build3
tdsodbc: 0.82-4
libsybdb5: 0.82-4
freetds-common and freetds-dev: 0.82-4
python2.6-dev
I have configured /etc/unixodbc.ini like this:
[FreeTDS]
Description = TDS driver (Sybase/MS SQL)
Driver ... | [
"Huh, just after offering the bounty, I've found out the solution.\nYou have to use SET TEXTSIZE 2147483647 on the query, in addition of text size configuration option in /etc/freetds/freetds.conf. \nI have used\ncur.execute('SET TEXTSIZE 2147483647 SELECT myimage FROM testing WHERE id = 1')\n\nAnd everything worke... | [
5,
3,
1
] | [] | [] | [
"freetds",
"image",
"pyodbc",
"python",
"sql_server"
] | stackoverflow_0001060035_freetds_image_pyodbc_python_sql_server.txt |
Q:
Google App Engine - Adding Methods to subclasses of db.model
I would like to know if I can add methods to a subclass of db.model. For example:
class Session(db.model):
sessionId = db.StringProperty()
# More Properties
def refreshSession(self):
#do some work
self.put()
Implementation:
... | Google App Engine - Adding Methods to subclasses of db.model | I would like to know if I can add methods to a subclass of db.model. For example:
class Session(db.model):
sessionId = db.StringProperty()
# More Properties
def refreshSession(self):
#do some work
self.put()
Implementation:
s = Session()
s.refreshSession()
Is this recommended?
| [
"This is the typical way to add behavior to model objects. Why wouldn't you do it this way?\n"
] | [
2
] | [] | [] | [
"google_app_engine",
"python"
] | stackoverflow_0006943712_google_app_engine_python.txt |
Q:
Syntax Error In Python SQLite
THE CODE BELOW IS UPDATED CODE THAT WORKS
I am getting a syntax error when I try to run this. Here is the relevant code:
import sqlite3
mydatabase="/Users/noahclark/cities.db"
connection=sqlite3.connect(mydatabase)
cur = connection.cursor()
def getDaysURLS(self):
day = cur.execut... | Syntax Error In Python SQLite | THE CODE BELOW IS UPDATED CODE THAT WORKS
I am getting a syntax error when I try to run this. Here is the relevant code:
import sqlite3
mydatabase="/Users/noahclark/cities.db"
connection=sqlite3.connect(mydatabase)
cur = connection.cursor()
def getDaysURLS(self):
day = cur.execute('select state from cities where c... | [
"SQLite follows the SQL standard: strings are enclosed in single quotes, not double quotes. Also, generally use = to check for string equality.\n",
"Only use is in sql when checking for null\n day = cur.execute('select state from cities where city = \"pointer\"')\n\nOr better yet:\n day = cur.execute('select s... | [
3,
1,
1
] | [] | [] | [
"database",
"python",
"sqlite"
] | stackoverflow_0006943874_database_python_sqlite.txt |
Q:
Request for new user account via email Django
I am trying to make a little function for a user to request an account and the information he puts in is sent to a person who will make an account.
I was following this example mostly http://djangosnippets.org/snippets/261/ but it is very old and might be inaccurate fo... | Request for new user account via email Django | I am trying to make a little function for a user to request an account and the information he puts in is sent to a person who will make an account.
I was following this example mostly http://djangosnippets.org/snippets/261/ but it is very old and might be inaccurate for I have got and thus I have problems with it.
I ha... | [
"RequestContext(request) needs to be used. In your code below the second return will never be hit so you are not passing RequestContext to the template. \n else:\n return render_to_response('new_account.html', {'form': NewAccountForm()})\n\n return render_to_response('new_account.html', {'form': NewAcc... | [
0,
0
] | [] | [] | [
"django",
"email",
"forms",
"python"
] | stackoverflow_0006943767_django_email_forms_python.txt |
Q:
Updating a wxPython progress bar after calling app.MainLoop()
I have a python script that performs a calculation, and I have created a class for a pop-up wxPython progress bar. Currently I have:
app=wx.App()
progress = ProgressBar()
app.MainLoop()
for i in xrange(len(toBeAnalysed)):
analyse(toBeAnalysed[i])
... | Updating a wxPython progress bar after calling app.MainLoop() | I have a python script that performs a calculation, and I have created a class for a pop-up wxPython progress bar. Currently I have:
app=wx.App()
progress = ProgressBar()
app.MainLoop()
for i in xrange(len(toBeAnalysed)):
analyse(toBeAnalysed[i])
progress.update(i/len(toBeAnalysed)*100)
Now, this example does... | [
"You should run your logic in a background thread and use wx.CallAfter to periodically update the GUI. CallAfter will invoke the provided function on the GUI thread, so it is safe to make GUI calls.\nimport wx\nimport threading\nimport time\n\ndef do_stuff(dialog): # put your logic here\n for i in range(101):\n ... | [
4
] | [] | [] | [
"multithreading",
"python",
"wxpython"
] | stackoverflow_0006943339_multithreading_python_wxpython.txt |
Q:
Xvfb instance for multiple processes
I am developing an application on one of the servers of webfaction. I have a python class with two functions defined in it. Each function uses a spynner.Browser() object, which requires an X server running. I am running Xvfb for this purpose.
Both functions run as expected on t... | Xvfb instance for multiple processes | I am developing an application on one of the servers of webfaction. I have a python class with two functions defined in it. Each function uses a spynner.Browser() object, which requires an X server running. I am running Xvfb for this purpose.
Both functions run as expected on their owns. The problem arises when I try t... | [
"Have you tried setting the display as an environment variable?\nos.environ[\"DISPLAY\"] = \":99\"\n"
] | [
0
] | [] | [] | [
"python",
"spynner",
"xvfb"
] | stackoverflow_0006943534_python_spynner_xvfb.txt |
Q:
Using a global flag for python RegExp compile
Would it be possible to define a global flag so that Python's re.compile() automatically sets it ? For instance I want to use re.DOTALL flag for all my RegExp in -- say -- a class?
It may sound weird at first, but I'm not really in control of this part of the code sinc... | Using a global flag for python RegExp compile | Would it be possible to define a global flag so that Python's re.compile() automatically sets it ? For instance I want to use re.DOTALL flag for all my RegExp in -- say -- a class?
It may sound weird at first, but I'm not really in control of this part of the code since it's generated by YAPPS. I just give YAPPS a stri... | [
"Yes, you can change it to be globally re.DOTALL. But you shouldn't. Global settings are a bad idea at the best of times -- this could cause any Python code run by the same instance of Python to break.\n\nSo, don't do this:\nThe way you can change it is to use the fact that the Python interpreter caches modules per... | [
11,
8
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0006943912_python_regex.txt |
Q:
How create an Etag with an expire date
I'm thinking about create an etag with an expire date.
Actually I create an etag with a large number of parameters but I would like to make it with an expire date.
I have the solution to keep an information in the server side but I prefer to encode any information into.
I'm s... | How create an Etag with an expire date | I'm thinking about create an etag with an expire date.
Actually I create an etag with a large number of parameters but I would like to make it with an expire date.
I have the solution to keep an information in the server side but I prefer to encode any information into.
I'm searching the better way to do that.
def etag... | [
"My solution to the problem would be to add a timestamp to the end of the etag in the form of hash-timestamp. You could then parse that out when you needed it.\n"
] | [
1
] | [] | [] | [
"etag",
"http",
"python"
] | stackoverflow_0006943115_etag_http_python.txt |
Q:
How to signal yourself (same PID)?
OK, so this may be an odd situation but please bear with me.
I have a Python program which calls up a C++ class via a SWIG interface. I came to a point where I must asynchronously signal (to update a status) the Python code from the C++ library. Originally I had inefficient busy ... | How to signal yourself (same PID)? | OK, so this may be an odd situation but please bear with me.
I have a Python program which calls up a C++ class via a SWIG interface. I came to a point where I must asynchronously signal (to update a status) the Python code from the C++ library. Originally I had inefficient busy loops which polled a flag. I wanted to r... | [
"If you are in the same program I am not sure what you would need signals for in this case. Take a look at the observer pattern. If you have your python event handlers subscribe to events in your C++ library, you can avoid signals all together.\n",
"Signals are not the right tool for the job here. Normally, th... | [
2,
2
] | [] | [] | [
"c++",
"python",
"signals"
] | stackoverflow_0006944619_c++_python_signals.txt |
Q:
Why are slices in Python 3 still copies and not views?
As I only now noticed after commenting on this answer, slices in Python 3 return shallow copies of whatever they're slicing rather than views. Why is this still the case? Even leaving aside numpy's usage of views rather than copies for slicing, the fact that d... | Why are slices in Python 3 still copies and not views? | As I only now noticed after commenting on this answer, slices in Python 3 return shallow copies of whatever they're slicing rather than views. Why is this still the case? Even leaving aside numpy's usage of views rather than copies for slicing, the fact that dict.keys, dict.values, and dict.items all return views in Py... | [
"\nAs well, the fact that you can use assignment to slices to modify the original list, but slices are themselves copies and not views.\n\nHmm.. that's not quite right; although I can see how you might think that. In other languages, a slice assignment, something like: \na[b:c] = d\n\nis equivalent to \ntmp = a.o... | [
15,
6
] | [] | [] | [
"language_design",
"python",
"python_3.x",
"slice"
] | stackoverflow_0006902235_language_design_python_python_3.x_slice.txt |
Q:
How to implement a category system
I want to implement a category structure that works with i18n. Since GAE has builtin db.CategoryPropertybut it doesn't implement subcategories and it seems I'm using the category property as it were a list object with my models.
class Vehicles(GeoModel,search.SearchableModel):
... | How to implement a category system | I want to implement a category structure that works with i18n. Since GAE has builtin db.CategoryPropertybut it doesn't implement subcategories and it seems I'm using the category property as it were a list object with my models.
class Vehicles(GeoModel,search.SearchableModel):
title=db.StringProperty(verbose_name="t... | [
"CategoryProperty is just a StringProperty with a semantic name: when it is serialized to XML it uses a different tag name. Nothing else is different, really.\nYour last snippet should work, but why rely on integer indexes? It may be problematic if you change the order one day. You could use a dict instead:\nchoice... | [
2
] | [] | [] | [
"django_forms",
"django_models",
"django_templates",
"google_app_engine",
"python"
] | stackoverflow_0006938954_django_forms_django_models_django_templates_google_app_engine_python.txt |
Q:
Python regex: find lines where period is missing in
I'm looking for a regular expression, implemented in Python, that will match on this text
WHERE PolicyGUID = '531B2310-403A-13DA-5964-E2EFA56B0753'
but will not match on this text
WHERE AsPolicy.PolicyGUID = '531B2310-403A-13DA-5964-E2EFA56B0753'
I'm doing th... | Python regex: find lines where period is missing in | I'm looking for a regular expression, implemented in Python, that will match on this text
WHERE PolicyGUID = '531B2310-403A-13DA-5964-E2EFA56B0753'
but will not match on this text
WHERE AsPolicy.PolicyGUID = '531B2310-403A-13DA-5964-E2EFA56B0753'
I'm doing this to find places in a large piece of SQL where the devel... | [
"re.compile('''WHERE [^.]+ =''')\n\nHere, the [] indicates \"match a set of characters,\" the ^ means \"not\" and the dot is a literal period. The + means \"one or more.\"\nWas that what you were looking for?\n",
"something like\nWHERE .*\\..* = .*\n\nnot sure how accurate can be, it depends on how your data loo... | [
2,
0,
0,
0
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0006944857_python_regex.txt |
Q:
Finding and adding to a .kml file using python
I am not a very good coder. But I really want to automate something I have to do at work. Basically, I have a bunch of placemarkers in google earth showing hand-holes of a municipal fiber network. I have a few pictures of each hand-hole that I want to place as a tag ... | Finding and adding to a .kml file using python | I am not a very good coder. But I really want to automate something I have to do at work. Basically, I have a bunch of placemarkers in google earth showing hand-holes of a municipal fiber network. I have a few pictures of each hand-hole that I want to place as a tag in the .kml file. Basically, I want to have it so wh... | [
"I'm assuming the reason your if line == \"<name>TO-101</name>\" line doesn't work is because it probably has whitespace preceding it. If you changed it to line.strip() == ... then it would presumably work.\nYour best bet would be to implement an XML handler to read in the existing file, parse it, and add the new ... | [
0
] | [] | [] | [
"python",
"string_parsing",
"text"
] | stackoverflow_0006944708_python_string_parsing_text.txt |
Q:
How do I split a list into a list of lists on a specific character in the elements?
I'm relatively new to programming and trying get a (very) long list of information into a table using Python. I installed HTML.py from Decalage and now need to get my list turned into into a list of lists that HTML.py can parse.
Is... | How do I split a list into a list of lists on a specific character in the elements? | I'm relatively new to programming and trying get a (very) long list of information into a table using Python. I installed HTML.py from Decalage and now need to get my list turned into into a list of lists that HTML.py can parse.
Is there an easy way to split a list like this:
['(617) 965-2555<br />\nOrganization Name'... | [
">>> a\n['(617) 965-2555<br />\\nOrganization Name', 'Street Name', 'City', 'Zip code', '(413) 333-2251<br />\\nOrg Name 2', 'Address', 'City', 'Zip code 2', '(617) 568-7777</p>\\n\\n']\n>>> [i.split(\"\\n\") for i in a]\n[['(617) 965-2555<br />', 'Organization Name'], ['Street Name'], ['City'], ['Zip code'], ['(41... | [
3,
0
] | [] | [] | [
"list",
"nested_lists",
"python",
"split"
] | stackoverflow_0006944985_list_nested_lists_python_split.txt |
Q:
PYTHON how to search a text file for a number
There's a text file that I'm reading line by line. It looks something like this:
3
3
67
46
67
3
46
Each time the program encounters a new number, it writes it to a text file. The way I'm thinking of doing this is writing the first number to the file, then looking at th... | PYTHON how to search a text file for a number | There's a text file that I'm reading line by line. It looks something like this:
3
3
67
46
67
3
46
Each time the program encounters a new number, it writes it to a text file. The way I'm thinking of doing this is writing the first number to the file, then looking at the second number and checking if it's already in the... | [
"Rather than searching your output file, keep a set of the numbers you've written, and only write numbers that are not in the set.\n",
"Instead of checking output file for the number if it was already written it is better to keep this information in a variable (a set or list). It will save you on disk reads.\nTo ... | [
5,
1,
0,
0,
0
] | [] | [] | [
"python",
"repeat",
"search"
] | stackoverflow_0006945398_python_repeat_search.txt |
Q:
PYTHON how to make as many variables as needed
I have a loop that's reading over a text file. Each time the loop finds something different, I want it to make a new variable and assign the value in that line of text to the newly created variable. So if the text file looks like this:
3
3
6
1
3
6
The program would've... | PYTHON how to make as many variables as needed | I have a loop that's reading over a text file. Each time the loop finds something different, I want it to make a new variable and assign the value in that line of text to the newly created variable. So if the text file looks like this:
3
3
6
1
3
6
The program would've made 3 variables, one for 1, one for 3, and one for... | [
"What you likely want is this...\n>>> set(\"3 3 6 1 3 6\".split())\nset(['1', '3', '6'])\n\n",
"There are a couple approaches:\nmydict = {}\nfor x in myfile.read().split():\n mydict[x] = None\nprint mydict\n\nOr:\nclass VarContainer(object):\n pass\nv = VarContainer()\nfor x in myfile.read().split():\n s... | [
3,
1,
1,
0,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0006945074_python.txt |
Q:
Fastest rising factorial (Pochhammer function) in python
I need to compute the rising factorial of big numbers, the best I found until now is the rising factorial function from the sympy package sympy package, that is really nice, but I would still need something faster.
What I would need exactly is a really fast ... | Fastest rising factorial (Pochhammer function) in python | I need to compute the rising factorial of big numbers, the best I found until now is the rising factorial function from the sympy package sympy package, that is really nice, but I would still need something faster.
What I would need exactly is a really fast version of this:
from itertools import combinations
from numpy... | [
"Try this package: http://tnt.math.se.tmu.ac.jp/nzmath/\nLike job said, the function you want is Stirling Number of the 1st kind (I'd worked out the recursive definition and was about to post it, but I didn't know the name). \nThe function is nzmath.combinatorial.stirling1\n",
"The other versions I know about are... | [
4,
3,
2
] | [] | [] | [
"performance",
"python",
"scipy",
"sympy"
] | stackoverflow_0006930412_performance_python_scipy_sympy.txt |
Q:
problem in pygtk multi-threaded chat application
Possible Duplicate:
Socket Thread and PyGTK
i want to build a GUI chat application.. I want to create a thread which able to accept the requested connection simultaneously. and show a message box to confirm requested connection to be accepted or rejected. The mess... | problem in pygtk multi-threaded chat application |
Possible Duplicate:
Socket Thread and PyGTK
i want to build a GUI chat application.. I want to create a thread which able to accept the requested connection simultaneously. and show a message box to confirm requested connection to be accepted or rejected. The message box haven't appearing when the application runnin... | [
"Gtk is not thread safe, it is merely \"thread aware\" (and essentially \"thread incapable\" in Windows). Only one thread can access a Gtk object at any time.\nIn your main program, you first need to call gtk.gdk.threads_init() before you call any other gtk functions. Then, in your thread, any time you want to acce... | [
1
] | [] | [] | [
"multithreading",
"pygtk",
"python",
"sockets"
] | stackoverflow_0006865962_multithreading_pygtk_python_sockets.txt |
Q:
different import results at different directories
I have a package MyPak and a module MyMod. The files are organized in the following way:
somedir/MyPak/MyMod.py
in MyMod.py there is only a Class whose name is also MyMod
in directory somedir/MyPak, if I do the import:
import MyMod
I got MyMod imported as a Modu... | different import results at different directories | I have a package MyPak and a module MyMod. The files are organized in the following way:
somedir/MyPak/MyMod.py
in MyMod.py there is only a Class whose name is also MyMod
in directory somedir/MyPak, if I do the import:
import MyMod
I got MyMod imported as a Module.
But in directory somedir/, if I do
from MyPak imp... | [
"This behavior is indicative that you have a file:\nsomedir/MyPak/__init__.py\n\nwherein you do the following:\nfrom MyMod import *\n\nWhen you import MyPak, it imports from that __init__.py - likewise, when you from MyPak import something, it's going to try to pull from the namespace for the package - which will l... | [
4
] | [] | [] | [
"python"
] | stackoverflow_0006945592_python.txt |
Q:
Nested for loop to search 2 lists
Using: Python 2.4
Currently, I have a nested for loop that iterates over 2 lists and makes a match based on two elements that exists on both lists. Once a match has been found, it the element from the r120Final list and puts in a new list called "r120Delta":
for r120item in r120F... | Nested for loop to search 2 lists | Using: Python 2.4
Currently, I have a nested for loop that iterates over 2 lists and makes a match based on two elements that exists on both lists. Once a match has been found, it the element from the r120Final list and puts in a new list called "r120Delta":
for r120item in r120Final:
for spectraItem in spectraFin... | [
"spectra_set = set((str(spectraItem[0]), str(spectraItem[25])) for spectraItem in spectraFinal)\n\nreturnList = []\nfor r120item in r120Final:\n if (r120item[2].strip(), r120item[10]) not in spectra_set:\n returnList.append(r120item)\n\nThis will add all items that didn't match to the returnList.\nYou can ... | [
2
] | [] | [] | [
"nested_lists",
"nested_loops",
"python",
"search",
"string_matching"
] | stackoverflow_0006945806_nested_lists_nested_loops_python_search_string_matching.txt |
Q:
How to create full transparency in a QTextEdit
I have been trying for many days to figure out a way to create a transparent Qtextedit with opaque text. Because the term "transparency" is often ambiguous, I define Qtextedit"transparency" as being able to see the text in the Qtextedit overlaid upon whatever is direc... | How to create full transparency in a QTextEdit | I have been trying for many days to figure out a way to create a transparent Qtextedit with opaque text. Because the term "transparency" is often ambiguous, I define Qtextedit"transparency" as being able to see the text in the Qtextedit overlaid upon whatever is directly behind the main window (such as the desktop back... | [
"To make your main window transparent, you have to set the Qt.WA_TranslucentBackground attribute (using setAttribute(Qt.WA_TranslucentBackground)). Under Windows, you also must set the Qt.FramelessWindowHint attribute on your main window. According to the docs, however, \"The user cannot move or resize a borderles... | [
1
] | [] | [] | [
"pyqt",
"pyqt4",
"python",
"user_interface"
] | stackoverflow_0006939063_pyqt_pyqt4_python_user_interface.txt |
Q:
set python recursion limit for a function
I have 2 solutions to a recursion problem that I need for a function (actually a method). I want it to be recursive, but I want to set the recursion limit to 10 and reset it after the function is called (or not mess with recursion limit at all). Can anyone think of a bette... | set python recursion limit for a function | I have 2 solutions to a recursion problem that I need for a function (actually a method). I want it to be recursive, but I want to set the recursion limit to 10 and reset it after the function is called (or not mess with recursion limit at all). Can anyone think of a better way to do this or recommend using one over th... | [
"You shouldn't change the system recursion limit at all. You should code your function to know how deep it is, and end the recursion when it gets too deep.\nThe reason the recursion limit seems differently applied in your program and the interpreter is because they have different tops of stack: the functions invok... | [
7,
1,
1,
0
] | [] | [] | [
"python",
"recursion"
] | stackoverflow_0006945620_python_recursion.txt |
Q:
Why doesn't this simple django IF statement work?
If I output the following in the template:
{{ latest_session.chat_room.is_open }}
It outputs
True
But when I do this check:
{% if latest_session.chat_room.is_open == 'True' %}
Online
{% else %}
Offline
{% endif %}
It outputs:
Offline
Shouldn't it output O... | Why doesn't this simple django IF statement work? | If I output the following in the template:
{{ latest_session.chat_room.is_open }}
It outputs
True
But when I do this check:
{% if latest_session.chat_room.is_open == 'True' %}
Online
{% else %}
Offline
{% endif %}
It outputs:
Offline
Shouldn't it output Online?
| [
"is_open is probably a BooleanField, so its python value is a boolean, not a string. Use {% if latest_session.chat_room.is_open %} to check for it.\n",
"True is a boolean value, not a string. Use {% if latest_session.chat_room.is_open %} instead.\n",
"According to the Django Book, \n\nThe {% if %} tag evaluates... | [
9,
3,
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0006946306_django_python.txt |
Q:
Trying to write some code to determine if a box has been checked in html pages
I am working with a large collection of documents that are prepared by more than 5K different entities. One of the things I am trying to do is to determine whether or not a box has been checked. The preparer needs to indicate some inf... | Trying to write some code to determine if a box has been checked in html pages | I am working with a large collection of documents that are prepared by more than 5K different entities. One of the things I am trying to do is to determine whether or not a box has been checked. The preparer needs to indicate some information by checking one of five different boxes.
The problem is that the preparer d... | [
"The way I see it, it appears like this.\nThe ascii value of 'S' is 83. If you look up 83 on wingdings, you get \"droplet\". The Unicode equivalent of \"droplet\" is .\nThe ascii value of 'x' is 120. Looking 120 up on wingdings, you get \"clear\". Unicode ⌧.\n252 is wingding \"checkbld\", unicode ✓.\n253 is win... | [
0
] | [] | [] | [
"html",
"lxml",
"python"
] | stackoverflow_0005533822_html_lxml_python.txt |
Q:
Find and Replace tags in XML using Python
I have proposed a similar question before, but this one is slightly different. I want to find and replace XML tags using python. I am using the XML's to upload as metadata for some GIS shapefiles. In the metadata editor, I have options to choose dates for when certain data... | Find and Replace tags in XML using Python | I have proposed a similar question before, but this one is slightly different. I want to find and replace XML tags using python. I am using the XML's to upload as metadata for some GIS shapefiles. In the metadata editor, I have options to choose dates for when certain data is collected. The options are 'single date', '... | [
"I believe I succeeded in making the code work. This will allow you to edit certain tags if you need to change them from an existing XML file. I needed to do this to create metadata for some GIS shapefiles in a batch processing script to change certain date values depending on if they were single dates, multiple da... | [
1
] | [] | [] | [
"python",
"tags",
"xml"
] | stackoverflow_0006918794_python_tags_xml.txt |
Q:
Syntax Error when trying to define multiple functions in python?
I'm trying to learn python, so I'm just writing some simple programs. I wrote these two bits of code to define two of the functions I want to use in the program, and they both do what they want but when I try to paste them into IDLE it says there is ... | Syntax Error when trying to define multiple functions in python? | I'm trying to learn python, so I'm just writing some simple programs. I wrote these two bits of code to define two of the functions I want to use in the program, and they both do what they want but when I try to paste them into IDLE it says there is a syntax error at the second def. Any idea what this is?
here's the co... | [
"Interactive interpreters (a.k.a. REPL, just \"interpreter\", and many other terms) usually expect only a single top-level statement (a function definition, a class definition, a global assignment, a loop, ...) at a time. You give it two and it's confused. Try putting in the first def, a blank line to confirm and a... | [
1,
0
] | [] | [] | [
"python",
"syntax"
] | stackoverflow_0006946515_python_syntax.txt |
Q:
How can I convert a UTF-16 encoded string to an encoding suitable for a Mac OS X filename?
I have a Localized.strings (UTF-16) file that contains some strings that I use to generate filenames for. I open the file in python with codecs.open("Localized.strings", "r", "utf-16")
The files are created successfully but... | How can I convert a UTF-16 encoded string to an encoding suitable for a Mac OS X filename? | I have a Localized.strings (UTF-16) file that contains some strings that I use to generate filenames for. I open the file in python with codecs.open("Localized.strings", "r", "utf-16")
The files are created successfully but with a '?' tacked onto the end of the filename, for example:
MainMenu.strings? - where the "?" ... | [
"OK, when reading lines from a file, it's advisable to always strip() or rstrip() them. :)\n"
] | [
1
] | [] | [] | [
"macos",
"python",
"utf_16",
"utf_8"
] | stackoverflow_0006934692_macos_python_utf_16_utf_8.txt |
Q:
How can a non-assigned string in Python have an address in memory?
Can someone explain this to me? So I've been playing with the id() command in python and came across this:
>>> id('cat')
5181152
>>> a = 'cat'
>>> b = 'cat'
>>> id(a)
5181152
>>> id(b)
5181152
This makes some sense to me except for one part: The s... | How can a non-assigned string in Python have an address in memory? | Can someone explain this to me? So I've been playing with the id() command in python and came across this:
>>> id('cat')
5181152
>>> a = 'cat'
>>> b = 'cat'
>>> id(a)
5181152
>>> id(b)
5181152
This makes some sense to me except for one part: The string 'cat' has an address in memory before I assign it to a variable. I... | [
"Python reuses string literals fairly aggressively. The rules by which it does so are implementation-dependent, but CPython uses two that I'm aware of:\n\nStrings that contain only characters valid in Python identifiers are interned, which means they are stored in a big table and reused wherever they occur. So, no ... | [
53,
48,
17,
8,
1
] | [] | [] | [
"memory_address",
"python"
] | stackoverflow_0006931880_memory_address_python.txt |
Q:
Replicate Java into Python
I'm not very well-versed in how the internets work, so I'm not really sure what this java method is doing or how to best replicate it in python. I have tried several different methods including urllibs and sockets, but nothing seems to work. The only time I get a response I end up gettin... | Replicate Java into Python | I'm not very well-versed in how the internets work, so I'm not really sure what this java method is doing or how to best replicate it in python. I have tried several different methods including urllibs and sockets, but nothing seems to work. The only time I get a response I end up getting a huge HTML document when the ... | [
"it looks like it's opening a connection to sHOSTNAME, sending the XML data generated by make_XML (apparently as a single POST parameter called XMLData, so sPROTOCOL must be HTTP), and then processing the response in parseResp.\nin python you would use httplib. the final example at http://docs.python.org/library/ht... | [
1
] | [] | [] | [
"http",
"java",
"python",
"sockets",
"xml"
] | stackoverflow_0006946443_http_java_python_sockets_xml.txt |
Q:
How do I get the last non-empty item in a list in Python?
I just started learning Python today.
I have a list:
[text:u'Oranges', text:u'Apples', empty:'', empty:'']
How do I get the last non-empty item in a list? In this case, 'Apples'.
I see in Get first non-empty string from a list in python, they get the first... | How do I get the last non-empty item in a list in Python? | I just started learning Python today.
I have a list:
[text:u'Oranges', text:u'Apples', empty:'', empty:'']
How do I get the last non-empty item in a list? In this case, 'Apples'.
I see in Get first non-empty string from a list in python, they get the first non-empty value. Not sure how to get the last.
| [
"next(s for s in reversed(list_of_string) if s)\n\nIf you really have a dictionary, use reversed(dictionary.values()), but keep in mind that anything you do to the dictionary can change it's ordering, and it's not ordered in a consistent way between different versions of Python even for a given state. \nUse an Orde... | [
9,
6
] | [] | [] | [
"generator",
"list",
"python"
] | stackoverflow_0006946578_generator_list_python.txt |
Q:
how to install python pip on python 2.7
2 days ago i had a problem with pypm and couldn't fix it so i uninstalled activepython, and I wanna install pip which suppose to be an alternative to pypm
I've been looking around for 6h and still stuck lol, I have installed setuptools, now what and how to run pip? from the ... | how to install python pip on python 2.7 | 2 days ago i had a problem with pypm and couldn't fix it so i uninstalled activepython, and I wanna install pip which suppose to be an alternative to pypm
I've been looking around for 6h and still stuck lol, I have installed setuptools, now what and how to run pip? from the command line? from python command line?...if ... | [
"\n2 days ago i had a problem with pypm and couldn't fix it\n\nI've responded to this problem in the ActiveState forum.\n\nso i uninstalled activepython, and I wanna install pip\n [...]\n I have installed setuptools,\n [...]\n I downloaded distribute\n\nThere is no reason why have to uninstall ActivePython. Eve... | [
2,
1
] | [] | [] | [
"easy_install",
"pip",
"pypi",
"python",
"virtualenv"
] | stackoverflow_0006940396_easy_install_pip_pypi_python_virtualenv.txt |
Q:
Translating in Perl (brief)
I am having trouble translatin this section to python.
If you guys could help it would be great!
Thanks!
@Node_Coords = ($x, $y, $z, $ZYX[$z][$y][$x][0]);
push @{ $HoA{$BufferNum} } , @Node_Coords;
A:
node_coords = x, y, z, zyx[z][y][x][0]
hoa[buffer_name].extend(node_coords)
| Translating in Perl (brief) | I am having trouble translatin this section to python.
If you guys could help it would be great!
Thanks!
@Node_Coords = ($x, $y, $z, $ZYX[$z][$y][$x][0]);
push @{ $HoA{$BufferNum} } , @Node_Coords;
| [
"node_coords = x, y, z, zyx[z][y][x][0]\nhoa[buffer_name].extend(node_coords)\n\n"
] | [
4
] | [] | [] | [
"arrays",
"hash",
"perl",
"python"
] | stackoverflow_0006946428_arrays_hash_perl_python.txt |
Q:
Reading a Dialog Box in Python
I am trying to automate a daily routine I do using Python. Using the win32gui library I have been able to put a cursor in a position, click, and sendkeys. During this task, several message/dialog boxes pop up, asking yes or no, to certain questions. I would like to be able to read ... | Reading a Dialog Box in Python | I am trying to automate a daily routine I do using Python. Using the win32gui library I have been able to put a cursor in a position, click, and sendkeys. During this task, several message/dialog boxes pop up, asking yes or no, to certain questions. I would like to be able to read the question in the message box , bu... | [
"Just to give you one possibility, you may be able to copy the full contents of a dialog box to the clipboard by sending a Ctrl-C with sendkeys while focus is on the dialog. The contents of the clipboard will generally look something like this:\n[Window Title]\nRename\n\n[Content]\nIf you change a file name extens... | [
1
] | [] | [] | [
"python",
"win32gui"
] | stackoverflow_0006752075_python_win32gui.txt |
Q:
python can't logging messages to cmd
My code as below, the problem is log.info("message") can't be printed to my console and log.error("message") can:
log = None
def initLogger():
global log
log = logging.getLogger("JsSDKBuilder")
console = logging.StreamHandler(sys.stdout)
console.setFormatter(lo... | python can't logging messages to cmd | My code as below, the problem is log.info("message") can't be printed to my console and log.error("message") can:
log = None
def initLogger():
global log
log = logging.getLogger("JsSDKBuilder")
console = logging.StreamHandler(sys.stdout)
console.setFormatter(logging.Formatter('[%(levelname)s] %(message... | [
"Instead of your own code, use this:\nlogging.basicConfig(level=logging.INFO)\n\n",
"Do you need to global log at the top of your main() ?\n"
] | [
1,
0
] | [] | [] | [
"logging",
"python"
] | stackoverflow_0006946942_logging_python.txt |
Q:
Can I get a socket.makefile to have the same read semantics as a regular file?
Python file objects have a read method which takes an optional size argument, which is basically the maximum number of bytes to return. For example:
fname = "message.txt"
open(fname, "w").write("Hello World!")
print open(fname).read() ... | Can I get a socket.makefile to have the same read semantics as a regular file? | Python file objects have a read method which takes an optional size argument, which is basically the maximum number of bytes to return. For example:
fname = "message.txt"
open(fname, "w").write("Hello World!")
print open(fname).read() # prints the entire file contents
print open(fname).read(5) # print "Hello"
print... | [
"The problem here is that client.read() tries to read from current position to the EOF, but the EOF for the socket appears only when the other side closes the connection. recv on the other hand will return any data ready to be read (if there are any), or may block according to blocking and timeout settings.\nCompar... | [
27
] | [] | [] | [
"file",
"io",
"python",
"sockets"
] | stackoverflow_0006946629_file_io_python_sockets.txt |
Q:
How to unpack Javascript in Python
I would like to retrieve the contents of a javascript script instead of executing it upon requesting it.
EDIT: I understand that Python is not executing the javascript code. The issue is that when I request this online JS script it gets executed. I'm unable to retrieve the conte... | How to unpack Javascript in Python | I would like to retrieve the contents of a javascript script instead of executing it upon requesting it.
EDIT: I understand that Python is not executing the javascript code. The issue is that when I request this online JS script it gets executed. I'm unable to retrieve the contents of the script. Maybe what I want is ... | [
"There is no HTML or JavaScript interpreter in urllib2. This module does nothing but fetch the resource and return it to you raw; it certainly will not attempt to execute any JavaScript code it receives. If you are not receiving the response you expect, check the URL with a tool like wget or monitor the network con... | [
2,
1
] | [] | [] | [
"javascript",
"python"
] | stackoverflow_0006946867_javascript_python.txt |
Q:
Creating ARFF from word frequencies
I have some code that gives me a list of words with their frequencies that they occur in the text, I'm looking to make it so the code converts the top 10 words automatically into an ARFF with
@RELATION wordfrequencies
@ATTRIBUTE word string
@ATTRIBUTE frequency numeric
and the ... | Creating ARFF from word frequencies | I have some code that gives me a list of words with their frequencies that they occur in the text, I'm looking to make it so the code converts the top 10 words automatically into an ARFF with
@RELATION wordfrequencies
@ATTRIBUTE word string
@ATTRIBUTE frequency numeric
and the top 10 as data with their frequency.
I'm ... | [
"I hope you don't mind the slight rewrite:\nimport re\nimport nltk\nfrom collections import defaultdict\n\n# Quran subset\nfilename = 'subsetQuran.txt'\n\n# create list of lower case words\nword_list = open(filename).read().lower().split()\nprint 'Words in text:', len(word_list)\n\n# remove stopwords\nword_list = [... | [
1
] | [] | [] | [
"arff",
"nltk",
"python",
"weka",
"word_frequency"
] | stackoverflow_0005500482_arff_nltk_python_weka_word_frequency.txt |
Q:
How to add set elements to a string in python
how would I add set elements to a string in python? I tried:
sett = set(['1', '0'])
elements = ''
for i in sett:
elements.join(i)
but no dice. when I print elements the string is empty. help
A:
I believe you want this:
s = set(['1', '2'])
asString = ''.join(... | How to add set elements to a string in python | how would I add set elements to a string in python? I tried:
sett = set(['1', '0'])
elements = ''
for i in sett:
elements.join(i)
but no dice. when I print elements the string is empty. help
| [
"I believe you want this:\ns = set(['1', '2'])\n\nasString = ''.join(s)\n\nBe aware that sets are not ordered like lists are. They'll be in the order added typically until something is removed, but the order could be different than the order you added them.\n",
"Strings are immutable.\nelements.join(i) does not ... | [
4,
1,
0,
0
] | [
"Don't know what you mean with \"add set elements\" to a string. But anyway: Strings are immutable in Python, so you cannot add anything to them.\n"
] | [
-1
] | [
"python",
"set",
"string"
] | stackoverflow_0006947210_python_set_string.txt |
Q:
Searching and Matching a part of a string in a CSV file using Python
This is a part of a large csv file which I have:
"66.35.223.128","66.35.223.143","1109647232","1109647247","AU","Australia"
"66.35.223.144","66.35.227.191","1109647248","1109648319","US","United States"
"66.35.227.192","66.35.227.207","1109648320... | Searching and Matching a part of a string in a CSV file using Python | This is a part of a large csv file which I have:
"66.35.223.128","66.35.223.143","1109647232","1109647247","AU","Australia"
"66.35.223.144","66.35.227.191","1109647248","1109648319","US","United States"
"66.35.227.192","66.35.227.207","1109648320","1109648335","JP","Japan"
"66.35.227.208","66.35.230.31","1109648336","1... | [
"import csv\nwith open('GeoIPCountryWhois.csv', mode='r') as f:\n reader = csv.reader(f)\n for num, row in enumerate(reader):\n if '66.35' in row[0]:\n print num, row\n\nKeep in mind this can give you false positives if '66.35' appears at other locations in the address or elsewhere in the li... | [
5,
1,
0
] | [] | [] | [
"csv",
"file",
"parsing",
"python",
"string"
] | stackoverflow_0006947279_csv_file_parsing_python_string.txt |
Q:
Model imports failing between apps in django (circular imports?)
I am having problems importing models between my apps in my current django project. When trying to run the dev server or sync the database, I receive the error:
File "/path/to/Project/../Project/app1/models.py", line 3, in <module>
class SomeModel(Th... | Model imports failing between apps in django (circular imports?) | I am having problems importing models between my apps in my current django project. When trying to run the dev server or sync the database, I receive the error:
File "/path/to/Project/../Project/app1/models.py", line 3, in <module>
class SomeModel(Thing):
NameError: name 'Thing' is not defined
Thing is defined in Proj... | [
"If you want to subclass those models, you need to remove circular dependency. Refactor common stuff into another module, and make those two import that instead of each other. If the model is only used as a foreign key, you can use string instead of an object to defer the import (e.g. ForeignKey('app.Model') — see ... | [
3
] | [] | [] | [
"django",
"import",
"nameerror",
"python"
] | stackoverflow_0006947476_django_import_nameerror_python.txt |
Q:
EOFError whilst pickling in Python
Here's the problem - I'm trying to pickle, and then unpickle hiscores. When I use pickle.load, Python seems to think that I'm trying to load a file called 'Pickle' that I have. Here's the code:
def recieve_hiscores():
hiscores_file = open("hiscores_file.dat", "rb")
for i ... | EOFError whilst pickling in Python | Here's the problem - I'm trying to pickle, and then unpickle hiscores. When I use pickle.load, Python seems to think that I'm trying to load a file called 'Pickle' that I have. Here's the code:
def recieve_hiscores():
hiscores_file = open("hiscores_file.dat", "rb")
for i in hiscores_file:
hiscores = pic... | [
"When you iterate over the file, you get newline separated lines. This is NOT how you get a series of pickles. The end of file error is raised because the first line has a partial pickle.\nTry this:\ndef recieve_hiscores():\n highscores = []\n with open(\"hiscores_file.dat\", \"rb\") as hiscores_file:\n ... | [
3
] | [] | [] | [
"eoferror",
"pickle",
"python"
] | stackoverflow_0006947220_eoferror_pickle_python.txt |
Q:
Help me simplify this code (Python)
I'm a beginner in Python, teaching myself off of Google Code University. I had this problem as an exercise, and was able to solve it using the solution shown below:
# F. front_back
# Consider dividing a string into two halves.
# If the length is even, the front and back halves a... | Help me simplify this code (Python) | I'm a beginner in Python, teaching myself off of Google Code University. I had this problem as an exercise, and was able to solve it using the solution shown below:
# F. front_back
# Consider dividing a string into two halves.
# If the length is even, the front and back halves are the same length.
# If the length is od... | [
"def front_back(a, b):\n ad = (len(a) + 1) // 2\n bd = (len(b) + 1) // 2\n return a[:ad] + b[:bd] + a[ad:] + b[bd:]\n\nUsing // for division makes this code work in both Python 2.x and 3.x.\n",
"Well, put it in a separate function.\ndef front_back(string):\n offset = len(string) / 2\n if len(string... | [
12,
4,
3,
2,
2,
1,
1
] | [] | [] | [
"code_formatting",
"python",
"simplify"
] | stackoverflow_0006947214_code_formatting_python_simplify.txt |
Q:
Keep selection on Tkinter Entry widget despite not having focus
When a user selects a portion of text in a Tkinter Entry widget it becomes highlighted. However, when the user clicks away from the widget the highlighting disappears.
Is there any way to keep the selected text highlighted despite the Entry widget not... | Keep selection on Tkinter Entry widget despite not having focus | When a user selects a portion of text in a Tkinter Entry widget it becomes highlighted. However, when the user clicks away from the widget the highlighting disappears.
Is there any way to keep the selected text highlighted despite the Entry widget not having focus?
I'm attempting to make a custom right-click menu not ... | [
"You want to set the exportselection option of the text widget to False\ntext_widget.configure(exportselection=False)\n\n"
] | [
5
] | [] | [] | [
"focus",
"python",
"tkinter",
"tkinter_entry",
"widget"
] | stackoverflow_0006946684_focus_python_tkinter_tkinter_entry_widget.txt |
Q:
Store hourly clicks with sharded counter in google appengine
I'm developing an app in python for google app engine that count different kind of clicks with sharded counters.
My problem is that I want to get statistics split by hour from the clicks and not just a total sum of all clicks.
One way to achieve that is ... | Store hourly clicks with sharded counter in google appengine | I'm developing an app in python for google app engine that count different kind of clicks with sharded counters.
My problem is that I want to get statistics split by hour from the clicks and not just a total sum of all clicks.
One way to achieve that is to add a timestamp to the index of the shards:
def txn():
index ... | [
"Your solution will work - just use the task queue to aggregate your sharded records into nice, reporting-friendly, summary records as you go.\n"
] | [
1
] | [] | [] | [
"bigtable",
"google_app_engine",
"python",
"sharding"
] | stackoverflow_0006943471_bigtable_google_app_engine_python_sharding.txt |
Q:
Why can't I install Python 2.7 under Centos 5.5?
Centos 5.5 comes with python 2.4 installed, and I needed python 2.7 for a project. I downloaded the source, ran, removed, and tried again with a couple alternative builds:
./configure && make && make install
./configure && make && make altinstall
./configure --pre... | Why can't I install Python 2.7 under Centos 5.5? | Centos 5.5 comes with python 2.4 installed, and I needed python 2.7 for a project. I downloaded the source, ran, removed, and tried again with a couple alternative builds:
./configure && make && make install
./configure && make && make altinstall
./configure --prefix=/opt/python2.7 && make && make install
I proceed... | [
"First off you don't indicate that you have compiled Python with --enable-shared. If that isn't a default for that Python version, that is not desirable. As per:\nhttp://code.google.com/p/modwsgi/wiki/InstallationIssues#Lack_Of_Python_Shared_Library\nyou can check whether Python was installed with a shared library ... | [
1
] | [] | [] | [
"gcc",
"python",
"setuptools",
"virtualenv",
"wsgi"
] | stackoverflow_0006946413_gcc_python_setuptools_virtualenv_wsgi.txt |
Q:
EOL stops python on Calculate Field
Would anyone be able to help me modify these scripts to ignore the error and continue running ? I just need to figure out how to make the script skip over these errors and finish the rest of the lines.
Here is the full Python script:
# Import system modules
import sys, string, ... | EOL stops python on Calculate Field | Would anyone be able to help me modify these scripts to ignore the error and continue running ? I just need to figure out how to make the script skip over these errors and finish the rest of the lines.
Here is the full Python script:
# Import system modules
import sys, string, os, arcgisscripting
# Create the geoproc... | [
"First option: wrap the gp.CalculateField_management(...) in a try/except, like so:\ntry:\n gp.CalculateField_management(...)\nexcept SyntaxError:\n pass\n\nThis should allow your script to keep going, but I'm not sure what the state of gp will be.\nA better option would be to preprocess each file, and deal ... | [
1
] | [] | [] | [
"arcmap",
"calculated_field",
"eol",
"python"
] | stackoverflow_0005953284_arcmap_calculated_field_eol_python.txt |
Q:
Determining execution time of queries in SQLite
I am creating a program for analyzing and generating queries. I was curious if there currently exists a method within SQLite such that I could query the time taken for a query to process? I am unable to modify my install in any way, so this method needs to work out... | Determining execution time of queries in SQLite | I am creating a program for analyzing and generating queries. I was curious if there currently exists a method within SQLite such that I could query the time taken for a query to process? I am unable to modify my install in any way, so this method needs to work out of the box. I am writing my tool in python, and alt... | [
"From within the sqlite3 command-line program you can do:\n.timer ON\nselect * from my_table;\n\nThis will print the CPU time taken for the query.\n"
] | [
61
] | [] | [] | [
"python",
"sql",
"sqlite"
] | stackoverflow_0006948270_python_sql_sqlite.txt |
Q:
While Loops Problem with Python Twitter Crawler
I'm continuing writing my twitter crawler and am running into more problems. Take a look at the code below:
from BeautifulSoup import BeautifulSoup
import re
import urllib2
url = 'http://mobile.twitter.com/NYTimesKrugman'
def gettweets(soup):
tags = soup.findA... | While Loops Problem with Python Twitter Crawler | I'm continuing writing my twitter crawler and am running into more problems. Take a look at the code below:
from BeautifulSoup import BeautifulSoup
import re
import urllib2
url = 'http://mobile.twitter.com/NYTimesKrugman'
def gettweets(soup):
tags = soup.findAll('div', {'class' : "list-tweet"})#to obtain tweet o... | [
"Your checkforstamp function returns non-empty, defined strings:\nreturn 'True'\n\nSo (not stamp) will always be false.\nChange it to return booleans like are_more_tweets does:\nreturn True\n\nand it should be fine.\nFor reference, see the boolean operations documentation:\n\nIn the context of Boolean operations, a... | [
1,
1
] | [] | [] | [
"html",
"python",
"twitter",
"web_crawler",
"while_loop"
] | stackoverflow_0006948330_html_python_twitter_web_crawler_while_loop.txt |
Q:
Why does Python treat tuples, lists, sets and dictionaries as fundamentally different things?
One of the reasons I love Python is the expressive power / reduced programming effort provided by tuples, lists, sets and dictionaries. Once you understand list comprehensions and a few of the basic patterns using in and... | Why does Python treat tuples, lists, sets and dictionaries as fundamentally different things? | One of the reasons I love Python is the expressive power / reduced programming effort provided by tuples, lists, sets and dictionaries. Once you understand list comprehensions and a few of the basic patterns using in and for, life gets so much better! Python rocks.
However I do wonder why these constructs are treated... | [
"tl;dr (duck-typing)\nYou're correct to see some similarities in all these data structures. Remember that python uses duck-typing (if it looks like a duck and quacks like a duck then it is a duck). If you can use two objects in the same situation then, for your current intents and purposes, they might as well be th... | [
16,
16,
2,
1,
1,
0,
0,
0
] | [] | [] | [
"collections",
"language_design",
"python",
"zen_of_python"
] | stackoverflow_0006948383_collections_language_design_python_zen_of_python.txt |
Q:
Best language for Molecular Dynamics Simulator, to be run in production. (Python+Numpy?)
I need to build a heavy duty molecular dynamics simulator. I am wondering if python+numpy is a good choice. This will be used in production, so I wanted to start with a good language. I am wondering if I should rather start wi... | Best language for Molecular Dynamics Simulator, to be run in production. (Python+Numpy?) | I need to build a heavy duty molecular dynamics simulator. I am wondering if python+numpy is a good choice. This will be used in production, so I wanted to start with a good language. I am wondering if I should rather start with a functional language like eg.scala. Do we have enough library support for scientific compu... | [
"The high performing MD implementations tend to be decidedly imperative (as opposed to functional) with big arrays of data trumping object-oriented design. I've worked with LAMMPS, and while it has its warts, it does get the job done. A perhaps more appealing option is HOOMD, which has been optimized from the begin... | [
13,
6,
6,
3
] | [] | [] | [
"numpy",
"python",
"scala",
"scientific_computing",
"simulation"
] | stackoverflow_0006948483_numpy_python_scala_scientific_computing_simulation.txt |
Q:
Is there a way to have separate pages for inline admin forms in Django?
Lets say i have a model A. Then, i have several models B, C, D, E etc that each have a foreignKey to model A. I know that i can set B, C, D etc as inlines to model A so that when i create a model A it will show formsets for adding multiple i... | Is there a way to have separate pages for inline admin forms in Django? | Lets say i have a model A. Then, i have several models B, C, D, E etc that each have a foreignKey to model A. I know that i can set B, C, D etc as inlines to model A so that when i create a model A it will show formsets for adding multiple items for each subModel, but i think this would make a fairly cluttered and ve... | [
"I’m looking for a way to do exactly the same thing. It looks like the answer might be 'proxy models'. It's suggested as an answer to this Stack Overflow query:\n\ndjango admin: separate read-only view and change view\n\n…and this query asking about multiple admin lists for the same model:\n\nMultiple ModelAdmins/v... | [
2,
0
] | [] | [] | [
"django",
"django_admin",
"python"
] | stackoverflow_0002814526_django_django_admin_python.txt |
Q:
Fixing and cleaning form input in Django
Presumably the clean_ methods in Django are designed to allow inline cleaning of input form data as well as accepting/rejecting submissions.
Given a model where
"FooBar"
is valid input. Is there a standard way of fixing things like
"FOOBAR"
"foo-bar"
"FooBar "
in a somew... | Fixing and cleaning form input in Django | Presumably the clean_ methods in Django are designed to allow inline cleaning of input form data as well as accepting/rejecting submissions.
Given a model where
"FooBar"
is valid input. Is there a standard way of fixing things like
"FOOBAR"
"foo-bar"
"FooBar "
in a somewhat fuzzy and generalizable manner before vali... | [
"Okay it is unclear what you actually want to do about changing, but something like this should work:\nfrom re import sub\n...\n#in your form:\ndef clean_myfield(self):\n data = self.cleaned_data['myfield']\n #Strip special chars\n data = sub(\"[\\s_\\-]\",\"\",a)\n if b.lower() != \"foobar\":\n ... | [
1,
1
] | [] | [] | [
"django",
"python",
"validation"
] | stackoverflow_0006948034_django_python_validation.txt |
Q:
Missing 'C:\Windows\system32\python27.zip' file
I recently upgraded my Python 2.7.1 installation to 2.7.2 using the .msi installer and the process seemed to go OK. However afterwards I happened to be looking at what the default values were for sys.path and noticed the entry for 'C:\Windows\system32\python27.zip'. ... | Missing 'C:\Windows\system32\python27.zip' file | I recently upgraded my Python 2.7.1 installation to 2.7.2 using the .msi installer and the process seemed to go OK. However afterwards I happened to be looking at what the default values were for sys.path and noticed the entry for 'C:\Windows\system32\python27.zip'. Wondering exactly what was in it, I decided to try op... | [
"From PEP 273 -- Import Modules from Zip Archives:\n\nJust as sys.path currently has default directory names, a default zip\n archive name is added too. Otherwise there is no way to import all\n Python library files from an archive.\n...\nThe problem is what the name should be. The name should be linked\n with... | [
5
] | [] | [] | [
"module",
"python",
"windows",
"zip"
] | stackoverflow_0006948779_module_python_windows_zip.txt |
Q:
pysqlite, save database, and open it later
Newbie to sql and sqlite.
I'm trying to save a database, then copy the file.db to another folder and open it. So far I created the database, copy and pasted the file.db to another folder but when I try to access the database the output says that it is empty.
So far I hav... | pysqlite, save database, and open it later | Newbie to sql and sqlite.
I'm trying to save a database, then copy the file.db to another folder and open it. So far I created the database, copy and pasted the file.db to another folder but when I try to access the database the output says that it is empty.
So far I have
from pysqlite2 import dbapi2 as sqlite
conn ... | [
"You need something like \nc.execute(\"SELECT * FROM mytable\")\nfor row in c:\n #process row\n\n",
"I will echo Mat and point out that is not valid syntax. More than that, you do not include any select request (or other sql command) in your example. If you actually do not have a select statement in your cod... | [
2,
1
] | [] | [] | [
"copy",
"pysqlite",
"python"
] | stackoverflow_0006948958_copy_pysqlite_python.txt |
Q:
Scipy Leastsq Optional Output Variable (Mesg)
SciPy's documentation on LeastSq is here. It states that ier is
An integer flag. If it is equal to 1, 2, 3 or 4, the solution was found. Otherwise, the solution was not found. In either case, the optional output variable ‘mesg’ gives more information.
But how do I re... | Scipy Leastsq Optional Output Variable (Mesg) | SciPy's documentation on LeastSq is here. It states that ier is
An integer flag. If it is equal to 1, 2, 3 or 4, the solution was found. Otherwise, the solution was not found. In either case, the optional output variable ‘mesg’ gives more information.
But how do I retrieve the optional variable mesg?
x,ier=leastsq(re... | [
"Use the full_output parameter:\nimport scipy.optimize as optimize\np,cov,infodict,mesg,ier = optimize.leastsq(\n residuals,p_guess,args=(x,y),full_output=True)\n\n"
] | [
3
] | [] | [] | [
"python",
"scipy"
] | stackoverflow_0006949049_python_scipy.txt |
Q:
Remembering Custom and Third Party Cookies Post Django Login
I've noticed that logging in a user using django.contrib.auth.login deletes all custom and third party cookies previously set. This is breaking lots of things, such as my Google Web Optimizer tests, which can no longer track the user. What's the best way... | Remembering Custom and Third Party Cookies Post Django Login | I've noticed that logging in a user using django.contrib.auth.login deletes all custom and third party cookies previously set. This is breaking lots of things, such as my Google Web Optimizer tests, which can no longer track the user. What's the best way to prevent this when logging in a user?
Looking at the code for l... | [
"are you sure your cookies are really on the same domain?\nTwo different domains\nwww.mysite.com\nmysite.com\n\nI've never had django screw with cookies, but I have had www vs non-www cookie issues.\n"
] | [
0
] | [] | [] | [
"cookies",
"django",
"django_authentication",
"python"
] | stackoverflow_0006946458_cookies_django_django_authentication_python.txt |
Q:
Python: login using 1 username but different passwords
I am trying to write a function that will understand how to login using one username but several passwords .
import sys
def login():
username = raw_input('username')
password = raw_input('password')
if username == 'pi':
return password
... | Python: login using 1 username but different passwords | I am trying to write a function that will understand how to login using one username but several passwords .
import sys
def login():
username = raw_input('username')
password = raw_input('password')
if username == 'pi':
return password
# if the correct user name is returned 'pi' I want to... | [
"\nif the correct user name is returned 'pi' I want to be prompted to enter a password.\n\nYour code prompts for both username and password. Only after that it checks what was entered.\nAssuming you want your login function to return the values and not to print them out, I believe what you want is something like th... | [
4,
2,
2
] | [] | [] | [
"function",
"python",
"raw_input"
] | stackoverflow_0006948969_function_python_raw_input.txt |
Q:
Python Tkinter Root Title doesn't work
I can't seem to title my windows. They all have the title "Tk".I believe my code is correct, so correct me if this is wrong...
from Tkinter import *
root = Tk()
root.title="Title"
root.mainloop()
The title is still Tk(). Could I maybe from Tkinter import Tk as MyTitle?
A... | Python Tkinter Root Title doesn't work | I can't seem to title my windows. They all have the title "Tk".I believe my code is correct, so correct me if this is wrong...
from Tkinter import *
root = Tk()
root.title="Title"
root.mainloop()
The title is still Tk(). Could I maybe from Tkinter import Tk as MyTitle?
| [
"root.title(\"Title\")\n\nTry that, its a method you invoke and pass in the parameter.\n"
] | [
21
] | [] | [] | [
"python",
"tkinter",
"user_interface"
] | stackoverflow_0006949265_python_tkinter_user_interface.txt |
Q:
Choose between many-to-many techniques in App Engine DB
There is going to be "articles" and "tags" in my App Engine application.
And there are two techniques to implement that (thanks to Nick Johnson's article):
# one entity just refers others
class Article(db.Model):
tags = db.ListProperty(Tag)
# via separate ... | Choose between many-to-many techniques in App Engine DB | There is going to be "articles" and "tags" in my App Engine application.
And there are two techniques to implement that (thanks to Nick Johnson's article):
# one entity just refers others
class Article(db.Model):
tags = db.ListProperty(Tag)
# via separate "join" table
class ArticlesAndTags(db.Model):
article = db.... | [
"Because of the lack of a 'reduce' feature in appengine's map reduce (nor an SQL group by like query), tag clouds are tricky to implement efficiently because you need to count all tags you have manually. Which ever implementation you go with, what I would suggest for the tag cloud is to have a separate model TagCou... | [
2,
2,
1,
0
] | [] | [] | [
"database_design",
"django_models",
"google_app_engine",
"python"
] | stackoverflow_0006943524_database_design_django_models_google_app_engine_python.txt |
Q:
Python Generator
def countDown(i):
if i<> 0:
For j in countDown( i - 1 ):
yield j
yield i
if __name__ == '__main__':
for k in countDown(5):
print k
if k == 6 : break
On debugging this code , the execution path was bit different from what I exp... | Python Generator | def countDown(i):
if i<> 0:
For j in countDown( i - 1 ):
yield j
yield i
if __name__ == '__main__':
for k in countDown(5):
print k
if k == 6 : break
On debugging this code , the execution path was bit different from what I expected.
My expectation:... | [
"Maybe this will clarify the order in which the calls/yields occur:\nEdit:\ndef countDown(i):\n if i<> 0:\n for j in countDown( i - 1 ):\n yield 'inner : ' + str(j)\n yield 'outer : ' + str(i) \n\n>>> for k in countDown(5): print k\n... \ninner : inner : inner : inner : outer : 1\ninne... | [
2,
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0006935106_python.txt |
Q:
SciPy LeastSq Dfun Usage
I'm trying to get my Jacobian to work with SciPy's Optimize library's leastsq function.
I have the following code:
#!/usr/bin/python
import scipy
import numpy
from scipy.optimize import leastsq
#Define real coefficients
p_real=[3,5,1]
#Define functions
def func(p, x): #Function
... | SciPy LeastSq Dfun Usage | I'm trying to get my Jacobian to work with SciPy's Optimize library's leastsq function.
I have the following code:
#!/usr/bin/python
import scipy
import numpy
from scipy.optimize import leastsq
#Define real coefficients
p_real=[3,5,1]
#Define functions
def func(p, x): #Function
return p[0]*numpy.exp(-p[1]... | [
"Change residuals to its negative:\ndef residuals(p, x, y):\n return func(p, x)-y\n\nand you get\n[ 3. 5. 1.]\n\nHope this helps :)\n"
] | [
4
] | [] | [] | [
"python",
"scipy"
] | stackoverflow_0006949370_python_scipy.txt |
Q:
Has threading in GTK w/ Python changed in PyGObject introspection?
I'm in the process of converting a program from PyGTK to PyGObject introspection for the first time and I've hit a roadblock with threading. I have a process that takes some time to complete, so I pop up a dialog with a progress bar on it and I use... | Has threading in GTK w/ Python changed in PyGObject introspection? | I'm in the process of converting a program from PyGTK to PyGObject introspection for the first time and I've hit a roadblock with threading. I have a process that takes some time to complete, so I pop up a dialog with a progress bar on it and I use a thread to do the process and to update the progress bar. This worked ... | [
"I managed to answer my own question by poking through some Gnome programs written in Python (Gnome Sudoku, in this case, which actually has helped me a couple of times).\nThe trick is that you have to call GObject.threads_init() at the beginning of your code, not GLib.thread_init() as the C documentation implies.\... | [
27
] | [] | [] | [
"gtk",
"multithreading",
"pygobject",
"pygtk",
"python"
] | stackoverflow_0006943098_gtk_multithreading_pygobject_pygtk_python.txt |
Q:
python help with extracting value from list
lst = [{"id": 1, "name": "ernest"}, .... {"id": 16, name:"gellner"}]
for d in lst:
if "id" in d and d["id"] == 16:
return d
I want to extract the dictionary that the key "id" equals to "16" from the list.
Is there a more pythonic way of this?
Thanks in adv... | python help with extracting value from list | lst = [{"id": 1, "name": "ernest"}, .... {"id": 16, name:"gellner"}]
for d in lst:
if "id" in d and d["id"] == 16:
return d
I want to extract the dictionary that the key "id" equals to "16" from the list.
Is there a more pythonic way of this?
Thanks in advance
| [
"Riffing on existing answers to get out of the comments:\nConsider using a generator expression when you only need the first matching element out of a sequence: \nd16 = (d for d in lst if d.get('id') == 16).next()\n\nThis is a pattern you'll see in my code often. This will raise a StopIteration if it turns out the... | [
4,
2,
1
] | [] | [] | [
"dictionary",
"list",
"python"
] | stackoverflow_0006949562_dictionary_list_python.txt |
Q:
Might GQL IN operator be used to search entities which have an item in a list Property?
I mean, if you have a model, just like this (Python)
class MahModel(db.Model):
which has a tags property(for instance)
tags = db.StringListProperty()
Can I do something like this in a query? WHERE 'x' IN tags
If not, w... | Might GQL IN operator be used to search entities which have an item in a list Property? | I mean, if you have a model, just like this (Python)
class MahModel(db.Model):
which has a tags property(for instance)
tags = db.StringListProperty()
Can I do something like this in a query? WHERE 'x' IN tags
If not, what kind of workaround could I use?
My actual code is like follows:
Ad.gql("WHERE paid = True... | [
"WHERE tags = 'x'\n\nwill return any entities that have 'x' at least once in the list.\n"
] | [
1
] | [] | [] | [
"datastore",
"google_app_engine",
"gql",
"python"
] | stackoverflow_0006949734_datastore_google_app_engine_gql_python.txt |
Q:
problem with accesing multiple values using django
I am new to python and I am using django for student database application .
Student database application must show id, firstname,lastname,subjectnames,marks.
Single student is having multiple subjects and their marks.
I am getting problem with accessing multiple v... | problem with accesing multiple values using django | I am new to python and I am using django for student database application .
Student database application must show id, firstname,lastname,subjectnames,marks.
Single student is having multiple subjects and their marks.
I am getting problem with accessing multiple values that student is having multiple subjects and marks... | [
"Your problem seems to lie in your how you try to create Marksheet, you can't assign a list of values to one field like that.\nUsing your currently formless, scary, no-validation, setup... you can do something like this-\np1=Person(firstname=request.POST['firstname'], \n lastname=request.POST['lastname'])\... | [
1,
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0006942106_django_python.txt |
Q:
python mechanize problem with selectcontrol
basically one of the select controls has a few "options" in which to choose from
if i use:
for t in br.forms():
print t
the output i get is
`SelectControl(ctl00$cph2$ddlSchool=[*2])
SelectControl(ctl00$cph2$ddlMarkingPeriod=[*1, 2, 3, 4])
SelectControl(ctl00$c... | python mechanize problem with selectcontrol | basically one of the select controls has a few "options" in which to choose from
if i use:
for t in br.forms():
print t
the output i get is
`SelectControl(ctl00$cph2$ddlSchool=[*2])
SelectControl(ctl00$cph2$ddlMarkingPeriod=[*1, 2, 3, 4])
SelectControl(ctl00$cph2$ddlCourseSection=[*1120:01:1, 1515:01:1, 2445... | [
"It looks to me like you're trying to assign multiple values to a single-select form field. You would have to have a multi-select to do that successfully. The asterisk indicates the selected element, the non-asterisk'd items are the other options in the list. Are you sure that you are working with a multi-select an... | [
0,
0
] | [] | [] | [
"asterisk",
"list",
"mechanize",
"python",
"screen_scraping"
] | stackoverflow_0006949773_asterisk_list_mechanize_python_screen_scraping.txt |
Q:
writing fixed width, space delimited CSV output in Python
I would like to write a fixed width, space delimited and minimally quoted CSV file using Python's csv writer.
An example of the output:
item1 item2
"next item1" "next item2"
anotheritem1 anotheritem2
If I use
writer.writerow( ("{0:15s}... | writing fixed width, space delimited CSV output in Python | I would like to write a fixed width, space delimited and minimally quoted CSV file using Python's csv writer.
An example of the output:
item1 item2
"next item1" "next item2"
anotheritem1 anotheritem2
If I use
writer.writerow( ("{0:15s}".format(item1), "{0:15s}".format(item2)) )
...
then, with t... | [
"The basic problem you are running into is that csv and fixed-format are basically opposing views of data storage. Making them work together is not a common practice. Also, if you only have quotes on the items with spaces in them, it will throw off the alignment on those rows:\ntesting \"rather hmm \"\nstrang... | [
8,
2,
0
] | [] | [] | [
"csv",
"fixed_width",
"python",
"space"
] | stackoverflow_0005638334_csv_fixed_width_python_space.txt |
Q:
How do I get rid of the arrow in a Tix.Balloon widget?
When I use the standard Tix.Balloon widget, bind it to a button and use a balloonmsg, I get the tooltip over the button, but I also get a stupid looking arrow inside the tooltip. (See the demo code from the Python source tree here.) Is it possible to get rid o... | How do I get rid of the arrow in a Tix.Balloon widget? | When I use the standard Tix.Balloon widget, bind it to a button and use a balloonmsg, I get the tooltip over the button, but I also get a stupid looking arrow inside the tooltip. (See the demo code from the Python source tree here.) Is it possible to get rid of this arrow, or do I need to use another type of widget to ... | [
"This will set the arrow image to a blank bitmap\nb = Tix.Balloon(root)\nb.subwidget('label')['image'] = Tkinter.BitmapImage()\n\nThere are two subwidgets within a balloon, label which is the arrow and message which is the text.\nI'm still new to python so there might be a better way to actually remove the arrow in... | [
1
] | [] | [] | [
"python",
"tix",
"tkinter"
] | stackoverflow_0004743169_python_tix_tkinter.txt |
Q:
Persistent In-Memory Storage in Python
I'm hoping to write a custom data model for my web application that exists in memory as a collection of custom python objects. The web application could manipulate data on these objects and run their methods on user requests, and after a request thread dies the objects persis... | Persistent In-Memory Storage in Python | I'm hoping to write a custom data model for my web application that exists in memory as a collection of custom python objects. The web application could manipulate data on these objects and run their methods on user requests, and after a request thread dies the objects persist in memory.
The model objects would have me... | [
"I think this mostly depends on how much work you want to put into what looks like building your own ORM.\nIf you're feeling up to the task of serializing your python objects, and depending on the complexity of your models, you could give a shot at Redis.\nRedis is a non-relational database, based on a key-value mo... | [
2
] | [] | [] | [
"design_patterns",
"models",
"python",
"web_applications"
] | stackoverflow_0006950045_design_patterns_models_python_web_applications.txt |
Q:
Package them all! Perl, python, java for naive users (in windows)
I have several scripts written in perl, python, and java (wrapped under java GUI with system calls to perl & python). And I have many not-tech-savy users that need to use this in their windows machines (xp & 7).
To avoid users from installing perl,... | Package them all! Perl, python, java for naive users (in windows) | I have several scripts written in perl, python, and java (wrapped under java GUI with system calls to perl & python). And I have many not-tech-savy users that need to use this in their windows machines (xp & 7).
To avoid users from installing perl,python,and java and to avoid potential incompatibility between various ... | [
"Try Portable Python and Portable Perl. You can unzip them into your application tree and they should work.\n",
"Why don't you try migrating your perl/python code into java and then packagin everything into a nice webstart application? What do perl/python offer that java doesn't support?\nFor perl you can use som... | [
2,
1
] | [] | [] | [
"installation",
"java",
"perl",
"python",
"windows"
] | stackoverflow_0006949915_installation_java_perl_python_windows.txt |
Q:
Python command line argument for an existing process
I am trying to write a script for controling cpu usage of a VM n KVM using cpulimit. With cpulimit i can limit the cpu usage of a VM with pid say 2112 by :
./cpulimit -p 2112 -l 50.
I want to write a script which can open an interface
setcpu (vm_pid,limit)... | Python command line argument for an existing process | I am trying to write a script for controling cpu usage of a VM n KVM using cpulimit. With cpulimit i can limit the cpu usage of a VM with pid say 2112 by :
./cpulimit -p 2112 -l 50.
I want to write a script which can open an interface
setcpu (vm_pid,limit)
Which can be called any number of times and I shud overw... | [
"Edit: If you need to talk to an existing cpulimit, you should look at the accepted answer to How to write data to existing process's STDIN from external process?\nBasically, do\n(while [ 1 ]; do sleep 1; done) | ./cpulimit -p 2112 -l 50.\n\nwhen you start cpulimit, because it's input needs to be a pipe. \nThen, fr... | [
1,
0
] | [] | [] | [
"arguments",
"linux",
"process",
"python"
] | stackoverflow_0006949959_arguments_linux_process_python.txt |
Q:
Proxy Server that supports smart pipelining/multiplexing
So, I want to develop a proxy server that when contacted checks the size of what it will be downloading to proxy (using head most likely) and if it's over a set size it splits the download of the request via pipelining and using Range into generally good siz... | Proxy Server that supports smart pipelining/multiplexing | So, I want to develop a proxy server that when contacted checks the size of what it will be downloading to proxy (using head most likely) and if it's over a set size it splits the download of the request via pipelining and using Range into generally good sized (1 megabyte or possibly using a config file) segments. The... | [
"I would look at twisted http://twistedmatrix.com/trac/ it is an great event based networking library for python. It takes a bit of getting used to, but it does this kind of thing very well.\n"
] | [
1
] | [] | [] | [
"http",
"pipelining",
"proxy",
"python",
"twisted"
] | stackoverflow_0006528399_http_pipelining_proxy_python_twisted.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.