content stringlengths 85 101k | title stringlengths 0 150 | question stringlengths 15 48k | answers list | answers_scores list | non_answers list | non_answers_scores list | tags list | name stringlengths 35 137 |
|---|---|---|---|---|---|---|---|---|
Q:
How to implement/construct the following permutation, given two n-tuples, efficiently?
I am studying queuing theory in which I am frequently presented with the following situation.
Let x, y both be n-tuples of nonnegative integers (depicting lengths of the n queues). In addition, x and y each have distinguished qu... | How to implement/construct the following permutation, given two n-tuples, efficiently? | I am studying queuing theory in which I am frequently presented with the following situation.
Let x, y both be n-tuples of nonnegative integers (depicting lengths of the n queues). In addition, x and y each have distinguished queue called their "prime queue". For example,
x = [3, 6, 1, 9, 5, 2] with x' = 1
y = [6, 1, 5... | [
"Since you must do the ranking, you can't get linear and will need to sort. So it looks pretty straightforward. You do 1. in O(1) and 2. in O(n) by just going over the n-tuples. At the same time, you can construct the copy of x and y with only those that are left for 3. but do not include only the value, but instea... | [
1
] | [] | [] | [
"python"
] | stackoverflow_0008145777_python.txt |
Q:
Scripted interaction with GUI elements in Python under Linux
A while ago I used a python framework that could control the mouse and keyboard of the machine it was running on, and it made it possible to automate GUI interaction. Is there anything like this for Linux? I need to control an application running under W... | Scripted interaction with GUI elements in Python under Linux | A while ago I used a python framework that could control the mouse and keyboard of the machine it was running on, and it made it possible to automate GUI interaction. Is there anything like this for Linux? I need to control an application running under Wine which doesn't seem to follow most windows convention, so I wou... | [
"I found a application called \"Dogtail\" by red hat that uses python framework. http://www.redhat.com/magazine/020jun06/features/dogtail/\nAlso, found a package for python called autopy\nhttp://www.autopy.org/\n"
] | [
3
] | [] | [] | [
"automation",
"python"
] | stackoverflow_0007943659_automation_python.txt |
Q:
How can I extract tweets from Twitter tagged with latitude and longitude in text file
I want to extract tweets with latitude and longitude from Twitter in text file, using python
For example, I want to have the following in the extracted text file:
[50.4146912, -119.2066755] 6 2011-08-28 19:24:29 @NaomiAKlein ... | How can I extract tweets from Twitter tagged with latitude and longitude in text file | I want to extract tweets with latitude and longitude from Twitter in text file, using python
For example, I want to have the following in the extracted text file:
[50.4146912, -119.2066755] 6 2011-08-28 19:24:29 @NaomiAKlein @TheRealRoseanne "BreakingNews: President Obama to deliver live statement on Hurricane Iren... | [
"Here's a link to the docs for the Twitter REST API.\nAnd here are the basics to start pulling information down from Twitter:\nimport urllib2, json, pprint\n\nu = urllib2.urlopen('http://search.twitter.com/search.json?q=obama&rpp=25')\nresultdict = json.load(u)\n\npprint.pprint(resultdict)\nfor tweet in resultdict[... | [
2
] | [] | [] | [
"python",
"twitter"
] | stackoverflow_0008146596_python_twitter.txt |
Q:
clustering of a text file
Original Question:
I have a flat file with each row representing text associated with an application. I would like to cluster applications based on the words associated with that application Is there a free code available for text mining a single flat file? Thank you.
Update 1:
There are ... | clustering of a text file | Original Question:
I have a flat file with each row representing text associated with an application. I would like to cluster applications based on the words associated with that application Is there a free code available for text mining a single flat file? Thank you.
Update 1:
There are 30,000 applications. I am tryin... | [
"My understanding is that your have a file like:\ngame Solitaire\nproductivity OpenOffice\ngame MineSweeper\n...\n\nAnd you want to categorize everything based on their tag word, as in putting applications in buckets based on their associated tag/description/...\nI think you can use a dictionary of lists for this p... | [
0
] | [] | [] | [
"cluster_analysis",
"python",
"text"
] | stackoverflow_0008145418_cluster_analysis_python_text.txt |
Q:
How do I include Stripe library with Google App Engine
I am trying to implement Stripe payment https://stripe.com/ in my app. I need to include this library https://stripe.com/docs/libraries. I downloaded and installed it on Lib/site-packages. I checked in IDLE and import stripe works. How do I include this in my... | How do I include Stripe library with Google App Engine | I am trying to implement Stripe payment https://stripe.com/ in my app. I need to include this library https://stripe.com/docs/libraries. I downloaded and installed it on Lib/site-packages. I checked in IDLE and import stripe works. How do I include this in my app's folder?
| [
"Just place the stripe directory from the library in your app's root directory.\n"
] | [
13
] | [] | [] | [
"google_app_engine",
"python",
"stripe_payments"
] | stackoverflow_0008146641_google_app_engine_python_stripe_payments.txt |
Q:
In pyqt, is there a way to signal a secondary thread(QThread) to raise an exception
My run function in the Secondary Thread looks like this:
def run(self):
try:
self.TestScript()
except Exception, e:
//Bunch of clean up code...
This is normally great because any exception allows the syst... | In pyqt, is there a way to signal a secondary thread(QThread) to raise an exception | My run function in the Secondary Thread looks like this:
def run(self):
try:
self.TestScript()
except Exception, e:
//Bunch of clean up code...
This is normally great because any exception allows the system to be cleaned up and put in a safe state. I want to add an Abort Button in the Primar... | [
"Please have a look at Signals and Slots Across Threads. I think you're after the Qt.QueuedConnection type that you should pass as an argument to connect.\n"
] | [
0
] | [] | [] | [
"exception",
"multithreading",
"pyqt",
"python",
"qthread"
] | stackoverflow_0008146086_exception_multithreading_pyqt_python_qthread.txt |
Q:
File uploading/handling in Django
I have worked on this for 3 days straight and I'm at my wit's end. I need someone to explain the literal step-by-step of what exactly is happening in this process and what the actual data is (or looks like) at each step.
I have a model with an ImageField() inside of it. I have a... | File uploading/handling in Django | I have worked on this for 3 days straight and I'm at my wit's end. I need someone to explain the literal step-by-step of what exactly is happening in this process and what the actual data is (or looks like) at each step.
I have a model with an ImageField() inside of it. I have a form based on that model. I pass the ... | [
"Consider giving django-stdimage a try. It is an extension of ImageField and will resize the image for you, here's an example snippet:\nclass MyClass(models.Model):\n image1 = StdImageField(upload_to='path/to/img') # works as ImageField\n image2 = StdImageField(upload_to='path/to/img', blank=True) # can be de... | [
1
] | [] | [] | [
"django",
"django_forms",
"django_models",
"python"
] | stackoverflow_0008146792_django_django_forms_django_models_python.txt |
Q:
Python pygame.transform.rotate
I am new to pygame and python itself.
But right now, i have to make a spinner. It should stop at random times.
What i was thinking was that i can have random.randint(0, 360). So i can make it stop at random times. But right now, I can only make it rotate 90, or else it moves of the... | Python pygame.transform.rotate | I am new to pygame and python itself.
But right now, i have to make a spinner. It should stop at random times.
What i was thinking was that i can have random.randint(0, 360). So i can make it stop at random times. But right now, I can only make it rotate 90, or else it moves of the screen.
Any help would be useful.
... | [
"I've noticed that if you keep rotate the rotated object repeatedly, as you're doing in ball = pygame.transform.rotate(ball, 45), the sprite gets distorted and starts to move off screen. I usually keep the original image and switch back to that when I rotate 360 degrees. \n",
"As noted here, rotating by angles th... | [
1,
0
] | [] | [] | [
"pygame",
"python",
"user_interface"
] | stackoverflow_0008145864_pygame_python_user_interface.txt |
Q:
How do I copy a class and its list members in Python 2.7 and not copy the references?
I read this about Python classes (link) and it seems to be the issue I am having.
Here is an excerpt from my class and other code:
class s_board:
def __init__(self):
self.__board = [[n for n in range(1, 10)] for m in... | How do I copy a class and its list members in Python 2.7 and not copy the references? | I read this about Python classes (link) and it seems to be the issue I am having.
Here is an excerpt from my class and other code:
class s_board:
def __init__(self):
self.__board = [[n for n in range(1, 10)] for m in range(81)]
self.__solved = [False for m in range(81)]
def copy(self):
... | [
"self.__board[:] creates a new list containing references to all the same objects that were in self.__board. Since self.__board contains lists, and lists are mutable, you end up with the two s_board instances with partially aliased data, and changing one affects the other.\nAs Raymond Hettinger suggested, you can u... | [
2,
0,
0
] | [] | [] | [
"class",
"copy",
"python",
"python_2.7"
] | stackoverflow_0008146995_class_copy_python_python_2.7.txt |
Q:
How do get matplotlib pyplot to generate a chart for viewing / output to .png at a specific resolution?
I'm fed up with manually creating graphs in excel and consequently, I'm trying to automate the process using Python to massage the .csv data into a workable form and matplotlib to plot the result.
Using matplotl... | How do get matplotlib pyplot to generate a chart for viewing / output to .png at a specific resolution? | I'm fed up with manually creating graphs in excel and consequently, I'm trying to automate the process using Python to massage the .csv data into a workable form and matplotlib to plot the result.
Using matplotlib and generating them is no problem but I can't work out is how to set the aspect ration / resolution of the... | [
"You can control the aspect ratio with ax.set_aspect:\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nfig = plt.figure()\nax=fig.add_subplot(1,1,1)\nax.set_aspect(0.3)\nx,y=np.random.random((2,100))\nplt.scatter(x,y) \n\nAnother way to set the aspect ratio (already mentioned by jterrace) is to use the fi... | [
5,
3,
0
] | [] | [] | [
"matplotlib",
"python"
] | stackoverflow_0008143439_matplotlib_python.txt |
Q:
array vs hash key search
So I'm a longtime perl scripter who's been getting used to python since I changed jobs a few months back. Often in perl, if I had a list of values that I needed to check a variable against (simply to see if there is a match in the list), I found it easier to generate hashes to check agains... | array vs hash key search | So I'm a longtime perl scripter who's been getting used to python since I changed jobs a few months back. Often in perl, if I had a list of values that I needed to check a variable against (simply to see if there is a match in the list), I found it easier to generate hashes to check against, instead of putting the valu... | [
"Dictionaries are hashes. An in test on a list has to walk through every element to check it against, while an in test on a dictionary uses hashing to see if the key exists. Python just doesn't make you explicitly loop through the list.\nPython also has a set datatype. It's basically a hash/dictionary without the r... | [
6
] | [] | [] | [
"python"
] | stackoverflow_0008147189_python.txt |
Q:
Python Generator - Mutate Last Result?
I'm trying to decide between the following two definitions of my generator. Which is better? Which is "more pythonic"? And is there anyway to mitigate the drawbacks of each one?
def myGenerator1(howMany):
result = [0,0,0]
yield result
for i in range(howMany)
... | Python Generator - Mutate Last Result? | I'm trying to decide between the following two definitions of my generator. Which is better? Which is "more pythonic"? And is there anyway to mitigate the drawbacks of each one?
def myGenerator1(howMany):
result = [0,0,0]
yield result
for i in range(howMany)
modifyListInPlace(result)
yield... | [
"Looking to the standard library as a guide, the combinatoric functions in the itertools module all return tuples eventhough the underlying algorithm is a mutate-in-place algorithm. For example, look at the code for itertools.permutations.\nThis design (returning tuples instead of lists) has proven to be robust. ... | [
3,
1
] | [] | [] | [
"generator",
"python",
"referential_transparency"
] | stackoverflow_0008147214_generator_python_referential_transparency.txt |
Q:
how to run a code in __init__.py
In src/webprofiles/__init__.py I have
def match(string)
Now how can I make a call to this match from `src/python.py, which contains
from webprofiles import *
for x in text
a= webprofiles.match(x)
Its giving me an error
NameError: global name 'webprofiles' is not defined
A:
... | how to run a code in __init__.py | In src/webprofiles/__init__.py I have
def match(string)
Now how can I make a call to this match from `src/python.py, which contains
from webprofiles import *
for x in text
a= webprofiles.match(x)
Its giving me an error
NameError: global name 'webprofiles' is not defined
| [
"When you use from import form, you must call function without module prefix.\njust call the functions and attributes via their names.\nfrom webprofiles import *\n\nfor x in text:\n a= match(x)\n\nbut i suggest to DO NOT use wildcard('*') imports.\nuse this instead:\nfrom webprofiles import match\n\nfor x in tex... | [
3,
1,
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0008147539_python.txt |
Q:
Odd behaviour of python's class
Here is a python class:
class TxdTest(object):
def __init__(self, name = '', atrributes = []):
self.name = name
self.attributes = atrributes
and then I use it like this:
def main():
for i in range(3):
test = TxdTest()
print test.name
... | Odd behaviour of python's class | Here is a python class:
class TxdTest(object):
def __init__(self, name = '', atrributes = []):
self.name = name
self.attributes = atrributes
and then I use it like this:
def main():
for i in range(3):
test = TxdTest()
print test.name
print test.attributes
test.na... | [
"When passing a mutable object (like a list) to a function or method in python, a single object is used across all invocations of the function or method. This means that ever time that function or method (in this case, your __init__ method) is called, the exact same list is used every time, holding on to modificati... | [
4,
1,
0
] | [] | [] | [
"class",
"constructor",
"initialization",
"python"
] | stackoverflow_0008145971_class_constructor_initialization_python.txt |
Q:
Reference manual for python?
Is there a recommended reference manual for python that's better than the official docs? I'm an experienced programmer (PHP, C#, javascript, and some C most recently), and I find the python manual pretty lacking compared the PHP manual and MSDN. In particular, the official docs never s... | Reference manual for python? | Is there a recommended reference manual for python that's better than the official docs? I'm an experienced programmer (PHP, C#, javascript, and some C most recently), and I find the python manual pretty lacking compared the PHP manual and MSDN. In particular, the official docs never seem to tell me what errors can hap... | [
"In practice, you either make a quick test program to check the behavior, or read the source code. Much of the Python standard library code is fairly clearly written and in fact rather self-documenting, so it's standard practice to refer to it when you need to know the nitty-gritty details of how something works.\n... | [
3,
1
] | [] | [] | [
"documentation",
"manual",
"python",
"reference"
] | stackoverflow_0008147704_documentation_manual_python_reference.txt |
Q:
Learning how to use the deferred library
I'm trying code nearly identical to the example from the manual to enable a download counter but I get an exception:
File "/media/Lexar/montao/wwwblob/handler.py", line 117, in FileInfo
download_count = db.IntegerProperty(required=True, count=0) TypeError: init() got... | Learning how to use the deferred library | I'm trying code nearly identical to the example from the manual to enable a download counter but I get an exception:
File "/media/Lexar/montao/wwwblob/handler.py", line 117, in FileInfo
download_count = db.IntegerProperty(required=True, count=0) TypeError: init() got an unexpected keyword argument 'count'
Here'... | [
"This line is the culprit:\ndownload_count = db.IntegerProperty(required=True, count=0)\n\nThe IntegerProperty constructor doesn't know what to do with count. Maybe you meant this:\ndownload_count = db.IntegerProperty(required=True, default=0)\n\n"
] | [
3
] | [] | [] | [
"google_app_engine",
"python"
] | stackoverflow_0008147819_google_app_engine_python.txt |
Q:
How can i get query for .save() in django?
I am updating a django model object. After setting value for each attribute when i call obj.save() it gaves me OperationalError: (2006, 'MySQL server has gone away'). I am desperate to know what is causing the following error. How can i get the the query?? As when save me... | How can i get query for .save() in django? | I am updating a django model object. After setting value for each attribute when i call obj.save() it gaves me OperationalError: (2006, 'MySQL server has gone away'). I am desperate to know what is causing the following error. How can i get the the query?? As when save method fail because of above error it does not log... | [
"You can try\nfrom django.db import connection\nconnection.queries\n\nit will give you list of all the queries that executed through Django (including .save()). To get your query you can do,\nfrom django.db import connection, OperationalError\ntry:\n modelObj.save()\nexcept OperationalError:\n print(connectio... | [
16
] | [] | [] | [
"django",
"django_models",
"mysql",
"python"
] | stackoverflow_0008148005_django_django_models_mysql_python.txt |
Q:
What is the correct way to extend a parent class method in modern Python
I frequently do this sort of thing:
class Person(object):
def greet(self):
print "Hello"
class Waiter(Person):
def greet(self):
Person.greet(self)
print "Would you like fries with that?"
The line Person.greet... | What is the correct way to extend a parent class method in modern Python | I frequently do this sort of thing:
class Person(object):
def greet(self):
print "Hello"
class Waiter(Person):
def greet(self):
Person.greet(self)
print "Would you like fries with that?"
The line Person.greet(self) doesn't seem right. If I ever change what class Waiter inherits from I'... | [
"You use super:\n\nReturn a proxy object that delegates\n method calls to a parent or sibling\n class of type. This is useful for\n accessing inherited methods that have\n been overridden in a class. The search\n order is same as that used by\n getattr() except that the type itself\n is skipped.\n\nIn other ... | [
22,
11,
5
] | [] | [] | [
"inheritance",
"python"
] | stackoverflow_0006070599_inheritance_python.txt |
Q:
how to get cookie in template webpy
How do I get the cookie in the index.html template:
render = web.template.render('templates/', base='layout', cache=False)
A:
import web
template_globals = {
"cookies": web.cookies,
}
render = web.template.render('templates/', globals=template_globals, base='layout', cache... | how to get cookie in template webpy | How do I get the cookie in the index.html template:
render = web.template.render('templates/', base='layout', cache=False)
| [
"import web\ntemplate_globals = {\n \"cookies\": web.cookies,\n}\nrender = web.template.render('templates/', globals=template_globals, base='layout', cache=False)\n\nYou can also do things like this:\nrender_partial = web.template.render('templates/', globals=template_globals)\ntemplate_globals.update(render=ren... | [
0
] | [] | [] | [
"python",
"web.py"
] | stackoverflow_0008147559_python_web.py.txt |
Q:
distributing a command line application
Python newbie here. I'm trying to package a console app following this doc. To this end I created the following directory structure:
.
├── bin
│ └── txts
├── setup.py
└── txtstyle
├── __init__.py
├── ...
└── [snip]
My app has one executable script which I plac... | distributing a command line application | Python newbie here. I'm trying to package a console app following this doc. To this end I created the following directory structure:
.
├── bin
│ └── txts
├── setup.py
└── txtstyle
├── __init__.py
├── ...
└── [snip]
My app has one executable script which I placed under bin. I could successfully run
python... | [
"You need to install the package. This puts all modules in the global module path, and thus allows you to import them. For development, use python setup.py develop which links the modules into the module python instead of copying them. This way you don't need to reinstall the package each time you changed a modu... | [
3
] | [] | [] | [
"distutils",
"python",
"setup.py",
"setuptools"
] | stackoverflow_0008146808_distutils_python_setup.py_setuptools.txt |
Q:
implementing exotic complex numbers to use with numpy
i'm using python + numpy + scipy to do some convolution filtering over a complex-number array.
field = np.zeros((field_size, field_size), dtype=complex)
...
field = scipy.signal.convolve(field, kernel, 'same')
So, when i want to use a complex array in numpy al... | implementing exotic complex numbers to use with numpy | i'm using python + numpy + scipy to do some convolution filtering over a complex-number array.
field = np.zeros((field_size, field_size), dtype=complex)
...
field = scipy.signal.convolve(field, kernel, 'same')
So, when i want to use a complex array in numpy all i need to do is pass the dtype=complex parameter.
For my ... | [
"It looks like you are trying to create a new dtype for e.g. dual numbers. It is possible to do this with the following code:\ndual_type = np.dtype([(\"a\", np.float), (\"b\", np.float)])\ndual_array = np.zeros((10,), dtype=dual_type)\n\nHowever this is just a way of storing the data type, and doesn't tell numpy an... | [
4,
1,
0
] | [] | [] | [
"numpy",
"python",
"scipy"
] | stackoverflow_0007900417_numpy_python_scipy.txt |
Q:
architecture questions about a multithreaded approach in python
I'm creating a socket server that will run forever and push files out to a remote service. The files will be big and many, so creating a threaded script that can help move things along. I have a few questions about how to approach this.
In this setup ... | architecture questions about a multithreaded approach in python | I'm creating a socket server that will run forever and push files out to a remote service. The files will be big and many, so creating a threaded script that can help move things along. I have a few questions about how to approach this.
In this setup I will be using the Queue provided by python because it implements th... | [
"Continually creating and terminating threads is expensive, error-prone and best avoided if at all possible on both performance and reliablilty grounds. Micro-managing threads from the 'main program' is just, well, just a really bad idea when you can just, well, not do it. Modern languages/environments/libraries a... | [
2
] | [] | [] | [
"multithreading",
"python"
] | stackoverflow_0008145041_multithreading_python.txt |
Q:
Accessing Chat Folder in Python Using Imaplib
I am trying to access the Chat Folder using imaplib but am not able to do so. The code mail.select("Chats") doesn't work since "chats" is not actually a label.
How do I access the emails in the Chats folder?
A:
any folder you want to access by imap. it should be allo... | Accessing Chat Folder in Python Using Imaplib | I am trying to access the Chat Folder using imaplib but am not able to do so. The code mail.select("Chats") doesn't work since "chats" is not actually a label.
How do I access the emails in the Chats folder?
| [
"any folder you want to access by imap. it should be allowed by mail server.\ne.g : for gmail, check below image for, how to set access of imap.\n\nhere, \"Show in IMAP\" should be checked for \"Chats\" folder.\nthen after, try below code snippets:\nsock = imaplib.IMAP4_SSL(\"imap.gmail.com\", 993)\nsock.login(\"yo... | [
4
] | [] | [] | [
"imaplib",
"python"
] | stackoverflow_0008146970_imaplib_python.txt |
Q:
How to display string which contains django template variables?
Let's say I have an string variable called *magic_string* which value is set to "This product name is {{ product.name }}" and it's avaible at django template. Is it ever possible to parse that variable to show me "This product name is Samsung GT-8500"... | How to display string which contains django template variables? | Let's say I have an string variable called *magic_string* which value is set to "This product name is {{ product.name }}" and it's avaible at django template. Is it ever possible to parse that variable to show me "This product name is Samsung GT-8500" instead (assuming that name of the product is "GT-8500" and variable... | [
"Write custom template tag and render that variable as a template.\nFor example look at how \"ssi\" tag is written.\nOn the other hand, can you render this string in your view? Anyway here is an untested version of that tag:\n@register.tag\ndef render_string(parser, token):\n bits = token.contents.split()\n i... | [
7,
6
] | [] | [] | [
"django",
"django_templates",
"python",
"string"
] | stackoverflow_0008148143_django_django_templates_python_string.txt |
Q:
Where to find PyUnicodeUCS4_Decode?
I am trying to test some 32 bit software on an Ubuntu 11.04 64 bit machine. After getting the 32 bit libraries installed, it now fails with :
Python 2.7.2 (default, Nov 4 2011, 19:26:59)
[GCC 4.5.2] on linux2
Type "help", "copyright", "credits" or "license" for more informatio... | Where to find PyUnicodeUCS4_Decode? | I am trying to test some 32 bit software on an Ubuntu 11.04 64 bit machine. After getting the 32 bit libraries installed, it now fails with :
Python 2.7.2 (default, Nov 4 2011, 19:26:59)
[GCC 4.5.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> from pyexpat import *
Traceback (m... | [
"This thread seemed to explain that it might be due to python supporting two different Unicode modes UCS2 (the default), and UCS4. It suggests recompiling from scratch.\nYou can download the package directly and then compile on your machine by running:\npython setup.py build\npython setup.py install\n\n"
] | [
2
] | [] | [] | [
"python"
] | stackoverflow_0008146785_python.txt |
Q:
Is there a way to deploy a (library) update without shutting down the main program
Here is an example, say, we have two python files:
Listener.py -- Keep Listening to some input stream
Process.py -- After we receive the data, Listener.py will call functions here and store results to file.
Let say I have to keep... | Is there a way to deploy a (library) update without shutting down the main program | Here is an example, say, we have two python files:
Listener.py -- Keep Listening to some input stream
Process.py -- After we receive the data, Listener.py will call functions here and store results to file.
Let say I have to keep "improving/changing" the Process.py, but the Listener.py itself is very stable. Is it p... | [
"I think you are looking for reload function.\nThus you can check module modification time:\nos.path.getmtime(filepath)\n\nand then if it's different from previous check - reload module:\nif module_source_is_modified(process):\n process = reload(process)\n\n"
] | [
2
] | [] | [] | [
"design_patterns",
"multiprocessing",
"python"
] | stackoverflow_0008148985_design_patterns_multiprocessing_python.txt |
Q:
generic function in python - calling a method with unknown number of arguments
i'm new to python and need some help...
I'm implementing a generic search function that accepts an argument "fringe", which can be a data structure of many types.
in the search method I have the line:
fringe.push(item, priority)
the p... | generic function in python - calling a method with unknown number of arguments | i'm new to python and need some help...
I'm implementing a generic search function that accepts an argument "fringe", which can be a data structure of many types.
in the search method I have the line:
fringe.push(item, priority)
the problem is that the push method in different data structures takes different number o... | [
"The method to get different number of arguments and still being able of selecting the right one is the use of *args and **keyword_args parameters.\nFrom Mark Lutz's Learning Python book:\n\n* and **, are designed to support functions that take any number of arguments. Both can appear in either the function definit... | [
17,
2,
1,
0
] | [] | [] | [
"generics",
"python"
] | stackoverflow_0008147737_generics_python.txt |
Q:
PyBluez does not detect the built-in bluetooth adapter
I want to start developing some tools that let me communicate between my phone and computer via bluetooth, and I want to use Python for it. I installed the python bluetooth module (PyBluez), but it does not detect my built in BT adapter (I'm on a Toshiba Satel... | PyBluez does not detect the built-in bluetooth adapter | I want to start developing some tools that let me communicate between my phone and computer via bluetooth, and I want to use Python for it. I installed the python bluetooth module (PyBluez), but it does not detect my built in BT adapter (I'm on a Toshiba Satellite A300).
import bluetooth
nearby_devices = bluetooth.disc... | [
"PyBluez uses MS Bluetooth driver stack and Widcom for Windows, for Linux it uses BlueZ. If your laptop has a different stack it is normal not to work.\n",
"You could uninstall the driver (if it is possible), then restart Windows and let it install the default drivers. \nIf you manage it, PyBluez will work better... | [
2,
1
] | [] | [] | [
"bluetooth",
"python"
] | stackoverflow_0004198203_bluetooth_python.txt |
Q:
Removing the panel that appears on the right hand side of OpenERP main page
How can we remove the panel that appears on right hand side of openERP's main page ,which shows ACTIONS ,LINKS,OTHER OPTIONS.From which file in openERP web server can we remove that.
Thanks,
Sameer
A:
serch for main_sidebar in web/addon... | Removing the panel that appears on the right hand side of OpenERP main page | How can we remove the panel that appears on right hand side of openERP's main page ,which shows ACTIONS ,LINKS,OTHER OPTIONS.From which file in openERP web server can we remove that.
Thanks,
Sameer
| [
"serch for main_sidebar in web/addons/openerp/controllers/templates/form.mako\nyou can hide the toolbar using this css file:\nweb/addons/openerp/static/css/screen.cs\n"
] | [
5
] | [] | [] | [
"openerp",
"python"
] | stackoverflow_0008148821_openerp_python.txt |
Q:
How to Add rows using subqueries in sqlalchemy?
I'm using Postgresql with SQLAlchemy but it seems sqlalchemy is having trouble adding rows when using subqueries.
In my example, I want to update a counter for a specific tag in a table.
In SqlAlchemy a test run class would look like the following:
class TestRun( bas... | How to Add rows using subqueries in sqlalchemy? | I'm using Postgresql with SQLAlchemy but it seems sqlalchemy is having trouble adding rows when using subqueries.
In my example, I want to update a counter for a specific tag in a table.
In SqlAlchemy a test run class would look like the following:
class TestRun( base ):
__tablename__ = 'test_runs'
id ... | [
"Instead of using subquery() call as_scalar() method:\n\nReturn the full SELECT statement represented by this Query, converted\n to a scalar subquery.\n\nExample:\nModels with classing parent-child relationship:\nclass Parent(Base):\n __tablename__ = 'parents'\n id = Column(Integer, primary_key=True)\n co... | [
7
] | [] | [] | [
"python",
"sqlalchemy",
"subquery"
] | stackoverflow_0008142923_python_sqlalchemy_subquery.txt |
Q:
Sending files via OBEX (lightblue/OBEXFTP)
I'm trying desperately to send files via OBEX, using python. I have two functioning codes, the first using lightblue and the other using obexftp. We've got here two android phones, the first is a Samsung Galaxy S and the second is HTC desire HD (running CyanogenMod 7.1). ... | Sending files via OBEX (lightblue/OBEXFTP) | I'm trying desperately to send files via OBEX, using python. I have two functioning codes, the first using lightblue and the other using obexftp. We've got here two android phones, the first is a Samsung Galaxy S and the second is HTC desire HD (running CyanogenMod 7.1). I'm trying to send files to these phones from a ... | [
"OBEX can be notoriusly buggy, there are a lot of Headset/Handsfree manufacturers investing massive amounts of money in testing OBEX and other BT protocols...\nMaybe this is the problem! Can you try more phones to test this?!\n"
] | [
1
] | [] | [] | [
"bluetooth",
"python"
] | stackoverflow_0007784781_bluetooth_python.txt |
Q:
How can I make pybluez return a list of discovered devices every X seconds and then repeat?
I've been trying to figure out how I can use pybluez to monitor nearby devices...
I want to be able to run my program and have it search for devices every 20 seconds. The problem is, how do I get pybluez to place nicely? :/... | How can I make pybluez return a list of discovered devices every X seconds and then repeat? | I've been trying to figure out how I can use pybluez to monitor nearby devices...
I want to be able to run my program and have it search for devices every 20 seconds. The problem is, how do I get pybluez to place nicely? :/
Using their example code http://code.google.com/p/pybluez/source/browse/trunk/examples/simple/in... | [
"This code worked for me:\n'''\nCreated on Nov 16, 2011 \n@author: Radu\n'''\nimport time\nimport bluetooth\n\ndef search(): \n devices = bluetooth.discover_devices(duration=20, lookup_names = True)\n return devices\n\nif __name__==\"__main__\":\n while True: \n results = search()\... | [
6,
0
] | [] | [] | [
"bluetooth",
"python"
] | stackoverflow_0003342760_bluetooth_python.txt |
Q:
possible to create ebook programmatically?
I am investigating whether it is possible to generate an ebook, say, a Kindle book, programmatically. are there any libraries, open source or proprietary? in particular, for python.
A:
An ebook or epub is just xhtml with some meta info and stuff. Every page is a xhtml f... | possible to create ebook programmatically? | I am investigating whether it is possible to generate an ebook, say, a Kindle book, programmatically. are there any libraries, open source or proprietary? in particular, for python.
| [
"An ebook or epub is just xhtml with some meta info and stuff. Every page is a xhtml file. \nHere is a tutorial on How to Make an ePub eBook by Hand.\n",
"Many but especially see calibre which can take text in various forms or HTML and convert to epub, mobi etc.\n",
"For .epub, as others have said, any tool tha... | [
5,
2,
2,
1,
1
] | [] | [] | [
"multimedia",
"publishing",
"python"
] | stackoverflow_0007547939_multimedia_publishing_python.txt |
Q:
can I capture remotely executed commands with its output in the logfile in python?
I am using paramiko for executing remote commands in python. I want to log the complete remote commandline details to the log file.
e.g. Like using Expect in perl we can log the below commands with its output to a log file
samir@ssa... | can I capture remotely executed commands with its output in the logfile in python? | I am using paramiko for executing remote commands in python. I want to log the complete remote commandline details to the log file.
e.g. Like using Expect in perl we can log the below commands with its output to a log file
samir@ssahoo-ub-in:~$ cat logfile.txt
samir@ssahoo-ub-in:~$ ls
Desktop Documents Downloads exa... | [
"Looks like from the paramiko.SSHClient docs, you can use the recv_ready and recv return the results of the shell/channel. For example, this worked for me:\nclient = SSHClient()\nlient.load_system_host_keys()\nclient.set_missing_host_key_policy(AllowAllKeys())\nclient.connect(HOST,username=USERNAME,password=PASSWO... | [
3,
0
] | [] | [] | [
"python"
] | stackoverflow_0008089498_python.txt |
Q:
from text file to csv using Python
I need help in parsing a very long text file which looks like:
NAME IMP4
DESCRIPTION small nucleolar ribonucleoprotein
CLASS Genetic Information Processing
Translation
Ribosome biogenesis in eukaryotes
DBLINKS NCBI-GI: 15529982
... | from text file to csv using Python | I need help in parsing a very long text file which looks like:
NAME IMP4
DESCRIPTION small nucleolar ribonucleoprotein
CLASS Genetic Information Processing
Translation
Ribosome biogenesis in eukaryotes
DBLINKS NCBI-GI: 15529982
NCBI-GeneID: 92856
... | [
"You could use itertools.groupby, once to collect lines into records, and a second time to collect multi-line fields into an iterator:\nimport csv\nimport itertools\n\ndef is_end_of_record(line):\n return line.startswith('///')\n\nclass FieldClassifier(object):\n def __init__(self):\n self.field=''\n ... | [
5,
0
] | [] | [] | [
"csv",
"parsing",
"python",
"text"
] | stackoverflow_0008150192_csv_parsing_python_text.txt |
Q:
Regular expression: how to match a string containing "\n" (newline)?
I'm trying to dump data from a SQL export file with regular expression. To match the field of post content, I use '(?P<content>.*?)'. It works fine most of the time, but if the field contains the string of '\n' the regular expression wouldn't mat... | Regular expression: how to match a string containing "\n" (newline)? | I'm trying to dump data from a SQL export file with regular expression. To match the field of post content, I use '(?P<content>.*?)'. It works fine most of the time, but if the field contains the string of '\n' the regular expression wouldn't match. How can I modify the regular expression to match them? Thanks!
Example... | [
"You should use DOTALL option:\n>>> re.findall(\"'(?P<content>.*?)'\",\"'<p>something, \\n something else</p>'\", re.DOTALL)\n['<p>something, \\n something else</p>']\n\nSee this.\n",
"You need the Dotall modifier, to make the dot also match newline characters.\n\nre.S\n re.DOTALL\n Make the '.' special charact... | [
30,
4
] | [] | [] | [
"escaping",
"line_breaks",
"python",
"regex"
] | stackoverflow_0008150745_escaping_line_breaks_python_regex.txt |
Q:
How to obtain better results using NLTK pos tag
I am just learning nltk using Python. I tried doing pos_tag on various sentences. But the results obtained are not accurate. How can I improvise the results ?
broke = NN
flimsy = NN
crap = NN
Also I am getting lot of extra words being categorized as NN. How can I fi... | How to obtain better results using NLTK pos tag | I am just learning nltk using Python. I tried doing pos_tag on various sentences. But the results obtained are not accurate. How can I improvise the results ?
broke = NN
flimsy = NN
crap = NN
Also I am getting lot of extra words being categorized as NN. How can I filter these out to get better results.?
| [
"Give the context, there you obtained these results. Just as example, I'm obtaining other results with pos_tag on the context phrase \"They broke climsy crap\":\nimport nltk\ntext=nltk.word_tokenize(\"They broke flimsy crap\")\nnltk.pos_tag(text)\n\n\n\n\n[('They', 'PRP'), ('broke', 'VBP'), ('flimsy', 'JJ'), ('crap... | [
10
] | [] | [] | [
"nltk",
"pos_tagger",
"python"
] | stackoverflow_0008146748_nltk_pos_tagger_python.txt |
Q:
Python and ctypes: why printf("%f", 10.1) is wrong
i have a question about ctypes in python
from ctypes import *
printf = cdll.msvcrt.printf
printf("%s\n", "Hello World!")
printf("%d\n", 100)
printf("%f\n", 10.1)
Result:
Hello World!
100
Traceback (most recent call last):
File "C:\Users\Windows7\Desktop\test.py... | Python and ctypes: why printf("%f", 10.1) is wrong | i have a question about ctypes in python
from ctypes import *
printf = cdll.msvcrt.printf
printf("%s\n", "Hello World!")
printf("%d\n", 100)
printf("%f\n", 10.1)
Result:
Hello World!
100
Traceback (most recent call last):
File "C:\Users\Windows7\Desktop\test.py", line 5, in <module>
printf("%f\n", 10.1)
ctypes.A... | [
"According to the ctypes documentation : \n\nNone, integers, longs, byte strings and unicode strings are the only\n native Python objects that can directly be used as parameters in these\n function calls. None is passed as a C NULL pointer, byte strings and\n unicode strings are passed as pointer to the memory b... | [
4,
3
] | [] | [] | [
"ctypes",
"printf",
"python"
] | stackoverflow_0008150648_ctypes_printf_python.txt |
Q:
How to set User-Agent in Python MozEmbed?
I have build a simple dedicated browser (like Prism) which I use for different sites. Sadly Google+ blocks all browsers, but four. So it blocks mine too.
How can I set the User-Agent in MozEmbed, so I can tell Goolge, I am using Firefox?
mozembed = gtkmozembed.MozEmbed... | How to set User-Agent in Python MozEmbed? | I have build a simple dedicated browser (like Prism) which I use for different sites. Sadly Google+ blocks all browsers, but four. So it blocks mine too.
How can I set the User-Agent in MozEmbed, so I can tell Goolge, I am using Firefox?
mozembed = gtkmozembed.MozEmbed()
mozembed.load_url("https://plus.google.c... | [
"Sorry, haven't tested it, because my Mozilla stuff is inherently broken atm.\nOne way to set it is to create custom settings file prefs.js and set that directory as profile directory:\nprofdir = '~/.config/mozilla'\nprofile = 'foo'\nmozembed.set_profile_path(profile_directory, profile)\n\nNow, gtkmozembed should r... | [
1,
0
] | [] | [] | [
"google_plus",
"mozilla",
"python"
] | stackoverflow_0008120489_google_plus_mozilla_python.txt |
Q:
For loop with multiple conditions in Python
I have 3 lists of equal sizes (List1,2 and 3). I want to iterate through the list and and perform operations on each of the items. Like
for x in List1, y in List2, z in List3:
if(x == "X" or x =="x"):
//Do operations on y
elif(y=="Y" or y=="y"):
... | For loop with multiple conditions in Python | I have 3 lists of equal sizes (List1,2 and 3). I want to iterate through the list and and perform operations on each of the items. Like
for x in List1, y in List2, z in List3:
if(x == "X" or x =="x"):
//Do operations on y
elif(y=="Y" or y=="y"):
//Do operations on x,z
So I want to traverse th... | [
"import itertools\nfor x, y, z in itertools.izip(List1, List2, List3):\n # ...\n\nOr just zip in Python 3.\n",
">>> map(lambda x, y, z: (x, y, z), range(0, 3), range(3, 6), range(6, 9))\n[(0, 3, 6), (1, 4, 7), (2, 5, 8)]\n\n"
] | [
8,
0
] | [] | [] | [
"for_loop",
"python",
"python_2.x"
] | stackoverflow_0008150846_for_loop_python_python_2.x.txt |
Q:
ERROR : No module named ""
I got a small problem using pylint to check my python code.
I use the opencv library in my code, which results in
E: 85: Module 'cv' has no 'MoveWindow' member
errors in my code.
The reason for that is explained here :
http://www.logilab.org/blogentry/78354
So I did just as they ask... | ERROR : No module named "" | I got a small problem using pylint to check my python code.
I use the opencv library in my code, which results in
E: 85: Module 'cv' has no 'MoveWindow' member
errors in my code.
The reason for that is explained here :
http://www.logilab.org/blogentry/78354
So I did just as they asked and created an astng_cv.py fi... | [
"put the astng_cv.py somewhere on your PYTHONPATH\n",
"The issue seems half solved here : http://www.logilab.org/5697\nI can load my module in setting the PYTHONPATH directly : \nPYTHONPATH=/home/jlengrand/bin/pypath pylint --load-plugins astng_cv tippy.py\n\nBut it is quite boring to have to set it each time. \n... | [
1,
0
] | [] | [] | [
"pychecker",
"pylint",
"python"
] | stackoverflow_0008135111_pychecker_pylint_python.txt |
Q:
webapp2 behaviour replicated in apache/php
In webapp2 (python) you can map urls to classes in one file.
app = webapp2.WSGIApplication([('/', pgMain), ('/test/', pgTest)], debug=True)
How would I setup such a thing in php & apache?
Thanks
EDIT:
What I am after is everything after a foldername to be redirected to ... | webapp2 behaviour replicated in apache/php | In webapp2 (python) you can map urls to classes in one file.
app = webapp2.WSGIApplication([('/', pgMain), ('/test/', pgTest)], debug=True)
How would I setup such a thing in php & apache?
Thanks
EDIT:
What I am after is everything after a foldername to be redirected to a file in that folder. eg.
/version/1.0/test/fol... | [
"Simplest way for doing this is to create .htaccess file in your app folder and put this code there:\nRewriteEngine On\nRewriteBase /\n\nRewriteRule \"(^|/)\\.\" - [F]\nRewriteCond %{REQUEST_FILENAME} !-f\nRewriteCond %{REQUEST_FILENAME} !-d\nRewriteCond %{REQUEST_URI} !=/favicon.ico\nRewriteRule ^ index.php [NC,NS... | [
1
] | [] | [] | [
"apache2",
"php",
"python",
"webapp2"
] | stackoverflow_0008150819_apache2_php_python_webapp2.txt |
Q:
Django: get url names from urls.py
The common url syntax for Django application is as following
url(URL_PATTERN, VIEW_ACTION, NAME)
Since I declared my urls I want to get the list of my urls using some sort this urls = get_urls(application) and get the output as a list of urls, I also found the same function used... | Django: get url names from urls.py | The common url syntax for Django application is as following
url(URL_PATTERN, VIEW_ACTION, NAME)
Since I declared my urls I want to get the list of my urls using some sort this urls = get_urls(application) and get the output as a list of urls, I also found the same function used in Django admin application, but I coul... | [
"You could reuse the code used by django-extensions show_urls() command.\n"
] | [
1
] | [] | [] | [
"django",
"django_urls",
"python"
] | stackoverflow_0008151512_django_django_urls_python.txt |
Q:
How to mock Pythonic way?
Mox mocking library allows you to be either specific or agnostic about the class you are mocking.
mock = mox.CreateMock(Foo) or
mock = mox.CreateMockAnything()
Mox documentation suggests to use the first way (basically check the type of the mock) wherever it is possible. Python as a dyn... | How to mock Pythonic way? | Mox mocking library allows you to be either specific or agnostic about the class you are mocking.
mock = mox.CreateMock(Foo) or
mock = mox.CreateMockAnything()
Mox documentation suggests to use the first way (basically check the type of the mock) wherever it is possible. Python as a dynamic language is type agnostic.... | [
"They are not the same. From the documentation:\n\nSome classes do not provide public interfaces; for example, they might\n use __getattribute__ to dynamically create their interface. For these\n classes, you can use a MockAnything. It does not enforce any\n interface, so any call your heart desires is valid. It... | [
2
] | [] | [] | [
"mocking",
"mox",
"python",
"unit_testing"
] | stackoverflow_0008151725_mocking_mox_python_unit_testing.txt |
Q:
Python close children when closing main process
I have have a main process that forks a number of subprocesses. I want to be able to kill these child processes off when my main process gets the kill signal. Ideally I would want to do something along the lines of:
def handler(signum, frame, pid_list):
log('Kil... | Python close children when closing main process | I have have a main process that forks a number of subprocesses. I want to be able to kill these child processes off when my main process gets the kill signal. Ideally I would want to do something along the lines of:
def handler(signum, frame, pid_list):
log('Killing Process')
for pid in pid_list:
os.kil... | [
"As @tony suggested you could set daemon=True flag on a child process created using multiprocessing module. To install it on python2.4, type: pip install multiprocessing.\nThe child processes won't be terminated if the main process is killed by a signal so you need to provide an appropriate signal handler:\n#!/usr/... | [
3,
1
] | [] | [] | [
"fork",
"kill",
"parallel_processing",
"python",
"signals"
] | stackoverflow_0008150319_fork_kill_parallel_processing_python_signals.txt |
Q:
tools or techniques to help avoid mistakes in python/django
What tools or techniques can help avoid bugs, especially silly mistakes such as typos, coding in Python and Django?
I know unit-testing every line of code is the "proper" way, but are there any shortcuts?
I know of pylint, but unfortunately it doesn't che... | tools or techniques to help avoid mistakes in python/django | What tools or techniques can help avoid bugs, especially silly mistakes such as typos, coding in Python and Django?
I know unit-testing every line of code is the "proper" way, but are there any shortcuts?
I know of pylint, but unfortunately it doesn't check Django ORM named parameters, where a typo can go unnoticed. Is... | [
"Sorry I don't know if I understand you correctly,\nBut I think a good IDE has automatic code validation and some of them also work with Django. For example, there is a good python plugin for Eclipse called PYDEV. There is also a good IDE based on Eclipse/Pydev called Aptana Studio that you can try (it also has goo... | [
2,
2,
0
] | [] | [] | [
"debugging",
"django",
"python",
"static_analysis"
] | stackoverflow_0008110952_debugging_django_python_static_analysis.txt |
Q:
In python, how can I prevent the "^C" from showing up when I press Ctrl+C in the terminal?
I have a signal handler which does its job, but the only ugly thing is whenever Ctrl+C is pressed, a "^C" shows up in the terminal. How do I get rid of that? Or is that a shell behavior?
A:
If you are on a Unix platform, t... | In python, how can I prevent the "^C" from showing up when I press Ctrl+C in the terminal? | I have a signal handler which does its job, but the only ugly thing is whenever Ctrl+C is pressed, a "^C" shows up in the terminal. How do I get rid of that? Or is that a shell behavior?
| [
"If you are on a Unix platform, the easiest way to control the terminal is the curses module. You can turn the echoing of typed characters off with curses.noecho(), turn it on again with curses.echo(), or wrap a function call in curses.wrapper() to turn echoing off during the function call. The latter is the pref... | [
1
] | [] | [] | [
"python"
] | stackoverflow_0008152202_python.txt |
Q:
Combining adjoining 2D polygons
Anyone know of an algorithm or toolkit for python3 which I can use to combine touching 2D polygons in one polygon? Where the polygon is defined in terms of the lines that define its outer and indeed inner boundaries (A donought, for example, has an inner boundary to define its hole)... | Combining adjoining 2D polygons | Anyone know of an algorithm or toolkit for python3 which I can use to combine touching 2D polygons in one polygon? Where the polygon is defined in terms of the lines that define its outer and indeed inner boundaries (A donought, for example, has an inner boundary to define its hole).
Before:
After:
In my case however... | [
"It looks like the General Polygon Clipper library might do what you're looking for.\n",
"I would say you can use GDAL, \nThey also support Python 3. \nhttp://trac.osgeo.org/gdal/wiki/GdalOgrInPython\n",
"There is huge geometry library called opencascade and its python bindings. I don't know if they support pyt... | [
2,
2,
1
] | [] | [] | [
"python",
"python_3.x"
] | stackoverflow_0008142694_python_python_3.x.txt |
Q:
Using IPython from the Python shell like `code.interact()`
Is it possible to use the IPython shell from an existing Python shell, as a shell-inside-a-shell, similarly to the built-in code.interact()?
A:
In IPython 0.11 the API has been overhauled and the shell is even easier to invoke:
import IPython
IPython.em... | Using IPython from the Python shell like `code.interact()` | Is it possible to use the IPython shell from an existing Python shell, as a shell-inside-a-shell, similarly to the built-in code.interact()?
| [
"In IPython 0.11 the API has been overhauled and the shell is even easier to invoke:\nimport IPython\n\nIPython.embed()\n\n",
"The recommended way of embedding IPython works fine:\n~ $ python\nPython 2.7 [...]\n>>> from IPython.Shell import IPShellEmbed\n>>> ipshell = IPShellEmbed()\n>>> ipshell()\n\nIn [1]: \n\n... | [
22,
3,
1
] | [] | [] | [
"ipython",
"python",
"shell"
] | stackoverflow_0003423741_ipython_python_shell.txt |
Q:
Concat all the text files and their content contained in all the .zip files in a text file using Python
I am trying to write a program that would read all files in a folder and output all of their contents into one single file. The files are ziped with the .gz extension. I managed to read one file but not all its ... | Concat all the text files and their content contained in all the .zip files in a text file using Python | I am trying to write a program that would read all files in a folder and output all of their contents into one single file. The files are ziped with the .gz extension. I managed to read one file but not all its contents and not the rest of the files. Here is my code:
import glob, gzip, re
import pickle
filed = open('... | [
"Try this (didn't touch your regular expression):\nimport glob, gzip, re\nimport cPickle\n\nlogformat = re.compile(r'^\\S+ \\S+ \\S+ \\[([\\w:/]+\\s[+\\-]\\d{4})\\] \"(\\S+) (\\S+) .*\" (\\d+) (\\d+) \"([^\"]*)\" \"[^\"]*\"')\n\nwith open('Logs.txt', 'w') as f_out:\n for i in glob.glob('*.gz'):\n with gzi... | [
3,
0
] | [] | [] | [
"file_io",
"python",
"readfile"
] | stackoverflow_0008152437_file_io_python_readfile.txt |
Q:
open persian url domains with urllib2
i'm trying to open an url http://الاعلي-للاتصالات.قطر/ar/news-events/event/future-internet-privacy
with the urllib2.urlopen but it reports always an error.
The similar occurs to http://الاعلي-للاتصالات.قطر/ar ... other pages (chinese ones) are opened ok.
Any ideas to point me ... | open persian url domains with urllib2 | i'm trying to open an url http://الاعلي-للاتصالات.قطر/ar/news-events/event/future-internet-privacy
with the urllib2.urlopen but it reports always an error.
The similar occurs to http://الاعلي-للاتصالات.قطر/ar ... other pages (chinese ones) are opened ok.
Any ideas to point me to the right way to open those urls?
urllib... | [
"As @Donal says, the URL has to be punycoded. Luckily Python includes this already. Here is a sample Python code\ndomain = \"الاعلي-للاتصالات.قطر\"\ndomain_unicode = unicode(domain, \"utf8\")\ndomain_idna = domain_unicode.encode(\"idna\")\nurllib2.urlopen(\"http://\" + domain_idna).read()\n\nHope this helps.\n"
] | [
8
] | [] | [] | [
"python",
"url",
"utf_8"
] | stackoverflow_0008152161_python_url_utf_8.txt |
Q:
Representing a multi-select field for weekdays in a Django model
I've been searching for an elegant way to represent a multi-select weekday field (Mon, Tues, Wed...) in a Django model. I was initially thinking of going integer field using bitwise math but I am not sure if this would be the way to go.
This would be... | Representing a multi-select field for weekdays in a Django model | I've been searching for an elegant way to represent a multi-select weekday field (Mon, Tues, Wed...) in a Django model. I was initially thinking of going integer field using bitwise math but I am not sure if this would be the way to go.
This would be a mostly-read field. I would want the Queryset method to be something... | [
"This is an old question, but I thought I would show how it could be done reasonably simply in Django.\nHere is a helper class for preparing your choices:\nclass BitChoices(object):\n def __init__(self, choices):\n self._choices = []\n self._lookup = {}\n for index, (key, val) in enumerate(choices):\n ... | [
16
] | [] | [] | [
"django",
"django_models",
"python"
] | stackoverflow_0003663898_django_django_models_python.txt |
Q:
Gstreamer+python: adding and removing audio sources while pipeline is running
I'm working on a sample python script, originally found here: Adding and removing audio sources to/from GStreamer pipeline on-the-go.
The aim is to make a script such as the one above, able to insert and remove audio sources while the pi... | Gstreamer+python: adding and removing audio sources while pipeline is running | I'm working on a sample python script, originally found here: Adding and removing audio sources to/from GStreamer pipeline on-the-go.
The aim is to make a script such as the one above, able to insert and remove audio sources while the pipeline is running but with an audioconvert element between the source and the adder... | [
"I found the answer myself, it was simple indeed... \nI added other components, but they live in the pipeline and keep having an independent play status. So the solution is set all the pipeline to playing, which in turn sets the status to all the children.\npipe.set_state(gst.STATE_PLAYING)\ninstead of:\nbuzzer2.se... | [
2
] | [] | [] | [
"audio",
"audio_converter",
"gstreamer",
"pipeline",
"python"
] | stackoverflow_0008142670_audio_audio_converter_gstreamer_pipeline_python.txt |
Q:
Stuck with Python HTTP Server with Basic Authentication using BaseHTTP
I am stuck trying to get a python based webserver to work.
I want to do Basic Authentication (sending a 401 header) and authenticating against a list of users. I have no trouble sending the 401 response with "WWW-Authorize" header, I can valida... | Stuck with Python HTTP Server with Basic Authentication using BaseHTTP | I am stuck trying to get a python based webserver to work.
I want to do Basic Authentication (sending a 401 header) and authenticating against a list of users. I have no trouble sending the 401 response with "WWW-Authorize" header, I can validate the users response (base64 encoded username & password), however, the log... | [
"Try this for size:\nimport SimpleHTTPServer\nimport SocketServer\nfrom BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer\n\nclass Handler(BaseHTTPRequestHandler):\n ''' Main class to present webpages and authentication. '''\n def do_HEAD(self):\n print \"send header\"\n self.send_respons... | [
21,
7
] | [] | [] | [
"basehttpserver",
"http_authentication",
"python"
] | stackoverflow_0004287019_basehttpserver_http_authentication_python.txt |
Q:
Why can't I access a list by its key in Python?
I am creating a list, and then accessing an element like this:
list = []
list.insert(42, "foo")
list.insert(43, "bar")
list.insert(44, "baz")
print(list[43])
And I have the folowing error:
print(list[43]) IndexError: list index out of range
What is wrong ? Do I... | Why can't I access a list by its key in Python? | I am creating a list, and then accessing an element like this:
list = []
list.insert(42, "foo")
list.insert(43, "bar")
list.insert(44, "baz")
print(list[43])
And I have the folowing error:
print(list[43]) IndexError: list index out of range
What is wrong ? Do I have to use a dictionary to do this ?
| [
"There are no \"keys\" in a list, there are just indices.\nThe reason your code doesn't work the way you expect is that list.insert(index, obj) does not pad the list with \"blank\" entries when index is past the end of the list; it simply appends obj to the list.\nYou could use a dictionary for this:\nIn [14]: d = ... | [
9,
1,
1,
0,
0
] | [] | [] | [
"list",
"python"
] | stackoverflow_0008151469_list_python.txt |
Q:
Cost of Inheritance Java (Android)
I am building an extension of ORMLite to target Android.
What I want to do
I want to reproduce one of the behavior that Doctrine and Symfony are achieving in PHP with models.
In a word:
From a yml file generate a bunch of BaseModel class with accessors
and things that won't ch... | Cost of Inheritance Java (Android) | I am building an extension of ORMLite to target Android.
What I want to do
I want to reproduce one of the behavior that Doctrine and Symfony are achieving in PHP with models.
In a word:
From a yml file generate a bunch of BaseModel class with accessors
and things that won't change.
Let the real model inherits from t... | [
"It's the correct, and probably only, Java way. In Java all calls are virtual anyway unless you use final all over the place, but that means you couldn't even use interfaces. So most calls will probably be virtual dispatch whatever you do. Inheritance does not incur any other significant penalty.\nBesides, Android ... | [
2
] | [] | [] | [
"android",
"inheritance",
"java",
"performance",
"python"
] | stackoverflow_0008153264_android_inheritance_java_performance_python.txt |
Q:
Django, innodb and row-level locking
I have a table with data to parse and a worker which takes several records from it, process it and saves them back. It also sets flag to 'parsed'.
Now I want to run several instances of the worker and make sure two workers won't pick the same row to process at once. So I need ... | Django, innodb and row-level locking | I have a table with data to parse and a worker which takes several records from it, process it and saves them back. It also sets flag to 'parsed'.
Now I want to run several instances of the worker and make sure two workers won't pick the same row to process at once. So I need to block it somehow.
I'm using django and ... | [
"2 predominant ways to store data in Mysql is MyISAM & InnoDB. Each have their own pros & cons -\n\nInnoDB recovers from a crash or other unexpected shutdown by replaying its logs.\nInnoDB can be run in a mode where it has lower reliability but in some cases higher performance.\nInnoDB automatically groups together... | [
1
] | [
"with a lock, the second worker would just get stuck waiting for the lock to release. \nmaybe you could mark entries as \"work started on this entry at [timestamp]\" before starting to process, and have subsequent workers ignore such rows. you can then have a cron job or similar \"releasing\" rows that have a times... | [
-1
] | [
"django",
"innodb",
"python"
] | stackoverflow_0008153291_django_innodb_python.txt |
Q:
Can't unpickle GeoAlchemy GeometryColumn. Possible solution: 2 sqlalchemy models for same table
I have some sqlalchemy models that has a GeometryColumn.
For my caching purposes i use cPickle.
Now, while this column is empty everything fine. However, if it has data I receive:
TypeError: buffer() takes at least 1 ar... | Can't unpickle GeoAlchemy GeometryColumn. Possible solution: 2 sqlalchemy models for same table | I have some sqlalchemy models that has a GeometryColumn.
For my caching purposes i use cPickle.
Now, while this column is empty everything fine. However, if it has data I receive:
TypeError: buffer() takes at least 1 argument (0 given)
while doing cPickle.loads(data)
I dont really need this column in this query, i wil... | [
"The single solution I found:\nA bit ugly, but works.\ntemp_geom=MyModel.geom\nMyModel.geom=None \nobjects_MyModel.send_to_cache() \nMyMyodel.geom=temp_geom \n\n"
] | [
0
] | [] | [] | [
"python",
"sqlalchemy"
] | stackoverflow_0008087110_python_sqlalchemy.txt |
Q:
redirect subprocess log to wxpython txt ctrl
I would like to capture log o/p from a python based subprocess . Here is part of my code. How do I ridirect my log also to this txt ctrl
Here is mytest.py:
import logging
log=logging.getLogger('test')
class MyTestClass():
def TestFunction(... | redirect subprocess log to wxpython txt ctrl | I would like to capture log o/p from a python based subprocess . Here is part of my code. How do I ridirect my log also to this txt ctrl
Here is mytest.py:
import logging
log=logging.getLogger('test')
class MyTestClass():
def TestFunction(self) :
log.info("start function"
# ru... | [
"You can try following the suggestion in this post.\nUpdate: You can set the logger in the subprocess to use a SocketHandler and set up a socket server in the GUI to listen for messages from the subprocess, using the technique in the linked-to post to actually make things appear in the GUI. A working socket server ... | [
1,
1
] | [] | [] | [
"logging",
"python",
"subprocess",
"wxpython"
] | stackoverflow_0008123962_logging_python_subprocess_wxpython.txt |
Q:
python MySQLdb: hook function to check connectivity
I have a python script that globally invokes a database connection object with mySQL. There is an insert function insertToTable(actionDate, action) which inserts a record to the table. The main section of the script inside if __name__=="__main__": runs as an infi... | python MySQLdb: hook function to check connectivity | I have a python script that globally invokes a database connection object with mySQL. There is an insert function insertToTable(actionDate, action) which inserts a record to the table. The main section of the script inside if __name__=="__main__": runs as an infinite while loop for hours/days.
The problem is, the mysq... | [
"You could create a decorator that calls the checkConnectivity function. Example:\ndef checkConnectivity():\n print 'Checking connection'\n\ndef CheckConnectionDecorator(fn):\n def new(*args, **kwargs):\n checkConnectivity()\n return fn(*args, **kwargs)\n return new\n\n@CheckConnectionDecorat... | [
1
] | [] | [] | [
"exception_handling",
"hook",
"mysql_python",
"python"
] | stackoverflow_0008151424_exception_handling_hook_mysql_python_python.txt |
Q:
Sort a numpy array like a table
I have a list
[[0, 3], [5, 1], [2, 1], [4, 5]]
which I have made into an array using numpy.array:
[[0 3]
[5 1]
[2 1]
[4 5]]
How do I sort this like a table? In particular, I want to sort by the second column in ascending order and then resolve any ties by having the first colum... | Sort a numpy array like a table | I have a list
[[0, 3], [5, 1], [2, 1], [4, 5]]
which I have made into an array using numpy.array:
[[0 3]
[5 1]
[2 1]
[4 5]]
How do I sort this like a table? In particular, I want to sort by the second column in ascending order and then resolve any ties by having the first column sorted in ascending order. Thus I d... | [
"See http://docs.scipy.org/doc/numpy/reference/generated/numpy.lexsort.html#numpy.lexsort\nSpecifically in your case,\nimport numpy as np\nx = np.array([[0,3],[5,1],[2,1],[4,5]])\nx[np.lexsort((x[:,0],x[:,1]))]\n\noutputs\narray([[2,1],[5,1],[0,3],[4,5]])\n\n",
"You can use numpy.lexsort():\n>>> a = numpy.array([... | [
9,
4,
2,
1
] | [] | [] | [
"python"
] | stackoverflow_0008153540_python.txt |
Q:
Error: Could not import settings 'app' (Is it on sys.path?): No module named settings on Local
I'm getting this error
Error: Could not import settings 'app_name.settings' (Is it on sys.path?): No module named settings
I'm running a development local server and it stopped worked after I made some 400 inserts. Any ... | Error: Could not import settings 'app' (Is it on sys.path?): No module named settings on Local | I'm getting this error
Error: Could not import settings 'app_name.settings' (Is it on sys.path?): No module named settings
I'm running a development local server and it stopped worked after I made some 400 inserts. Any pointers as to what caused this? The files are there and permissions are correct.
Update:
I've tried... | [
"Have you tried this ?:\n./manage.py runserver --settings=your_settings_file_name\n\n",
"I copied the project folder to another directory, deleted .DStore as well, and copied the folder back, and it works now\n"
] | [
1,
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0008152729_django_python.txt |
Q:
calculation in Mysql
I'm using the command
select video_info count(distinct src_ip) from videoinfo
group by video_info
order by count(distinct src_ip) DESC
to fetch 2 columns of data, the first column represents identifiers for each video items, the second column records how many times they have been downl... | calculation in Mysql | I'm using the command
select video_info count(distinct src_ip) from videoinfo
group by video_info
order by count(distinct src_ip) DESC
to fetch 2 columns of data, the first column represents identifiers for each video items, the second column records how many times they have been downloaded.
I also want to calc... | [
"In Python you can use this:\ncur.execute(\"SELECT video_info, COUNT(distinct src_ip) \"\n \"FROM videoinfo \"\n \"GROUP BY video_info \"\n \"ORDER BY COUNT(DISTINCT src_ip) DESC\")\n\ncounter = dict(cur)\nfor n in xrange(1, max(counter.itervalues()) + 1):\n perc = 100. / sum(1 f... | [
2
] | [] | [] | [
"mysql",
"python"
] | stackoverflow_0008154164_mysql_python.txt |
Q:
Building 64-bit C Python extensions on Windows
I am asking this question because I need to build a specific module (aspell_python, http://wm.ite.pl/proj/aspell-python/) to work with my 64-bit Python 2.6 which runs on a Windows 7 (64-bit of course) machine. I also always wanted to know how to speed up certain funct... | Building 64-bit C Python extensions on Windows | I am asking this question because I need to build a specific module (aspell_python, http://wm.ite.pl/proj/aspell-python/) to work with my 64-bit Python 2.6 which runs on a Windows 7 (64-bit of course) machine. I also always wanted to know how to speed up certain functions with C code so I'd like to make my own external... | [
"I've successfully compiled C extensions for Python on 64-bit Windows before by running the following commands from the \"Visual Studio 2008 x64 Win64 Command Prompt\" in the top level directory of the source distribution of the extension:\nset DISTUTILS_USE_SDK=1\nset MSSdk=1\npython setup.py install\n\n",
"I'd ... | [
9,
2
] | [] | [] | [
"64_bit",
"c",
"python"
] | stackoverflow_0004624507_64_bit_c_python.txt |
Q:
Python. Phrase representation, how to change?
I don't know what's the encoding present in this phrases (and I'd like a answer to this too). Mainly, I'd like change my phrases to it.
For example:
Hello World! becomes Hello%20World!%0A
Olá mundo! becomes Ol%C3%A1%20mundo!%0A%0A
I'd like a python solution for this.... | Python. Phrase representation, how to change? | I don't know what's the encoding present in this phrases (and I'd like a answer to this too). Mainly, I'd like change my phrases to it.
For example:
Hello World! becomes Hello%20World!%0A
Olá mundo! becomes Ol%C3%A1%20mundo!%0A%0A
I'd like a python solution for this.
If I have
>>>Phrase='Olá mundo!'
How to change i... | [
">>> import urllib2\n>>> urllib2.quote\n<function quote at 0x104a10848>\n>>> urllib2.quote(\"ü\")\n'%C3%BC'\n>>> urllib2.quote('Olá mundo!')\n'Ol%C3%A1%20mundo%21'\n\n"
] | [
3
] | [] | [] | [
"character_encoding",
"encoding",
"html",
"python",
"web_applications"
] | stackoverflow_0008154439_character_encoding_encoding_html_python_web_applications.txt |
Q:
-1 usage python
I understand using 0 and 1 for true and false evaluation, but can someone please explain the use of -1 to me in the following. s is a file name string.
if s.find(".py")==-1:
return False
A:
The s.find() method returns the index of the given substring in s. It is a number between 0 and len(st... | -1 usage python | I understand using 0 and 1 for true and false evaluation, but can someone please explain the use of -1 to me in the following. s is a file name string.
if s.find(".py")==-1:
return False
| [
"The s.find() method returns the index of the given substring in s. It is a number between 0 and len(str) - 1 in case the substring was found. In case it was not found, -1 was chosen as return value because it does not collide with any valid return value for the case that it was found.\nNote that this line would ... | [
7,
5,
1,
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0008154436_python.txt |
Q:
Looking for algorithm to help determine shortest path from one terminal screen to another
I am using a terminal client to interact with a mainframe computer. The entire interface is based on the concept of screens. An example workflow might look like:
Login Screen: enter login credentials, press enter
Menu Scre... | Looking for algorithm to help determine shortest path from one terminal screen to another | I am using a terminal client to interact with a mainframe computer. The entire interface is based on the concept of screens. An example workflow might look like:
Login Screen: enter login credentials, press enter
Menu Screen: enter the number of the menu item you want (lets say "6" for memos), press enter
Memo Scree... | [
"If you have created a topology of the screens, the A* algorithm should work fine.\n",
"Since I am using an unweighted graph, it looks like the simplest approach is going to be Breadth-first search:\nhttp://en.wikipedia.org/wiki/Breadth-first_search\nEdit: I found a library which does everything I need:\nhttp://n... | [
0,
0
] | [] | [] | [
"graph_algorithm",
"python"
] | stackoverflow_0008153525_graph_algorithm_python.txt |
Q:
Reading lines from a file
I am writing a program to read lines of text from 5 files and compile the text from these 5 files into respective lists.
However I am having a great deal of trouble getting the program to actually read the text to a list, here is my code so far:
from random import random
from dice import... | Reading lines from a file | I am writing a program to read lines of text from 5 files and compile the text from these 5 files into respective lists.
However I am having a great deal of trouble getting the program to actually read the text to a list, here is my code so far:
from random import random
from dice import choose
b = open ('E:\Videos, ... | [
"when handling Windows pathnames, always use raw string literals:\nr'E:\\Videos, TV etc\\Python\\ca2\\beginning.txt'\n\nbecause otherwise the backslashes may be interpreted as starting an escape sequence.\nAlso, watch out with backslashes at the end of a string: r'C:\\' is not what you think it is.\n",
"'\\' is u... | [
8,
3,
2
] | [] | [] | [
"function",
"import",
"python",
"text"
] | stackoverflow_0008154490_function_import_python_text.txt |
Q:
Python special character unicode
I have a python script in which one I specify an argument :
parser = optparse.OptionParser()
parser.add_option("-D", "--departure", dest="departure",default="", type="string",help="specify departure")
and in my script i have to to a few things with the string entered.
When I type ... | Python special character unicode | I have a python script in which one I specify an argument :
parser = optparse.OptionParser()
parser.add_option("-D", "--departure", dest="departure",default="", type="string",help="specify departure")
and in my script i have to to a few things with the string entered.
When I type : -D "Düsseldorf"
the string is not re... | [
"PEP-0264 explains you how to use Unicode in python scripts.\nOr, for lazy ones, start your script with:\n#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nprint u\"Düsseldorf\" \n\nAnd do not forget to solve it as UTF-8 without BOM.\n",
"Not only do you need to specify a character encoding for your Python source... | [
0,
0
] | [] | [] | [
"python",
"unicode",
"variables"
] | stackoverflow_0008151726_python_unicode_variables.txt |
Q:
Simulating Mouseclick on Mac
How can I do this? Specifically, I want to simulate those mouseclicks at certain coords in a flash window on a hotkey.
I did applescript, with click at (x,y), but the script could identify anything in the flash window, so it failed.
I tried automator, but it's too clumsy to do on a hot... | Simulating Mouseclick on Mac | How can I do this? Specifically, I want to simulate those mouseclicks at certain coords in a flash window on a hotkey.
I did applescript, with click at (x,y), but the script could identify anything in the flash window, so it failed.
I tried automator, but it's too clumsy to do on a hotkey.
I heard that python can do th... | [
"Maybe what you are looking for is something like this:\nhttp://tjjr.fi/sw/python-uinput/\npython-uinput\nThey also have a github page that will probably be useful to you - https://github.com/tuomasjjrasanen/python-uinput\n",
"I have released a command line utility MouseTools for this. You can run that using appl... | [
0,
0
] | [] | [] | [
"applescript",
"hotkeys",
"python"
] | stackoverflow_0008153882_applescript_hotkeys_python.txt |
Q:
How to keep backslash in the result of a regular expression, when working in Python?
The strings I want to match includes some escape sequences, like 'It\'s something'. It's no problem to match it with '.*?', however the result is escaped automatically. How to prevent the automatic escaping, and keep the backslash... | How to keep backslash in the result of a regular expression, when working in Python? | The strings I want to match includes some escape sequences, like 'It\'s something'. It's no problem to match it with '.*?', however the result is escaped automatically. How to prevent the automatic escaping, and keep the backslashes as they are?
For example:
>>> re.findall('\((?P<content>.*?)\)','(It\'s something)')
["... | [
"The input string needs to be a raw string also. Otherwise, it is converted before the regex sees it:\n>>> import re\n>>> re.findall('\\((?P<content>.*?)\\)',r'(It\\'s something)')\n[\"It\\\\'s something\"]\n>>> _ == [r\"It\\'s something\"]\nTrue\n\n",
"There is no backslash in your input string.\n>>> re.findall... | [
3,
1
] | [] | [] | [
"escaping",
"python",
"regex"
] | stackoverflow_0008154801_escaping_python_regex.txt |
Q:
Moving specific files in subdirectories into a directory - python
Im rather new to python but I have been attemping to learn the basics.
Anyways I have several files that once i have extracted from their zip files (painfully slow process btw) produce several hundred subdirectories with 2-3 files in each. Now what ... | Moving specific files in subdirectories into a directory - python | Im rather new to python but I have been attemping to learn the basics.
Anyways I have several files that once i have extracted from their zip files (painfully slow process btw) produce several hundred subdirectories with 2-3 files in each. Now what I want to do is extract all those files ending with 'dem.tif' and place... | [
"First, welcome to the community, and python! You might want to change your user name, especially if you frequent here. :)\nI suggest the following (stolen from Mr. Beazley):\n# genfind.py\n#\n# A function that generates files that match a given filename pattern\n\nimport os\nimport shutil\nimport fnmatch\n\ndef ge... | [
9,
3,
3,
0
] | [] | [] | [
"python",
"shutil",
"subdirectory"
] | stackoverflow_0008155060_python_shutil_subdirectory.txt |
Q:
Python: how to grab a substrings when the indices are dynamic
I am working with many lines in a file, in which I want to retrieve a certain element which may be of varying length, and is not flanked consistently by the same characters.
Here's an example. I want to retrieve the item that starts with "OOO_" on each... | Python: how to grab a substrings when the indices are dynamic | I am working with many lines in a file, in which I want to retrieve a certain element which may be of varying length, and is not flanked consistently by the same characters.
Here's an example. I want to retrieve the item that starts with "OOO_" on each line:
blah blah OOO_128934( blah blah
blah bloop OOO_231 bloop blo... | [
"Then maybe:\ntext = \"\"\"\nblah blah OOO_128934( blah blah\nblah bloop OOO_231 bloop bloop\nbeep OOO_421398234beep beep\n\"\"\"\n\nimport re\n\nprint re.findall(r'OOO_\\d+', text) \n>>> ['OOO_128934', 'OOO_231', 'OOO_421398234']\n\n",
">>> s = \"blah bloop OOO_231 bloop bloop\"\n>>> next(x for x in s.split() if... | [
4,
1
] | [] | [] | [
"python",
"string",
"substring"
] | stackoverflow_0008155169_python_string_substring.txt |
Q:
Which simplejson module to use for Google AppEngine?
I'm trying to figure out which simplejson module to use. Having looked back through my project I can see in some places I am using a mixture of both:
django.utils.simplejson
google.appengine.ext.key_range.simplejson
Which should I be using and why?
A:
Where ... | Which simplejson module to use for Google AppEngine? | I'm trying to figure out which simplejson module to use. Having looked back through my project I can see in some places I am using a mixture of both:
django.utils.simplejson
google.appengine.ext.key_range.simplejson
Which should I be using and why?
| [
"Where did you see anything recommending the use of google.appengine.ext.key_range.simplejson? That is only available because the key_range package happens to import simplejson. Don't use it like that.\n",
"For a least a few months now, you can simply:\nimport simplejson\n\nand it works fine; no need to find it i... | [
2,
1,
0
] | [] | [] | [
"django",
"google_app_engine",
"python"
] | stackoverflow_0008151044_django_google_app_engine_python.txt |
Q:
Python: dynamically create methods based on other classes'
I've looked for quite a while but couldn't find a proper answer to my question:
I have a class containing methods which operate on arrays and I want dynamically create methods with a similar name in another class with a modified output.
I've got something ... | Python: dynamically create methods based on other classes' | I've looked for quite a while but couldn't find a proper answer to my question:
I have a class containing methods which operate on arrays and I want dynamically create methods with a similar name in another class with a modified output.
I've got something like this so far, can anyone guide me ?
Thanks
Class A():
d... | [
"I think you are trying to make an advanced use of Python without using/knowing its advanced features, like you are borrowing techniques from another language.\nThis is not a criticism, but you should have a look on Python tutorial, Python introspection or metaclasses.\nI think that if you just complete your knowle... | [
1,
0
] | [] | [] | [
"dynamic",
"methods",
"python"
] | stackoverflow_0008152483_dynamic_methods_python.txt |
Q:
Make a thumbnail with PIL, enhanced way
I know there is a thumbnail method in PIL. What I want to make differently is how it resizes the original image. Assume I have a 300x360px vertical image. I want to resize it to a constrained box that is 150x100px horizontal image. So I need to find the smallest side of the ... | Make a thumbnail with PIL, enhanced way | I know there is a thumbnail method in PIL. What I want to make differently is how it resizes the original image. Assume I have a 300x360px vertical image. I want to resize it to a constrained box that is 150x100px horizontal image. So I need to find the smallest side of the original image, resize to it, and then crop t... | [
"from PIL import Image\n\nwidth = 150\nheight = 100\ninfile = Image.open(in_filename)\nim = infile.copy()\n\nif im.size[0] >= im.size[1]:\n im = im.resize((height * im.size[0]/im.size[1], height))\n im = im.crop(((im.size[0] - width)/2, 0, (im.size[0] + width)/2, height))\nelse:\n im = im.resize((width, wi... | [
3
] | [] | [] | [
"python",
"python_imaging_library"
] | stackoverflow_0008151282_python_python_imaging_library.txt |
Q:
How to create a .deb of a single Python script
I've created a GUI frontend in Python for playing and recording audio streams and would like to create a .deb file so my friends can easily install the script on their Ubuntu systems. This is my first time attempting to create a .deb file and so far I'm a bit confused... | How to create a .deb of a single Python script | I've created a GUI frontend in Python for playing and recording audio streams and would like to create a .deb file so my friends can easily install the script on their Ubuntu systems. This is my first time attempting to create a .deb file and so far I'm a bit confused by all the different tutorials on the web. The scri... | [
"The best documentation, although not the friendliest, is the Debian New Maintainer's Guide. You could always pop into #debian-mentors on irc://irc.oftc.net for help if your stuck after reading the guide.\n",
"See https://github.com/hpfem/hermes/wiki/Create-.deb-Package-for-Femhub\nSee also Making a deb from a p... | [
2,
1
] | [] | [] | [
"deb",
"packaging",
"python",
"ubuntu"
] | stackoverflow_0004979998_deb_packaging_python_ubuntu.txt |
Q:
Can't resolve WindowsError: [Error 2] The system cannot find the file specified
I'm trying to rename all the pictures in a directory. I need to add a couple of pre-pending zero's to the filename. I'm new to Python and I have written the following script.
import os
path = "c:\\tmp"
dirList = os.listdir(path)
for ... | Can't resolve WindowsError: [Error 2] The system cannot find the file specified | I'm trying to rename all the pictures in a directory. I need to add a couple of pre-pending zero's to the filename. I'm new to Python and I have written the following script.
import os
path = "c:\\tmp"
dirList = os.listdir(path)
for fname in dirList:
fileName = os.path.splitext(fname)[0]
fileName = "00" + fna... | [
"You should pass the absolute path to os.rename. Right now your only passing the filename itself. It isn't looking in the correct place. Use os.path.join.\nTry this:\nimport os\n\npath = \"c:\\\\tmp\"\ndirList = os.listdir(path)\n\nfor fname in dirList:\n fileName = os.path.splitext(fname)[0]\n fileName = \"0... | [
16
] | [] | [] | [
"python"
] | stackoverflow_0008155945_python.txt |
Q:
How to assign RGB color values to grid mesh with matplotlib
Please consider this simplified snippet:
import numpy as np
x = np.arange(3)
y = np.arange(2)
X, Y = np.meshgrid(x,y)
I would like to assign already prepared color values to every grid cell.
I have color values of same shape as XY grid for every RGB ch... | How to assign RGB color values to grid mesh with matplotlib | Please consider this simplified snippet:
import numpy as np
x = np.arange(3)
y = np.arange(2)
X, Y = np.meshgrid(x,y)
I would like to assign already prepared color values to every grid cell.
I have color values of same shape as XY grid for every RGB channel as normalized RGB values - so it's 3 numpy arrays each cons... | [
"You want imshow rather than pcolor. (Though you can use pcolor or pcolormesh for this.)\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n# Make some random data to represent your r, g, b bands.\nny, nx = 2, 3\nr, g, b = [np.random.random(ny*nx).reshape((ny, nx)) for _ in range(3)]\n\nc = np.dstack([r,g,b])\... | [
4
] | [] | [] | [
"matplotlib",
"python"
] | stackoverflow_0008145791_matplotlib_python.txt |
Q:
Scalable Widget for Rendering Foreign Keys in Django Admin
Is there a widget for rendering a foreign key field in Django admin that can scale to handle an arbitrarily large table and provide a user-friendly interface for looking up a FK?
The default widget in Django 1.3 is a select box that lists every record in t... | Scalable Widget for Rendering Foreign Keys in Django Admin | Is there a widget for rendering a foreign key field in Django admin that can scale to handle an arbitrarily large table and provide a user-friendly interface for looking up a FK?
The default widget in Django 1.3 is a select box that lists every record in the referenced table. For tables containing hundreds of thousands... | [
"are you getting all the static files? raw_id_fields come with an ajax widget, which puts a little magnifying glass next to the text box with the input widget. clicking brings up a popup with a changelist (including e.g. search) that you can use to find the id. (and automatically insert by clicking the entry)\nsee ... | [
3,
3
] | [] | [] | [
"django",
"django_admin",
"python"
] | stackoverflow_0008155937_django_django_admin_python.txt |
Q:
How do I parse through an infinite scrolling page (ex. Wallbase.cc/search/sky) with Python?
Not sure if there's anything with Mechanize or BeautifulSoup that could help. Any suggestions would be greatly appreciated!
A:
Mechanize and Beautiful soup can't inteface with the javascript used for the infinite scroll.
... | How do I parse through an infinite scrolling page (ex. Wallbase.cc/search/sky) with Python? | Not sure if there's anything with Mechanize or BeautifulSoup that could help. Any suggestions would be greatly appreciated!
| [
"Mechanize and Beautiful soup can't inteface with the javascript used for the infinite scroll.\nSelenium can.\nAdditionally if you were to view the ajax requests when you use the infinite scroll you would see a post request to http://wallbase.cc/search/160 with the request data: \nquery:sky\nboard:123\nres_opt:eqeq... | [
3
] | [] | [] | [
"beautifulsoup",
"html_parsing",
"mechanize",
"python"
] | stackoverflow_0008156012_beautifulsoup_html_parsing_mechanize_python.txt |
Q:
Drawing a correlation graph in matplotlib
Suppose I have a data set of discrete vectors with n=2:
DATA = [
('a', 4),
('b', 5),
('c', 5),
('d', 4),
('e', 2),
('f', 5),
]
How can I plot that data set with matplotlib so as to visualize any correlation between the two variables?
Any simple cod... | Drawing a correlation graph in matplotlib | Suppose I have a data set of discrete vectors with n=2:
DATA = [
('a', 4),
('b', 5),
('c', 5),
('d', 4),
('e', 2),
('f', 5),
]
How can I plot that data set with matplotlib so as to visualize any correlation between the two variables?
Any simple code examples would be great.
| [
"Joe Kington has the correct answer, but your DATA probably is more complicated that is represented. It might have multiple values at 'a'. The way Joe builds the x axis values is quick but would only work for a list of unique values. There may be a faster way to do this, but this how I accomplished it:\nimport matp... | [
20,
7
] | [] | [] | [
"data_visualization",
"graph",
"matplotlib",
"python"
] | stackoverflow_0008154511_data_visualization_graph_matplotlib_python.txt |
Q:
Printing issue in Python
I feel like an idiot for even asking this but does anyone have any idea why my code is printing the list after every shuffle?
def shuffle(L, nswaps):
n = 0
for item in L:
while n < nswaps:
card_one = choose(L)
card_two = choose(L)
if card... | Printing issue in Python | I feel like an idiot for even asking this but does anyone have any idea why my code is printing the list after every shuffle?
def shuffle(L, nswaps):
n = 0
for item in L:
while n < nswaps:
card_one = choose(L)
card_two = choose(L)
if card_two == card_one:
... | [
"Your print statement is inside the for loop, so it's going to print L for each element in L.\nTry un-indenting it to the same level as the for loop, to put it outside the loop\n",
"Your print statement is inside the for, so It'll be executed once for each element in the list :).\nTry doing something like this:\n... | [
1,
1,
0
] | [] | [] | [
"list",
"printing",
"python",
"shuffle"
] | stackoverflow_0008156350_list_printing_python_shuffle.txt |
Q:
Mapping data from excel with Python
I am reading data from an xls spreadsheet with xlrd. First, I gather the index for the column that contains the data that I need (may not always be in the same column in every instance):
amr_list, pssr_list, inservice_list = [], [], []
for i in range(sh.ncols):
for j in rang... | Mapping data from excel with Python | I am reading data from an xls spreadsheet with xlrd. First, I gather the index for the column that contains the data that I need (may not always be in the same column in every instance):
amr_list, pssr_list, inservice_list = [], [], []
for i in range(sh.ncols):
for j in range(sh.nrows):
if 'amrprojectnumber... | [
"Maybe this can help:\nA = ['4006BA','4006BA','4007AC','4007AC','4007AC']\nB = ['4006BA(1)','4006BA(2)','4007AC(1)','4007AC(2)','4007AC(3)']\nC = [40780.0, '', 40749.0, 40764.0, '']\n\nresult = dict()\nfor item in xrange(len(A)):\n key = A[item]\n result.setdefault(key, [])\n result[key].append( (B[item], ... | [
2,
1
] | [] | [] | [
"mapping",
"python",
"xlrd"
] | stackoverflow_0008156142_mapping_python_xlrd.txt |
Q:
Python/Glade/PyGTK - Download Percentage in Glade Label
I'm trying to setup a little download application using Glade, PyGTK, and Python. I have it planned how I'd like to script this progress bar and all, though I feel I'm going about it the wrong way as... Well... It's not working.
I'm using a little script I fo... | Python/Glade/PyGTK - Download Percentage in Glade Label | I'm trying to setup a little download application using Glade, PyGTK, and Python. I have it planned how I'd like to script this progress bar and all, though I feel I'm going about it the wrong way as... Well... It's not working.
I'm using a little script I found for a checking the percentage of a download and then usua... | [
"After the line\nself.label1.set_text(status)\n\nAdd:\nwhile gtk.events_pending():\n gtk.main_iteration()\n\nThis will update the GUI and run the main loop while you are waiting for the file to download, and you won't have to use threads.\n",
"You will need to use threads for this. If you are downloading in th... | [
4,
1
] | [] | [] | [
"glade",
"gtk",
"progress_bar",
"pygtk",
"python"
] | stackoverflow_0008148729_glade_gtk_progress_bar_pygtk_python.txt |
Q:
Upload a video to Youtube using the python API and set it as unlisted
I'm using the python client library to upload videos to youtube.
I need to the set it's privacy as unlisted, but the API page only shows examples of how to set them as private.
Anyone knows how to change the privacy control of these videos?
Than... | Upload a video to Youtube using the python API and set it as unlisted | I'm using the python client library to upload videos to youtube.
I need to the set it's privacy as unlisted, but the API page only shows examples of how to set them as private.
Anyone knows how to change the privacy control of these videos?
Thanks!
| [
"The XML element that you need is described in http://code.google.com/apis/youtube/2.0/reference.html#youtube_data_api_tag_yt:accessControl\nFollowing the API documentation, you can build this element as follows:\nfrom gdata.media import YOUTUBE_NAMESPACE\nfrom atom import ExtensionElement\n\n# set video as unliste... | [
4
] | [] | [] | [
"python",
"youtube_api"
] | stackoverflow_0006770362_python_youtube_api.txt |
Q:
Python Link Fetcher Performance Issue
So I am writing link fetchers to find new links on particular sites for a given group of 'starting links'.
Currently I am using Python/Beautiful Soup to accomplish this with decent success.
I have an input file [for each site] that I build the 'starting links' list from.
I use... | Python Link Fetcher Performance Issue | So I am writing link fetchers to find new links on particular sites for a given group of 'starting links'.
Currently I am using Python/Beautiful Soup to accomplish this with decent success.
I have an input file [for each site] that I build the 'starting links' list from.
I use urllib2 to load the webpages and then beau... | [
"You could use Python Shelves if you want a simple on disk persisitant hashtable\nhttp://docs.python.org/library/shelve.html\n",
"You should consider using hashes for comparing the previously collected list. Instead of storing a list of links as strings, store a list of MD5 or SHA1 hashes for those links. Compa... | [
1,
0
] | [] | [] | [
"beautifulsoup",
"python"
] | stackoverflow_0008156736_beautifulsoup_python.txt |
Q:
python parallel processing
I am new to Python. I have 2000 files each about 100 MB. I have to read each of them and merge them into a big matrix (or table). Can I use parallel processing for this so that I can save some time? If yes, how? I tried searching and things seem very complicated. Currently, it takes abou... | python parallel processing | I am new to Python. I have 2000 files each about 100 MB. I have to read each of them and merge them into a big matrix (or table). Can I use parallel processing for this so that I can save some time? If yes, how? I tried searching and things seem very complicated. Currently, it takes about 8 hours to get this done seria... | [
"You make be able to preprocess the files in separate processes using the subprocess module; however, if the final table is kept in memory, then that process will end up being you bottleneck.\nThere is another possible approach using shared memory with mmap objects. Each subprocess can be responsible for loading t... | [
1
] | [] | [] | [
"parallel_processing",
"python"
] | stackoverflow_0008157068_parallel_processing_python.txt |
Q:
django: select_related() on an already-existing object?
If I am retrieving an object with django, I can use .select_related() to instruct django to get all foreign key objects as well, to wit:
obj = ModelClass.objects.select_related().get(id=4) #1 db hit
foo = obj.long.chain.of.stuff #no db hit
If I already have ... | django: select_related() on an already-existing object? | If I am retrieving an object with django, I can use .select_related() to instruct django to get all foreign key objects as well, to wit:
obj = ModelClass.objects.select_related().get(id=4) #1 db hit
foo = obj.long.chain.of.stuff #no db hit
If I already have obj, without it having been .select_related(), that is:
def d... | [
"I suppose I can do:\ndef doit(obj):\n obj = obj.__class__.objects.select_related().get(id=obj.id) #1 db hit\n obj.long.chain.of.stuff #no db hits\n\nBut is there any nicer way?\n"
] | [
6
] | [] | [] | [
"database",
"django",
"performance",
"python",
"sql"
] | stackoverflow_0008156999_database_django_performance_python_sql.txt |
Q:
Change the font style of one item in a wx python ListCtrl
I am having issues changing the font of a single item in an wx list ctrl. I have 1 row and 3 columns in my ListCtrl. The code below should change the font of the item located at row = 0 col = 0 to bold. But instead it changes the font style of ALL the item... | Change the font style of one item in a wx python ListCtrl | I am having issues changing the font of a single item in an wx list ctrl. I have 1 row and 3 columns in my ListCtrl. The code below should change the font of the item located at row = 0 col = 0 to bold. But instead it changes the font style of ALL the items in row 0 to bold. In summary, I only want the first item in t... | [
"with wx.ListCtrl, you can't have control at the sub item level.\nIf you change font, it will change for entire row.\nTherefore this is not possible.\nHeres the ticket number:\nhttp://trac.wxwidgets.org/ticket/3030\n"
] | [
1
] | [] | [] | [
"fonts",
"listctrl",
"python",
"wxwidgets"
] | stackoverflow_0008129826_fonts_listctrl_python_wxwidgets.txt |
Q:
Handling backreferences to capturing groups in re.sub replacement pattern
I want to take the string 0.71331, 52.25378 and return 0.71331,52.25378 - i.e. just look for a digit, a comma, a space and a digit, and strip out the space.
This is my current code:
coords = '0.71331, 52.25378'
coord_re = re.sub("(\d), (\d)... | Handling backreferences to capturing groups in re.sub replacement pattern | I want to take the string 0.71331, 52.25378 and return 0.71331,52.25378 - i.e. just look for a digit, a comma, a space and a digit, and strip out the space.
This is my current code:
coords = '0.71331, 52.25378'
coord_re = re.sub("(\d), (\d)", "\1,\2", coords)
print coord_re
But this gives me 0.7133,2.25378. What am I... | [
"You should be using raw strings for regex, try the following:\ncoord_re = re.sub(r\"(\\d), (\\d)\", r\"\\1,\\2\", coords)\n\nWith your current code, the backslashes in your replacement string are escaping the digits, so you are replacing all matches the equivalent of chr(1) + \",\" + chr(2):\n>>> '\\1,\\2'\n'\\x01... | [
174,
28
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0008157267_python_regex.txt |
Q:
Alternative to TCP/IP for local program-to-program data streaming?
I have a GNU C++ program and a python script that need to pass strings to each other quite frequently (~70-80 messages a minute). They will run local to each other in CentOS (hosted in the same environment). It feels that although TCP/IP can and wi... | Alternative to TCP/IP for local program-to-program data streaming? | I have a GNU C++ program and a python script that need to pass strings to each other quite frequently (~70-80 messages a minute). They will run local to each other in CentOS (hosted in the same environment). It feels that although TCP/IP can and will get the job done, what other options do I have?
Keep in mind that I c... | [
"If you already have a TCP or UDP server, the easiest way will probably be to switch to UNIX domain sockets.\nThey come in \"stream\" and \"datagram\" modes, just like TCP/UDP sockets, and they're always local, as they use the filesystem namespace (instead of port numbers like TCP/UDP).\n",
"Named pipes are the s... | [
8,
5,
2,
0
] | [] | [] | [
"c++",
"gcc",
"linux",
"networking",
"python"
] | stackoverflow_0008157348_c++_gcc_linux_networking_python.txt |
Q:
Add options not found to args
Possible Duplicate:
How can I get optparse’s OptionParser to ignore invalid arguments?
I want to use optparse to parse my input. How do I get optparse to ignore the options not provided and just append them to args instead? The users of my program are not computer-savvy, and I do no... | Add options not found to args |
Possible Duplicate:
How can I get optparse’s OptionParser to ignore invalid arguments?
I want to use optparse to parse my input. How do I get optparse to ignore the options not provided and just append them to args instead? The users of my program are not computer-savvy, and I do not want to explain to them that the... | [
"Just set default values with default=, then if the arg is not given, the default value will be used:\nfrom optparse import OptionParser\n[...]\nparser = OptionParser()\nparser.add_option(\"-f\", \"--file\", dest=\"filename\",\n help=\"write report to FILE\", metavar=\"FILE\")\nparser.add_option(\"... | [
1
] | [] | [] | [
"optparse",
"python"
] | stackoverflow_0008157227_optparse_python.txt |
Q:
Unsorted numeric list creates improper output in histogram calculation
I am making a function which will make a list which includes a histogram of a requested list and requested values to use as the values of the histogram. Values above the requested value are included last.
The program is working with a list that... | Unsorted numeric list creates improper output in histogram calculation | I am making a function which will make a list which includes a histogram of a requested list and requested values to use as the values of the histogram. Values above the requested value are included last.
The program is working with a list that is sorted in ascending order numerically, but when a list that is not sorte... | [
"Your problem is that you are removing items from the list sample while you are iterating over it, this is a bad idea because it will result in skipping some elements.\nTry taking out the line sample.remove(x), you should get the expected result. If you really do need to remove elements from the input list you sho... | [
1
] | [] | [] | [
"histogram",
"python"
] | stackoverflow_0008157599_histogram_python.txt |
Q:
How efficient is my Python search code
Below is the nuts and bolts of my Python file search app. I'm still a noob in Python, and have been more pleased with getting working code than considering efficiency and performance. I want to know from you Python, or any other language, veterans is there anything I can do t... | How efficient is my Python search code | Below is the nuts and bolts of my Python file search app. I'm still a noob in Python, and have been more pleased with getting working code than considering efficiency and performance. I want to know from you Python, or any other language, veterans is there anything I can do to make my code more efficient, thereby faste... | [
"This is a very reasonable solution.\nIt is possible to make it go faster with more regex magic but you would lose some clarity.\nKeep in mind that the running time is likely dominated by the FTP file retrieval and not the search itself. So, additional optimization of an IO bound process would likely be wasted. S... | [
1
] | [] | [] | [
"performance",
"python"
] | stackoverflow_0008157876_performance_python.txt |
Q:
cx_Oracle 5.1.1 under apache+mod_wsgi
if I use cx_Oracle 5.0.4, I can connect from python console, and works under apache+django+mod_wsgi
but when I update cx_Oracle 5.1.1, I can connect from python console, BUT same code doesn't work under apache+django+mod_wsgi
File "C:\Python27\lib\site-packages\django\db\backe... | cx_Oracle 5.1.1 under apache+mod_wsgi | if I use cx_Oracle 5.0.4, I can connect from python console, and works under apache+django+mod_wsgi
but when I update cx_Oracle 5.1.1, I can connect from python console, BUT same code doesn't work under apache+django+mod_wsgi
File "C:\Python27\lib\site-packages\django\db\backends\oracle\base.py", line 24, in
rais... | [
"Need a solution as well. \nI have the same setup on WinXP (Apache 2.2.21/ mod_wsgi 3.3/ python 2.7.2/ cx_Oracle 5.x.x). I found that cx_Oracle 5.1 also fails with the same error. Only 5.0.4 works. \nHere is the list of changes that were made from 5.0.4 to 5.1:\n\nRemove support for UNICODE mode and permit Unic... | [
1
] | [] | [] | [
"apache",
"cx_oracle",
"python"
] | stackoverflow_0008151815_apache_cx_oracle_python.txt |
Q:
Shuffling a list
in this program I'm trying to shuffle a list by randomly choosing two items from a list and swapping them round, and then repeating this process several times.
The problem I have encountered is I don't know how I can swap the items round and print the shuffled list.
For instance if my two random v... | Shuffling a list | in this program I'm trying to shuffle a list by randomly choosing two items from a list and swapping them round, and then repeating this process several times.
The problem I have encountered is I don't know how I can swap the items round and print the shuffled list.
For instance if my two random values were a and b, if... | [
"In Python, you can swap two variables like this:\na, b = b, a\n\nThis is called multiple assignment, you can find more information about it here.\nIn other languages this is usually done by assigning a temporary variable:\ntmp = a\na = b\nb = tmp\n\nIsn't Python great?\n",
"The random.shuffle function uses swapp... | [
4,
4,
3,
1,
0
] | [] | [] | [
"list",
"python",
"swap"
] | stackoverflow_0008155890_list_python_swap.txt |
Q:
Python: Files stop being opened at a certain point
I've written the following program in Python:
import re
import os
import string
folder = 'C:\Users\Jodie\Documents\Uni\Final Year Project\All Data'
folderlisting = os.listdir(folder)
for eachfolder in folderlisting:
print eachfolder
if os.path.isdir(fold... | Python: Files stop being opened at a certain point | I've written the following program in Python:
import re
import os
import string
folder = 'C:\Users\Jodie\Documents\Uni\Final Year Project\All Data'
folderlisting = os.listdir(folder)
for eachfolder in folderlisting:
print eachfolder
if os.path.isdir(folder + '\\' + eachfolder):
filelisting = os.listdi... | [
"You should use os.walk() http://docs.python.org/library/os.html#os.walk\nAlso, you need to read the contents of the file, you don't want to print the file object. And you need to close the file when you're done or use a context manager to close it for you.\nwould look something like:\nfor root, dirs, files in os.... | [
0
] | [] | [] | [
"python"
] | stackoverflow_0008157260_python.txt |
Q:
Can I iterate over several dicts in succession without merging them?
In python, let's say I have three dicts:
d1, d2, d3 = {...}, {...}, {...}
I need to iterate over each of them and perform the same operation:
for k, v in d1.iteritems():
do_some_stuff(k, v)
for k, v in d3.iteritems():
do_some_stuff(k, v)... | Can I iterate over several dicts in succession without merging them? | In python, let's say I have three dicts:
d1, d2, d3 = {...}, {...}, {...}
I need to iterate over each of them and perform the same operation:
for k, v in d1.iteritems():
do_some_stuff(k, v)
for k, v in d3.iteritems():
do_some_stuff(k, v)
for k, v in d3.iteritems():
do_some_stuff(k, v)
Is there a way to do... | [
"You want chain:\nfrom itertools import chain\n\nfor k,v in chain(d1.iteritems(), d2.iteritems(), d3.iteritems()):\n do_some_stuff(k, v)\n\nor more general\nds = d1,d2,d3\nfor k,v in chain.from_iterable(d.iteritems() for d in ds):\n do_some_stuff(k, v)\n\n"
] | [
10
] | [] | [] | [
"dictionary",
"for_loop",
"python"
] | stackoverflow_0008158298_dictionary_for_loop_python.txt |
Q:
Easily exporting python to someone without the interpreter
Suppose I have a group of people to whom I want to show my python program. I don't want to have to tell them each "Ok, go to the python website, install the interpreter, open IDLE, open my program, press F5, and then it will run". Is there some way I can j... | Easily exporting python to someone without the interpreter | Suppose I have a group of people to whom I want to show my python program. I don't want to have to tell them each "Ok, go to the python website, install the interpreter, open IDLE, open my program, press F5, and then it will run". Is there some way I can just send them a file of some format and they can run it easily?
... | [
"I like cx-freeze for simplicity, but PyInstaller is also easy to use. Py2exe may be the traditional solution, but it hasn't been updated in 3 years.\n",
"One of the traditional solutions is: http://www.py2exe.org/\n"
] | [
3,
0
] | [] | [] | [
"embed",
"export",
"interpreter",
"java",
"python"
] | stackoverflow_0008146691_embed_export_interpreter_java_python.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.