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:
reorder columns of a csv file containing float, integer and text data?
I would like to do a similar process to a csv file as detailed in this question, but I get an error message saying:
TypeError: list indices must be integers
The csv file that I want to rearrange has a combination of float, text, and integer... | reorder columns of a csv file containing float, integer and text data? | I would like to do a similar process to a csv file as detailed in this question, but I get an error message saying:
TypeError: list indices must be integers
The csv file that I want to rearrange has a combination of float, text, and integer data types. I'm assuming this is the problem, but can't figure out a way t... | [
"operator.itemgetter() is all you need:\ninp=csv.reader(open(...))\noutp=csv.writer(open(...))\nmap(outp.writerow,map(operator.itemgetter(x,y,z),inp))\n\nWhere x,y,z are the columns you want to re-order.\nHowever, since the first row in Summary.csv is headers, then you might consider using DictReader and DictWriter... | [
2
] | [] | [] | [
"python"
] | stackoverflow_0007583850_python.txt |
Q:
How to monitor a directory for changes in Python?
Possible Duplicate:
Monitoring files/directories with python
I am making an API server that allows hot-deploying of code. And yes, there are dozens of questions about re-importing modules. I just want to monitor a directory, and when a change is detected, perform... | How to monitor a directory for changes in Python? |
Possible Duplicate:
Monitoring files/directories with python
I am making an API server that allows hot-deploying of code. And yes, there are dozens of questions about re-importing modules. I just want to monitor a directory, and when a change is detected, perform an action.
path_to_monitor="c:\\app\\package"
def act... | [
"You can use a Python thread which uses os.listdir() to list files. If you want to monitor other file properties than the file name, os.stat might help you.\n"
] | [
0
] | [] | [] | [
"python"
] | stackoverflow_0007584626_python.txt |
Q:
Convert HTML into PDF using Python
I am trying to convert HTML into a PDF document in Django and haven't been successful.
I have tried using wkhtmltopdf 0.9.9, however Apache throws an error that wkhtmltopdf cannot connect to server. When I use wkhtmltopdf directly, it runs perfectly fine and converts the HTML int... | Convert HTML into PDF using Python | I am trying to convert HTML into a PDF document in Django and haven't been successful.
I have tried using wkhtmltopdf 0.9.9, however Apache throws an error that wkhtmltopdf cannot connect to server. When I use wkhtmltopdf directly, it runs perfectly fine and converts the HTML into a PDF document.
I have also tried usin... | [
"Configuring Pisa for Django shouldn't be too hard.\nThere are really several examples on the net that show you how to do it and\nexplain how to link to external resources in your templates:\n\nhttp://www.arnebrodowski.de/blog/501-Pisa-and-Reportlab-pitfalls.html\ndjango - pisa : adding images to PDF output\nhttp:/... | [
4,
0,
0
] | [] | [] | [
"django",
"html",
"html2pdf",
"python",
"wkhtmltopdf"
] | stackoverflow_0007584546_django_html_html2pdf_python_wkhtmltopdf.txt |
Q:
Return an item in a nested list (python)
I'm doing a lab for a basic programming class in Python, and I can't figure out how to return a number in a list, in another list.
I'm supposed to return 4 with "one expression and no parenthesis"
[1,[2,[3,4]]]
Any ideas?
All I've gotten so far is returning [2,[3,4]] and I... | Return an item in a nested list (python) | I'm doing a lab for a basic programming class in Python, and I can't figure out how to return a number in a list, in another list.
I'm supposed to return 4 with "one expression and no parenthesis"
[1,[2,[3,4]]]
Any ideas?
All I've gotten so far is returning [2,[3,4]] and I haven't been able to figure out anything past... | [
">>> a = [1,[2,[3,4]]]\n>>> a[1]\n[2, [3, 4]]\n>>> a[1][1]\n[3, 4]\n>>> a[1][1][1]\n4\n>>> \n\n",
"One expression:\n>>> [1,[2,[3,4]]][1][1][1]\n4\n\n",
"In case you don't know, to access the last element of a list you can use negative index. a[-1] means the first element from the end. It's very useful when you ... | [
7,
2,
2
] | [] | [] | [
"nested_lists",
"python"
] | stackoverflow_0007584653_nested_lists_python.txt |
Q:
python: what's the point of adding`__dict__` to `__slots__`
The whole point of __slots__ is to save space.
But I saw people add __dict__ to it so that new attributes can be added. Isn't this defeating the goal of __slots__?
A:
Yes. If you want __dict__, then just don't use __slots__.
| python: what's the point of adding`__dict__` to `__slots__` | The whole point of __slots__ is to save space.
But I saw people add __dict__ to it so that new attributes can be added. Isn't this defeating the goal of __slots__?
| [
"Yes. If you want __dict__, then just don't use __slots__.\n"
] | [
4
] | [] | [] | [
"python"
] | stackoverflow_0007585284_python.txt |
Q:
How does one omit the closing slash on elements using WTForms?
I've been noticing that WTForms (and Flask-WTF) output <input> elements with a closing slash like so:
<input name="text" type="text" value="" />
My documents are HTML5 and therefore need no XHTML-type closure. How would I make WTForms output the input... | How does one omit the closing slash on elements using WTForms? | I've been noticing that WTForms (and Flask-WTF) output <input> elements with a closing slash like so:
<input name="text" type="text" value="" />
My documents are HTML5 and therefore need no XHTML-type closure. How would I make WTForms output the input tag as such?
<input name="text" type="text" value="">
I've been tear... | [
"Use any revision past this one (or simply download tip) - WTForms is moving to the HTML5 way of generating form elements and adding some new widgets too (I believe). See this thread and this one for a bit more information.\n* There is also an extension for WTForms that adds the XHTML back in, if you decide you nee... | [
2
] | [] | [] | [
"flask",
"html",
"jinja2",
"python",
"wtforms"
] | stackoverflow_0007574381_flask_html_jinja2_python_wtforms.txt |
Q:
Traceback for regular expression
Lets say i have a regular expression:
match = re.search(pattern, content)
if not match:
raise Exception, 'regex traceback' # i want to throw here the regex matching process.
If regular expression fails to match then i want to throw in exception Its working and where it fails t... | Traceback for regular expression | Lets say i have a regular expression:
match = re.search(pattern, content)
if not match:
raise Exception, 'regex traceback' # i want to throw here the regex matching process.
If regular expression fails to match then i want to throw in exception Its working and where it fails to match the regular expression pattern... | [
"I've used Kodos (http://kodos.sourceforge.net/about.html) in the past to perform RegEx debugging. It's not the ideal solution since you want something for run-time, but it may be helpful to you.\n",
"if you need to test the re, you can probably use groups followed by * ... as in ( sometext)*\nuse this along w/ ... | [
0,
0,
0
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0007584435_python_regex.txt |
Q:
Android, HTTP GET not returning
I have an Android app that sends commands to a robot via HTTP. (The robot server is written in Python using the BaseHttpServer class.) I'm setting up my connection in the app correctly as far as I can tell, but most requests fail to return and if they do there is a very long delay... | Android, HTTP GET not returning | I have an Android app that sends commands to a robot via HTTP. (The robot server is written in Python using the BaseHttpServer class.) I'm setting up my connection in the app correctly as far as I can tell, but most requests fail to return and if they do there is a very long delay. Here is the initialization code:
... | [
"This may be related to keep-alive. Android sends Connection: Keep-Alive and Python sends back a Connection: close. I've looked at the HTTP headers that are being sent from Firefox and HttpClient and there is no difference (other than Firefox sending some additional Accept headers). Somehow Android is expecting ... | [
1
] | [] | [] | [
"android",
"http",
"python"
] | stackoverflow_0007577932_android_http_python.txt |
Q:
How to draw a pixel on the screen directly?
I'm wanting to do something like the following:
...
pixel[0,0] = [ 254, 0, 0 ] # Draw R at pixel x0y0
pixel[2,1] = [ 0, 254, 0 ] # Draw G at pixel x2y1
pixel[4,2] = [ 0, 0, 254 ] # Draw B at pixel x4y2
...
I hope to display many different configurations of pixels and co... | How to draw a pixel on the screen directly? | I'm wanting to do something like the following:
...
pixel[0,0] = [ 254, 0, 0 ] # Draw R at pixel x0y0
pixel[2,1] = [ 0, 254, 0 ] # Draw G at pixel x2y1
pixel[4,2] = [ 0, 0, 254 ] # Draw B at pixel x4y2
...
I hope to display many different configurations of pixels and colours in a short space of time -- writing to an i... | [
"Direct answer:\nThis can only be done with OS-specific APIs. Some OSes do not allow changing pixels on the screen directly.\nOn Windows, you can use pywin32 libraries to get screen's device context with dc = GetDC(0) call, then paint pixels with SetPixel(dc, x, y, color).\nimport win32gui\nimport win32api\n\ndc = ... | [
26,
4,
3
] | [] | [] | [
"pixel",
"python"
] | stackoverflow_0007585447_pixel_python.txt |
Q:
® gets converted to ® in Python while parsing XML
My RSS feed ontains:
<title><![ CDATA[HBO Wins 19 Emmy® Awards, The Most of Any Network This Year]]></title>
Now I am parsing RSS and then assigning the title to title as below:
for item in XML.ElementFromURL(feed).xpath('//item',namespaces=NEWS_NS):
tit... | ® gets converted to ® in Python while parsing XML | My RSS feed ontains:
<title><![ CDATA[HBO Wins 19 Emmy® Awards, The Most of Any Network This Year]]></title>
Now I am parsing RSS and then assigning the title to title as below:
for item in XML.ElementFromURL(feed).xpath('//item',namespaces=NEWS_NS):
title = item.find('title').text
Log("Title :"+title... | [
"You state that the encoding of the feed is ISO-8859-1.\nIn that case, if the bytes that you say should be interpreted as ® are in fact C2 AE, then the text really, truly is Emmy® Awards, and everything is working as it should. If the sender intended different text, they would have sent different data or set the ... | [
1,
0,
0
] | [] | [] | [
"non_ascii_characters",
"python",
"rss",
"xml"
] | stackoverflow_0007566991_non_ascii_characters_python_rss_xml.txt |
Q:
Django planmember_set issue
I have a question that I hope someone can help me with. I'm using a form to have the user select a "plan". Now I want to list all the members in the plan, in the form. I have a function 'get_owners' that grabs all the members in the plan, by using this function:
def get_owners(self):... | Django planmember_set issue | I have a question that I hope someone can help me with. I'm using a form to have the user select a "plan". Now I want to list all the members in the plan, in the form. I have a function 'get_owners' that grabs all the members in the plan, by using this function:
def get_owners(self):
owners = self.planmember_set... | [
"You can use values_list:\nowners = self.planmember_set.filter(\n ownership_type__code__in=[\"primary\",\"joint\"]\n ).values_list('name', 'type')\n\n",
"def get_owners(self):\n owners = self.planmember_set.filter(ownership_type__code__in=[\"primary\",\"joint\"]).values_list('name_field', '... | [
0,
0
] | [] | [] | [
"django",
"django_forms",
"django_models",
"django_views",
"python"
] | stackoverflow_0007585612_django_django_forms_django_models_django_views_python.txt |
Q:
How to create a mesh object in ITK using Python bindings?
I am trying to create a Mesh object in Python. I am using the python bindings which are being installed from the following web page. As far as the c++ code is concerned we can do it as follows
MeshType::Pointer mesh = MeshType::New();
I am very new ... | How to create a mesh object in ITK using Python bindings? | I am trying to create a Mesh object in Python. I am using the python bindings which are being installed from the following web page. As far as the c++ code is concerned we can do it as follows
MeshType::Pointer mesh = MeshType::New();
I am very new to use even ITK. Have no idea how to create it. In the construc... | [
"If I were you I would take a look at the Python bindings that come with ITK 4.0. You can get access to them by turning on the option WRAP_ITK_PYTHON in cmake.\nOnce, you compile ITK with the python bindings turned on you can create 2 mesh types out of the box:\nimport itk\nmeshType2D = itk.Mesh.D2Q.New()\nmeshTyp... | [
3
] | [] | [] | [
"itk",
"python"
] | stackoverflow_0007584373_itk_python.txt |
Q:
CSV Writer writing over itself
I am trying to create a CSV file with a list of URLs.
I am pretty new to programming, so please excuse any sloppy code.
I have a loop that runs through a list of places to get the list of URLs.
I then have a loop within that loop that exports the data to a CSV file.
import urllib, cs... | CSV Writer writing over itself | I am trying to create a CSV file with a list of URLs.
I am pretty new to programming, so please excuse any sloppy code.
I have a loop that runs through a list of places to get the list of URLs.
I then have a loop within that loop that exports the data to a CSV file.
import urllib, csv, re
from BeautifulSoup import Beau... | [
"Don't put this inside any loop:\nout = csv.writer(open(\"file_location\", \"wb\"), delimiter=\";\")\n\nInstead:\nwith open(\"file_location\", \"wb\") as fout:\n out = csv.writer(fout, delimiter=\";\")\n # put for-loop here\n\nNotes:\n\nopen(\"file_location\", \"wb\") creates a new file, destroying any old f... | [
5,
1,
0
] | [] | [] | [
"csv",
"excel",
"python"
] | stackoverflow_0007585909_csv_excel_python.txt |
Q:
Why is a .get() on a filtered query returning None?
I'm following the instruction from an answer, why is my object that is returned by the function None and not an entity?
class FileInfo(db.Model):
blob = blobstore.BlobReferenceProperty(required=True)
randomvalue = db.FloatProperty()
uploaded_by = db.... | Why is a .get() on a filtered query returning None? | I'm following the instruction from an answer, why is my object that is returned by the function None and not an entity?
class FileInfo(db.Model):
blob = blobstore.BlobReferenceProperty(required=True)
randomvalue = db.FloatProperty()
uploaded_by = db.UserProperty()
facebook_user_id = db.StringProperty()... | [
"q.filter('random >=', random.random())\n\nshould be corrected in:\nq.filter('randomvalue >=', random.random())\n\n"
] | [
3
] | [] | [] | [
"google_app_engine",
"python",
"random"
] | stackoverflow_0007586310_google_app_engine_python_random.txt |
Q:
How to avoid getting billed on EC2 for unused time?
I have a periodic task that I need to run on the EC2. This task will not take more than 10 minutes to run and I do not want to end up paying for the other 50 minutes that this task will be idle for. From my understanding, if I start an instance and run this task,... | How to avoid getting billed on EC2 for unused time? | I have a periodic task that I need to run on the EC2. This task will not take more than 10 minutes to run and I do not want to end up paying for the other 50 minutes that this task will be idle for. From my understanding, if I start an instance and run this task, no matter whether I use any resources or not, I will be ... | [
"Try picloud and pay per second. \n",
"You will pay for the full hour no matter what you do. \nAs soon as you start an EC2 instance (you refer to them as nodes, but that's wrong), you pay for an hour. Any partial hour is billed as a full hour.\nIf you snap an AMI (backup image) of a machine, you have to pay for... | [
7,
5
] | [] | [] | [
"amazon_ec2",
"distributed",
"python"
] | stackoverflow_0006714988_amazon_ec2_distributed_python.txt |
Q:
Is there a "startswith" method in pyparsing
Hey I have written a very simple parser with pyparsing which detects some tokens in a text and then replaces them with a different string. The problem is that right now my code only works with exact matches. What I'd like to do is detect partial matches too. For example ... | Is there a "startswith" method in pyparsing | Hey I have written a very simple parser with pyparsing which detects some tokens in a text and then replaces them with a different string. The problem is that right now my code only works with exact matches. What I'd like to do is detect partial matches too. For example if the token is "foobar" I'd like to match a word... | [
"Literal('foobar')+Word(pyp.alphas) defines a pyparsing ParseExpression which requires the text to startwith 'foobar' followed by any alphacharacter. For example:\nimport pyparsing as pyp\nident = pyp.Combine(pyp.Literal('foobar')+pyp.Word(pyp.alphas))('foo')\nfor match in ident.searchString('bar foobarfoo bar foob... | [
3,
3
] | [] | [] | [
"parsing",
"pyparsing",
"python"
] | stackoverflow_0007586722_parsing_pyparsing_python.txt |
Q:
Limiting concurrency and rate for Python threads
Given a number threads I want to limit the rate of calls to the worker function to a rate of say one per second.
My idea was to keep track of the last time a call was made across all threads and compare this to the current time in each thread. Then if current_time -... | Limiting concurrency and rate for Python threads | Given a number threads I want to limit the rate of calls to the worker function to a rate of say one per second.
My idea was to keep track of the last time a call was made across all threads and compare this to the current time in each thread. Then if current_time - last_time < rate. I let the thread sleep for a bit. S... | [
"It seems weird to me to try and limit the rate across multiple threads. If you limit each thread independently you can avoid all the locking nonsense. \nJust a guess, but I think you want to set last_time[0] to time.time() (not current_time) after the sleep.\n",
"\nI get mostly 2 calls at the same time (1 for ea... | [
1,
1
] | [] | [] | [
"concurrency",
"multithreading",
"python",
"rate_limiting"
] | stackoverflow_0007586743_concurrency_multithreading_python_rate_limiting.txt |
Q:
Convert not_camel_case to notCamelCase and/or NotCamelCase in Python?
Basically, the reverse of this. Here's my attempt, but it's not working.
def titlecase(value):
s1 = re.sub('(_)([a-z][A-Z][0-9]+)', r'\2'.upper(), value)
return s1
A:
def titlecase(value):
return "".join(word.title() for word in va... | Convert not_camel_case to notCamelCase and/or NotCamelCase in Python? | Basically, the reverse of this. Here's my attempt, but it's not working.
def titlecase(value):
s1 = re.sub('(_)([a-z][A-Z][0-9]+)', r'\2'.upper(), value)
return s1
| [
"def titlecase(value):\n return \"\".join(word.title() for word in value.split(\"_\"))\n\nPython is more readable than regex, and easier to fix when it's not doing what you want.\nIf you want the first letter lowercase as well, I would use a second function that calls the function above to do most of the work, t... | [
9,
2,
2,
2,
0
] | [] | [] | [
"python"
] | stackoverflow_0007060384_python.txt |
Q:
How to use Python's DictReader class in the csv library?
I'm getting to grips with my first Python project and have got pretty stumped trying to use Python's csv.DictReader class to consume a CSV file.
Code is as follows:
import os
import csv
f = open('MyCsvFile.txt', 'rb')
d = csv.Sniffer().sniff(f.read(1024), ... | How to use Python's DictReader class in the csv library? | I'm getting to grips with my first Python project and have got pretty stumped trying to use Python's csv.DictReader class to consume a CSV file.
Code is as follows:
import os
import csv
f = open('MyCsvFile.txt', 'rb')
d = csv.Sniffer().sniff(f.read(1024), ',')
csvDict = csv.DictReader(csvfile = f, dialect = d)
for l... | [
"You need to pass the csvfile as a positional argument, not as a keyword argument:\ncsvDict = csv.DictReader(f, dialect = d)\n\n",
"According to the code supplied in the documentation, this would work better:\nwith open('MyCsvFile.txt', 'rb') as source:\n dialect = csv.Sniffer().sniff(source.read(1024), ',')\n... | [
3,
2
] | [] | [] | [
"csv",
"python"
] | stackoverflow_0007587105_csv_python.txt |
Q:
matplotlib cla() issue
i am trying to make some animation using matplotlib.
fig = plt.figure()
ax = fig.gca(projection='3d')
...
for k in xrange(10):
...
ax.cla()
ax.plot_surface(X, Y, field.real, rstride=2, cstride=2, cmap=cm.hot,
linewidth=0, antialiased=False)
ax.set_zlim3d(-50, 150)
fi... | matplotlib cla() issue | i am trying to make some animation using matplotlib.
fig = plt.figure()
ax = fig.gca(projection='3d')
...
for k in xrange(10):
...
ax.cla()
ax.plot_surface(X, Y, field.real, rstride=2, cstride=2, cmap=cm.hot,
linewidth=0, antialiased=False)
ax.set_zlim3d(-50, 150)
filename = "out_%d.png" % k
... | [
"I'm running the latest version of Matplotlib from github on ubuntu 11.04. I wrote a code snippet where I create a new axis instance each time, and this seems to produce the plots that you want with axis intact. The problem you're seeing might just be a bug, but I think this works around it. I made plots of rando... | [
0
] | [] | [] | [
"matplotlib",
"python"
] | stackoverflow_0007486178_matplotlib_python.txt |
Q:
Is it possible to get an object by its primary key in django-nonrel / Google App Engine?
I'm trying to retrieve a model object like the code below:
(r'^album/(?P<album_id>\w+)/$', 'core.views.album'),
def album(request, album_id):
album = Album.objects.get(pk=album_id)
The problem is that the PK is not an in... | Is it possible to get an object by its primary key in django-nonrel / Google App Engine? | I'm trying to retrieve a model object like the code below:
(r'^album/(?P<album_id>\w+)/$', 'core.views.album'),
def album(request, album_id):
album = Album.objects.get(pk=album_id)
The problem is that the PK is not an integer:
>>> a = Album.objects.all()[0]
>>> a.pk
46L
The error I'm getting when I run the view:... | [
"46L is a long integer, not a string, so you should treat it as a number and not a word in urls.py:\n(r'^album/(?P<album_id>\\d+)/$', 'core.views.album'),\n\nthen the url /album/46/ will end up calling:\ndef album(request, album_id):\n #album = Album.objects.get(pk=46L)\n album = Album.objects.get(pk=album_id... | [
1,
0
] | [] | [] | [
"django",
"django_nonrel",
"google_app_engine",
"python"
] | stackoverflow_0007577451_django_django_nonrel_google_app_engine_python.txt |
Q:
Setup for high volume of database writing
I am researching a project that would require hundreds of database writes per a minute. I have never dealt with this level of data writes before and I am looking for good scalable techniques and technologies.
I am a comfortable python developer with experience in django an... | Setup for high volume of database writing | I am researching a project that would require hundreds of database writes per a minute. I have never dealt with this level of data writes before and I am looking for good scalable techniques and technologies.
I am a comfortable python developer with experience in django and sql alchemy. I am thinking I will build the d... | [
"Follow the trends, in other words, enter the world of NOSQL. Some technologies that are worthy include mongodb and redis. They are really fast, scalable, and with decent python drivers. For example, mongodb plays really nice with django, and has many common things with traditional SQL, like MySQL. On the other han... | [
0,
0,
0
] | [] | [] | [
"amazon_web_services",
"database_design",
"django",
"python"
] | stackoverflow_0007586999_amazon_web_services_database_design_django_python.txt |
Q:
Django: How to concatenate translation and constant string in template
I'd like to pass a translation with variable to template tag. I'm trying to do it this way:
{% my_tag _("Entries for tag")|add:" '"|add:tag|add:"'" %}
But this does not work. Is there any solution?
A:
What's wrong with <span>{% my_tag _("Ent... | Django: How to concatenate translation and constant string in template | I'd like to pass a translation with variable to template tag. I'm trying to do it this way:
{% my_tag _("Entries for tag")|add:" '"|add:tag|add:"'" %}
But this does not work. Is there any solution?
| [
"What's wrong with <span>{% my_tag _(\"Entries for tag\") %} '{{tag}}'</span>\n",
"One solution would probably be:\n{% blocktrans with tag=tag %}\n <span>Entries for tag</span> '{{ tag }}'\n{% endblocktrans %}\n\nBut putting HTML inside translated strings is not the best idea. What is much worse though is assu... | [
0,
0
] | [] | [] | [
"django",
"python",
"string_concatenation",
"templates",
"translation"
] | stackoverflow_0007586096_django_python_string_concatenation_templates_translation.txt |
Q:
Eclipse + PyDev define function based on function call
I have noticed a particular feature in Visual Studio and I am wondering if this feature is also available in Eclipse + PyDev.
In Visual Studio, if one were to type a function call and that particular function does not already exist, VS would show a code error ... | Eclipse + PyDev define function based on function call | I have noticed a particular feature in Visual Studio and I am wondering if this feature is also available in Eclipse + PyDev.
In Visual Studio, if one were to type a function call and that particular function does not already exist, VS would show a code error and give an option to generate a new empty function matching... | [
"Thank you @Eric Wilson.\nIf I type the function call processString(myString) then hit 'CTRL+1' the code completion/template window appears offering me the option to create a new class, method, assign to a field, or assign to a variable.\nThis was exactly what I was looking for.\n"
] | [
2
] | [] | [] | [
"code_completion",
"eclipse",
"pydev",
"python",
"templates"
] | stackoverflow_0007501533_code_completion_eclipse_pydev_python_templates.txt |
Q:
Should you hold a HTTP request while the server performs a time consuming operation? Or let the request go?
Lets say an operation could take 2 to 10 minutes on the server to perform, for example to update an index which is time consuming.
Would you perform the operation while holding the request? ie not sending a... | Should you hold a HTTP request while the server performs a time consuming operation? Or let the request go? | Lets say an operation could take 2 to 10 minutes on the server to perform, for example to update an index which is time consuming.
Would you perform the operation while holding the request? ie not sending a HTTP Response until the operation has finished? And if the client/browser drops the request, just continue with ... | [
"You might also use a chunked response. First, push a chunk with some code that would display the “please wait” screen, flush the response and start the work. Then you can either push and flush chunks with periodical progress updates or just push one at the end with a “completed” information. Obviously you can empl... | [
3,
2,
0
] | [] | [] | [
"http",
"python",
"request"
] | stackoverflow_0007587939_http_python_request.txt |
Q:
Program not entering if statement
In my python program, an if statement is not being entered. I have simplified the code to the following:
x = -5
while x < 5:
if (x == 0):
print 0
x += .01
This program does not output anything.
However, changing the last line to x += .5 makes the program output 0.... | Program not entering if statement | In my python program, an if statement is not being entered. I have simplified the code to the following:
x = -5
while x < 5:
if (x == 0):
print 0
x += .01
This program does not output anything.
However, changing the last line to x += .5 makes the program output 0. What's the problem?
| [
"Floating point number representation might not be accurate enough. You should never test for zero equality but instead use something along\nif (abs(x) < 1E-10) ...\n\n",
"Behold the power of the print statement...\nLet us insert a print statement...\nx = -5\nwhile x < 5:\n if (x == 0):\n print 0\n x... | [
9,
7,
3,
3,
0,
0,
0
] | [] | [] | [
"floating_point",
"python"
] | stackoverflow_0007586221_floating_point_python.txt |
Q:
How do I quickly match the fields of two files that are sorted but one is a subset of the other
I have two sorted files and want to merge them to make a third, but I need the output to be sorted. One column in the second file is a subset of the first and any place the second file doesn't match the first should be ... | How do I quickly match the fields of two files that are sorted but one is a subset of the other | I have two sorted files and want to merge them to make a third, but I need the output to be sorted. One column in the second file is a subset of the first and any place the second file doesn't match the first should be filled in with a NA. The files are large (~20,000,000) records each so loading things into memory is... | [
"join is your friend here.\njoin -a 1 file1 file2\n\nshould do the trick. The only difference to your example output is that the unpairable lines are printed directly from file1, i.e. without the NA.\nEdit: Here is a version that also handles the NAs:\njoin -a 1 -e NA -o 1.1 1.2 2.2 file1 file2\n\n",
"If I under... | [
6,
1,
0,
0
] | [] | [] | [
"merge",
"perl",
"python",
"shell",
"sorting"
] | stackoverflow_0005904503_merge_perl_python_shell_sorting.txt |
Q:
Does a line profiler for code require a parse tree and is that sufficient?
I am trying to determine what is necessary to write a line profiler for a language, like those available for Python and Matlab.
A naive way to interpret "line profiler" is to assume that one can insert time logging around every line, but th... | Does a line profiler for code require a parse tree and is that sufficient? | I am trying to determine what is necessary to write a line profiler for a language, like those available for Python and Matlab.
A naive way to interpret "line profiler" is to assume that one can insert time logging around every line, but the definition of a line is dependent on how a parser handles whitespace, which is... | [
"It sounds like what you mean by line profiler is something that measures time spent (i.e. instrumenting) within each line.\nI hope what you mean by time is wall-clock time, because in real good-size software if you only look at CPU time you're going to be missing a lot.\nAnother way to do it is stack-sampling on w... | [
3,
3
] | [] | [] | [
"language_agnostic",
"parse_tree",
"profiling",
"python",
"r"
] | stackoverflow_0007309890_language_agnostic_parse_tree_profiling_python_r.txt |
Q:
Ignore Unicode Error
When I run a loop over a bunch of URLs to find all links (in certain Divs) on those pages I get back this error:
Traceback (most recent call last):
File "file_location", line 38, in <module>
out.writerow(tag['href'])
UnicodeEncodeError: 'ascii' codec can't encode character u'\u2026' in positio... | Ignore Unicode Error | When I run a loop over a bunch of URLs to find all links (in certain Divs) on those pages I get back this error:
Traceback (most recent call last):
File "file_location", line 38, in <module>
out.writerow(tag['href'])
UnicodeEncodeError: 'ascii' codec can't encode character u'\u2026' in position 0: ordinal not in range(... | [
"You can wrap the writerow method call in a try and catch the exception to ignore it:\nfor tag in soup_3.findAll('a', href=True):\n try:\n out.writerow(tag['href'])\n except UnicodeEncodeError:\n pass\n\nbut you almost certainly want to pick an encoding other than ASCII for your CSV file (utf-8 ... | [
6
] | [] | [] | [
"ascii",
"csv",
"python",
"unicode"
] | stackoverflow_0007588575_ascii_csv_python_unicode.txt |
Q:
Passing arguments to ForeignKey class
I am using stdimage to auto resize my images, I have something like that :
class Image(models.Model):
image = stdimage.StdImageField(upload_to="images/uploads/", size=(width, height))
class Nevermind(models.Model):
w, h = 300, 150
image = models.ForeignKey(Image)... | Passing arguments to ForeignKey class | I am using stdimage to auto resize my images, I have something like that :
class Image(models.Model):
image = stdimage.StdImageField(upload_to="images/uploads/", size=(width, height))
class Nevermind(models.Model):
w, h = 300, 150
image = models.ForeignKey(Image)
class Nevermind2(models.Model):
w, h... | [
"I'm not sure exactly what your goal is, but you could try using model methods to define extra paramenters with the models.\n#model\nclass Nevermind2(models.Model):\n image = models.ForeignKey(image)\n\n def size(self):\n w,h = 100,100\n return w, h\n\n#example use\n>>> a = Nevermind2.objects.ge... | [
0
] | [] | [] | [
"django",
"django_models",
"python"
] | stackoverflow_0007573605_django_django_models_python.txt |
Q:
Posting from one RequestHandler to another in App Engine
Goal: Using app engine's basic webapp framework I want to create a new request, with post data, to send to another RequestHandler. Something like pageGenerator.post({'message':'the message','datum1':datum1,...})...
Problem Description: One request handler,... | Posting from one RequestHandler to another in App Engine | Goal: Using app engine's basic webapp framework I want to create a new request, with post data, to send to another RequestHandler. Something like pageGenerator.post({'message':'the message','datum1':datum1,...})...
Problem Description: One request handler, call it pageGenerator, creates a page with a form on it. When... | [
"Sounds like you're over-complicating things. Consider just having a common method to show the form that can be invoked in different circumstances:\nclass FormHandler(webapp.RequestHandler):\n\n def get(self):\n self.show_form()\n\n def post(self):\n if form_is_valid():\n handle_success()\n else:\n ... | [
3
] | [] | [] | [
"google_app_engine",
"python",
"webapp2"
] | stackoverflow_0007588050_google_app_engine_python_webapp2.txt |
Q:
SciPy LeastSq Goodness of Fit Estimator
I have a data surface that I'm fitting using SciPy's leastsq function.
I would like to have some estimate of the quality of the fit after leastsq returns. I'd expected that this would be included as a return from the function, but, if so, it doesn't seem to be clearly docume... | SciPy LeastSq Goodness of Fit Estimator | I have a data surface that I'm fitting using SciPy's leastsq function.
I would like to have some estimate of the quality of the fit after leastsq returns. I'd expected that this would be included as a return from the function, but, if so, it doesn't seem to be clearly documented.
Is there such a return or, barring that... | [
"If you call leastsq like this:\nimport scipy.optimize\np,cov,infodict,mesg,ier = optimize.leastsq(\n residuals,a_guess,args=(x,y),full_output=True)\n\nwhere \ndef residuals(a,x,y):\n return y-f(x,a)\n\nthen, using the definition of R^2 given here,\nss_err=(infodict['fvec']**2).sum()\nss_tot=((y-y.mean())... | [
23
] | [] | [] | [
"data_fitting",
"python",
"scipy"
] | stackoverflow_0007588371_data_fitting_python_scipy.txt |
Q:
Convert letters to lower case
I use the following with respect to letters from any language:
text = regex.sub("[^\p{alpha}\d]+"," ",text
Can I use p{alpha} to convert letters to their lower case equivalent if such an equivalency exists? How would this regex look?
A:
>>> re.sub('[AEIOU]+', lambda m: m.group(0).l... | Convert letters to lower case | I use the following with respect to letters from any language:
text = regex.sub("[^\p{alpha}\d]+"," ",text
Can I use p{alpha} to convert letters to their lower case equivalent if such an equivalency exists? How would this regex look?
| [
">>> re.sub('[AEIOU]+', lambda m: m.group(0).lower(), 'SOME TEXT HERE')\n'SoMe TeXT HeRe'\n\n",
"As oxtopus suggested, you can simply convert letters to their lowercase version with text.lower() (no need for a regular expression). This works with Unicode strings too (À -> à, etc.)\n",
"I believe you can find y... | [
50,
6,
5,
1
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0007588574_python_regex.txt |
Q:
os.walk multiple directories at once
Possible Duplicate:
How to join two generators in Python?
Is there a way in python to use os.walk to traverse multiple directories at once?
my_paths = []
path1 = '/path/to/directory/one/'
path2 = '/path/to/directory/two/'
for path, dirs, files in os.walk(path1, path2):
my... | os.walk multiple directories at once |
Possible Duplicate:
How to join two generators in Python?
Is there a way in python to use os.walk to traverse multiple directories at once?
my_paths = []
path1 = '/path/to/directory/one/'
path2 = '/path/to/directory/two/'
for path, dirs, files in os.walk(path1, path2):
my_paths.append(dirs)
The above example do... | [
"To treat multiples iterables as one, use itertools.chain:\nfrom itertools import chain\n\npaths = ('/path/to/directory/one/', '/path/to/directory/two/', 'etc.', 'etc.')\nfor path, dirs, files in chain.from_iterable(os.walk(path) for path in paths):\n\n",
"Use itertools.chain().\nfor path, dirs, files in itertool... | [
31,
6,
5,
1
] | [] | [] | [
"os.walk",
"python"
] | stackoverflow_0007588620_os.walk_python.txt |
Q:
Python sockets question: socket.MSG_DONTWAIT in Windows
I have a Python app that uses UDP sendto/recvfrom with the socket.MSG_DONTWAIT flag. In Linux and Mac OS X, this works just fine. However, this flag doesn't exist in the Windows environment.
What is the equivalent flag in Windows? Alternatively, how can I do... | Python sockets question: socket.MSG_DONTWAIT in Windows | I have a Python app that uses UDP sendto/recvfrom with the socket.MSG_DONTWAIT flag. In Linux and Mac OS X, this works just fine. However, this flag doesn't exist in the Windows environment.
What is the equivalent flag in Windows? Alternatively, how can I do non-blocking sendto/recvfrom in Windows?
| [
"socket.setblocking(False) switches your socket into non-blocking mode on any platform. Call this once on socket creation, and you can remove all the MSG_DONTWAIT flags.\nIf you need to switch between blocking and nonblocking I/O (which is usually not the case), call socket.setblocking every time you want to switch... | [
4
] | [] | [] | [
"python",
"sockets",
"windows"
] | stackoverflow_0007588936_python_sockets_windows.txt |
Q:
Python : Accessing Column Values in multi dimension array
Example:
a = [[1,2,3],[4,5,6],[7,8,9]]
By doing something like a[:][0], I expect it to give me 1st elements in each row [1,4,7]
However, I get [1,2,3]. I can always make a function to do it.
def column(array,index):
result = []
for row in array:
... | Python : Accessing Column Values in multi dimension array | Example:
a = [[1,2,3],[4,5,6],[7,8,9]]
By doing something like a[:][0], I expect it to give me 1st elements in each row [1,4,7]
However, I get [1,2,3]. I can always make a function to do it.
def column(array,index):
result = []
for row in array:
result.append(row[index])
return result
But I was w... | [
"The de facto standard way of manipulating arrays in such a way is to use the dedicated NumPy package.\nThings work the way you want, with NumPy:\n>>> import numpy\n>>> a = numpy.array([[1,2,3],[4,5,6],[7,8,9]])\n>>> a[:,0]\narray([1, 4, 7])\n\nIn fact, the purpose of NumPy is to provide powerful array manipulation... | [
3,
3,
2,
2,
1
] | [] | [] | [
"arrays",
"python"
] | stackoverflow_0007589082_arrays_python.txt |
Q:
How to add http headers in suds 0.3.6?
I have an application in python 2.5 which sends data through suds 0.3.6.
The problem is that the data contains non-ascii characters, so I need the following header to exist in the soap message:
Content-Type="text/html; charset="utf-8"
and the header that exists in the SOAP me... | How to add http headers in suds 0.3.6? | I have an application in python 2.5 which sends data through suds 0.3.6.
The problem is that the data contains non-ascii characters, so I need the following header to exist in the soap message:
Content-Type="text/html; charset="utf-8"
and the header that exists in the SOAP message is just:
Content-Type="text/html"
I kn... | [
"At least in suds 0.4 (maybe earlier?) HTTP headers can also be passed in to the constructor or via the set_options method:\nclient = suds.client.Client(url, headers={'key': 'value'})\nclient.set_options(headers={'key2': 'value'})\n\n",
"When you create the opener in urllib2, you can use some handlers to do whate... | [
13,
4
] | [] | [] | [
"header",
"http",
"python",
"suds"
] | stackoverflow_0002804062_header_http_python_suds.txt |
Q:
Python introspection: Automatic wrapping of methods
object of type A and Is there a way to programatically wrap a class object?
Given
class A(object):
def __init__(self):
## ..
def f0(self, a):
## ...
def f1(self, a, b):
## ..
I want another class that wraps an A, such as
cla... | Python introspection: Automatic wrapping of methods | object of type A and Is there a way to programatically wrap a class object?
Given
class A(object):
def __init__(self):
## ..
def f0(self, a):
## ...
def f1(self, a, b):
## ..
I want another class that wraps an A, such as
class B(object):
def __init__(self):
self.a = A(... | [
"If you want to create class B by calling a function on a predefined class A, you can simply do B = wrap_class(A) with a function wrap_class that looks like this:\nimport copy\n\ndef wrap_class(cls):\n 'Wraps a class so that exceptions in its methods are caught.'\n # The copy is necessary so that mutable clas... | [
4,
2,
0
] | [] | [] | [
"inspection",
"python",
"reflection",
"wrapper"
] | stackoverflow_0007589208_inspection_python_reflection_wrapper.txt |
Q:
matplotlib, rectangular plot in polar axes
Is it possible to have a standard rectangular (aka Cartesian) plot, but displayed on a polar set of axes?
I just want the masking appearance of the grey border provided by the polar() function, but I do not want to convert my coordinates to polar, and use polar().
A:... | matplotlib, rectangular plot in polar axes | Is it possible to have a standard rectangular (aka Cartesian) plot, but displayed on a polar set of axes?
I just want the masking appearance of the grey border provided by the polar() function, but I do not want to convert my coordinates to polar, and use polar().
| [
"If you just want to be able to call two arrays in rectangular coordinates, while plotting on a polar grid, this will give you what you need. Here, x and y are your arrays that, in rectangular, would give you an x=y line. It returns the same trend line but on in polar coordinates. If you require more of a mask, ... | [
0
] | [] | [] | [
"matplotlib",
"python"
] | stackoverflow_0007569997_matplotlib_python.txt |
Q:
Two simultaneous Python loops with one result
I currently have a Python 2.6 piece of code that runs two loops simultaneously. The code uses the gps (gpsd) module and the scapy module. Basically the first function (gpsInfo) contains a continual while loop grabbing GPS data from a GPS device and writing the location... | Two simultaneous Python loops with one result | I currently have a Python 2.6 piece of code that runs two loops simultaneously. The code uses the gps (gpsd) module and the scapy module. Basically the first function (gpsInfo) contains a continual while loop grabbing GPS data from a GPS device and writing the location to console. The second function (ClientDetect) run... | [
"A simple way of getting this is store the gps location in a global variable, and have the wifi sniffing thread read that global when it needs to print some data; The gotcha is that since two threads can be accessing the global variable at the same time, you'll want to wrap it with a mutex;\nlast_location = (None,... | [
2,
1,
1
] | [] | [] | [
"gps",
"gpsd",
"python",
"python_multithreading",
"queue"
] | stackoverflow_0007589507_gps_gpsd_python_python_multithreading_queue.txt |
Q:
Combining several tables with some common fields into a single table
I have a series of text files (one per year) which contain the answers to an annual survey/questionnaire. Column headings in the files refer to question numbers, and each row represents one person's answers to the questions e.g.
Q1, Q2, Q3, .... | Combining several tables with some common fields into a single table | I have a series of text files (one per year) which contain the answers to an annual survey/questionnaire. Column headings in the files refer to question numbers, and each row represents one person's answers to the questions e.g.
Q1, Q2, Q3, ...
P1A1, P1A2, P1A3, ...
P2A1, P2A2, P2A3, ...
etc.
[where Q1 is Question ... | [
"Step 1. Stop coding.\nStep 2. Buy a book on data warehousing and star-schema design. Ralph Kimball's Data Warehouse Toolkit, for example. http://www.amazon.com/Data-Warehouse-Toolkit-Complete-Dimensional/dp/0471200247\nStep 3. Design a proper star schema. Question is a dimension. Time (specifically year) is... | [
2,
1,
1
] | [] | [] | [
"python",
"sql",
"sqlite"
] | stackoverflow_0007589745_python_sql_sqlite.txt |
Q:
DjangoUnicodeDecodeError codec can't decode byte 0xdd in position
I have a Django Web Application running in Apache with mod_wsgi in my dedicated server with Centos 5.5.
However, sometimes (six or seven times in a day) it starts to give 500 Error for some random pages. But if I refresh the page two or three times,... | DjangoUnicodeDecodeError codec can't decode byte 0xdd in position | I have a Django Web Application running in Apache with mod_wsgi in my dedicated server with Centos 5.5.
However, sometimes (six or seven times in a day) it starts to give 500 Error for some random pages. But if I refresh the page two or three times, the page turns to normal.
But once it starts to give 500 error, every ... | [
"In this request the client is sending a <WSGIRequest> with the client header 'HTTP_ACCEPT_ENCOD\\\\xddNG': 'gzip, deflate' in it.\nIf the actual encoding of the <WSGIRequest> is supposed to be UTF-8, then the server error is legitimate (unless this is not really what the client sent). In UTF-8 byte value 0xdd can... | [
2,
1
] | [] | [] | [
"apache",
"django",
"mod_wsgi",
"python",
"unicode"
] | stackoverflow_0007582826_apache_django_mod_wsgi_python_unicode.txt |
Q:
SVN Batch Rename Whitespace Issue
I'm trying to batch rename some files in svn. I have an issue where some files have a space in them. when I try to run I get this error:
svn: Cannot copy path '00009.png' into its own child '00009.png'
my code is:
import subprocess.call
call("svn rename " + "test 00009.png" + ... | SVN Batch Rename Whitespace Issue | I'm trying to batch rename some files in svn. I have an issue where some files have a space in them. when I try to run I get this error:
svn: Cannot copy path '00009.png' into its own child '00009.png'
my code is:
import subprocess.call
call("svn rename " + "test 00009.png" + " test1 00009.png")
looks like it's sp... | [
"Backslash escape your whitespace.\nSo:\nimport subprocess.call\ncall(\"svn rename \" + r\"test\\ 00009.png\" + r\" test1\\ 00009.png\")\n\nThe r'' syntax means that python should treat the \\s literally, not as escapes in themselves. It passes them through svn where they are treated as escapes.\n",
"This should... | [
2,
1
] | [] | [] | [
"call",
"python",
"svn",
"syntax"
] | stackoverflow_0007590416_call_python_svn_syntax.txt |
Q:
Dictionary Iteration Python
I am newbie in Python.
Dictionary has multiple values.
dc = {1:['2', '3'], 2:['3'], 3:['3', '4']}
If you iterate over 'dc' you find there are three occurrences of '3'. First occurrence is in 1:['2','3'].
I would like to iterate over dict so that
if first occurrence of '3' occurs:
d... | Dictionary Iteration Python | I am newbie in Python.
Dictionary has multiple values.
dc = {1:['2', '3'], 2:['3'], 3:['3', '4']}
If you iterate over 'dc' you find there are three occurrences of '3'. First occurrence is in 1:['2','3'].
I would like to iterate over dict so that
if first occurrence of '3' occurs:
dosomething()
else occurrence of ... | [
"Assuming the values in the dict are the lists:\nfoundThree = False\nfor key, val in dc.items():\n if '3' in val and not foundThree:\n foundThree = True\n # doSomething()\n elif '3' in val:\n # doSomethingElse()\n else:\n # doAnotherThing()\n\n\nEdit (update for your comments ab... | [
4,
3,
3,
2,
1,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0007577732_python.txt |
Q:
Access self from decorator
In setUp() method of unittest I've setup some self variables, which are later referenced in actual tests. I've also created a decorator to do some logging. Is there a way in which I can access those self variables from decorator?
For the sake of simplicity, I'm posting this code:
def dec... | Access self from decorator | In setUp() method of unittest I've setup some self variables, which are later referenced in actual tests. I've also created a decorator to do some logging. Is there a way in which I can access those self variables from decorator?
For the sake of simplicity, I'm posting this code:
def decorator(func):
def _decorator... | [
"Since you're decorating a method, and self is a method argument, your decorator has access to self at runtime. Obviously not at parsetime, because there are no objects yet, just a class.\nSo you change your decorator to:\ndef decorator(func):\n def _decorator(self, *args, **kwargs):\n # access a from Te... | [
144
] | [] | [] | [
"python",
"scope",
"unit_testing"
] | stackoverflow_0007590682_python_scope_unit_testing.txt |
Q:
Why does this enumerate this way?
For the following function
KEYS = {}
def get(kind):
"returns a new key of a particular kind"
global KEYS
try:
return KEYS[kind].pop(0)
except (KeyError, IndexError):
handmade_key = Key.from_path(kind, 1)
start, end = allocate_ids(handma... | Why does this enumerate this way? | For the following function
KEYS = {}
def get(kind):
"returns a new key of a particular kind"
global KEYS
try:
return KEYS[kind].pop(0)
except (KeyError, IndexError):
handmade_key = Key.from_path(kind, 1)
start, end = allocate_ids(handmade_key, 3)
id_range = range(sta... | [
"So it looks like when your captured output begins, the datastore is empty but KEYS[kind] has two values already populated. The datastore isn't allocating the same IDs twice, you just have leftover IDs that have never been allocated. Either track down what else is writing to KEYS, or just wipe it out at the beginni... | [
1,
1,
0
] | [] | [] | [
"google_app_engine",
"python",
"unit_testing"
] | stackoverflow_0007588878_google_app_engine_python_unit_testing.txt |
Q:
Embed a web browser in a Python program
How can I embed a web browser in a Python program? It needs to run on Linux (GTK, Qt are fine), or cross-platform.
I have looked at embedding pywebgtk and Qt's WebKit widget. But these seem to have little more than a rendering engine. In particular, I'd like support for back... | Embed a web browser in a Python program | How can I embed a web browser in a Python program? It needs to run on Linux (GTK, Qt are fine), or cross-platform.
I have looked at embedding pywebgtk and Qt's WebKit widget. But these seem to have little more than a rendering engine. In particular, I'd like support for back/forward and tabbed browsing. Is something li... | [
"http://pypi.python.org/pypi/selenium/2.7.0\nYou can install the selenium package and run a server (same machine, just a different process) with it which you connect to with your python code:\njava -jar selenium-server-standalone-2.7.0.jar\n\nthen:\nfrom selenium import webdriver\nfrom selenium.common.exceptions im... | [
4
] | [] | [] | [
"browser",
"linux",
"python"
] | stackoverflow_0007590143_browser_linux_python.txt |
Q:
Get label value from dynamically created menu items [tkinter]
I have a cascade menu in a parent menu. The cascade items are created dynamically with add_checkbutton method.
A user should be able to "check" menu items and select/confirm them. However, I don't know how to access text in the menu items, to decide whi... | Get label value from dynamically created menu items [tkinter] | I have a cascade menu in a parent menu. The cascade items are created dynamically with add_checkbutton method.
A user should be able to "check" menu items and select/confirm them. However, I don't know how to access text in the menu items, to decide which item is selected.
Obvious solution is to generate tk.StringVar d... | [
"You can use the entrycget method of a menu item to get any of its attributes, including the label and value.\n"
] | [
2
] | [] | [] | [
"menu",
"python",
"tkinter"
] | stackoverflow_0007571184_menu_python_tkinter.txt |
Q:
List of unique items in a list of tuples
I have a list of tuples like this: mylist = [(1,2,3),(6,1,1),(7,8,1),(3,4,5)]. If I use the list comprehension slist = [item for sublist in mylist for item in sublist], I could get slist = [1,2,3,6,1,1,7,8,1,3,4,5].
How should I modify if I need only unique elements in slis... | List of unique items in a list of tuples | I have a list of tuples like this: mylist = [(1,2,3),(6,1,1),(7,8,1),(3,4,5)]. If I use the list comprehension slist = [item for sublist in mylist for item in sublist], I could get slist = [1,2,3,6,1,1,7,8,1,3,4,5].
How should I modify if I need only unique elements in slist like this [1,2,3,6,7,8,4,5]?
| [
"Use a set instead of a list.\nset(slist)\n\nIf you really need it as a list then you can convert it back to a list:\nslist = list(set(slist))\n\nNote that this conversion won't preserve the original order of the elements. If you need the same order you can use this instead:\n>>> result = []\n>>> seen = set()\n>>> ... | [
11,
7,
2,
1
] | [] | [] | [
"list",
"python",
"tuples"
] | stackoverflow_0007590950_list_python_tuples.txt |
Q:
Get tuples with max value from each key from a list
I have a list of tuples like this:
[(1, 0), (2, 1), (3, 1), (6, 2), (3, 2), (2, 3)]
I want to keep the tuples which have the max first value of every tuple with the same second value. For example (2, 1) and (3, 1) share the same second (key) value, so I just want... | Get tuples with max value from each key from a list | I have a list of tuples like this:
[(1, 0), (2, 1), (3, 1), (6, 2), (3, 2), (2, 3)]
I want to keep the tuples which have the max first value of every tuple with the same second value. For example (2, 1) and (3, 1) share the same second (key) value, so I just want to keep the one with the max first value -> (3, 1). In t... | [
"from operator import itemgetter\nfrom itertools import groupby\n\n[max(items) for key, items in groupby(L,key = itemgetter(1))]\n\nIt's assuming that you initial list of tuples is sorted by key values.\ngroupby creates an iterator that yields objects like (0, <itertools._grouper object at 0x01321330>), where the f... | [
6,
4,
0,
0
] | [] | [] | [
"algorithm",
"list",
"python",
"tuples"
] | stackoverflow_0007590932_algorithm_list_python_tuples.txt |
Q:
ctypes double array encodes wrong (1.35689368162e-312-->0.047098)
I have a function that accepts a double array as first parameter
cb_type = CFUNCTYPE(c_void_p, c_double * 2, c_int, c_int)
def mycb(cube, ndim, nparams):
print "cube before", [v for v in cube]
for i in range(ndim):
cube[i] = cube[i] ... | ctypes double array encodes wrong (1.35689368162e-312-->0.047098) | I have a function that accepts a double array as first parameter
cb_type = CFUNCTYPE(c_void_p, c_double * 2, c_int, c_int)
def mycb(cube, ndim, nparams):
print "cube before", [v for v in cube]
for i in range(ndim):
cube[i] = cube[i] * 10 * math.pi
print "cube after", [v for v in cube]
I hand it ove... | [
"I fixed it by using POINTER(c_double) instead of c_double * 2.\nThe new output looks like this: \nvalues before: 0.905349, 0.270400\ncube before [0.905348643442958, 0.2703996141057701]\ncube after [28.44236647177882, 8.494854412082024]\nvalues after : 28.442366, 8.494854\n\n"
] | [
0
] | [] | [] | [
"arrays",
"ctypes",
"double",
"python"
] | stackoverflow_0007556746_arrays_ctypes_double_python.txt |
Q:
How to kill a process which is create by popen and uses communicate()?
I have a program, P1, which I need to run about 24*20000 times with different inputs. The problem is the P1 hangs and I should force it to quite manually (kill). My first solution was writing a python script to call P1 and passing the proper in... | How to kill a process which is create by popen and uses communicate()? | I have a program, P1, which I need to run about 24*20000 times with different inputs. The problem is the P1 hangs and I should force it to quite manually (kill). My first solution was writing a python script to call P1 and passing the proper input and receiving the output using popen and communicate. But due to the nat... | [
"If you're not required to use Python, you might consider using Cygwin Bash along with the timeout(1) command to run a command with a timeout. However, since Cygwin's implementation of fork() is not very fast and you're creating an enormous number of processes, you'll likely have an enormous overhead of just creat... | [
2,
2,
0,
0
] | [] | [] | [
"kill",
"popen",
"python",
"subprocess",
"terminate"
] | stackoverflow_0007003836_kill_popen_python_subprocess_terminate.txt |
Q:
Configuring and installing python2.6.7 and mod_wsgi3.3 on RHEL for production
This is a long question detailing all that I did from the start. Hope it helps.
I am working on a django application and need to deploy it on to the production server. The production server is a virtual server managed by IT, and I do not... | Configuring and installing python2.6.7 and mod_wsgi3.3 on RHEL for production | This is a long question detailing all that I did from the start. Hope it helps.
I am working on a django application and need to deploy it on to the production server. The production server is a virtual server managed by IT, and I do not have the root access. They have given me rights to manage the installations of my ... | [
"Egg cache issue solved by setting environment variable in WSGI script:\nhttp://code.google.com/p/modwsgi/wiki/ApplicationIssues#Access_Rights_Of_Apache_User\nor in Apache configuration:\nhttp://code.google.com/p/modwsgi/wiki/ConfigurationDirectives#WSGIPythonEggs\nhttp://code.google.com/p/modwsgi/wiki/Configuratio... | [
2
] | [] | [] | [
"apache",
"django",
"failed_installation",
"mod_wsgi",
"python"
] | stackoverflow_0007590880_apache_django_failed_installation_mod_wsgi_python.txt |
Q:
Import troubles
Here is part of my module: gm.py
def avg_list(list):
sum = 0
for num in list:
sum += num
avg = float(sum)/len(list)
print avg
def median(list):
i = len(list)
if not i%2: # if i divided my 2 has no remainder
return (list[(i/2)-1]+list[i/2])/2.0 # return t... | Import troubles | Here is part of my module: gm.py
def avg_list(list):
sum = 0
for num in list:
sum += num
avg = float(sum)/len(list)
print avg
def median(list):
i = len(list)
if not i%2: # if i divided my 2 has no remainder
return (list[(i/2)-1]+list[i/2])/2.0 # return the value of this bl... | [
"Either reference the functions on the module object:\nimport gm\ndef stats(list):\n\n stats = {} # empty dict named stats\n stats['average'] = gm.avg_list(list) # Stats(key)[average] = mean of the list of numbers [values]\n stats['median'] = gm.median(list) # same for median\n return stats\n\nor impor... | [
4,
2
] | [] | [] | [
"import",
"importerror",
"python"
] | stackoverflow_0007591234_import_importerror_python.txt |
Q:
counting source code lines in python project
How do I calculate the number of lines written in a project containing multiple sub dirs in a python project. for example a dir structure is like
A
\ <*some files here*>\
B
\ <*some files here*>\ ... and so on...
A:
You could use the find utility in linu... | counting source code lines in python project | How do I calculate the number of lines written in a project containing multiple sub dirs in a python project. for example a dir structure is like
A
\ <*some files here*>\
B
\ <*some files here*>\ ... and so on...
| [
"You could use the find utility in linux.\nOn the command prompt:\n$ find <project_directory_path> -name '*.py' | xargs wc -l\n\nThis will give you the count of all files ending with .py in the project_directory and finally the total. (I am assuming you just want the count of .py files)\nIf you just want the total ... | [
12
] | [] | [] | [
"code_metrics",
"python",
"version_control"
] | stackoverflow_0007591231_code_metrics_python_version_control.txt |
Q:
Find string in another string using python
Lets say that you have an email address xxx@yyy.com and you want to create something like this in python:
email = 'mystuff@yyy.com'
try:
if "@yyy.com":
#do something
if "@zzz.com":
#do something else
except:
#do something
How would I do this?
A:
email_... | Find string in another string using python | Lets say that you have an email address xxx@yyy.com and you want to create something like this in python:
email = 'mystuff@yyy.com'
try:
if "@yyy.com":
#do something
if "@zzz.com":
#do something else
except:
#do something
How would I do this?
| [
"email_addr = \"foo@yyy.com\"\n\nif email_addr.endswith(\"@yyy.com\"):\n # do something\nelif email_addr.endswith(\"@zzz.com\"):\n # do something else\n\n# or...\n\nif \"@yyy.com\" in email_addr:\n # do something\nelif \"@zzz.com\" in email_addr:\n # do something else\n\n",
"email = \"xxx@yyy.com\"\ni... | [
7,
0
] | [] | [] | [
"python"
] | stackoverflow_0007591291_python.txt |
Q:
setuptools entry_points. Installing executable to /usr/sbin
I have a setup.py script, that has entry_points defined like this:
entry_points = {
'console_scripts': [
'gun = gun.sync:main'
]
},
This installs the executable into /usr/bin. Is there an... | setuptools entry_points. Installing executable to /usr/sbin | I have a setup.py script, that has entry_points defined like this:
entry_points = {
'console_scripts': [
'gun = gun.sync:main'
]
},
This installs the executable into /usr/bin. Is there any way I can tell entry_points to install it to /usr/sbin instead?... | [
"No. You have to pass the --script-dir option to easy_install to specify that.\n(You could add it to your project's setup.cfg file, but it's not recommended because it'll surprise people who have configured their Python installation to install scripts to some other location... and even if you do it, it'll only ta... | [
5
] | [] | [] | [
"entry_point",
"packaging",
"python",
"setuptools"
] | stackoverflow_0007556168_entry_point_packaging_python_setuptools.txt |
Q:
Fading the start of a sound with Python
I'm a student in a programming class and I just can't get this fading in to work... Right now it's just muting the first few samples of length fade_length... can anyone tell me why it does so so I can find out a way to fix it?
<code erased>
Help without direct answers would... | Fading the start of a sound with Python | I'm a student in a programming class and I just can't get this fading in to work... Right now it's just muting the first few samples of length fade_length... can anyone tell me why it does so so I can find out a way to fix it?
<code erased>
Help without direct answers would be great. Thank you
| [
"If you're using Python 2.x, try \nfactor = 1.0 * index / fade_length\n\nAn int divided by a larger int is 0. You have to coerce the operation to floating point division.\nEdit: \nYou can also use from __future__ import division to make the division operator use true division like Python 3. Use '//' for floor divis... | [
2
] | [] | [] | [
"audio",
"fadein",
"python"
] | stackoverflow_0007591334_audio_fadein_python.txt |
Q:
Why is Python more strict with circular imports when using from-imports?
I know that Python discourages any situation which can get you into a circular import. But I wanted understand the Python internals of why from-imports are seemingly arbitrarily less forgiving than normal imports in circular import situations... | Why is Python more strict with circular imports when using from-imports? | I know that Python discourages any situation which can get you into a circular import. But I wanted understand the Python internals of why from-imports are seemingly arbitrarily less forgiving than normal imports in circular import situations.
For example, this code compiles:
# main.py
import CommonUtil
# commonutil.p... | [
"Modules are executed from top to bottom. When an import is seen for the first time, execution of the current module is suspended so that the other module can be imported. When the other module attempts to import the first module, it gets a reference to the currently partially-executed module. Since code located af... | [
2,
1
] | [] | [] | [
"python",
"python_import",
"python_internals"
] | stackoverflow_0007591525_python_python_import_python_internals.txt |
Q:
Hidden Markov Models inplementation in R or python
Do you know any good literature and/or tutorials about how to implement HMM in python, R (Bioconductor)? (especially for sequence analysis)
A:
There is the HMM package on CRAN, which might be a good place to start.
http://cran.at.r-project.org/web/packages/HMM/... | Hidden Markov Models inplementation in R or python | Do you know any good literature and/or tutorials about how to implement HMM in python, R (Bioconductor)? (especially for sequence analysis)
| [
"There is the HMM package on CRAN, which might be a good place to start. \nhttp://cran.at.r-project.org/web/packages/HMM/index.html\nThis is easily found from R itself: \nRSiteSearch(\"HMM\")\n\n",
"GHMM for python has a tutorial, but it's short and they admit that \"Currently, the GHMM is utterly lacking in docu... | [
5,
5
] | [] | [] | [
"bioconductor",
"hidden_markov_models",
"python",
"r"
] | stackoverflow_0007591311_bioconductor_hidden_markov_models_python_r.txt |
Q:
Can I combine Create and List class based generic views using mixins?
I'm looking for the easiest way to combine List and Create functionally with generic class views.
I want to have a page that has an item list and a form to add a new item on the bottom.
I thought that mixin architecture would allow to combine ne... | Can I combine Create and List class based generic views using mixins? | I'm looking for the easiest way to combine List and Create functionally with generic class views.
I want to have a page that has an item list and a form to add a new item on the bottom.
I thought that mixin architecture would allow to combine necessary classes but I had no luck yet.
This almost works:
class ResourceLis... | [
"\nNote: I no longer advocate this solution, as this is a much cleaner one.\n\nBy trial and error (and looking at Django source), I wrote this:\nclass ListCreateView(ListView, BaseCreateView):\n def get_context_data(self, **kwargs):\n self.object = None\n self.object_list = self.get_queryset()\n\n ... | [
6
] | [] | [] | [
"django",
"django_1.3",
"django_class_based_views",
"django_generic_views",
"python"
] | stackoverflow_0007591529_django_django_1.3_django_class_based_views_django_generic_views_python.txt |
Q:
Middleware class being create but process_template_response not executed
I have defined a middleware class. and i have added it to the middleware_classes attribute in setting. When a request comes in, the middleware class gets created (the debugger catches the code when the breakpoint is on the class CommonFiilter... | Middleware class being create but process_template_response not executed | I have defined a middleware class. and i have added it to the middleware_classes attribute in setting. When a request comes in, the middleware class gets created (the debugger catches the code when the breakpoint is on the class CommonFiilter(): line)
Now i expect the function def process_template_response(self, reque... | [
"from the docs: \n\nprocess_template_response() will only be called if the response\n instance has a render() method, indicating that it is a\n TemplateResponse.\n\n"
] | [
1
] | [] | [] | [
"django",
"middleware",
"python",
"response",
"templates"
] | stackoverflow_0007591044_django_middleware_python_response_templates.txt |
Q:
Python for a beginner Shell scripting learner?
I'm learning Linux administration and after that i'm going to learn programming on Linux using Python.
While i'm reading in a Linux Administration book, i came into Shell scripting chapter. I saw Bash language and i got dizzy. Let's say it's not one of the good-lookin... | Python for a beginner Shell scripting learner? | I'm learning Linux administration and after that i'm going to learn programming on Linux using Python.
While i'm reading in a Linux Administration book, i came into Shell scripting chapter. I saw Bash language and i got dizzy. Let's say it's not one of the good-looking languages in my humble opinion.
And i said to myse... | [
"Python is not a shell scripting language, because there are basically no Python shells in production use. You can do everything in Python that you can do in bash, but it won't be as natural if you're fundamentally trying to write \"shell scripts\" in the classic sense--scripts that just invoke a series of other p... | [
2
] | [] | [] | [
"bash",
"python",
"shell"
] | stackoverflow_0007591833_bash_python_shell.txt |
Q:
Mental block with os.walk - want to process a file not the filename string
Trying to implement a little script to move the older log files out of apache (actually using a simple bash script to do this in 'real life' - this is just an exercise to practice using Python). I'm getting the filename as a string as the v... | Mental block with os.walk - want to process a file not the filename string | Trying to implement a little script to move the older log files out of apache (actually using a simple bash script to do this in 'real life' - this is just an exercise to practice using Python). I'm getting the filename as a string as the variable f, but I want this to actually be a file when i pass it to self.processF... | [
"Use os.path.abspath:\nself.processFile(root, open(os.path.abspath(f)), age, inString)\n\nLike so:\nimport os\nfor root, dirs, files in os.walk(basedir):\n for f in files:\n m=self.fileFormatRegex.match(f)\n if m:\n if (set('access_log.', 'error.', 'access.', 'error_log.','mod_jk.log.').... | [
1,
1
] | [] | [] | [
"os.walk",
"python"
] | stackoverflow_0007591920_os.walk_python.txt |
Q:
pythonw.exe processes not quitting after running script
Every time I restart the shell or run a script and instance of pythonw.exe*32 is created. When I close out of IDLE these processes don't go away in the task manager. Any ideas on how to fix this?
Thanks!
A:
Have you tried using python.exe instead of pytho... | pythonw.exe processes not quitting after running script | Every time I restart the shell or run a script and instance of pythonw.exe*32 is created. When I close out of IDLE these processes don't go away in the task manager. Any ideas on how to fix this?
Thanks!
| [
"Have you tried using python.exe instead of pythonw.exe?\nIm pretty sure this is the intended default behavior for the window python interperter (pythonw.exe).\nIf its a .pyw file, just right click \"Open With...\" and use python.exe\n"
] | [
1
] | [] | [] | [
"process",
"python",
"python_idle"
] | stackoverflow_0007592008_process_python_python_idle.txt |
Q:
Dict construction with elements in a list
I have a list ['a','b','c','d']. I need to construct a dict out of this list with all the elements of the list as keys in the dict with some default value for all the elements such as None.
How to do that? Should I need to write a function for that or is there a constructo... | Dict construction with elements in a list | I have a list ['a','b','c','d']. I need to construct a dict out of this list with all the elements of the list as keys in the dict with some default value for all the elements such as None.
How to do that? Should I need to write a function for that or is there a constructor available?
| [
"See dict.fromkeys().\ndict.fromkeys(['a','b','c','d']) will return a dictionary with None for all of its values.\ndict.fromkeys(['a','b','c','d'], foo) will return a dictionary with foo for all of its values.\n",
"You can use a generator to quickly convert it to a dictionary:\ndict((x, None) for x in L)\n\n(Wher... | [
6,
2,
2,
1
] | [] | [] | [
"dictionary",
"python"
] | stackoverflow_0007592097_dictionary_python.txt |
Q:
Exporting Layout Positions for a Graph Using NetworkX
After generating x/y layout coordinates for a graph in NetworkX, how do I export the graph, along with node positions, as part of the node definition using something like GraphML?
The layout algorithms don't seem to annotate the graph directly? Or do they?!
A:... | Exporting Layout Positions for a Graph Using NetworkX | After generating x/y layout coordinates for a graph in NetworkX, how do I export the graph, along with node positions, as part of the node definition using something like GraphML?
The layout algorithms don't seem to annotate the graph directly? Or do they?!
| [
"The layout algorithms don't set node attributes (but they should). Here is how to set the attributes:\nIn [1]: import networkx as nx\n\nIn [2]: G=nx.path_graph(4)\n\nIn [3]: pos=nx.spring_layout(G)\n\nIn [4]: nx.set_node_attributes(G,'pos',pos)\n\nIn [5]: G.node\nOut[5]: \n{0: {'pos': array([ 0., 0.])},\n 1: {'p... | [
11
] | [] | [] | [
"graph",
"graphml",
"networkx",
"python"
] | stackoverflow_0007591154_graph_graphml_networkx_python.txt |
Q:
Python: Type error when drawing contour plot
despite using the search function I've been unable to find an answer. I got two assumptions, but don't know in how far they may apply. Now the problem:
I'd like to plot a contour. For this I've got here the following python code:
import numpy as np
import matplotlib.pyp... | Python: Type error when drawing contour plot | despite using the search function I've been unable to find an answer. I got two assumptions, but don't know in how far they may apply. Now the problem:
I'd like to plot a contour. For this I've got here the following python code:
import numpy as np
import matplotlib.pyplot as plt
xi=list_of_distance
yi=list_of_angle
... | [
"As @rocksportrocker implies, you need to take into account that histogram2d returns the edges in addition to the histogram. Another detail is that you probably want to explicitly pass in a range, otherwise one will be chosen for you based on the actual min and max values in your data. You then want to convert the ... | [
2,
0
] | [] | [] | [
"matplotlib",
"numpy",
"python"
] | stackoverflow_0007556499_matplotlib_numpy_python.txt |
Q:
Nginx + uWsgi + Django strange json response behavior
Some tech specifications:
CentOS 6.0
uWSGI 0.9.9.2
Nginx 1.0.5
Django 1.3.1
uWSGI:
[uwsgi]
socket = 127.0.0.1:3031
master = true
processes = 5
uid = xx
gid = xx
env = DJANGO_SETTINGS_MODULE=xx.settings
module = django.core.hand... | Nginx + uWsgi + Django strange json response behavior | Some tech specifications:
CentOS 6.0
uWSGI 0.9.9.2
Nginx 1.0.5
Django 1.3.1
uWSGI:
[uwsgi]
socket = 127.0.0.1:3031
master = true
processes = 5
uid = xx
gid = xx
env = DJANGO_SETTINGS_MODULE=xx.settings
module = django.core.handlers.wsgi:WSGIHandler()
post-buffering = 8192
harak... | [
"have you tried disabling the python optimizer (remove the optimize option from the uWSGI config file)?\nEven if it looks like more a js/html/client issue some object can make some sort of mess with optimizations enabled. And please do not follow silly advise like downgrading to unsupported more than 1-years-old ve... | [
0
] | [] | [] | [
"django",
"json",
"nginx",
"python",
"uwsgi"
] | stackoverflow_0007582199_django_json_nginx_python_uwsgi.txt |
Q:
Setting a value to a dictionary's dictionary value
The code:
>>> mydict = {}
>>> keylist = ['a','b','c']
>>> mydict=dict.fromkeys(keylist,{})
>>> mydict['a']['sample'] = 1
>>> mydict
{'a': {'sample': 1}, 'c': {'sample': 1}, 'b': {'sample': 1}}
I was expecting mydict['a']['sample'] = 1 would set the value just for... | Setting a value to a dictionary's dictionary value | The code:
>>> mydict = {}
>>> keylist = ['a','b','c']
>>> mydict=dict.fromkeys(keylist,{})
>>> mydict['a']['sample'] = 1
>>> mydict
{'a': {'sample': 1}, 'c': {'sample': 1}, 'b': {'sample': 1}}
I was expecting mydict['a']['sample'] = 1 would set the value just for a's dictionary value and would get this: {'a': {'sample... | [
"The problem is that you added the same dictionary to mydict for every key. You want to add different dictionaries, like so:\nmydict = dict((key, {}) for key in keylist)\n\nIn the above code, you create a new dictionary to pair with each key. In your original code, the function fromkeys took the argument (the empty... | [
6
] | [] | [] | [
"dictionary",
"python"
] | stackoverflow_0007592592_dictionary_python.txt |
Q:
Generating second graph in different window - VPython
If I have a graph like this in VPython: graphX = gcurve(color = color.cyan), how can I make another graph (graphY = gcurve(color = color.red)) in a different window (different set of axes)?
A:
use gdisplay() to create graph window:
from visual.graph import *
... | Generating second graph in different window - VPython | If I have a graph like this in VPython: graphX = gcurve(color = color.cyan), how can I make another graph (graphY = gcurve(color = color.red)) in a different window (different set of axes)?
| [
"use gdisplay() to create graph window:\nfrom visual.graph import *\ngraphX = gcurve(color = color.cyan)\ngdisplay()\ngraphY = gcurve(color = color.red)\n\n"
] | [
2
] | [] | [] | [
"graph",
"python",
"vpython"
] | stackoverflow_0007592840_graph_python_vpython.txt |
Q:
Transparency with Python Image Library
I'm trying to place a PNG watermark with partial transparency on top of a Facebook profile pic (jpg) using the Python Image Library. The part that should be transparent simply comes off as white. Here's my code:
con = urllib2.urlopen('facebook_link_to_profile_pic')
im = Image... | Transparency with Python Image Library | I'm trying to place a PNG watermark with partial transparency on top of a Facebook profile pic (jpg) using the Python Image Library. The part that should be transparent simply comes off as white. Here's my code:
con = urllib2.urlopen('facebook_link_to_profile_pic')
im = Image.open(cStringIO.StringIO(con.read()))
overl... | [
"The 3rd option to paste is a mask (see the docs). It accepts an RGBA image, so the simplest solution is to use your overlay image again: im.paste(overlay, (0, 0), overlay).\n"
] | [
8
] | [] | [] | [
"python",
"python_imaging_library",
"transparency"
] | stackoverflow_0007592981_python_python_imaging_library_transparency.txt |
Q:
Convert pseudo code to Python
Just to be fully up front, this is regarding a homework, but this in itself is not the assignment. The assignment is using noise to create cool graphics. I have a bit of experience in Python but not enough to figure this simple thing out.
I'm having trouble generating a seeded-random ... | Convert pseudo code to Python | Just to be fully up front, this is regarding a homework, but this in itself is not the assignment. The assignment is using noise to create cool graphics. I have a bit of experience in Python but not enough to figure this simple thing out.
I'm having trouble generating a seeded-random [-1,1]. The pseudocode my teacher g... | [
"The & symbol stands for bitwise AND\nThe ^ symbol stands for bitwise XOR\nand the 7FFFFFFF is a HEX number.\nIn programming you can represent a hex number using 0x where 7FFFFFFF is 0x7FFFFFFF\nSome further reading on hex numbers.\nTo do a binary AND in python you just use & 0x7FFFFFFF\nsee more here about bitwise... | [
3,
1,
1
] | [] | [] | [
"python"
] | stackoverflow_0007592305_python.txt |
Q:
invalid types ‘float[int]’ for array subscript error and passing variables to scipy.weave.inline
I've been playing with Scipy's inline tool (via weave) for fun, but I'm running into some trouble. My C is rusty and I have a feeling that I'm missing something simple.
The function below is designed to take a 3D float... | invalid types ‘float[int]’ for array subscript error and passing variables to scipy.weave.inline | I've been playing with Scipy's inline tool (via weave) for fun, but I'm running into some trouble. My C is rusty and I have a feeling that I'm missing something simple.
The function below is designed to take a 3D float32 numpy array. I'm using a massive set of gridded atmospheric data, but this should work with any 3D ... | [
"you can create the out array in python first, and pass it to C++. In C++ you can get the shape of x by Nx[0], Nx[1], Nx[2]. And you can use macros defined for array to access it's elements. For example: X3(k,j,i) is the same as x[k,j,i] in python, and OUT2(j,i) is the same as out[j,i] in python. You can view the a... | [
1,
0
] | [] | [] | [
"c",
"numpy",
"python",
"scipy"
] | stackoverflow_0007587810_c_numpy_python_scipy.txt |
Q:
display subsets of vtkPoints using different glyphs
I am trying to display some timeseries data in 3D using colormapped values using VTK.
I have a single array of 3D positions for two different kinds of objects, say cones and spheres. These positions are interspersed. I also have a 2D array with timeseries data fo... | display subsets of vtkPoints using different glyphs | I am trying to display some timeseries data in 3D using colormapped values using VTK.
I have a single array of 3D positions for two different kinds of objects, say cones and spheres. These positions are interspersed. I also have a 2D array with timeseries data for these objects. n-th entry in position array correponds ... | [
"I bypassed the issue by storing the indices of the two kinds of objects (i.e., cone_indices and sphere_indices). I also create to vtkPoints objects with the cone positions and the sphere positions. These are used to create the vtkPolyData for the respective classes. In the update method of the timer class, I use t... | [
0
] | [] | [] | [
"numpy",
"python",
"vtk"
] | stackoverflow_0007566287_numpy_python_vtk.txt |
Q:
How to check if phone number entered by user includes country code?
Is there an easy way to check whether a phone number entered by the user includes country code and to validate that the number is correct? I don't use any specific formats, the number itself must be only digits, no ('s, -'s and the like. Is such v... | How to check if phone number entered by user includes country code? | Is there an easy way to check whether a phone number entered by the user includes country code and to validate that the number is correct? I don't use any specific formats, the number itself must be only digits, no ('s, -'s and the like. Is such validation possible without asking user for a country? The trick is that I... | [
"Here is Google's library for dealing with phone numbers (it's in Java). However, as Google is a Python shop as well, I imagine they might have a Python version available somewhere or you may be able to extract what you need and translate it. \n",
"I studied this subject for a while. We have a huge database with ... | [
4,
2,
2
] | [] | [] | [
"phone_number",
"python",
"validation"
] | stackoverflow_0003125021_phone_number_python_validation.txt |
Q:
What does this code segment in python mean?
I'm trying to understand what is going on here, specifically how curids is getting set:
for idx in xrange(0, int(math.ceil(float(len(mids))/chunk))):
curids = mids[int(idx*chunk):int((idx*chunk)+chunk)]
I'm not sure what the syntax for mids[int(idx*chunk):i... | What does this code segment in python mean? | I'm trying to understand what is going on here, specifically how curids is getting set:
for idx in xrange(0, int(math.ceil(float(len(mids))/chunk))):
curids = mids[int(idx*chunk):int((idx*chunk)+chunk)]
I'm not sure what the syntax for mids[int(idx*chunk):int((idx*chunk)+chunk)] is trying to do.
| [
"It extracts blocks of mids into curids, where each block consists of chunk elements.\nIf you change the loop to print out the values of int(idx*chunk) and int((idx*chunk)+chunk)], you'll see that for yourself.\nFor example, if len(mids)==50 and chunk==12, the indices that would get printed are:\n0 12\n12 24\n24 36... | [
2,
0,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0007593398_python.txt |
Q:
Formatting timedelta object python
I wrote this little script to format a timedelta object according to my needs:
def due_format(self):
time_diff = abs((self.due - datetime.datetime.now()).total_seconds())
days = time_diff / 60 / 60 / 24
hours = time_diff / 60 / 60
minutes = time... | Formatting timedelta object python | I wrote this little script to format a timedelta object according to my needs:
def due_format(self):
time_diff = abs((self.due - datetime.datetime.now()).total_seconds())
days = time_diff / 60 / 60 / 24
hours = time_diff / 60 / 60
minutes = time_diff / 60
hours_wo_days = hours... | [
"timedelta instance have attributes .days and .seconds which save a few lines. They also keep the values small, so you can convert to int once early instead of for each string format. This also removes the need for abs() and .floor.\n"
] | [
2
] | [] | [] | [
"formatting",
"python",
"timedelta"
] | stackoverflow_0007593410_formatting_python_timedelta.txt |
Q:
Extending Django-Registration: Getting error on setting url.py
am trying to follow the answers provided in Django-Registration & Django-Profile, using your own custom form and Creating a Django Registration Form by Extending Django-Registation Application to extend the django-registration form. I added the followi... | Extending Django-Registration: Getting error on setting url.py | am trying to follow the answers provided in Django-Registration & Django-Profile, using your own custom form and Creating a Django Registration Form by Extending Django-Registation Application to extend the django-registration form. I added the following code in url.py
url(r'^accounts/register/$', register, {'backend'... | [
"That dictionary in your urls.py entry gets passed as keyword arguments to the view function, register, when you access the page. register doesn't have a keyword argument form_class.\nIf the register your first link is referring to is the register from the second, the first link is wrong. Because that register do... | [
1
] | [] | [] | [
"django",
"django_registration",
"python"
] | stackoverflow_0007593574_django_django_registration_python.txt |
Q:
Embedding chaco in GTK
Embedding Chaco into Qt and Wx seems to be no problem. Does anyone have an example or an idea how to embed Chaco into GTK?
A:
I use python with matplotlib.
To have a graphic inserted in the GUI, I need a "backend" : http://matplotlib.sourceforge.net/faq/installing_faq.html#backends
Code sn... | Embedding chaco in GTK | Embedding Chaco into Qt and Wx seems to be no problem. Does anyone have an example or an idea how to embed Chaco into GTK?
| [
"I use python with matplotlib.\nTo have a graphic inserted in the GUI, I need a \"backend\" : http://matplotlib.sourceforge.net/faq/installing_faq.html#backends\nCode snippet :\nfrom matplotlib.backends.backend_gtkagg import FigureCanvasGTKAgg as Canvas\n\nThen, instance it (the add_subplot prepares a place for one... | [
2
] | [] | [] | [
"chaco",
"gtk",
"plot",
"pygtk",
"python"
] | stackoverflow_0007585611_chaco_gtk_plot_pygtk_python.txt |
Q:
Python nested list within a nested list without looping
I want to add a dictionary to a nested list within a nested list.
so;
['master_list 1', ['list 1', ['sub_list 1']], ['list 2'], ['list 3']]
would end up like;
['master_list_1', ['list_1', ['sub_list_1',{key_1:value_1}]], ['list_2'], ['list_3']]
I know the e... | Python nested list within a nested list without looping | I want to add a dictionary to a nested list within a nested list.
so;
['master_list 1', ['list 1', ['sub_list 1']], ['list 2'], ['list 3']]
would end up like;
['master_list_1', ['list_1', ['sub_list_1',{key_1:value_1}]], ['list_2'], ['list_3']]
I know the exact position within the lists that I want to add the diction... | [
"master_list[1][1].append({key_1:value_1})\n\n"
] | [
3
] | [] | [] | [
"nested_lists",
"python"
] | stackoverflow_0007594580_nested_lists_python.txt |
Q:
How to determine when DST starts or ends in a specific location in Python?
I'm looking for a method of determining when DST starts or ends for a given timezone in a Python script I'm working on.
I know pytz can convert the UTC dates I'm working into localtime, and will take DST into account, however for this parti... | How to determine when DST starts or ends in a specific location in Python? | I'm looking for a method of determining when DST starts or ends for a given timezone in a Python script I'm working on.
I know pytz can convert the UTC dates I'm working into localtime, and will take DST into account, however for this particular application I need to know the point of the changeover.
Any suggestions?
| [
"You could have a look to the _utc_transition_times memberof the timezone you're using.\n>>> from pytz import timezone\n>>> tz = timezone(\"Europe/Paris\")\n>>> print tz._utc_transition_times\n\n[datetime.datetime(1, 1, 1, 0, 0), datetime.datetime(1911, 3, 10, 23, 51, 39), datetime.datetime(1916, 6, 14, 23, 0), dat... | [
24
] | [] | [] | [
"dst",
"python",
"pytz",
"timezone"
] | stackoverflow_0007594656_dst_python_pytz_timezone.txt |
Q:
Pickup directories: How not to pickup files that are still being written?
I have a Python script that checks on a pickup directory and processes any files that it finds, and then deletes them.
How can I make sure not to pickup a file that is still being written by the process that drops files in that directory?
M... | Pickup directories: How not to pickup files that are still being written? | I have a Python script that checks on a pickup directory and processes any files that it finds, and then deletes them.
How can I make sure not to pickup a file that is still being written by the process that drops files in that directory?
My test case is pretty simple. I copy-paste 300MB of files into the pickup direc... | [
"As a workaround, you could listen to file modified events (watchdog is cross-platform). The modified event (on OS X at least) isn't fired for each write, it's only fired on close. So when you detect a modified event you can assume all writes are complete.\nOf course, if the file is being written in chunks, and bei... | [
2,
1,
1,
1,
0
] | [] | [] | [
"batch_processing",
"file_io",
"python"
] | stackoverflow_0007591598_batch_processing_file_io_python.txt |
Q:
Python: Conditional elements in array
A question from a complete Python novice.
I have a column array where I need to force certain values to zero depending on a conditional statement applied to another array. I have found two solutions, which both provide the correct answer. But they are both quite time consuming... | Python: Conditional elements in array | A question from a complete Python novice.
I have a column array where I need to force certain values to zero depending on a conditional statement applied to another array. I have found two solutions, which both provide the correct answer. But they are both quite time consuming for the larger arrays I typically need (>1... | [
"use bool array to access elements in array y:\ndef testC(y, f, FC1, FC2):\n f2 = abs(f)\n idx = (f2>=FC1) & (f2<=FC2)\n y[~idx] = 0\n return y\n\n",
"All of these are slower than HYRY solution by a large factor:\nHow about\n( x[1] if FC1<=abs(x[0])<=FC2 else 0 for x in itertools.izip(f,x) )\nIf you ... | [
5,
0
] | [] | [] | [
"arrays",
"conditional",
"python"
] | stackoverflow_0007594204_arrays_conditional_python.txt |
Q:
What back end tech to use for a 2-player, turn based, ajax web game?: Python or Java, FastCGI or app server?
I'm building a web based 2 player game, client side interface will all be done in an ajax manor with html/css/javascript. I want clients to be able to initiate games and join others, chat etc, but I'm stuck... | What back end tech to use for a 2-player, turn based, ajax web game?: Python or Java, FastCGI or app server? | I'm building a web based 2 player game, client side interface will all be done in an ajax manor with html/css/javascript. I want clients to be able to initiate games and join others, chat etc, but I'm stuck on what the best way to code and communicate with the server is, I would like to use either Java or Python.
Pytho... | [
"Some direct benefits of using Django instead of rolling your own\n\nDatabase ORM\nTemplating\nUser authentication\nPluggable applications (use other people's stuff, yay!)\n\nAlso, Django can be deployed as a FCGI application.\n"
] | [
0
] | [] | [] | [
"ajax",
"java",
"python",
"web_applications"
] | stackoverflow_0007595124_ajax_java_python_web_applications.txt |
Q:
Module's source changes don't take effect
I am having an issue with python which looks really weird to me. My script starts to be quite big and is suposed to run a test suite for a program.
My inclusion tree is:
run.py --> Module --> Section --> Test
The weird behavior I am having is that when I add a modificati... | Module's source changes don't take effect | I am having an issue with python which looks really weird to me. My script starts to be quite big and is suposed to run a test suite for a program.
My inclusion tree is:
run.py --> Module --> Section --> Test
The weird behavior I am having is that when I add a modification to my Module, Section or Test module's sourc... | [
"I suspect you have at least one other module with the same name as one of yours in your PYTHONPATH. Either look for old copies you left around or try changing your module names and see what happens.\nYou'd see a similar effect if you forgot to reload your modules before running them after you modified them, but re... | [
3
] | [] | [] | [
"module",
"python"
] | stackoverflow_0007595297_module_python.txt |
Q:
How to retrieve two IMAP4.select()
I'd like to retrieve two folders using the select method. I'd like to get the "Inbox" as well as the "Sent".
Is there a way to do this? Currently, the only way I know of, I can only get one folder at a time using:
IMAP4.select('INBOX')
A:
Selecting an IMAP folder does not retri... | How to retrieve two IMAP4.select() | I'd like to retrieve two folders using the select method. I'd like to get the "Inbox" as well as the "Sent".
Is there a way to do this? Currently, the only way I know of, I can only get one folder at a time using:
IMAP4.select('INBOX')
| [
"Selecting an IMAP folder does not retrieve any messages, it just selects that folder. If you to get a message (or attributes of it like flags or the internal date), you need to use FETCH. \nIf you want to get all messages in two folders, simply loop through each of them in turn. \n"
] | [
1
] | [] | [] | [
"imap",
"python"
] | stackoverflow_0007592262_imap_python.txt |
Q:
Explanation of syntax in for loop?
I was trying to do some of the problems on projecteuler, and I got to the one with the sum of squares and squares of sums. I didn't want to brute force it, so I looked up the solution, which was:
sum1 = 0
sum2 = 0
for i in ((x,x ** 2) for x in range(1,100+1)):
sum1 += i[0]
... | Explanation of syntax in for loop? | I was trying to do some of the problems on projecteuler, and I got to the one with the sum of squares and squares of sums. I didn't want to brute force it, so I looked up the solution, which was:
sum1 = 0
sum2 = 0
for i in ((x,x ** 2) for x in range(1,100+1)):
sum1 += i[0]
sum2 += i[-1]
print(sum1 ** 2 - sum2... | [
"When confronted with complex syntax, add print statements.\nfor i in ((x,x ** 2) for x in range(1,100+1)):\n print i\n\nNot too helpful.\nTry this.\na = ((x,x ** 2) for x in range(1,100+1))\nprint a\nfor i in a:\n print i\n\nHelpful? Maybe.\nTry this:\na = ((x,x ** 2) for x in range(1,100+1))\nb = list(a)\... | [
4
] | [] | [] | [
"for_loop",
"javascript",
"object",
"python"
] | stackoverflow_0007595009_for_loop_javascript_object_python.txt |
Q:
why my code does not load the kml file ..(it is the simplest way)
this is my google-map code:
<!DOCTYPE html PUBLIC "-//WAPFORUM//DTD XHTML Mobile 1.0//EN" "http://www.wapforum.org/DTD/xhtml-mobile10.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<meta http-equiv="Content-Type" content="tex... | why my code does not load the kml file ..(it is the simplest way) | this is my google-map code:
<!DOCTYPE html PUBLIC "-//WAPFORUM//DTD XHTML Mobile 1.0//EN" "http://www.wapforum.org/DTD/xhtml-mobile10.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta name="viewport" content="width=d... | [
"My first thought is that you were missing <Document></Document> -- but looking at the docs I'm not sure that's right.\nIs b.kml being served with the mime type application/vnd.google-earth.kml+xml? Looking at the documentation, it seems like that's a requirement:\nhttp://code.google.com/apis/kml/documentation/kml_... | [
0,
0
] | [] | [] | [
"google_maps",
"javascript",
"kml",
"python"
] | stackoverflow_0002486846_google_maps_javascript_kml_python.txt |
Q:
Downloading files in background with Python
I have got a working web application in Python that downloads a file into the web server upon a user's request. This works fine for small file downloads but when the user requests a larger file, the connection times out. So, I think I need to process the download in the ... | Downloading files in background with Python | I have got a working web application in Python that downloads a file into the web server upon a user's request. This works fine for small file downloads but when the user requests a larger file, the connection times out. So, I think I need to process the download in the background but I'm not sure what tool is most sui... | [
"Timout duration is up to you, you could just make it longer.\nAnyway there are plenty of flash or AJAX uploaders out there, nothing you can do only server side AFAIK\n"
] | [
2
] | [] | [] | [
"background",
"python",
"web_applications"
] | stackoverflow_0007595809_background_python_web_applications.txt |
Q:
How to upload files to Google Docs through Google Data API?
I developing an application which works with Google API, according to my understanding.
def push_to_ga(request):
client = gdata.docs.service.DocsService()
client.ClientLogin('account@gmail.com', 'password')
entrys = Entry.objects.all()
fo... | How to upload files to Google Docs through Google Data API? | I developing an application which works with Google API, according to my understanding.
def push_to_ga(request):
client = gdata.docs.service.DocsService()
client.ClientLogin('account@gmail.com', 'password')
entrys = Entry.objects.all()
for entry in entrys:
splitted = entry.file.split('/')
... | [
"Which version of the Google API are you using?\nAccording to the Google documentation, for versions 1.0 and 2.0 you have to wrap the document as a MediaSource object in order to pass it to the Upload method. So, I think you need to replace:\nclient.UploadDocument(entry.file, splitted[-1])\n\nwith:\nms = gdata.Medi... | [
1
] | [] | [] | [
"google_api",
"python"
] | stackoverflow_0007595174_google_api_python.txt |
Q:
Getting list element's Attribute
I have two list.
List1 contain objects and each object has node1 property.
List2 contain lists of node which are the properties of objects stored in list1.
I want to create separate list which contain list of objects whose node present in list2. I want to create this list without u... | Getting list element's Attribute | I have two list.
List1 contain objects and each object has node1 property.
List2 contain lists of node which are the properties of objects stored in list1.
I want to create separate list which contain list of objects whose node present in list2. I want to create this list without using for loop because my object list i... | [
"Sounds like it's time to redesign your program. Replace list 2 with a defaultdict(None) mapping the objects in list 1 to their node properties. Call it node so you can get the node of an object x with node[x]. You can get the list of all nodes (unordered) with node.values() in O(m) time where m is the number of ob... | [
2,
0
] | [] | [] | [
"python"
] | stackoverflow_0007596108_python.txt |
Q:
os.path.join returning Errno22 in Enthought/Python
I'm working with a fairly complex Enthought/Python program that is returning this error:
File "C:\Users\riddle\Desktop\FCI2\src\equation.py", line 41, in main
fci_data = np.load(os.path.join(local_data_path, "fci_data.npy"))
File "C:\Python27\lib\site-packages\num... | os.path.join returning Errno22 in Enthought/Python | I'm working with a fairly complex Enthought/Python program that is returning this error:
File "C:\Users\riddle\Desktop\FCI2\src\equation.py", line 41, in main
fci_data = np.load(os.path.join(local_data_path, "fci_data.npy"))
File "C:\Python27\lib\site-packages\numpy\lib\npyio.py", line 329, in load
fid = open(file, "rb... | [
"try first to normalize the path :\nlocal_data_path = os.path.normpath(local_data_path)\n\n"
] | [
0
] | [] | [] | [
"enthought",
"errno",
"numpy",
"path",
"python"
] | stackoverflow_0007577888_enthought_errno_numpy_path_python.txt |
Q:
Dynamically import a package from a directory
I am making a server that listens on a socket. Whenever a new request comes in, the server spawns a new instance of handle_request. Each instance of handle_request.py imports the relevant handler from request_handlers.
server.py
handle_request.py
request_handlers
|_han... | Dynamically import a package from a directory | I am making a server that listens on a socket. Whenever a new request comes in, the server spawns a new instance of handle_request. Each instance of handle_request.py imports the relevant handler from request_handlers.
server.py
handle_request.py
request_handlers
|_handler_beta
|_handler_1
|_handler_2
While handlerX i... | [
"Create __init__.py in the directory. That makes it a package. If you're scanning the directory for .py files, you'll probably then want to skip __init__.py.\nThen, you can import them with __import__('request_handlers.' + module, fromlist=['']) (the fromlist is important, otherwise you'll get request_handlers rath... | [
2,
0
] | [] | [] | [
"python"
] | stackoverflow_0007596096_python.txt |
Q:
parsing parenthesized list in python's imaplib
I am looking for simple way to split parenthesized lists that come out of IMAP responses into Python lists or tuples. I want to go from
'(BODYSTRUCTURE ("text" "plain" ("charset" "ISO-8859-1") NIL NIL "quoted-printable" 1207 50 NIL NIL NIL NIL))'
to
(BODYSTRUCTURE, (... | parsing parenthesized list in python's imaplib | I am looking for simple way to split parenthesized lists that come out of IMAP responses into Python lists or tuples. I want to go from
'(BODYSTRUCTURE ("text" "plain" ("charset" "ISO-8859-1") NIL NIL "quoted-printable" 1207 50 NIL NIL NIL NIL))'
to
(BODYSTRUCTURE, ("text", "plain", ("charset", "ISO-8859-1"), None, No... | [
"pyparsing's nestedExpr parser function parses nested parentheses by default:\nfrom pyparsing import nestedExpr\n\ntext = '(BODYSTRUCTURE (\"text\" \"plain\" (\"charset\" \"ISO-8859-1\") NIL NIL \"quotedprintable\" 1207 50 NIL NIL NIL NIL))'\n\nprint nestedExpr().parseString(text)\n\nprints:\n[['BODYSTRUCTURE', ['\... | [
6,
1,
1
] | [] | [] | [
"imap",
"imaplib",
"parsing",
"python"
] | stackoverflow_0003973963_imap_imaplib_parsing_python.txt |
Q:
Form-based authentication with Python
I'm trying to use a code read in Kent's Korner for Form-based authentication. At least I'm told the web site I'm trying to read is form-based authenticated.
But I don't seem to be able to get past the login page. The code I'm using is
Import urllib, urllib2, cookielib, string
... | Form-based authentication with Python | I'm trying to use a code read in Kent's Korner for Form-based authentication. At least I'm told the web site I'm trying to read is form-based authenticated.
But I don't seem to be able to get past the login page. The code I'm using is
Import urllib, urllib2, cookielib, string
# configure an opener that will handle coo... | [
"You can simulate a web browser in Python without using much too resources with mechanize\n(Debian/Ubuntu package is called python-mechanize). It handles both cookies and submitting forms, just the way a web browser would do, one great example is a Python Dropbox Uploader script, which you can transform to your nee... | [
3
] | [] | [] | [
"cookies",
"forms_authentication",
"python"
] | stackoverflow_0004847226_cookies_forms_authentication_python.txt |
Q:
Regex for wrapping digits with curly braces?
I am trying to using Python's re.sub() to match a string with an e character and insert curly braces immediately after the e character and after the lastdigit. For example:
12.34e56 to 12.34e{56}
1e10 to 1e{10}
I can't seem to find the correct regex to insert the desir... | Regex for wrapping digits with curly braces? | I am trying to using Python's re.sub() to match a string with an e character and insert curly braces immediately after the e character and after the lastdigit. For example:
12.34e56 to 12.34e{56}
1e10 to 1e{10}
I can't seem to find the correct regex to insert the desired curly braces. For example, I can properly inser... | [
"re.sub(r'e(\\d+)', r'e{\\1}', '12.34e56')\n\nreturns '12.34e{56}'\nor, the same result but different logic (don't replace e with e):\nre.sub(r'(?<=e)(\\d+)', r'{\\1}', '12.34e56')\n\n",
"Your brace placement is incorrect.\nHere's a solution ensuring the that there's a number with optional decimal place before th... | [
7,
1
] | [] | [] | [
"backreference",
"python",
"regex"
] | stackoverflow_0007596667_backreference_python_regex.txt |
Q:
How to: From one string to another in a long list of strings
Imagine a long string of characters:
"AATTAATCTATATATTGAAATGGGGCCCCAATTTTCCCAAATC ...."
I define 4 strings:
"AAT"
"ATG"
"TTT"
"ATC"
My mission is to find the "end point" for every string "AAT" in the long string of characters. My end points are the thr... | How to: From one string to another in a long list of strings | Imagine a long string of characters:
"AATTAATCTATATATTGAAATGGGGCCCCAATTTTCCCAAATC ...."
I define 4 strings:
"AAT"
"ATG"
"TTT"
"ATC"
My mission is to find the "end point" for every string "AAT" in the long string of characters. My end points are the three last strings "ATG", "TTT", "ATC", which means I need to find th... | [
"You can do this with a regex:\n>>> import re\n>>> s = \"AATTAATCTATATATTGAAATGGGGCCCCAATTTTCCCAAATC ....\"\n>>> [(m.start(), m.end()) for m in re.finditer('AAT.*?(?:ATG|TTT|ATC)', s)]\n[(0, 8), (18, 34)]\n\nre.finditer searches for multiple non-overlapping matches of a regex and returns a MatchObject for each one.... | [
1
] | [] | [] | [
"list",
"python",
"string"
] | stackoverflow_0007575779_list_python_string.txt |
Q:
passing boost python enum as parameter
I defined
enum_<mytype>("mytype")
.value("one",1)
.value("two",2)
;
in my BOOST_PYTHON_MODULE.
when I expose a class with a function taking a parameter of type mytype (essentially, an int), like:
void myfunc(mytype m) {
...
}
I get the following compiler warning... | passing boost python enum as parameter | I defined
enum_<mytype>("mytype")
.value("one",1)
.value("two",2)
;
in my BOOST_PYTHON_MODULE.
when I expose a class with a function taking a parameter of type mytype (essentially, an int), like:
void myfunc(mytype m) {
...
}
I get the following compiler warning:
dereferencing pointer 'p.2311' (or whateve... | [
"It's hard to say exactly without seeing the warning, but it's most likely caused by some macros from Python headers. To be safe, compile the code that uses Python (and Boost.Python) with -fno-strict-aliasing.\n"
] | [
1
] | [] | [] | [
"boost_python",
"c++",
"python"
] | stackoverflow_0007596757_boost_python_c++_python.txt |
Q:
MatchTemplate in OpenCV with Python
I'm using opencv with python bindings. I'm trying to use the template match, but it's not performing exactly as I need it to. If there is no image matching the template I supply it, I don't want it to return a match. It seems to always return a match whether the actual templa... | MatchTemplate in OpenCV with Python | I'm using opencv with python bindings. I'm trying to use the template match, but it's not performing exactly as I need it to. If there is no image matching the template I supply it, I don't want it to return a match. It seems to always return a match whether the actual template exists at all in the image I supply it... | [
"See this answer: OpenCV. Drawing rectangle when matching\nYou are having exactly the same problem - MatchTemplate returns a kind of similarity map instead of single match position.\n"
] | [
2
] | [] | [] | [
"opencv",
"python"
] | stackoverflow_0007597120_opencv_python.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.