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:
Why can't I get two lists from one list comprehension?
So I have an array of the following form:
[(1, u'first_type', u'data_gid_1'),
(2, u'first_type', u'data_gid_2'),
(3, u'first_type', u'data_gid_3'),
(4, u'first_type', u'data_gid_4')]
Now I want to extract the first and the last element of each inside li... | Why can't I get two lists from one list comprehension? | So I have an array of the following form:
[(1, u'first_type', u'data_gid_1'),
(2, u'first_type', u'data_gid_2'),
(3, u'first_type', u'data_gid_3'),
(4, u'first_type', u'data_gid_4')]
Now I want to extract the first and the last element of each inside list into separate lists. So if I do:
>>> ids = [dat[0] for da... | [
"It doesn't work because the length of [(dat[0], dat[2]) for dat in all_data] is the same as the lenght of all_data, which is not the same length as the tuple (ids, gds).\nTry this instead:\n(ids, gds) = zip(*[(dat[0], dat[2]) for dat in all_data])\n\nor even shorter:\n(ids, gds) = zip(*all_data)[::2]\n\nAs noted i... | [
9,
4,
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0007105006_python.txt |
Q:
C++ equivalent of Python properties
Is there an equivalent of Python properties in C++? Or would it just be better to do this using getters and setters?
A:
In C++ you're either calling a member function, or you're accessing a data member. Python properties are essentially a way of doing the former using the synt... | C++ equivalent of Python properties | Is there an equivalent of Python properties in C++? Or would it just be better to do this using getters and setters?
| [
"In C++ you're either calling a member function, or you're accessing a data member. Python properties are essentially a way of doing the former using the syntax of the latter and there's no sensible way to do that in C++.\nIn theory you could hack together something with a macro, #define looks_like_data really_a_fu... | [
14,
13,
7
] | [] | [] | [
"c++",
"properties",
"python"
] | stackoverflow_0007105202_c++_properties_python.txt |
Q:
Performance of symmetric sparse matrix of dimension 5 000 000: Save to Database or File?
I have a huge dataset (around 5 000 000 rows in a database) which I want to represent as a graph. For algorithmic reasons it is required to store the dataset in a adjacency matrix. The Matrix will be very sparse and symmmetric... | Performance of symmetric sparse matrix of dimension 5 000 000: Save to Database or File? | I have a huge dataset (around 5 000 000 rows in a database) which I want to represent as a graph. For algorithmic reasons it is required to store the dataset in a adjacency matrix. The Matrix will be very sparse and symmmetric.
First I thought of storing the graph in a database table. This would require 5 000 000 rows,... | [
"You can use the numpy sparse matrix format. But all of your questions depend on the number of non-zero entries (NNZ) in the matrix. Storage and lots of computations are dependent (approximately) only on the NNZ. Start here.\n",
"I suggest using a dict to represent the matrix, which you can wrap in a class if you... | [
2,
0
] | [] | [] | [
"database",
"file",
"python",
"sparse_matrix"
] | stackoverflow_0007102933_database_file_python_sparse_matrix.txt |
Q:
PYTHON: How to take a .txt file as input from user using raw_input in Python and then read that file row wise?
I want to take a .txt file as input from user through raw_input.
Once the input is taken, I want the txt file name given by user to be accessed and the contents from it written into another file (each in ... | PYTHON: How to take a .txt file as input from user using raw_input in Python and then read that file row wise? | I want to take a .txt file as input from user through raw_input.
Once the input is taken, I want the txt file name given by user to be accessed and the contents from it written into another file (each in next row).
I am having a problem with how to connect a and b above or how to link raw input with reading of file. I ... | [
"for row in data: \n row = row.strip().split(';')\n\nThe fact that you perform split(';') has for consequence that a row (you should write: line) split according to ';' gives always a not empty list, even if it is an empty line, and even after having been stripped with strip() : ''.split(';') gives [''] . So you... | [
3,
0
] | [] | [] | [
"python"
] | stackoverflow_0007102030_python.txt |
Q:
How to set default encoding in Python (setdefaultencoding() function does not exist)?
Possible Duplicate:
Changing default encoding of python?
I am reading dive in python and it mentions setting python's default encoding scheme in the XML parsing chapter.
The setdefaultencoding is used in python-installed-dir... | How to set default encoding in Python (setdefaultencoding() function does not exist)? |
Possible Duplicate:
Changing default encoding of python?
I am reading dive in python and it mentions setting python's default encoding scheme in the XML parsing chapter.
The setdefaultencoding is used in python-installed-dir/site-packages/pyanaconda/sitecustomize.py
import sys
sys.setdefaultencoding('utf-8')
But... | [
"Python's sys module has had a setdefaultencoding function since Python 2.0. However,\n\nThis function is only intended to be used by the site module implementation and, where needed, by sitecustomize. Once used by the site module, it is removed from the sys module’s namespace.\n\nThe docs back to at least Python 2... | [
8,
7
] | [] | [] | [
"default",
"encoding",
"python"
] | stackoverflow_0007105441_default_encoding_python.txt |
Q:
Divide number into digits and save them in list (array) using python
I want to divide number into digits and save them in list (or array) in python. So firstly I should create list like
dig = [0 for i in range(10)]
and then
i = 0
while num > 9:
dig[i] = num % 10
i += 1
num /= 10
dig[i] = num
But I d... | Divide number into digits and save them in list (array) using python | I want to divide number into digits and save them in list (or array) in python. So firstly I should create list like
dig = [0 for i in range(10)]
and then
i = 0
while num > 9:
dig[i] = num % 10
i += 1
num /= 10
dig[i] = num
But I don't really like just creating list for 10 spaces, is it possible to get l... | [
"Since you're just adding the digits from smallest to greatest in order, just use an empty list:\ndig = []\ni = 0\nwhile num > 9:\n dig.append(num % 10)\n i += 1\n num /= 10\ndig.append(num)\n\nAlternatively, just do\ndig = list(int(d) for d in str(num))\n\nWhich will turn i.e. 123 into '123' then turn eac... | [
10,
5,
2
] | [] | [] | [
"arrays",
"digits",
"list",
"numbers",
"python"
] | stackoverflow_0007106276_arrays_digits_list_numbers_python.txt |
Q:
long time cron in App Engine
I want to rewrite a webapp to Python and to use App Engine but I have several cron scripts that can be long running. Some time ago I used App Engine and wanted to know if there are now methods to run these scripts because App Engine has its limits.
If you want to get an idea of one o... | long time cron in App Engine | I want to rewrite a webapp to Python and to use App Engine but I have several cron scripts that can be long running. Some time ago I used App Engine and wanted to know if there are now methods to run these scripts because App Engine has its limits.
If you want to get an idea of one of the scripts there is one that ca... | [
"Well, you won't be running any SQL queries, because AppEngine doesn't use SQL.\nTwo new options for running expensive calculations are backends and MapReduce - which you choose depends on exactly what you want to achieve.\n",
"If it's just the scheduling scripts that you're asking about, then there is cron for A... | [
2,
0
] | [] | [] | [
"cron",
"google_app_engine",
"python"
] | stackoverflow_0007106405_cron_google_app_engine_python.txt |
Q:
two question about python regular expressions
Q1. why we can not use word boundary and back reference without using r at start of regex?
e.g. '\b[a-z]{5}\d{3}\b' this not works but this r'\b[a-z]{5}\d{3}\b' works
Q2. why python does not support variable length negative look behind assertions while it supports vari... | two question about python regular expressions | Q1. why we can not use word boundary and back reference without using r at start of regex?
e.g. '\b[a-z]{5}\d{3}\b' this not works but this r'\b[a-z]{5}\d{3}\b' works
Q2. why python does not support variable length negative look behind assertions while it supports variable length negative look ahead assertion, c# suppo... | [
"It does work without raw strings:\n'\\\\b[a-z]{5}\\\\d{3}\\\\b'\n\nYou just need to double escape the special chars (actually, what you do is escape all backslashes).\nVariable length assertions are one of those features that some implementations support and some don't. Check out the regex module on PyPI for a ver... | [
4,
1,
0
] | [] | [] | [
"c#",
"python",
"regex"
] | stackoverflow_0007106487_c#_python_regex.txt |
Q:
Something from string in list python
I have a list with keywords id = ['pop','ppp','cre'] and now I am going through a bunch of files/large strings and if any of these keywords are in these files than I have to be able to do something...
like:
id = ['pop','ppp','cre']
if id in dataset:
print id
But i thi... | Something from string in list python | I have a list with keywords id = ['pop','ppp','cre'] and now I am going through a bunch of files/large strings and if any of these keywords are in these files than I have to be able to do something...
like:
id = ['pop','ppp','cre']
if id in dataset:
print id
But i think now all of these 3 or later maybe more ... | [
"You can use all to make sure all the values in your id list are in the dataset:\nid = ['pop', 'ppp', 'cre']\nif all(i in dataset for i in id):\n print id\n\n",
"Your code as it stands will actually look through dataset for the entire list \"['pop', 'ppp', 'cre']\". Why don't you try something like this:\nfor ... | [
1,
1,
1
] | [] | [] | [
"list",
"python"
] | stackoverflow_0007106614_list_python.txt |
Q:
How to write Big files into Blobstore using experimental API?
I have dilemma.. I'm uploading files both in scribd store and blobstore using tipfy as framework.
I have webform with action is not created by blobstore.create_upload_url (i'm just using url_for('myhandler')). I did it because if i'm using blobstore han... | How to write Big files into Blobstore using experimental API? | I have dilemma.. I'm uploading files both in scribd store and blobstore using tipfy as framework.
I have webform with action is not created by blobstore.create_upload_url (i'm just using url_for('myhandler')). I did it because if i'm using blobstore handler the POST response parsed and I cannot use normal python-scribd... | [
"You need to make multiple, smaller calls to the file API, for instance like this:\nwith files.open(file_name, 'a') as f:\n data = uploaded_file.read(65536)\n while data:\n f.write(data)\n data = uploaded_file.read(65536)\n\nNote that the payload size limit on regular requests to App Engine apps is ... | [
7,
6
] | [] | [] | [
"blobstore",
"google_app_engine",
"python",
"scribd",
"tipfy"
] | stackoverflow_0005638894_blobstore_google_app_engine_python_scribd_tipfy.txt |
Q:
Scalar Variables from Perl to Python?
I am translating a program from perl to python and I really don't know how to translate a scalar variable to python. My problem is that I want to call the first value that comes in based on all the scalar variables used in the code, a scalar variable when mentioned it refers t... | Scalar Variables from Perl to Python? | I am translating a program from perl to python and I really don't know how to translate a scalar variable to python. My problem is that I want to call the first value that comes in based on all the scalar variables used in the code, a scalar variable when mentioned it refers to the value assigned to it.
the specific ar... | [
"I'm not exactly sure what you are asking for, but just FYI Python does not attach types to the names in the script. The type is the object that the name refers to. So there is not distinction of \"scalar\" variable or \"list context\", or anything like that. \nSo it looks like you have a list. you can do:\nmymin =... | [
3,
3,
1
] | [] | [] | [
"perl",
"python",
"variables"
] | stackoverflow_0007101395_perl_python_variables.txt |
Q:
pythonic way to access data in file structures
I want to access every value (~10000) in .txt files (~1000) stored in directories (~20) in the most efficient manner possible. When the data is grabbed I would like to place them in a HTML string. I do this in order to display a HTML page with tables for each file. Ps... | pythonic way to access data in file structures | I want to access every value (~10000) in .txt files (~1000) stored in directories (~20) in the most efficient manner possible. When the data is grabbed I would like to place them in a HTML string. I do this in order to display a HTML page with tables for each file. Pseudo:
fh=open('MyHtmlFile.html','w')
fh.writ... | [
"import os, os.path\n# If you're on Python 2.5 or newer, use 'with'\n# needs 'from __future__ import with_statement' on 2.5\nfh=open('MyHtmlFile.html','w')\nfh.write('<html>\\r\\n<head><title>Lots of tables</title></head>\\r\\n<body>\\r\\n')\n# this will recursively descend the tree\nfor dirpath, dirname, filenames... | [
3,
1
] | [] | [] | [
"html",
"performance",
"python"
] | stackoverflow_0007106596_html_performance_python.txt |
Q:
Best way to safely store Python tuple of strings and integers in memcached?
So I have a webapp where I want to store current rankings of posts based on an algo every minute. To render the updated posts, I would like to avoid the db and get the data (e.g. post title, author, rank, etc.) from memcached (faster, righ... | Best way to safely store Python tuple of strings and integers in memcached? | So I have a webapp where I want to store current rankings of posts based on an algo every minute. To render the updated posts, I would like to avoid the db and get the data (e.g. post title, author, rank, etc.) from memcached (faster, right?).
One idea is (I'm using Django btw) for the view to convert a serialized str... | [
"Why not just let django.core.cache take care of that for you? I'm doing this from a django project that has memcached hooked up as the cache backend:\n$ python manage.py shell\nIn [1]: from django.core.cache import cache\n\nIn [2]: cache.set('woot', (3, 'blah', 590))\n\nIn [3]: cache.get('woot')\nOut[3]: (3, 'blah... | [
0
] | [] | [] | [
"django",
"performance",
"python"
] | stackoverflow_0007099466_django_performance_python.txt |
Q:
raw_input in python variable to cmd
How can I take this code, and take the raw_input and add "ping" before it in cmd, so it'll look like this in command prompt: [ping (raw_input)]
HERE IS THE CODE:
RS_usr = raw_input('input user here: ')
from subprocess import Popen, PIPE, STDOUT
p =... | raw_input in python variable to cmd | How can I take this code, and take the raw_input and add "ping" before it in cmd, so it'll look like this in command prompt: [ping (raw_input)]
HERE IS THE CODE:
RS_usr = raw_input('input user here: ')
from subprocess import Popen, PIPE, STDOUT
p = Popen(['cmd.exe'], stdout=PIPE, stdin=P... | [
"If I understood you correctly you should change a couple of lines in your script:\np = Popen(['cmd.exe', '/k', 'set PROMPT=[Hello, (' + RS_usr + ')]' ], stdout=PIPE, stdin=PIPE, stderr=STDOUT)\n\nout,err = p.communicate()\n\n"
] | [
0
] | [] | [] | [
"cmd",
"command_prompt",
"python"
] | stackoverflow_0007106569_cmd_command_prompt_python.txt |
Q:
Importing a module which have the same name with a system module
My situation is similar to one in this question... The difference is,
In our python/django project, we have a directory called utils, which keeps basic functions...
Sometimes, we need to test some modules by running thm from console like
python mypro... | Importing a module which have the same name with a system module | My situation is similar to one in this question... The difference is,
In our python/django project, we have a directory called utils, which keeps basic functions...
Sometimes, we need to test some modules by running thm from console like
python myproject/some_module.py
It is all good, until python tries to import some... | [
"See the PEP on absolute and relative imports for the semantics. You probably want\nfrom .utils.custom_modules import some_function\n\nif you're in a file at the top level of your package.\nEdit: This can only be done from inside a package. This is for a good reason -- if you're importing something that is part of ... | [
6
] | [
"I'm not going to bother telling you to try and make sure you don't name your own modules after the stdlib modules;\nIf you want to leave the name like this, you'll have to use something like this in everything that imports your own utils module:\nimport sys, imp\n\nutils = sys.modules.get('utils')\nif not utils: u... | [
-1
] | [
"django",
"importerror",
"python",
"pythonpath"
] | stackoverflow_0007106967_django_importerror_python_pythonpath.txt |
Q:
Django Deployment: ImportError: Could not import settings 'settings.py' (Is it on sys.path?): No module named settings.py
Hi All and thank you for taking the time to look at my question.
I'm a newbie to Python, thought I have experience in php/mysql.
I was just handed a code repository of a django site and asked t... | Django Deployment: ImportError: Could not import settings 'settings.py' (Is it on sys.path?): No module named settings.py | Hi All and thank you for taking the time to look at my question.
I'm a newbie to Python, thought I have experience in php/mysql.
I was just handed a code repository of a django site and asked to get it up and running on a server.
I've been able to run syncdb and migrate.
Now I'm trying to navigate to my site in the bro... | [
"It should be just:\nSetEnv DJANGO_SETTINGS_MODULE settings\n\nNo '.py'. Ie., it is a Python module path, not a file name.\nDo note that mod_python is officially a dead project. The support in Django has been deprecated. You should look at alternatives instead of mod_python for hosting Django.\n",
"I think you sh... | [
1,
0
] | [] | [] | [
"deployment",
"importerror",
"python",
"sys.path"
] | stackoverflow_0007105691_deployment_importerror_python_sys.path.txt |
Q:
Combine enumerate + itertools.izip in Python
I would like to iterate + enumerate over two lists in Python. The following code looks ugly. Is there any better solution?
for id, elements in enumerate(itertools.izip(as, bs)):
a = elements[0]
b = elements[1]
# do something with id, a and b
Thank you.
A:
You c... | Combine enumerate + itertools.izip in Python | I would like to iterate + enumerate over two lists in Python. The following code looks ugly. Is there any better solution?
for id, elements in enumerate(itertools.izip(as, bs)):
a = elements[0]
b = elements[1]
# do something with id, a and b
Thank you.
| [
"You can assign a and b during the for loop:\nfor id, (a, b) in enumerate(itertools.izip(as, bs)):\n # do something with id, a and b\n\n",
"You could use itertools.count instead of enumerate:\nfor id_, a, b in itertools.izip(itertools.count(), as_, bs):\n # do something with id_, a and b\n\nNote that I've chang... | [
17,
12
] | [] | [] | [
"enumerate",
"python",
"python_itertools"
] | stackoverflow_0007107323_enumerate_python_python_itertools.txt |
Q:
Matching files using python program
I have to two files as follows
File1
ids
CID5265
CID7263
CID9289
....
File 2
ids
CID7363 3.5e-06 -3837
CID5265 4.5 -938
CID9289 8.9 -9873
....
I want compare file1 with file2 to match any ids in file1 is present in file2 if yes i should print whole line as fol... | Matching files using python program | I have to two files as follows
File1
ids
CID5265
CID7263
CID9289
....
File 2
ids
CID7363 3.5e-06 -3837
CID5265 4.5 -938
CID9289 8.9 -9873
....
I want compare file1 with file2 to match any ids in file1 is present in file2 if yes i should print whole line as follows
CIDS9289 8.9 -9873
....
to acheiv... | [
"Use the following:\nprint [line for id in searchTxtData for line in inFileData if id.strip() in line]\n\nOr using with statement:\nids = [id.strip() for id in open(\"file1.txt\",\"r\") if id.strip()]\n\nwith open(\"file2.txt\",\"r\") as dataFile:\n for line in dataFile: \n if line.strip() and ... | [
2,
2,
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0007106734_python.txt |
Q:
Nonblocking redirection of output from multiprocess process
I asked a question yesterday about a problem with a program I'm writing in Python ( Passing wxPython objects as multiprocessor arguments ). I managed to solve that problem by using a multiprocess process for the function that evaluates the scripts. Howeve... | Nonblocking redirection of output from multiprocess process | I asked a question yesterday about a problem with a program I'm writing in Python ( Passing wxPython objects as multiprocessor arguments ). I managed to solve that problem by using a multiprocess process for the function that evaluates the scripts. However, since the scripts are runned from a different process, their o... | [
"The solution to your immediate problem is to use two Queue.Queues instead of just one. Let's call them inqueue and outqueue. Then\ndef runtest(inqueue,outqueue):\n test = inqueue.get()\n module=__import__(test)\n ret=getattr(module,test)() \n outqueue.put(ret)\n\nThe larger issue concerns how to con... | [
1
] | [] | [] | [
"multiprocessing",
"pipe",
"python",
"stdout",
"wxpython"
] | stackoverflow_0007107187_multiprocessing_pipe_python_stdout_wxpython.txt |
Q:
Extending the Django Admin with images
django.db.models.Model defines an app_label which can be changed within a Model by appending:
class Meta:
app_label = "something"
Now I am trying to find a not too hacky/pythonic way to let each app have an image. I don't really want to break into the django contrib stuff... | Extending the Django Admin with images | django.db.models.Model defines an app_label which can be changed within a Model by appending:
class Meta:
app_label = "something"
Now I am trying to find a not too hacky/pythonic way to let each app have an image. I don't really want to break into the django contrib stuff, because that tends to get complicated.. Is... | [
"You shouldn't change app_label for model, this value is not only used for admin and changing it can break things badly.\nIf you want to change admin index page presentation then override the admin template (see https://docs.djangoproject.com/en/1.3/ref/contrib/admin/#overriding-admin-templates ) and put the HTML a... | [
1
] | [] | [] | [
"django",
"python"
] | stackoverflow_0007104242_django_python.txt |
Q:
python method as argument
So I know in python everything is an 'object' meaning that it can be passed as an argument to a method. But I'm trying to understand how exactly does this work. So I was trying out the following example:
class A:
def __init__(self):
self.value = 'a'
def my_method(self)
... | python method as argument | So I know in python everything is an 'object' meaning that it can be passed as an argument to a method. But I'm trying to understand how exactly does this work. So I was trying out the following example:
class A:
def __init__(self):
self.value = 'a'
def my_method(self)
print self.value
class ... | [
"When you access a.my_method Python sees that it is an attribute of the class and that A.my_method has a method __get__() so it calls A.my_method.__get__(a), that method creates a new object (the 'bound method') which contains both a reference to A.my_method and a reference to a itself. When you call the bound meth... | [
8,
4,
1,
1
] | [] | [] | [
"python"
] | stackoverflow_0007107510_python.txt |
Q:
Python: Anything wrong with dynamically assigning instance methods as instance attributes
I came up with the following code to decorate instance methods using a decorator that requires the instance itself as an argument:
from functools import wraps
def logging_decorator(tricky_instance):
def wrapper(fn):
... | Python: Anything wrong with dynamically assigning instance methods as instance attributes | I came up with the following code to decorate instance methods using a decorator that requires the instance itself as an argument:
from functools import wraps
def logging_decorator(tricky_instance):
def wrapper(fn):
@wraps(fn)
def wrapped(*a, **kw):
if tricky_instance.log:
... | [
"It's not really clear to me why you would ever want to do this. If you want to assign a new method type dynamically use types:\nimport types\n\nclass Tricky(object):\n def __init__(self):\n def method(self):\n print('Hello')\n self.method = types.MethodType(method, self)\n\nIf you want ... | [
4,
2
] | [] | [] | [
"oop",
"python"
] | stackoverflow_0007101126_oop_python.txt |
Q:
Python: Installing and using Exscript module Windows x86
I have been banging my head against the wall trying to get Exscript installed. After multiple failed attempts at doing it manually, I installed ActivePython and had success running "pypm install Exscript" from the cmd prompt.
I am now going through the Exsc... | Python: Installing and using Exscript module Windows x86 | I have been banging my head against the wall trying to get Exscript installed. After multiple failed attempts at doing it manually, I installed ActivePython and had success running "pypm install Exscript" from the cmd prompt.
I am now going through the Exscript documentation (found here https://github.com/knipknap/exs... | [
"One common way packages are installed is as directories. So check your site-packages directory for an Exscript directory, and inside that there should be a util directory, and inside that there should be an interact.py file. Look for similar spellings in case the tutorial misspelled something.\n"
] | [
1
] | [] | [] | [
"module",
"python"
] | stackoverflow_0007108084_module_python.txt |
Q:
How can I get a full list of class members without instantiating a class?
Good day!
I'm writing a little tool that builds a GUI for my data-aware app.
The basic idea is to get a module containing a model description (sqla/elixir entities) as an input, and to present the user with a list of available classes (inhe... | How can I get a full list of class members without instantiating a class? | Good day!
I'm writing a little tool that builds a GUI for my data-aware app.
The basic idea is to get a module containing a model description (sqla/elixir entities) as an input, and to present the user with a list of available classes (inherited from Entity()) and their fields (inherited from Field()) from this module... | [
"I'm not sure I know what you mean:\nclass a(object):\n b = 'a'\n c = 'd'\n\nprint dir(a)\n\nprints\n['__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '_... | [
5
] | [] | [] | [
"python"
] | stackoverflow_0007108222_python.txt |
Q:
Frequently repeated try/except in Python
Firstly, I'm not sure if my approach is proper, so I'm open to a variety of suggestions.
If try/except statements are frequently repeated in code, are there any good ways to shorten them or avoid fully writing them out?
try:
# Do similar thing
os.remove('/my/file')
... | Frequently repeated try/except in Python | Firstly, I'm not sure if my approach is proper, so I'm open to a variety of suggestions.
If try/except statements are frequently repeated in code, are there any good ways to shorten them or avoid fully writing them out?
try:
# Do similar thing
os.remove('/my/file')
except OSError, e:
# Same exception handin... | [
"The best way to abstract exception handling is with a context manager:\nfrom contextlib import contextmanager\n@contextmanager\ndef common_handling():\n try:\n yield\n finally:\n # whatever your common handling is\n\nthen:\nwith common_handling():\n os.remove('/my/file')\n\nwith common_handl... | [
28,
4,
2,
1
] | [] | [] | [
"exception",
"python"
] | stackoverflow_0007108193_exception_python.txt |
Q:
Google app engine Big table database with Python desktop applications
Just out of curiosity, do Big table can be used as back-end for data storage for DESKTOP applications(stand alone applications).
Suppose a scenario:
Application start and check automatically for Internet access.
Once connection exists, we can ... | Google app engine Big table database with Python desktop applications | Just out of curiosity, do Big table can be used as back-end for data storage for DESKTOP applications(stand alone applications).
Suppose a scenario:
Application start and check automatically for Internet access.
Once connection exists, we can perform CRUD operation on Big table through application.
Is this possible?... | [
"There is nothing \"out of the box\" to do this for you, but in theory this is no different from having a web-based GUI performing CRUD operations against the datastore. Your desktop app will still be communicating with your appengine app via HTTP requests.\n\nYou would still have to decide on how to structure you ... | [
1,
0
] | [] | [] | [
"google_app_engine",
"python"
] | stackoverflow_0007107240_google_app_engine_python.txt |
Q:
Python and arbitrary command line options
I am writing a command-line plugin-based program where the plugins will provide additional functionality on top of whatever I provide.
So for example suppose I wrote a simple script that parsed images and stored them, and that's all I do. Then someone else can write a set ... | Python and arbitrary command line options | I am writing a command-line plugin-based program where the plugins will provide additional functionality on top of whatever I provide.
So for example suppose I wrote a simple script that parsed images and stored them, and that's all I do. Then someone else can write a set of scripts to manipulate the image, putting his... | [
"argparse lets you partially parse an argument list with the parse_known_args method, returning what was parsed correctly, together with a list of the remaining arguments.\n",
"The solution you want is probably to treat the command line arguments as a sort of in process pipeline. Which options are also a part of... | [
6,
1
] | [] | [] | [
"command_line_arguments",
"python",
"windows"
] | stackoverflow_0007108443_command_line_arguments_python_windows.txt |
Q:
parsing XML configuration file using Etree in python
Please help me parse a configuration file of the below prototype using lxml etree. I tried with for event, element with tostring. Unfortunately I don't need the text, but the XML between
<template name>
<config>
</template>
for a given attribute.
I sta... | parsing XML configuration file using Etree in python | Please help me parse a configuration file of the below prototype using lxml etree. I tried with for event, element with tostring. Unfortunately I don't need the text, but the XML between
<template name>
<config>
</template>
for a given attribute.
I started with this code, but get a key error while searching f... | [
"You could try to iterate over all template elements in the XML and parse them with the following code:\nfor template in root.iterfind(\"template\"):\n name = template.get(\"name\")\n request = template.find(requst)\n password = template.findtext(\"request/password\")\n username = ...\n ...\n # Do... | [
1,
1
] | [] | [] | [
"config",
"lxml",
"python",
"xml",
"xml.etree"
] | stackoverflow_0007108319_config_lxml_python_xml_xml.etree.txt |
Q:
error with appending to a file and using an array
I have written this code:
class component(object):
def __init__(self,
name = None,
height = None,
width = None):
self.name = name
self.height = height
... | error with appending to a file and using an array | I have written this code:
class component(object):
def __init__(self,
name = None,
height = None,
width = None):
self.name = name
self.height = height
self.width = width
class system(object):
de... | [
"You've got things out of order in your __init__:\n def __init__(self, *component, **kwargs):\n\n self.name = kwargs.get('name')\n self.component = component\n\n self.lines = kwargs.get('lines', [])\n\nWill work. You need lines and name to be after the * item that collects the component. \nIn Python 2, yo... | [
2,
1,
0
] | [] | [] | [
"append",
"arrays",
"python"
] | stackoverflow_0007108378_append_arrays_python.txt |
Q:
How does this while loop exit?
So, how does this code exit the while statement when the thread is started? (Please do not consider indentation)
class ThreadUrl(threading.Thread):
"""Threaded Url Grab"""
def __init__(self, queue, out_queue):
threading.Thread.__init__(self)
self.queue = queue... | How does this while loop exit? | So, how does this code exit the while statement when the thread is started? (Please do not consider indentation)
class ThreadUrl(threading.Thread):
"""Threaded Url Grab"""
def __init__(self, queue, out_queue):
threading.Thread.__init__(self)
self.queue = queue
self.out_queue = out_queue
... | [
"It doesn't have to exit the while statement for the code to terminate. All that is happening here is that the thread has consumed everything in the queue at which point queue.join() returns.\nAs soon as the call to queue.join() in the main code returns the main code will exit and because you marked the thread as a... | [
6,
1,
1,
0
] | [] | [] | [
"multithreading",
"python",
"while_loop"
] | stackoverflow_0007105371_multithreading_python_while_loop.txt |
Q:
text output with color
Fellow programmers,
I am running a Monte Carlo type simulation in python that generates long strings of 0,1, and 2's and I'm trying to output them in a text or html file for further analysis.
I'd like to print these strings in an external file, and use different colors for the different di... | text output with color | Fellow programmers,
I am running a Monte Carlo type simulation in python that generates long strings of 0,1, and 2's and I'm trying to output them in a text or html file for further analysis.
I'd like to print these strings in an external file, and use different colors for the different digits.
Say, 0 = red, 1 = gre... | [
"just write to a file like this and open it in a webbrowser:\ndef write_red(f, str_):\n f.write('<p style=\"color:#ff0000\">%s</p>' % str_)\n\ndef write_blue(f, str_):\n # ...\n\nf = open('out.html', 'w')\nf.write('<html>')\n\nwrite_red(f, thing_i_want_to_be_red_in_output)\n\nf.write('</html>')\nf.close()\n\n... | [
3
] | [] | [] | [
"html",
"python"
] | stackoverflow_0007108855_html_python.txt |
Q:
how can i redirect a user to a different server with python?
I'm trying to write a script which will monitor packets (using pypcap) and redirect certain URLs/IPs to something I choose. I know I could just edit the hosts file, but that won't work because I'm not an admin.
I'm thinking that CGI might be useful, but ... | how can i redirect a user to a different server with python? | I'm trying to write a script which will monitor packets (using pypcap) and redirect certain URLs/IPs to something I choose. I know I could just edit the hosts file, but that won't work because I'm not an admin.
I'm thinking that CGI might be useful, but this one has really got me confused.
EDIT:
sorry if it sounded ma... | [
"pypcap needs administrative rights, so this is not an option.\nAnd you don't have access to the pcs internals, to the source code or to the webserver.\nThere are a few options left:\n\nModify the host name in the applications files with a hexeditor and disassembler.\nModify the loaded application in memory with Ch... | [
0
] | [] | [] | [
"http",
"pcap",
"python",
"redirect"
] | stackoverflow_0006378018_http_pcap_python_redirect.txt |
Q:
Regex for parsing list of floating numbers in python
What's the best why to parse lists of floating numbers separated by space in python?
I have rows of this kind that will come out from a source:
string = " 4 1.6 8.29 0 0 3.55e-15 -1.28e-13 "
with an unknown number of whitespaces separating the numb... | Regex for parsing list of floating numbers in python | What's the best why to parse lists of floating numbers separated by space in python?
I have rows of this kind that will come out from a source:
string = " 4 1.6 8.29 0 0 3.55e-15 -1.28e-13 "
with an unknown number of whitespaces separating the numbers and on the beggining or end of the string.
I usually j... | [
"No regex is needed. Simply use string.split() without any arguments; it will split on any amount of whitespace.\n",
"An example of using the str.split() method with a list comprehension -- mildly more Pythonic, and IMHO clearer, than map:\n>>> string = \" 4 1.6 8.29 0 0 3.55e-15 -1.28e-13 \"\n>>> flo... | [
11,
2
] | [] | [] | [
"parsing",
"python",
"regex"
] | stackoverflow_0007108776_parsing_python_regex.txt |
Q:
using two consecutive values from a list in each iteration
I have posted a part of my code below. Newton() function calls Bezier() function. The Bezier() function has a list from where I get p0 and p3. What I am trying to do is, in 1st iteration the program should take the first and second items from the plist as ... | using two consecutive values from a list in each iteration | I have posted a part of my code below. Newton() function calls Bezier() function. The Bezier() function has a list from where I get p0 and p3. What I am trying to do is, in 1st iteration the program should take the first and second items from the plist as p0 and p3. Then in 2nd iteration, p0 and p3 are the second and t... | [
">>> p = [1, 2, 3, 4, 5]\n>>> for p1, p2 in zip(p, p[1:]):\n... print p1, p2\n... \n1 2\n2 3\n3 4\n4 5\n\nDoes it help?\n",
"Perhaps the pairwise iterator from itertools recipes will help?\nfrom itertools import izip, tee\ndef pairwise(iterable):\n \"s -> (s0,s1), (s1,s2), (s2, s3), ...\"\n a, b = tee(i... | [
8,
4,
3,
2,
1
] | [] | [] | [
"python"
] | stackoverflow_0007108184_python.txt |
Q:
Python: loop doing the same thing to one item n-times as opposed doing it once to n-items
Here is the example:
I am trying to grab a series of XML pages, and then extract data from them.
It downloads each individual page, as the while loop was designed to do but the tester() function prints the data from the fir... | Python: loop doing the same thing to one item n-times as opposed doing it once to n-items | Here is the example:
I am trying to grab a series of XML pages, and then extract data from them.
It downloads each individual page, as the while loop was designed to do but the tester() function prints the data from the first file it downloads V number of times despite it downloading and clearing the file after each ... | [
"The problem is the linecache module. It assumes that same-named files are the same.\nBut why write the data to a file just to read it again anyway?\ndef tester(text):\n line12 = text.splitlines()[11]\n print line12\n\ndef grab_data(year, rcvote):\n link = \"XXX/%s/roll%03d.xml\" % (year, rcvote)\n sit... | [
3
] | [] | [] | [
"loops",
"python",
"while_loop"
] | stackoverflow_0007109149_loops_python_while_loop.txt |
Q:
expanding the image viewer example of pyqt or QT
im trying to expand the pyqt image veiwer example to have a feature of drawing over images
i added a couple of tested functions that takes mouse events and draw over image
in the image viewer example my i chosed my painter to paint over imageLabel's pixmap
def mou... | expanding the image viewer example of pyqt or QT | im trying to expand the pyqt image veiwer example to have a feature of drawing over images
i added a couple of tested functions that takes mouse events and draw over image
in the image viewer example my i chosed my painter to paint over imageLabel's pixmap
def mousMoveEvent(self,event):
painter = QtGui.QPainter(s... | [
"Start off by just capturing mouse events and displaying the results using print statements to make sure you are getting the mouse data correctly. The next step is to use that mouse data and mouse events to feed into the drawing routines.\nWhile it doesn't include taking mouse input, this tutorial on drawing in PyQ... | [
1,
0
] | [] | [] | [
"pyqt",
"python",
"qt"
] | stackoverflow_0003226863_pyqt_python_qt.txt |
Q:
How to show/hide a child QWidget with a motion animation?
I am working on an application with two children. One's a widget that functions as a toolbar, the second, below, functions as dashboard, on which information would appear. The latter can be shown/hidden with buttons on the former. Here's a screen-cast of th... | How to show/hide a child QWidget with a motion animation? | I am working on an application with two children. One's a widget that functions as a toolbar, the second, below, functions as dashboard, on which information would appear. The latter can be shown/hidden with buttons on the former. Here's a screen-cast of the prototype.
Now I am looking at doing the same but with a moti... | [
"I think you can get what you want by using a QPropertyAnimation that animates the geometry property of your widget.\nBut IMHO this is the window manager's role to do what you want. Maybe you will have some headaches bypassing it (but I'm maybe wrong).\nAfter better reading of your question, it seems that you want ... | [
3
] | [] | [] | [
"animation",
"pyqt",
"python",
"qt4"
] | stackoverflow_0007108715_animation_pyqt_python_qt4.txt |
Q:
increasing width of figure in matplotlib according to number of x values
I was trying to draw a barchart using matplotlib.The number of items to be plotted can vary . I cannot set the figure.set_size_inches(w,h) or set_figwidth(w) with constants(like 6.,8. or 8.,12. etc),since I cannot tell in advance what the va... | increasing width of figure in matplotlib according to number of x values | I was trying to draw a barchart using matplotlib.The number of items to be plotted can vary . I cannot set the figure.set_size_inches(w,h) or set_figwidth(w) with constants(like 6.,8. or 8.,12. etc),since I cannot tell in advance what the value of w or h should be.I want the width of figure to increase as the number o... | [
"You can set the width when you initialize the figure:\n# default scale is 1 in your original case, scales with other cases:\nwidthscale = len(yvalues)/4 \nfigsize = (8*widthscale,6) # fig size in inches (width,height)\nfigure = pylab.figure(figsize = figsize) # set the figsize\n\nReplace the figure = pylab.figure(... | [
5
] | [] | [] | [
"figure",
"matplotlib",
"python",
"width"
] | stackoverflow_0007108852_figure_matplotlib_python_width.txt |
Q:
File Storage Problem with Python Web Crawler
I am screen scraping data using a web crawler and storing the results - (tweets from a twitter page) as separate html files for each user I'm crawling. I intend to later parse the html files and store the data into a database for analysis. However, I am having a bizarre... | File Storage Problem with Python Web Crawler | I am screen scraping data using a web crawler and storing the results - (tweets from a twitter page) as separate html files for each user I'm crawling. I intend to later parse the html files and store the data into a database for analysis. However, I am having a bizarre problem.
When I run the following program - a sm... | [
"The depth value is different between the snippet and the full code (you're only going to get one level of recursion in the full code). Also, you only grab the first five names from the followers list: for name in list(names)[0:5]: So you get six people total: the starting follower and their first five friends.\n"
... | [
1
] | [] | [] | [
"python",
"web_crawler"
] | stackoverflow_0007109464_python_web_crawler.txt |
Q:
Process communication in Python
What is the best way to establish communication between two processes in python? After some googling, I tried to do so:
parent_pipe, child_pipe = Pipe()
p = Process(target = instance_tuple.instance.run(), \
args = (parent_pipe, child_pipe,))
p.start()
Sending data to the child ... | Process communication in Python | What is the best way to establish communication between two processes in python? After some googling, I tried to do so:
parent_pipe, child_pipe = Pipe()
p = Process(target = instance_tuple.instance.run(), \
args = (parent_pipe, child_pipe,))
p.start()
Sending data to the child process:
command = Command(command_na... | [
"You can have a look here : http://docs.python.org/library/multiprocessing.html#exchanging-objects-between-processes\nThe solution is close to yours but seems easier.\n",
"If I understand the documentation, in child process you should read from the child part of the pipe.\n# Process Target function\n\nwhile True:... | [
5,
0
] | [] | [] | [
"multiprocessing",
"python"
] | stackoverflow_0007109672_multiprocessing_python.txt |
Q:
Some python argparse usage questions: retrieving arguments
Some questions that I couldn't figure out from reading the docs and some other questions.
1: I was stumped by "how do I actually retrieve the arguments" so I looked around and someone suggested to use the __dict __ function to access it like a dictionary. ... | Some python argparse usage questions: retrieving arguments | Some questions that I couldn't figure out from reading the docs and some other questions.
1: I was stumped by "how do I actually retrieve the arguments" so I looked around and someone suggested to use the __dict __ function to access it like a dictionary. Which works, but is that the only way? This seems like a rather ... | [
"You can use the parse_args() function to retrieve parameters. For example:\nparser = argparse.ArgumentParser(description=\"Test\")\nparser.add_argument('command')\n\nparameters = parser.parse_args()\ncmd = parameters.command\n\nTo answer your second question, it's not recommended that you do this. Simply adding th... | [
4,
3
] | [] | [] | [
"argparse",
"python"
] | stackoverflow_0007109987_argparse_python.txt |
Q:
Where can I find out why creators of modules in Python create multiple packages based on hardware
I use lxml and some other third party packages that I download and install using their MSI executables. However, I have long wondered why they specify different processor architectures.
Here is the list of download... | Where can I find out why creators of modules in Python create multiple packages based on hardware | I use lxml and some other third party packages that I download and install using their MSI executables. However, I have long wondered why they specify different processor architectures.
Here is the list of downloads for lxml's 2.3 release
http://pypi.python.org/pypi/lxml/2.3#downloads
I don't see one for Win-Intel64... | [
"Simple answer: if the module/package has machine code as well as Python code, architecture matters, otherwise it does not.\nCaveat: if it is pure Python code, but interfaces with the hardware in some way, then architecture may matter.\nLooking at lxml, I see at least two .pyd files, which are machine code.\n"
] | [
1
] | [] | [] | [
"architecture",
"installation",
"package",
"processor",
"python"
] | stackoverflow_0005369544_architecture_installation_package_processor_python.txt |
Q:
Given a latitude and longitude, and distance, I want to find a bounding box
Given a latitude and longitude, and distance, I want to find a bounding box where the distances are less than the given distance.
This questions was asked here: How to calculate the bounding box for a given lat/lng location?
I donot want ... | Given a latitude and longitude, and distance, I want to find a bounding box | Given a latitude and longitude, and distance, I want to find a bounding box where the distances are less than the given distance.
This questions was asked here: How to calculate the bounding box for a given lat/lng location?
I donot want this partcularly accurate, so I have modified and simplified it to
def boundingBo... | [
"This code didn't quite work, it jumps between KM and M.\nFixed code, made names more PEP8 style, and added a simple box object:\nclass BoundingBox(object):\n def __init__(self, *args, **kwargs):\n self.lat_min = None\n self.lon_min = None\n self.lat_max = None\n self.lon_max = None\n... | [
10,
2
] | [] | [] | [
"bounding_box",
"geocoding",
"python"
] | stackoverflow_0001648917_bounding_box_geocoding_python.txt |
Q:
Proper CPython String Concatenation
Last night I was at a Boston Python Meetup that described various Python implementations. Part of the discussion included string concatenation.
Apparently for CPython there is less heap fragmentation if strings are concatenated starting with an empty string and then using join. ... | Proper CPython String Concatenation | Last night I was at a Boston Python Meetup that described various Python implementations. Part of the discussion included string concatenation.
Apparently for CPython there is less heap fragmentation if strings are concatenated starting with an empty string and then using join.
Is this an OK way to construct a string
... | [
"You could use a multi-line string literal with .format:\nsql_statement_format = \"\"\"\n select count(*)\n from ept_inv e\n where e.ept_type = {device_type} \n and e.inv_id = {endpoint_id};\n\"\"\"\nsql_statement = sql_statement_format.format(\n device_type=in_row[cs.DeviceType],\n endpoint_id=in... | [
3,
2,
1,
0,
0
] | [] | [] | [
"python",
"string"
] | stackoverflow_0007107188_python_string.txt |
Q:
How to connect to sql server 2008 via an IP address using pyodbc in Python
I am able to connect to server with mssql management studio but not able to connect using python I think some problem in connection string please help below is string I am using.
import pyodbc as p
connStr = ( r'DRIVER={SQL Server};Server... | How to connect to sql server 2008 via an IP address using pyodbc in Python | I am able to connect to server with mssql management studio but not able to connect using python I think some problem in connection string please help below is string I am using.
import pyodbc as p
connStr = ( r'DRIVER={SQL Server};Server=ip; Network=DBMSSOCN;Initial Catalog=' + database + ';User ID=' + id +';Passwor... | [
"After lots of trial and error this string ended up working:\nconnStr = ('DRIVER={SQL Server Native Client 10.0};Server=ip;port=port;Network Library=DBMSSOCN;Database=TEST;uid=id;pwd=pass;')\n\n",
"There are actually two or three SQL Server drivers written and distrubuted by Microsoft: one referred to as \"SQL Se... | [
7,
3
] | [] | [] | [
"pyodbc",
"python",
"sql"
] | stackoverflow_0004647037_pyodbc_python_sql.txt |
Q:
How to start ropemacs-mode automatically?
When I open a python file I have to manually start ropemacs-mode to get the key bindings each time. I tried adding something like this to automatically start ropemacs:
(add-hook 'python-mode-hook (lambda ()
(ropemacs-mode)
... | How to start ropemacs-mode automatically? | When I open a python file I have to manually start ropemacs-mode to get the key bindings each time. I tried adding something like this to automatically start ropemacs:
(add-hook 'python-mode-hook (lambda ()
(ropemacs-mode)
))
But it seems to break flymake. ... | [
"Dont use ropemacs but the readme says like this \nAfter installing pymacs, add these lines to your ~/.emacs file::\n\n (require 'pymacs)\n (pymacs-load \"ropemacs\" \"rope-\")\n\n",
"My problem was with some code for using autocomplete.el along with ropemacs and yas which I found here:\nhttp://hide1713.wordpr... | [
1,
1
] | [] | [] | [
"emacs",
"python",
"rope"
] | stackoverflow_0007096147_emacs_python_rope.txt |
Q:
Namespace in method parameters
I'm surprised that the namespace of function parameters in a method is the class and not the global scope.
def a(x):
print("Global A from {}".format(x))
class Test:
def a(self, f=a):
print("A")
f("a") # this will call the global method a()
def b(self, f... | Namespace in method parameters | I'm surprised that the namespace of function parameters in a method is the class and not the global scope.
def a(x):
print("Global A from {}".format(x))
class Test:
def a(self, f=a):
print("A")
f("a") # this will call the global method a()
def b(self, f=a):
print("B")
f("b... | [
"Namespace lookups always check the local scope first. In a method definition, that is the class. \nAt the time of the definition of Test.a, there is no local named a, only the global a. By the time Test.b is defined, Test.a has already been defined, so the local name a exists, and the global scope is not checked. ... | [
2
] | [] | [] | [
"class",
"namespaces",
"python"
] | stackoverflow_0007110269_class_namespaces_python.txt |
Q:
python libxml2 serialization problem
I'm having some problems while attempting to serialize a libxml2 object in python.
In particular, if I run :
xmlstring = cdoc.serialize('UTF-8', 1)
where cdoc is a libxml2 document created before,
I have something like this : ( on a mac - port python 2.5.6)
<?xml version="1.0"... | python libxml2 serialization problem | I'm having some problems while attempting to serialize a libxml2 object in python.
In particular, if I run :
xmlstring = cdoc.serialize('UTF-8', 1)
where cdoc is a libxml2 document created before,
I have something like this : ( on a mac - port python 2.5.6)
<?xml version="1.0" encoding="UTF-8"?>
<body>
<journal>
... | [
"I just noticed that I was running:\nxmlstring = cdoc.serialize('UTF-8', 2) \n\nand not \nxmlstring = cdoc.serialize('UTF-8', 1) \n\nThis, for some reasons, on libxml2 2.6 indents also the text node and on libxml2 2.7 doesn't.\n",
"It could be a behaviour difference between the version of libxml2 on the different... | [
1,
0
] | [] | [] | [
"libxml2",
"python",
"serialization",
"xml_serialization"
] | stackoverflow_0007100047_libxml2_python_serialization_xml_serialization.txt |
Q:
How do I provide an informal string representation of a python Class (not instance)
I understand how I can provide an informal representation of an instance of the object, but I am interested in providing an informal string representation of the Class name.
So specifically, I want to override what is returned when... | How do I provide an informal string representation of a python Class (not instance) | I understand how I can provide an informal representation of an instance of the object, but I am interested in providing an informal string representation of the Class name.
So specifically, I want to override what is returned when I print the Class (__main__.SomeClass).
>>> class SomeClass:
... def __str__(self):
..... | [
"Your problem is called meta class confusion. Of class A, if A.__str__(self) is a template for methods of instances of A, how can I provide a method __str__() for A itself? Meta classes to the rescue.\nThe following links explain this better than I could here.\nhttp://gnosis.cx/publish/programming/metaclass_1.html\... | [
8,
3,
2,
1,
1
] | [] | [] | [
"python"
] | stackoverflow_0007110311_python.txt |
Q:
os.environ doesn't show some variables
I have an environment variable that I set (on Centos 6) using profile.d, as follows:
[bankap@tnt-integration-test ~]$ cat /etc/profile.d/tnt.sh
TNT_SERVER_URL=http://tnt-integration-test:8000/
and when I log in, I see the variable:
[bankap@tnt-integration-test ~]$ echo $TNT_... | os.environ doesn't show some variables | I have an environment variable that I set (on Centos 6) using profile.d, as follows:
[bankap@tnt-integration-test ~]$ cat /etc/profile.d/tnt.sh
TNT_SERVER_URL=http://tnt-integration-test:8000/
and when I log in, I see the variable:
[bankap@tnt-integration-test ~]$ echo $TNT_SERVER_URL
http://tnt-integration-test:8000/... | [
"You have a quoting problem:\nchange\npython -c 'import os;os.environ.get('TNT_SERVER_URL')'\n\ninto\npython -c 'import os;os.environ.get(\"TNT_SERVER_URL\")'\n ^ ^\n\nYou also (probably) need to export the variable:\nexport TNT_SERVER_URL; python -c 'import os;os.env... | [
8
] | [] | [] | [
"linux",
"python"
] | stackoverflow_0007110587_linux_python.txt |
Q:
Python string.replace() not replacing characters
Some background information: We have an ancient web-based document database system where I work, almost entirely consisting of MS Office documents with the "normal" extensions (.doc, .xls, .ppt). They are all named based on some sort of arbitrary ID number (i.e. 124... | Python string.replace() not replacing characters | Some background information: We have an ancient web-based document database system where I work, almost entirely consisting of MS Office documents with the "normal" extensions (.doc, .xls, .ppt). They are all named based on some sort of arbitrary ID number (i.e. 1245.doc). We're switching to SharePoint and I need to re... | [
"That's because filename and foldername get thrown away with each iteration of the loop. The .replace() method returns a string, but you're not saving the result anywhere.\nYou should use:\nfilename = line[2]\nfoldername = line[5]\n\nfor letter in bad_characters:\n filename = filename.replace(letter, \"_\")\n ... | [
30,
6,
4,
3,
1
] | [] | [] | [
"python",
"str_replace",
"string"
] | stackoverflow_0003523054_python_str_replace_string.txt |
Q:
Why am I getting an invalid literal error?
I need to split a two digit value from a pyqt spinbox in half for math operations. In order to do this I'm converting the value to a string. This works fine for the first digit and it goes back to an integer without a problem. The second digit however won't convert back a... | Why am I getting an invalid literal error? | I need to split a two digit value from a pyqt spinbox in half for math operations. In order to do this I'm converting the value to a string. This works fine for the first digit and it goes back to an integer without a problem. The second digit however won't convert back and keeps throwing a base 10 invalid literal erro... | [
"To find out what's going on throw some prints in there:\nw1b2 = w1a[1:]\nprint(repr(w1b2))\n\nthen you can see exactly what's in there, including whatever characters are not base 10 valid literals.\n"
] | [
0
] | [] | [] | [
"int",
"pyqt4",
"python",
"string"
] | stackoverflow_0007011901_int_pyqt4_python_string.txt |
Q:
IMAP Fetch Encoding
I'm trying to fetch some email info from gmail using imap like this
"(BODY.PEEK[HEADER.FIELDS (subject from date)] X-GM-MSGID X-GM-LABELS X-GM-THRID)"
The problem is that it doesn't work well with special and accented characters. For example,
Stéphane Maniaci
is rendered as
=?ISO-8859-1?Q?St... | IMAP Fetch Encoding | I'm trying to fetch some email info from gmail using imap like this
"(BODY.PEEK[HEADER.FIELDS (subject from date)] X-GM-MSGID X-GM-LABELS X-GM-THRID)"
The problem is that it doesn't work well with special and accented characters. For example,
Stéphane Maniaci
is rendered as
=?ISO-8859-1?Q?St=E9phane_Maniaci?=
How d... | [
"Okay. I found out that email.utils can help out a lot here.\nIt has methods to parse date, emails, and any other information from imap messages. \nIt also has methods to decode imap strings. Like this\nfrom email.header import decode_header\nvalue, charset = decode_header(string_to_be_decoded)\n\n"
] | [
4
] | [] | [] | [
"character_encoding",
"gmail_imap",
"imap",
"imaplib",
"python"
] | stackoverflow_0006969639_character_encoding_gmail_imap_imap_imaplib_python.txt |
Q:
Segfault on accessing a C initialised ctypes structure element
I am trying to access elements of a structure from ctypes. The structure is created in an init function in the C code and pointer to it is returned to Python. The problem I am having is that I get a segfault when trying to access elements of the return... | Segfault on accessing a C initialised ctypes structure element | I am trying to access elements of a structure from ctypes. The structure is created in an init function in the C code and pointer to it is returned to Python. The problem I am having is that I get a segfault when trying to access elements of the returned structure. Here is the code:
The C code (which I've called ctypes... | [
"To make this work, replace the wrong line\nself._c_ctypes_test.init.restypes = ctypes.POINTER(SimpleStructure)\n\nby the correct line\nself._c_ctypes_test.init.restype = ctypes.POINTER(SimpleStructure)\n\nAlso consider to remove the pointless cast\nself.simple_structure = ctypes.cast(\n self._c_ctypes_test.init... | [
4,
1
] | [] | [] | [
"c",
"ctypes",
"ffi",
"python"
] | stackoverflow_0007109237_c_ctypes_ffi_python.txt |
Q:
How can I plot just the data with no borders using pylab
Using pylab, I want to plot just the data with no axes or borders to a png file. In code below, I still get borders to the left and right of the data.
import pylab
scores = [[ 82.,78., 71.5, 76., 79.5, 77., 73.5, 70.5, 74., 74.5 ],
[ 79.... | How can I plot just the data with no borders using pylab | Using pylab, I want to plot just the data with no axes or borders to a png file. In code below, I still get borders to the left and right of the data.
import pylab
scores = [[ 82.,78., 71.5, 76., 79.5, 77., 73.5, 70.5, 74., 74.5 ],
[ 79. , 75.75, 71., 76., 78.25, 73.25, 72.25 ,73.25, 74.75, 73... | [
"import pylab\nscores = [[ 82.,78., 71.5, 76., 79.5, 77., 73.5, 70.5, 74., 74.5 ],\n[ 79. , 75.75, 71., 76., 78.25, 73.25, 72.25 ,73.25, 74.75, 73.5 ],\n[ 77., 75., 70.5, 73. , 77., 73.5, 71.75, 75.25, 76.75, 74. ],\n[ 76., 74.75, 72.5, 72.25 ,75.25, 76.5, 73.5, 73., 75.25,... | [
3
] | [] | [] | [
"matplotlib",
"plot",
"python"
] | stackoverflow_0007110897_matplotlib_plot_python.txt |
Q:
Is there a way to disable built-in deadlines on App Engine dev_appserver?
I realize that dev_appserver.py is meant to simulate the production App Engine environment as much as possible, but I'm having trouble debugging an app locally due to slow connection issues (I keep getting DeadlineExceededError exceptions). ... | Is there a way to disable built-in deadlines on App Engine dev_appserver? | I realize that dev_appserver.py is meant to simulate the production App Engine environment as much as possible, but I'm having trouble debugging an app locally due to slow connection issues (I keep getting DeadlineExceededError exceptions). Since it's not the connection itself that I'm concerned about, is there any way... | [
"When running on the development server, you could set a higher default urlfetch deadline:\nimport os\nif os.environ['SERVER_SOFTWARE'].startswith('Dev'):\n from google.appengine.api import urlfetch\n urlfetch.set_default_fetch_deadline(60)\n\n"
] | [
4
] | [] | [] | [
"google_app_engine",
"python",
"sdk"
] | stackoverflow_0007102501_google_app_engine_python_sdk.txt |
Q:
XML-RPC returning value before executing all function code
I have XML-RPC server:
import time
import xmlrpclib
from SimpleXMLRPCServer import SimpleXMLRPCServer
class Worker(object):
def start_work(self):
# is it possible do return value to client here?
self.do_work()
return 'we start... | XML-RPC returning value before executing all function code | I have XML-RPC server:
import time
import xmlrpclib
from SimpleXMLRPCServer import SimpleXMLRPCServer
class Worker(object):
def start_work(self):
# is it possible do return value to client here?
self.do_work()
return 'we started!'
def do_work(self):
while(True):
pr... | [
"If you want XML-RPC with long-running, early returning tasks, you probably need to rewrite your server into an asynchronous framework, like twisted\n",
"I'm not sure this is a good idea to do such a thing without threads or without reimplement some parts of the SimpleXMLRPCServer or without breaking XMLRPC proto... | [
4,
1
] | [] | [] | [
"multithreading",
"python",
"simplexmlrpcserver",
"xml_rpc",
"xmlrpclib"
] | stackoverflow_0007106422_multithreading_python_simplexmlrpcserver_xml_rpc_xmlrpclib.txt |
Q:
How to change the colour of a scatterplot in a loop/if statement? (Python)
I'm trying to make it so that if the scatterplot for Events is above the Diatomite scatterplot, then the color of the plot changes from blue to red. (Similarly from blue to yellow if otherwise).
I've looked around for quite some time, but i... | How to change the colour of a scatterplot in a loop/if statement? (Python) | I'm trying to make it so that if the scatterplot for Events is above the Diatomite scatterplot, then the color of the plot changes from blue to red. (Similarly from blue to yellow if otherwise).
I've looked around for quite some time, but it doesn't seem to be working.
Here's the code as follows:
for line in open('C:\.... | [
"It looks like you almost have it. First define the colors, then make the scatter plot. So after print Tave, build a list containing the colors; I used a list comprehension to do this:\ny0colors = ['red' if value > Tave else 'yellow' for value in y0]\n\nThen when you make 'Events', set color=y0colors, like so:\nEve... | [
5
] | [] | [] | [
"matplotlib",
"python"
] | stackoverflow_0007110648_matplotlib_python.txt |
Q:
SQLAlchemy - don't enforce foreign key constraint on a relationship
I have a Test model/table and a TestAuditLog model/table, using SQLAlchemy and SQL Server 2008. The relationship between the two is Test.id == TestAuditLog.entityId, with one test having many audit logs. TestAuditLog is intended to keep a histor... | SQLAlchemy - don't enforce foreign key constraint on a relationship | I have a Test model/table and a TestAuditLog model/table, using SQLAlchemy and SQL Server 2008. The relationship between the two is Test.id == TestAuditLog.entityId, with one test having many audit logs. TestAuditLog is intended to keep a history of changes to rows in the Test table. I want to track when a Test is d... | [
"You can solve this by:\n\nPOINT-1: not having a ForeignKey neither on the RDBMS level nor on the SA level\nPOINT-2: explicitly specify join conditions for the relationship \nPOINT-3: mark relationship cascades to rely on passive_deletes flag\n\nFully working code snippet below should give you an idea (points are h... | [
16
] | [] | [] | [
"foreign_keys",
"join",
"python",
"sql_server",
"sqlalchemy"
] | stackoverflow_0007110118_foreign_keys_join_python_sql_server_sqlalchemy.txt |
Q:
Missing PyGST Plugin?
I'm running python 2.6 and PyGST (most recent available for Python 2.6). I've installed all the plugins - good, bad, and ugly.
I have the following code:
import sys, os
import pygtk, gtk, gobject
import pygst
pygst.require("0.10")
import gst
class GTK_Main:
def __init__(self):
wi... | Missing PyGST Plugin? | I'm running python 2.6 and PyGST (most recent available for Python 2.6). I've installed all the plugins - good, bad, and ugly.
I have the following code:
import sys, os
import pygtk, gtk, gobject
import pygst
pygst.require("0.10")
import gst
class GTK_Main:
def __init__(self):
window = gtk.Window(gtk.WINDO... | [
"What you need is a full uri: \nif you handle only files on your local filesystem and want to insert the file path only, change the line \nself.player.set_property(\"uri\", filepath)\n\nto something like this:\nself.player.set_property(\"uri\", \"file://\"+filepath)\n\nAND: GST has some routines to handle uri bette... | [
1,
0
] | [] | [] | [
"gstreamer",
"python"
] | stackoverflow_0006975374_gstreamer_python.txt |
Q:
Why my Tkinter gui is not responding?
Possible Duplicate:
How can I monitor Tkinter buttons when Python is busy?
I have a problem with tkinter gui code i wrote.It stops responding when i press a button and the function is executed.Here is an example code to make things clearer:
from Tkinter import*
import Tkinte... | Why my Tkinter gui is not responding? |
Possible Duplicate:
How can I monitor Tkinter buttons when Python is busy?
I have a problem with tkinter gui code i wrote.It stops responding when i press a button and the function is executed.Here is an example code to make things clearer:
from Tkinter import*
import Tkinter as tk
import tkFileDialog
import urllib
... | [
"This question is a duplicate, so look at the answers for the original. Short answer: the window needs the event loop to be running so that redraw events can be processed, but while your loop is running the event loop is stopped. \nTo answer the question in the comments:\nthe event loop is an infinite loop that run... | [
1
] | [] | [] | [
"python",
"tkinter",
"user_interface"
] | stackoverflow_0007086849_python_tkinter_user_interface.txt |
Q:
Hex converter help - Python
I have this code that converts binary to hex
## The Input part
l = raw_input('Input 8-bit number: ')
j = list(l)
## Value Error part
t = [int(x) for x in j]
if len(t) != 8 or len([n for n in t if n not in (1, 0)]) != 0:
raise ValueError('NOT 1 OR 0, or NOT CORRECT LENGTH')
## T... | Hex converter help - Python | I have this code that converts binary to hex
## The Input part
l = raw_input('Input 8-bit number: ')
j = list(l)
## Value Error part
t = [int(x) for x in j]
if len(t) != 8 or len([n for n in t if n not in (1, 0)]) != 0:
raise ValueError('NOT 1 OR 0, or NOT CORRECT LENGTH')
## The Conversion part
a = l[0]
b =... | [
"If I understand you correctly, you want to print out a 2-digit hex number that is gotten from the binary input l. You can do that as follows:\nprint 'Hex: ', hex(int(l, 2))[2:].zfill(2)\n\n",
"Skip all that coding.\nFirst off, try hex(): http://docs.python.org/library/functions.html#hex\nThen, check out format()... | [
2,
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0007111503_python.txt |
Q:
How to use the 'count' parameter in tweepy's streaming API?
I can use the streaming API just fine when I don't include the count parameter in filter() call, but when I try to specify how many tweets from my history I want to receive, my stream object returns None.
import tweepy
from tweepy.streaming import StreamL... | How to use the 'count' parameter in tweepy's streaming API? | I can use the streaming API just fine when I don't include the count parameter in filter() call, but when I try to specify how many tweets from my history I want to receive, my stream object returns None.
import tweepy
from tweepy.streaming import StreamListener, Stream
class Listener (StreamListener):
def on_stat... | [
"Stream.filter always returns None, its job is just to pass the data on to the StreamListener.\nYour problem is that Twitter only allows the count parameter for certain \"roles\".\n\nFirehose, Links, Birddog and Shadow clients interested in capturing all statuses should maintain a current estimate of the number of ... | [
9
] | [] | [] | [
"python",
"tweepy",
"twitter"
] | stackoverflow_0007111346_python_tweepy_twitter.txt |
Q:
Does Python provide "free" default iterators?
Possible Duplicate:
Why does defining getitem on a class make it iterable in python?
I have a class that is basically a wrapper for a python list. Within this class I have defined __getitem__, __setitem__, and __len__ . I have not defined __iter__ for this class.
whe... | Does Python provide "free" default iterators? |
Possible Duplicate:
Why does defining getitem on a class make it iterable in python?
I have a class that is basically a wrapper for a python list. Within this class I have defined __getitem__, __setitem__, and __len__ . I have not defined __iter__ for this class.
when I go:
thing = ListWrapper(range(4))
for i in thi... | [
"If a class doesn't have __iter__, but does have __getitem__, the iteration machinery will call it with consecutive integers until it runs out.\n"
] | [
4
] | [] | [] | [
"default",
"iterator",
"python"
] | stackoverflow_0007111736_default_iterator_python.txt |
Q:
Is there a library to benchmark my Django App for SQL requests?
I have a large complex Django App that we use that does lots of things. From looking at the Django Debug Toolbar some of our views do a lot of SQL requests. I want to increase the performance of it by reducing the number of SQL requests (e.g. by addin... | Is there a library to benchmark my Django App for SQL requests? | I have a large complex Django App that we use that does lots of things. From looking at the Django Debug Toolbar some of our views do a lot of SQL requests. I want to increase the performance of it by reducing the number of SQL requests (e.g. by adding more select_related, more clever queries, etc.). I would like to be... | [
"This information is only available in debug mode. I'm not aware of any library to do exactly what you are trying to do, however you could probably rig something up pretty easily.\nIf you are in running in debug mode, then you can view all the queries that have been run with connection.queries. This is effectivel... | [
4
] | [] | [] | [
"benchmarking",
"django",
"django_orm",
"performance",
"python"
] | stackoverflow_0007111149_benchmarking_django_django_orm_performance_python.txt |
Q:
Python Read Formatted String
I have a file with a number of lines formatted with the following syntax:
FIELD POSITION DATA TYPE
------------------------------
COOP ID 1-6 Character
LATITUDE 8-15 Real
LONGITUDE 17-25 Real
ELEVATION 27-32 Real
STATE 34-35 Character
NAME ... | Python Read Formatted String | I have a file with a number of lines formatted with the following syntax:
FIELD POSITION DATA TYPE
------------------------------
COOP ID 1-6 Character
LATITUDE 8-15 Real
LONGITUDE 17-25 Real
ELEVATION 27-32 Real
STATE 34-35 Character
NAME 37-66 Character
COMPONENT1 6... | [
"EDIT: You can still use the struct module:\nSee the struct module documentation. Looks to me like you want to use struct.unpack()\nWhat you want is probably something like:\nimport struct\nwith open(\"filename.txt\", \"r\") as f:\n for line in f:\n (coop_id, lat, lon, elev, state, name, c1, c2, c3, utc_o... | [
16,
1,
0
] | [] | [] | [
"io",
"python"
] | stackoverflow_0007111690_io_python.txt |
Q:
How do you change font color. - Python
Possible Duplicate:
Print in terminal with colors using python?
Just curious
So I want to print 'Blah' in red how do i do this.
I only want to change the color of that statement.
A:
You need ANSI Colors, for your command line. But this isn't always supported by the comput... | How do you change font color. - Python |
Possible Duplicate:
Print in terminal with colors using python?
Just curious
So I want to print 'Blah' in red how do i do this.
I only want to change the color of that statement.
| [
"You need ANSI Colors, for your command line. But this isn't always supported by the computer.\nWith a litle bit of looking around on the web, I found this helpful link: http://linux.byexamples.com/archives/184/print-text-in-colors-with-a-simple-command-line/\n",
"This will print red text in Terminal on OSX:\npri... | [
1,
1
] | [] | [] | [
"python"
] | stackoverflow_0007112028_python.txt |
Q:
plotting multiple (x,y) co-ordinates in a single curve with gnuplot
Hi I want to plot multiple (x,y) coordinates in a single graph. Say I have a data file which has the contents like the following:
x y
0.0 0.5
0.12 0.1
0.16 0.4
0.2 0.35
0.31 0.8
0.34 0.6
0.38 1.0
0.46 0.2
0.51 0.7
0.7 ... | plotting multiple (x,y) co-ordinates in a single curve with gnuplot | Hi I want to plot multiple (x,y) coordinates in a single graph. Say I have a data file which has the contents like the following:
x y
0.0 0.5
0.12 0.1
0.16 0.4
0.2 0.35
0.31 0.8
0.34 0.6
0.38 1.0
0.46 0.2
0.51 0.7
0.7 0.9
could I have a some more data in this file like,
x y x1 ... | [
"gnuplot can only plot column format data as far as I know. That said, you will have to plot it in after transpose your data as follows:\nx 0.000000 y 0.500000 x 0.120000 y 0.100000 ...\nx1 0.040000 y1 0.700000 x1 0.080000 y1 0.740000 ...\n\nand plot data us 1:2, data us 3:4, data us 5:6.\nTo transpose the da... | [
2
] | [] | [] | [
"gnuplot",
"python"
] | stackoverflow_0007107552_gnuplot_python.txt |
Q:
How to test for existence of child nodes using Python to iterate over XML (using xml.dom.minidom)
I am using Python, and xml.dom.minidom, to iterate over an exported Excel Spreadsheet, outputting an HTML table for our dining hall menu with various calls to .write. The difficulty lies in that the XML that Excel out... | How to test for existence of child nodes using Python to iterate over XML (using xml.dom.minidom) | I am using Python, and xml.dom.minidom, to iterate over an exported Excel Spreadsheet, outputting an HTML table for our dining hall menu with various calls to .write. The difficulty lies in that the XML that Excel outputs isn't structured. To compensate for this, I have set up a number of variables (day, previousDay, m... | [
"My quick inclination is to have a nested for-loop with a get-out-of-node-free-card (um, exception) like the following. \nClass BadNodeException (Exception):\npass\nfor node in dome.getElementsByTagName('data'):\ntry: \n for child in node.childNodes:\n if child.nodeValue == 'test':\n raise BadN... | [
0,
0,
0
] | [] | [] | [
"minidom",
"python",
"xml"
] | stackoverflow_0005585117_minidom_python_xml.txt |
Q:
python array.fromfile vs struct.unpack
I am currently using struct.unpack to read a binary file. Frequently, I would be reading different types of values, so I might read a few longs, then read 8 floats, then read 2 shorts, a couple bytes, etc.
But they are generally grouped nicely so you might get a bunch of long... | python array.fromfile vs struct.unpack | I am currently using struct.unpack to read a binary file. Frequently, I would be reading different types of values, so I might read a few longs, then read 8 floats, then read 2 shorts, a couple bytes, etc.
But they are generally grouped nicely so you might get a bunch of longs, and then a bunch of floats, and then a bu... | [
"Sounds like you are in the best position to do the time trials. You already have the struct.unpack version, so make an array.fromfile version and then use the timeit module to do some benchmarks. Something like this:\npython -m timeit -s \"import struct_version\" \"struct_version.main()\"\n\npython -m timeit -s ... | [
1
] | [] | [] | [
"binaryfiles",
"performance",
"python"
] | stackoverflow_0006615421_binaryfiles_performance_python.txt |
Q:
python bitwise operations on C data types?
Is it possible to do bitwise operations on C data types in Python?
Python 2.7.1+ (r271:86832, Apr 11 2011, 18:13:53)
[GCC 4.5.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> from ctypes import c_uint8
>>> foo = c_uint8(4)
>>> foo <... | python bitwise operations on C data types? | Is it possible to do bitwise operations on C data types in Python?
Python 2.7.1+ (r271:86832, Apr 11 2011, 18:13:53)
[GCC 4.5.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> from ctypes import c_uint8
>>> foo = c_uint8(4)
>>> foo << 1
Traceback (most recent call last):
File "<... | [
"This works, but it isn't done at the C level:\nfoo.value << 1\n\n",
"Try foo.value << 1\nor to update foo,\nfoo.value <<= 1\n\n",
"from ctypes import c_uint8\nfoo = c_uint8(4)\nprint foo.value << 1\n\nwill print 8 as you want. To change foo, use\nfoo.value <<= 1\n\n"
] | [
4,
4,
2
] | [] | [] | [
"bit_manipulation",
"ctypes",
"python"
] | stackoverflow_0007112572_bit_manipulation_ctypes_python.txt |
Q:
Use Cython as Python to C Converter
I have huge Python modules(+8000 lines) .They basically have tons of functions for interacting with a hardware platform via serial port by reading and writing to hardware registers.
They are not numerical algorithms. So application is just reading/writing to hardware registers/m... | Use Cython as Python to C Converter | I have huge Python modules(+8000 lines) .They basically have tons of functions for interacting with a hardware platform via serial port by reading and writing to hardware registers.
They are not numerical algorithms. So application is just reading/writing to hardware registers/memory. I use these libraries to write cus... | [
"\nYes, at its core this is what Cython does. But ...\nYou don't need Cython, however, you do need libpython. You may feel like it doesn't use that many Python features, but I think if you try this you'll find it's not true -- you won't be able to separate your program from its dependence on libpython while still u... | [
42,
2
] | [] | [] | [
"c",
"cython",
"python"
] | stackoverflow_0007112812_c_cython_python.txt |
Q:
Sending data in a POST message to a RESTful web service
I need to send some JSON data in a POST message to a RESTful webservice.
Which python module should I be using for this? Is there some sample code I can refer to?
A:
Which bit are you having trouble with? The JSON, or the POST?
For JSON, the json module ha... | Sending data in a POST message to a RESTful web service | I need to send some JSON data in a POST message to a RESTful webservice.
Which python module should I be using for this? Is there some sample code I can refer to?
| [
"Which bit are you having trouble with? The JSON, or the POST?\nFor JSON, the json module has been included in Python since version 2.5. Just do json.dumps(my_data) to convert a data variable to JSON.\nFor the POST, there are various modules in the standard library, but the best bet is to install the third-party re... | [
3,
0,
0
] | [] | [] | [
"python",
"rest",
"web_services"
] | stackoverflow_0007112125_python_rest_web_services.txt |
Q:
Python: Move files from Folder and subfolders to another similar directory
I have two source file paths:
C:\Same\Path\To\File\unknown\
C:\Same\Path\To\File\unrecognized\
And one destination path:
C:\Same\Path\To\File\Import
The subfolders for all these paths are the same. They are 10-15 folders that have 3 dig... | Python: Move files from Folder and subfolders to another similar directory | I have two source file paths:
C:\Same\Path\To\File\unknown\
C:\Same\Path\To\File\unrecognized\
And one destination path:
C:\Same\Path\To\File\Import
The subfolders for all these paths are the same. They are 10-15 folders that have 3 digit names (233 for example).
If any files are in these subfolders of the source p... | [
"I think what you want is shutil.move (py3k docs):\n\nHelp on function move in module shutil:\n\nmove(src, dst)\nRecursively move a file or directory to another location. This is\nsimilar to the Unix \"mv\" command.\n\nIf the destination is a directory or a symlink to a directory, the source\nis moved inside the di... | [
3,
1
] | [] | [] | [
"python"
] | stackoverflow_0007113062_python.txt |
Q:
Make a list out of variables
This is part of my script:
for line in range(0,len(lines),2):
num = lines[line].split()[8]
num1= abs(num)
Obviously I can produce many num1 here from each line....
Here I want to put all these num1 into one list, then how can I do? thx
Sorry guys, this is python! lol
... | Make a list out of variables | This is part of my script:
for line in range(0,len(lines),2):
num = lines[line].split()[8]
num1= abs(num)
Obviously I can produce many num1 here from each line....
Here I want to put all these num1 into one list, then how can I do? thx
Sorry guys, this is python! lol
| [
"li = []\nfor line in range(0,len(lines),2):\n num = lines[line].split()[8]\n li.append(abs(num))\n\nor\nli = [abs(lines[line].split()[8]) for line in range(0,len(lines),2)]\n\n",
"In Python, we iterate directly. You want items from the list of lines, so ask for items of the list of lines. Don't ask... | [
4,
0,
-1
] | [] | [] | [
"list",
"python",
"variables"
] | stackoverflow_0007112840_list_python_variables.txt |
Q:
How can I convert Shift_JIS character codes to unicode characters in python?
I have a list of Shift_JIS character codes (in integers) that I want to convert into unicode characters. I think I need a version of the chr()/unichr() function that works in other encodings.
I've tried decode() in combination with hex()... | How can I convert Shift_JIS character codes to unicode characters in python? | I have a list of Shift_JIS character codes (in integers) that I want to convert into unicode characters. I think I need a version of the chr()/unichr() function that works in other encodings.
I've tried decode() in combination with hex(), but it only decodes the string itself, not the hexadecimal value.
Example input ... | [
"If you start with something like this:\nbytearray = [65, 66, 67, 200, 156, 130]\nThen this would do it:\n>>> ustring = reduce(operator.add, map(chr, bytearray)).decode('shift_jis')\n>>> ustring\nu'ABC\\uff88\\u6029'\n\n"
] | [
0
] | [] | [] | [
"character",
"encoding",
"python",
"shift_jis"
] | stackoverflow_0007113206_character_encoding_python_shift_jis.txt |
Q:
Iterating over multiple lists in Python
I have a list within a list, and I am trying to iterate through one list, and then in the inner list I want to search for a value, and if this value is present, place that list in a variable.
Here's what I have, which doesn't seem to be doing the job:
for z, g in range(len(t... | Iterating over multiple lists in Python | I have a list within a list, and I am trying to iterate through one list, and then in the inner list I want to search for a value, and if this value is present, place that list in a variable.
Here's what I have, which doesn't seem to be doing the job:
for z, g in range(len(tablerows), len(andrewlist)):
tablerowslis... | [
"Assuming you have a list whose elements are lists, this is what I'd do:\nandrewlist = [row for row in tablerows if \"Andrew Alexander\" in row]\n\n",
"\nfor z, g in range(len(tablerows), len(andrewlist)):\n\nThis means \"make a list of the numbers which are between the length of tablerows and the length of andre... | [
4,
1,
1
] | [] | [] | [
"list",
"python"
] | stackoverflow_0007113456_list_python.txt |
Q:
Poor division of labor using multiprocessing in python?
Consider the following program:
import Queue
from multiprocessing import Queue as Q
from multiprocessing import Process, Value, Array
from time import time
from numpy import sum, zeros
from numpy.random import normal
def enche(queue, cnts, tims, t0, proc):
... | Poor division of labor using multiprocessing in python? | Consider the following program:
import Queue
from multiprocessing import Queue as Q
from multiprocessing import Process, Value, Array
from time import time
from numpy import sum, zeros
from numpy.random import normal
def enche(queue, cnts, tims, t0, proc):
while True:
try:
queue.get(False)
... | [
"The task it does in parallel is rather small compared to process start overhead, so that one process can do many iterations before other processes get a chance to start running. \nIf the line:\nx = sum(normal(size = 1000))\n\nis changed to:\nx = sum(normal(size = 100000))\n\nThis is what I get:\n25/100, 366.2 ms, ... | [
5,
1
] | [] | [] | [
"multicore",
"multiprocessing",
"parallel_processing",
"python"
] | stackoverflow_0007113218_multicore_multiprocessing_parallel_processing_python.txt |
Q:
Python dictionary get method in assignment
All,
I'm looping over a dictionary and counting the values that occur. To do this, I'm using the get method in the assignment statement for another dictionary. This returns a syntax error "can't assign to function call"
counts = {}
mydict = {'a':[1,2,5], 'b': [1,2,10]}
fo... | Python dictionary get method in assignment | All,
I'm looping over a dictionary and counting the values that occur. To do this, I'm using the get method in the assignment statement for another dictionary. This returns a syntax error "can't assign to function call"
counts = {}
mydict = {'a':[1,2,5], 'b': [1,2,10]}
for key,value in mydict.iteritems():
counts(va... | [
"counts = {}\nmydict = {'a':[1,2,5], 'b': [1,2,10]}\nfor key,value in mydict.iteritems():\n counts[value[1]] = counts.get(value[1], 0) + 1\n\nYou need brackets, not parenthesis, to get an item from a dictionary.\nAlso, You're doing this the hard way.\nfrom collections import defaultdict\n\n# automatically start ... | [
2,
1,
0,
0
] | [] | [] | [
"python",
"syntax_error"
] | stackoverflow_0007113600_python_syntax_error.txt |
Q:
insertion sort get indices?
I use the following algorithm for insertion sort:
def insertionSort(A):
indices = [z for z in xrange(len(A))]
for j in range(1, len(A)):
key = A[j]
i = j-1
while (i>=0) and (A[i]<key):
A[i+1] = A[i]
indices[j-i-1] = i+1
... | insertion sort get indices? | I use the following algorithm for insertion sort:
def insertionSort(A):
indices = [z for z in xrange(len(A))]
for j in range(1, len(A)):
key = A[j]
i = j-1
while (i>=0) and (A[i]<key):
A[i+1] = A[i]
indices[j-i-1] = i+1
i = i-1
A[i+... | [
"Why are you writing a sort? Use Python's builtin sorting.\ndef sort_with_indexes(data):\n sorted_data = sorted(enumerate(data), key=lambda key: key[1])\n indexes = range(len(data))\n indexes.sort(key=lambda key: sorted_data[key][0])\n return [i[1] for i in sorted_data], indexes\n\ndata, indexes = sort... | [
4,
2,
0,
0,
0,
0
] | [] | [] | [
"insertion_sort",
"python",
"sorting"
] | stackoverflow_0005185060_insertion_sort_python_sorting.txt |
Q:
How to specify each index number - Python
I'm writing this program that is supposed to convert binary to hex. I have to use the for loop. The part I need is how do I get the program to get the integer and its index number.
my code so far
q = raw_input('asdf ')
p = list(q)
t = [int(x) for x in p]
for i in t:
if... | How to specify each index number - Python | I'm writing this program that is supposed to convert binary to hex. I have to use the for loop. The part I need is how do I get the program to get the integer and its index number.
my code so far
q = raw_input('asdf ')
p = list(q)
t = [int(x) for x in p]
for i in t:
if i == 1:
w=i*(2**(3-t[x]))
print w
the... | [
"You can use the enumerate function.\nfor rank, item in enumerate(my_list):\n # here you have the index of the item (rank)\n # and the item ( the same as my_list[rank] )\n\nfor your example you can do something like this : \n inital_binary = raw_input(\"polop\")\n for rank, letter in enumerate(inital_binary):\n... | [
4,
0
] | [] | [] | [
"python"
] | stackoverflow_0007110654_python.txt |
Q:
How do I copy lines following a tag in a python script?
I am trying to copy lines a certain number of times following a certain tag.
If I have a text file like the following:
##TextLines##
Hi
Hello
##TextLines##
How do I erase the tags and copy the line once?
The end text file would look like:
Hi
Hello
Hi
Hell... | How do I copy lines following a tag in a python script? | I am trying to copy lines a certain number of times following a certain tag.
If I have a text file like the following:
##TextLines##
Hi
Hello
##TextLines##
How do I erase the tags and copy the line once?
The end text file would look like:
Hi
Hello
Hi
Hello
Right now, I have a regular expression to find the tags an... | [
"This should do the job\nimport re \nregex = re.compile(\"^##.*##\\n$\")\nout = open(\"result.txt\",\"w\")\nmatchfound = True\ninmatch =False\nfor line in open('myfile.txt'):\n if regex.match(line):\n matchfound = True\n else:\n matchfound = False\n if matchfound and not inmatch:\n inmatch ... | [
1,
0
] | [] | [] | [
"python",
"scripting"
] | stackoverflow_0007113307_python_scripting.txt |
Q:
Windows preventing reg query on HKLM; returns HKCU instead
I'm using ActivePython 2.5 to read the registry for entries that pGina makes. Specifically, the entries concerning which GIDs are allowed on the computer. This information can periodically change for each computer as edited through pGina, so I want my Pyth... | Windows preventing reg query on HKLM; returns HKCU instead | I'm using ActivePython 2.5 to read the registry for entries that pGina makes. Specifically, the entries concerning which GIDs are allowed on the computer. This information can periodically change for each computer as edited through pGina, so I want my Python script to be able to check these values each time.
Easy enoug... | [
"Use winreg. (winreg.OpenKey and winreg.Query*). Way faster, no need to thunk out to running a shell command, and it will even return you tricky registry value types like BINARY as well, all in an OO way.\n#import _winreg as winreg # the 'correct' idiom for importing\nfrom _winreg import *\n\nwith OpenKey(HKEY_LOCA... | [
1,
0
] | [] | [] | [
"python",
"registry",
"registry_virtualization",
"windows",
"windows_7"
] | stackoverflow_0007071972_python_registry_registry_virtualization_windows_windows_7.txt |
Q:
does closing a file opened with os.fdopen close the os-level fd?
I'm making a temporary file with tempfile.mkstemp(). It returns an os-level fd along with the path to the file. I want to os.fdopen() the os-level file descriptor to write to it. If I then close the file that os.fdopen() returned, will the os-level f... | does closing a file opened with os.fdopen close the os-level fd? | I'm making a temporary file with tempfile.mkstemp(). It returns an os-level fd along with the path to the file. I want to os.fdopen() the os-level file descriptor to write to it. If I then close the file that os.fdopen() returned, will the os-level file descriptor be closed, or do I have to os.close() it explicitly? Th... | [
"I'm pretty sure the fd will be closed. If you don't want that you can dup it first. Of course you can always test this easily enough.\nTest is like this:\nfrom __future__ import print_function\n\nimport os\nimport tempfile\nimport errno\n\nfd, tmpname = tempfile.mkstemp()\nfo = os.fdopen(fd, \"w\")\nfo.write(\"som... | [
10
] | [] | [] | [
"file_io",
"operating_system",
"python"
] | stackoverflow_0007114059_file_io_operating_system_python.txt |
Q:
Iterator with memory?
I'm working on an application which use a markov chain.
An example on this code follows:
chain = MarkovChain(order=1)
train_seq = ["","hello","this","is","a","beautiful","world"]
for i, word in enum(train_seq):
chain.train(previous_state=train_seq[i-1],next_state=word)
What I am looking fo... | Iterator with memory? | I'm working on an application which use a markov chain.
An example on this code follows:
chain = MarkovChain(order=1)
train_seq = ["","hello","this","is","a","beautiful","world"]
for i, word in enum(train_seq):
chain.train(previous_state=train_seq[i-1],next_state=word)
What I am looking for is to iterate over train_... | [
"window will give you n items from iterable at a time.\nfrom collections import deque\n\ndef window(iterable, n=3):\n it = iter(iterable)\n d = deque(maxlen = n)\n for elem in it:\n d.append(elem)\n yield tuple(d)\n\n\nprint [x for x in window([1, 2, 3, 4, 5])]\n# [(1,), (1, 2), (1, 2, 3), (2... | [
6,
1,
0
] | [] | [] | [
"iterator",
"python"
] | stackoverflow_0007113724_iterator_python.txt |
Q:
Execute a file (installer) in Python and immediately exit
I'm writing an installer of sorts. When a user runs my python file (compiled to executable), it downloads the actual installer then needs to run the installer and immediately exit (i.e. the real installer keeps running). My question is how do I do this bi... | Execute a file (installer) in Python and immediately exit | I'm writing an installer of sorts. When a user runs my python file (compiled to executable), it downloads the actual installer then needs to run the installer and immediately exit (i.e. the real installer keeps running). My question is how do I do this bit? How do I execute the installer from the python script and e... | [
"You should look at os.exec* functions:\n\nThese functions all execute a new program, replacing the current process; they do not return. On Unix, the new executable is loaded into the current process, and will have the same process id as the caller.\n\nIf you must exit the python script, may be you could use subpro... | [
4,
2
] | [] | [] | [
"python",
"python_2.7"
] | stackoverflow_0007114256_python_python_2.7.txt |
Q:
Uploading data with bulkloader
In short: how can I configure bulkloader to insert data into 2 models with references?
I have a person and fruit class, with person linking to fruit:
class Fruit(db.Model):
name = db.StringProperty()
class Person(db.Model):
name = db.StringProperty()
customer = db.Refe... | Uploading data with bulkloader | In short: how can I configure bulkloader to insert data into 2 models with references?
I have a person and fruit class, with person linking to fruit:
class Fruit(db.Model):
name = db.StringProperty()
class Person(db.Model):
name = db.StringProperty()
customer = db.ReferenceProperty(Fruit)
And I want to ... | [
"Sure.\nThe basic problem is that there's a step missing. You have a fruit name, what you want to store a reference to is a fruit key. You can accomplish this in a few ways.\nIf Banana or Apple is a permanent, unique identifier for a fruit, you can use transform.create_foreign_key('Fruit'). This will give you a fru... | [
4,
1,
0
] | [] | [] | [
"bulkloader",
"google_app_engine",
"python"
] | stackoverflow_0005937011_bulkloader_google_app_engine_python.txt |
Q:
commands module problem
Hi I'm trying to execute bash command in python by importing commands module.I think I ask the same question here before. However this time it doesn't work.
The script is as below:
#!/usr/bin/python
import os,sys
import commands
import glob
path= '/home/xxx/nearline/bamfiles'
bamfiles = gl... | commands module problem | Hi I'm trying to execute bash command in python by importing commands module.I think I ask the same question here before. However this time it doesn't work.
The script is as below:
#!/usr/bin/python
import os,sys
import commands
import glob
path= '/home/xxx/nearline/bamfiles'
bamfiles = glob.glob(path + '/*.bam')
for... | [
"I would recommend using subprocess\nFrom the commands documentation:\n\nDeprecated since version 2.6: The commands module has been removed in Python 3.0. Use the subprocess module instead.\n\nUpdate: Just realized you're using Python 2.4. An easy way to execute a command is os.system()\n",
"A quick google search... | [
2,
1
] | [] | [] | [
"command",
"python"
] | stackoverflow_0007114475_command_python.txt |
Q:
Accessing fields from a text file
I'm new to python. I need to access fields from a text file which is basically a tweet stream in json format. The text file looks like this:
{u'favorited': False, u'entities': {u'user_mentions': [{u'indices': [76, 84], u'id': 10228272, u'id_str': u'10228272', u'name': u'YouTube', ... | Accessing fields from a text file | I'm new to python. I need to access fields from a text file which is basically a tweet stream in json format. The text file looks like this:
{u'favorited': False, u'entities': {u'user_mentions': [{u'indices': [76, 84], u'id': 10228272, u'id_str': u'10228272', u'name': u'YouTube', u'screen_name': u'YouTube'}], u'hashtag... | [
"I very much doubt that that's the raw JSON text format. That to me looks like the output once you've loaded it into Python with json.loads().\nGiven that it's already a dictionary, you just do data['screen_name'].\n",
"That looks more like a Python string than json. If you already have that in a string, say s yo... | [
2,
2,
1
] | [] | [] | [
"json",
"python"
] | stackoverflow_0007105194_json_python.txt |
Q:
How do I change the colour of a specific branch within QTreeView?
I have a QTreeView, and I've figured out how to set its style by using setStyleSheet in my main class:
self.view.setStyleSheet("""
QTreeView::item {
margin: 2px;
}
""")
That will style the entire QTreeView. But I want certain items ... | How do I change the colour of a specific branch within QTreeView? | I have a QTreeView, and I've figured out how to set its style by using setStyleSheet in my main class:
self.view.setStyleSheet("""
QTreeView::item {
margin: 2px;
}
""")
That will style the entire QTreeView. But I want certain items in the tree to be bolded. When I create the branches (using [the parent... | [
"Qt's model-view architecture allows for data that describes the different roles being performed. For example, there is a role for editing data, displaying data, etc. You're interested in the font role (i.e. Qt::FontRole) as the font has a weight enum of which bold is one value.\nWhen you build your branches you f... | [
1,
0
] | [] | [] | [
"python",
"qt"
] | stackoverflow_0007097881_python_qt.txt |
Q:
How to query the maximum of counts of related records satisfying a predicate
I am working on a Django app for which I have encountered a tricky aggregate query that I would like to evaluate.
In the demo app of my project, I declared the following model classes for representing libraries' holdings:
from django.db i... | How to query the maximum of counts of related records satisfying a predicate | I am working on a Django app for which I have encountered a tricky aggregate query that I would like to evaluate.
In the demo app of my project, I declared the following model classes for representing libraries' holdings:
from django.db import models
class Book(models.Model):
interesting = models.BooleanField()
c... | [
"I think I figured it out:\nLibrary.objects.filter(books__interesting=True).annotate(num_interesting_books=Count('pk')).aggregate(max=Max('num_interesting_books'))\n\nTranslated to SQL, this is:\nselect max(a.num_interesting_books) as max\nfrom (select demo_library.*, count(demo_library.id) as num_interesting_books... | [
9
] | [] | [] | [
"django",
"django_aggregation",
"django_models",
"python"
] | stackoverflow_0007114591_django_django_aggregation_django_models_python.txt |
Q:
python logging decorator for views
A common functionality that I would like to write a decorator for is the following:
in a django view, I have following code:
def view(request):
try:
# do stuff and return success case view response
return render_to_response(...)
except:
# log the exce... | python logging decorator for views | A common functionality that I would like to write a decorator for is the following:
in a django view, I have following code:
def view(request):
try:
# do stuff and return success case view response
return render_to_response(...)
except:
# log the exception stack trace and return error case ... | [
"Don't call fileConfig in your views: do this in settings.py, as recommended in my answer to another question. Your view code should only contain the code to define the logger (as you already have it) as well as the logging calls themselves. Post your findings once you've made this change.\nAlso, don't post comment... | [
1
] | [] | [] | [
"decorator",
"django",
"logging",
"python",
"view"
] | stackoverflow_0007114337_decorator_django_logging_python_view.txt |
Q:
How do you create a LabelFrame with a scrollbar in Tkinter?
I'm using Python and Tkinter to create a GUI for a program I'm writing, and I'm having a couple of problems.
I have three objects descended from LabelFrame in an object descended from Frame. One of the LabelFrame descendants is two columns of correspondi... | How do you create a LabelFrame with a scrollbar in Tkinter? | I'm using Python and Tkinter to create a GUI for a program I'm writing, and I'm having a couple of problems.
I have three objects descended from LabelFrame in an object descended from Frame. One of the LabelFrame descendants is two columns of corresponding Label and Entry objects.
The problem is that there are a vary... | [
"Labelframes don't support scrolling. So the short answer to your question is \"you can't\". It sounds obvious, but if the documentation for a widget doesn't say it supports scrolling, it doesn't support scrolling. \nHowever, there is a simple solution. First, add a canvas as a child to the labelframe and pack it s... | [
3
] | [] | [] | [
"python",
"scrollbar",
"tkinter"
] | stackoverflow_0007113937_python_scrollbar_tkinter.txt |
Q:
How would the Python pipes module do a 'cat'
I am trying to do this in python:
cat foo | ssh me@xxxx hadoop fs -put - bar/foo
I have originally tried a check_call:
foo = 'foo'
subprocess.check_call(['cat', foo, '|','ssh',os.environ['USER']+'@'+hadoopGateway,'hadoop','fs','-put', '-', inputArgs.targetDir+'/'+foo])... | How would the Python pipes module do a 'cat' | I am trying to do this in python:
cat foo | ssh me@xxxx hadoop fs -put - bar/foo
I have originally tried a check_call:
foo = 'foo'
subprocess.check_call(['cat', foo, '|','ssh',os.environ['USER']+'@'+hadoopGateway,'hadoop','fs','-put', '-', inputArgs.targetDir+'/'+foo])
which produces the error:
cat: invalid option --... | [
"You don't need cat or a pipeline for this; all you need is to provide the file as standard input to the ssh command. In shell, that would be\nssh ${USER}@${hadoopGateway} hadoop fs -put - ${targetDir}/foo < foo\n\nand with the Python subprocess module it's only a tiny bit more involved:\nfoo='foo'\nsubprocess.che... | [
4
] | [] | [] | [
"pipe",
"python"
] | stackoverflow_0007114866_pipe_python.txt |
Q:
Matching string of numbers and letters and of a specific length
So I have this exercise and can't solve it:
I can only accept a string, if it's constructed of numbers AND letters, has to contain at least one of both; and it has to be 6-8 characters long. The string is only one word.
The first part is fine, though ... | Matching string of numbers and letters and of a specific length | So I have this exercise and can't solve it:
I can only accept a string, if it's constructed of numbers AND letters, has to contain at least one of both; and it has to be 6-8 characters long. The string is only one word.
The first part is fine, though I'm not sure about using match:
re.match('([a-zA-Z]+[0-9]+)', string)... | [
"Try this one:\n^(?=.*\\d)(?=.*[a-zA-Z])[a-zA-Z\\d]{6,8}$\n\nExplanation:\n^ //The Start of the string\n(?=.*\\d) //(?= ) is a look around. Meaning it\n //checks that the case is matched, but\n //doesn't capture anything\n //In this case, it's looking for... | [
7
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0007115298_python_regex.txt |
Q:
Using Float values in Imagedraw
Is there a way to set PIL and by extension Imagedraw to allow float values for such commands as Arc and Ellipse? I am running into major problems and cannot do what I need to do because of the seeming requirement that angles and bounding box position specifiers must be integers, and... | Using Float values in Imagedraw | Is there a way to set PIL and by extension Imagedraw to allow float values for such commands as Arc and Ellipse? I am running into major problems and cannot do what I need to do because of the seeming requirement that angles and bounding box position specifiers must be integers, and I cannot use a different package, no... | [
"If you want sub-pixel positioning, one possible-if-inefficient solution would be to scale everything up by a factor of, say, 10, rounding (original_floating_point_coordinates * 10) to integers, then resize the whole image back down at the end. Doesn't help with angles, I suppose.\n"
] | [
0
] | [] | [] | [
"generator",
"image",
"python",
"python_imaging_library"
] | stackoverflow_0007114946_generator_image_python_python_imaging_library.txt |
Q:
Are there already python generators that do these basic things?
I found myself using these 2 custom generators and thinking "there's got to be an itertools function or something that already does this! Didn't find any though. Am I missing something? Thanks!
def gothru(iters):
for i in iters:
for j in i:
... | Are there already python generators that do these basic things? | I found myself using these 2 custom generators and thinking "there's got to be an itertools function or something that already does this! Didn't find any though. Am I missing something? Thanks!
def gothru(iters):
for i in iters:
for j in i:
yield j
def overnover(fn,startval):
val = startval
while Tr... | [
"The first one is chain.from_iterable.\nThe closest thing to overnover is something like tabulate:\ndef tabulate(function, start=0):\n \"Return function(0), function(1), ...\"\n return imap(function, count(start))\n\nwhich is a special case of your function where it outputs sequential numbers. count also take... | [
5
] | [] | [] | [
"generator",
"iterator",
"python"
] | stackoverflow_0007115428_generator_iterator_python.txt |
Q:
Python List operations
This is code I have, but it looks like non-python.
def __contains__(self, childName):
"""Determines if item is a child of this item"""
for c in self.children:
if c.name == childName:
return True
return False
What is the most "python" way of doing this? Use a ... | Python List operations | This is code I have, but it looks like non-python.
def __contains__(self, childName):
"""Determines if item is a child of this item"""
for c in self.children:
if c.name == childName:
return True
return False
What is the most "python" way of doing this? Use a lambda filter function? For ... | [
"I would use:\nreturn any(childName == c.name for c in self.children)\n\nThis is short, and has the same advantage as your code, that it will stop when it finds the first match.\nIf you'll be doing this often, and speed is a concern, you can create a new attribute which is the set of child names, and then just use ... | [
7,
5,
1
] | [] | [] | [
"coding_style",
"list",
"python"
] | stackoverflow_0007115525_coding_style_list_python.txt |
Q:
How to generate quality windows icons with images of capital letters inside using Python?
I want to get 26 files (for starters): A.ico, B.ico, ... Z.ico, where they are composed of 16x16 256-color image, and a 32x32 256-color image, where the color of the text is black, and the font is ... say Calibri, and the siz... | How to generate quality windows icons with images of capital letters inside using Python? | I want to get 26 files (for starters): A.ico, B.ico, ... Z.ico, where they are composed of 16x16 256-color image, and a 32x32 256-color image, where the color of the text is black, and the font is ... say Calibri, and the size - whatever fits best into the square. I would like to do this using Python Image Library if p... | [
"Start with a large blank image and draw the character on the center of it. Find the edges of the character and extract a square from the image that includes all of the character. Use the thumbnail function with the ANTIALIAS option to reduce it to the 16x16 or 32x32 size required. Then reduce the number of colors ... | [
2,
2
] | [] | [] | [
"icons",
"python",
"python_imaging_library",
"windows"
] | stackoverflow_0007110728_icons_python_python_imaging_library_windows.txt |
Q:
Windows - running .py directly vs running python blah.py behaves differently
I have a python script that uses subprocess:
import subprocess
print "Running stuff"
subprocess.check_call(["do_stuff.bat"])
print "Stuff run"
If this was named blah.py, and I run (from a command prompt):
python blah.py
I will get the o... | Windows - running .py directly vs running python blah.py behaves differently | I have a python script that uses subprocess:
import subprocess
print "Running stuff"
subprocess.check_call(["do_stuff.bat"])
print "Stuff run"
If this was named blah.py, and I run (from a command prompt):
python blah.py
I will get the output from do_stuff.bat (or whatever I run).
If this is run as:
blah.py
Then I do... | [
"I had common problem using threads, but all of my code was in python. Threads can not write to standard output using print. Just main thread could do that. I used somethnig like this\nimport sys\nsys.stdout.write(\"this was printed by thread\")\n\nI know that probably it wont help you with bat file...\n"
] | [
1
] | [] | [] | [
"python",
"subprocess",
"windows"
] | stackoverflow_0007104920_python_subprocess_windows.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.